From 2665cfa7b660c4579e4dbbe448b84c9d0b002318 Mon Sep 17 00:00:00 2001 From: rasm-its Date: Mon, 12 Oct 2026 14:35:51 +0200 Subject: [PATCH] noindex fix --- dist/modules/content/searchContent.js | 2 +- dist/modules/content/searchContent.js.map | 2 +- dist/modules/seo/buildLlmsTxt.js | 4 +- dist/modules/seo/buildLlmsTxt.js.map | 2 +- dist/modules/seo/buildMetadata.d.ts | 9 ++- dist/modules/seo/buildMetadata.js | 4 +- dist/modules/seo/buildMetadata.js.map | 2 +- dist/modules/seo/buildNoindexField.d.ts | 27 ++++---- dist/modules/seo/buildNoindexField.js | 60 ++++------------- dist/modules/seo/buildNoindexField.js.map | 2 +- dist/modules/seo/buildSitemapEntries.js | 6 +- dist/modules/seo/buildSitemapEntries.js.map | 2 +- dist/modules/seo/createPageMetadata.js | 1 + dist/modules/seo/createPageMetadata.js.map | 2 +- docs/seo.md | 28 +++++--- package.json | 2 +- src/modules/content/searchContent.ts | 3 +- src/modules/seo/buildLlmsTxt.ts | 5 +- src/modules/seo/buildMetadata.ts | 10 ++- src/modules/seo/buildNoindexField.ts | 71 +++++---------------- src/modules/seo/buildSitemapEntries.ts | 8 ++- src/modules/seo/createPageMetadata.ts | 3 + 22 files changed, 110 insertions(+), 145 deletions(-) diff --git a/dist/modules/content/searchContent.js b/dist/modules/content/searchContent.js index f2b8e70..600ea66 100644 --- a/dist/modules/content/searchContent.js +++ b/dist/modules/content/searchContent.js @@ -47,7 +47,7 @@ import { buildLocalizedPath, getDefaultLocale, isValidLocale } from '../i18n/ind if (doc._status && doc._status !== 'published') { continue; } - if (doc.meta?.noindex) { + if (doc.noindex || doc.meta?.noindex) { continue; } const title = typeof doc.title === 'string' ? doc.title : undefined; diff --git a/dist/modules/content/searchContent.js.map b/dist/modules/content/searchContent.js.map index 1584e29..fb12eb1 100644 --- a/dist/modules/content/searchContent.js.map +++ b/dist/modules/content/searchContent.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/content/searchContent.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { buildLocalizedPath, getDefaultLocale, isValidLocale } from '../i18n/index.js'\n\nexport type SearchResult = {\n description?: string\n slug: string\n title: string\n /** Locale-aware path, prefixed with baseUrl when given. */\n url: string\n}\n\ntype SearchContentArgs = {\n /** Absolute origin to prefix URLs with. Omit for relative paths. */\n baseUrl?: string\n /** Pages collection. Default 'pages'. */\n collection?: string\n config: I18nConfig\n /** Home slug map/string so the home result collapses to root. */\n homeSlug?: Record | string\n /** Max results. Default 10, clamped 1–50. */\n limit?: number\n /** Locale to search/return. Defaults to config.defaultLocale; invalid → default. */\n locale?: string\n payload: BasePayload\n /** Keywords. */\n query: string\n /**\n * Field holding a richer AI summary (see buildSummaryField). When set and\n * present on a doc, it's preferred over meta.description for the result's\n * description.\n */\n summaryField?: string\n}\n\ntype PageRow = {\n [key: string]: unknown\n _status?: string\n id: number | string\n meta?: { description?: unknown; noindex?: boolean } | null\n slug?: unknown\n title?: unknown\n}\n\n/**\n * Shared content search: title / meta-description keyword match over a\n * collection, returning structured results (published, non-noindex only). One\n * implementation behind BOTH the JSON search route (createSearchRoute) and the\n * MCP server's search_content tool — so site search, API and AI all rank the\n * same way.\n *\n * Degrades to [] (never throws) when the collection's fields aren't queryable —\n * same guard class as the drafts/_status lesson.\n */\nexport async function searchContent({\n baseUrl,\n collection = 'pages',\n config,\n homeSlug,\n limit = 10,\n locale,\n payload,\n query,\n summaryField,\n}: SearchContentArgs): Promise {\n const q = query.trim()\n if (!q) {return []}\n\n const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config)\n const max = Math.min(Math.max(Math.trunc(limit) || 10, 1), 50)\n const origin = baseUrl?.replace(/\\/$/, '') ?? ''\n\n let docs: PageRow[] = []\n try {\n const res = await payload.find({\n collection: collection as never,\n depth: 0,\n limit: max * 3, // over-fetch; drafts/noindex filtered in memory\n locale: loc as never,\n where: {\n or: [{ title: { like: q } }, { 'meta.description': { like: q } }],\n } as never,\n })\n docs = (res?.docs ?? []) as PageRow[]\n } catch {\n return []\n }\n\n const results: SearchResult[] = []\n for (const doc of docs) {\n if (doc._status && doc._status !== 'published') {continue}\n if (doc.meta?.noindex) {continue}\n const title = typeof doc.title === 'string' ? doc.title : undefined\n const slug = typeof doc.slug === 'string' ? doc.slug : undefined\n if (!title || !slug) {continue}\n const path = buildLocalizedPath({ config, homeSlug, locale: loc, slugs: { [loc]: slug } })\n // Prefer the richer AI summary when configured and present, else meta.description.\n const summary =\n summaryField && typeof doc[summaryField] === 'string'\n ? (doc[summaryField])\n : undefined\n const description =\n summary?.trim() ||\n (typeof doc.meta?.description === 'string' ? doc.meta.description : undefined)\n results.push({\n slug,\n title,\n url: `${origin}${path ?? `/${slug}`}`,\n ...(description ? { description } : {}),\n })\n if (results.length >= max) {break}\n }\n\n return results\n}\n"],"names":["buildLocalizedPath","getDefaultLocale","isValidLocale","searchContent","baseUrl","collection","config","homeSlug","limit","locale","payload","query","summaryField","q","trim","loc","max","Math","min","trunc","origin","replace","docs","res","find","depth","where","or","title","like","results","doc","_status","meta","noindex","undefined","slug","path","slugs","summary","description","push","url","length"],"mappings":"AAIA,SAASA,kBAAkB,EAAEC,gBAAgB,EAAEC,aAAa,QAAQ,mBAAkB;AA0CtF;;;;;;;;;CASC,GACD,OAAO,eAAeC,cAAc,EAClCC,OAAO,EACPC,aAAa,OAAO,EACpBC,MAAM,EACNC,QAAQ,EACRC,QAAQ,EAAE,EACVC,MAAM,EACNC,OAAO,EACPC,KAAK,EACLC,YAAY,EACM;IAClB,MAAMC,IAAIF,MAAMG,IAAI;IACpB,IAAI,CAACD,GAAG;QAAC,OAAO,EAAE;IAAA;IAElB,MAAME,MAAMN,UAAUP,cAAcO,QAAQH,UAAUG,SAASR,iBAAiBK;IAChF,MAAMU,MAAMC,KAAKC,GAAG,CAACD,KAAKD,GAAG,CAACC,KAAKE,KAAK,CAACX,UAAU,IAAI,IAAI;IAC3D,MA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EAAED,MAAM,EAAE;YACrC,GAAII,cAAc;gBAAEA;YAAY,IAAI,CAAC,CAAC;QACxC;QACA,IAAIV,QAAQa,MAAM,IAAI3B,KAAK;YAAC;QAAK;IACnC;IAEA,OAAOc;AACT"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/content/searchContent.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { buildLocalizedPath, getDefaultLocale, isValidLocale } from '../i18n/index.js'\n\nexport type SearchResult = {\n description?: string\n slug: string\n title: string\n /** Locale-aware path, prefixed with baseUrl when given. */\n url: string\n}\n\ntype SearchContentArgs = {\n /** Absolute origin to prefix URLs with. Omit for relative paths. */\n baseUrl?: string\n /** Pages collection. Default 'pages'. */\n collection?: string\n config: I18nConfig\n /** Home slug map/string so the home result collapses to root. */\n homeSlug?: Record | string\n /** Max results. Default 10, clamped 1–50. */\n limit?: number\n /** Locale to search/return. Defaults to config.defaultLocale; invalid → default. */\n locale?: string\n payload: BasePayload\n /** Keywords. */\n query: string\n /**\n * Field holding a richer AI summary (see buildSummaryField). When set and\n * present on a doc, it's preferred over meta.description for the result's\n * description.\n */\n summaryField?: string\n}\n\ntype PageRow = {\n [key: string]: unknown\n _status?: string\n id: number | string\n meta?: { description?: unknown; noindex?: boolean } | null\n noindex?: boolean | null\n slug?: unknown\n title?: unknown\n}\n\n/**\n * Shared content search: title / meta-description keyword match over a\n * collection, returning structured results (published, non-noindex only). One\n * implementation behind BOTH the JSON search route (createSearchRoute) and the\n * MCP server's search_content tool — so site search, API and AI all rank the\n * same way.\n *\n * Degrades to [] (never throws) when the collection's fields aren't queryable —\n * same guard class as the drafts/_status lesson.\n */\nexport async function searchContent({\n baseUrl,\n collection = 'pages',\n config,\n homeSlug,\n limit = 10,\n locale,\n payload,\n query,\n summaryField,\n}: SearchContentArgs): Promise {\n const q = query.trim()\n if (!q) {return []}\n\n const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config)\n const max = Math.min(Math.max(Math.trunc(limit) || 10, 1), 50)\n const origin = baseUrl?.replace(/\\/$/, '') ?? ''\n\n let docs: PageRow[] = []\n try {\n const res = await payload.find({\n collection: collection as never,\n depth: 0,\n limit: max * 3, // over-fetch; drafts/noindex filtered in memory\n locale: loc as never,\n where: {\n or: [{ title: { like: q } }, { 'meta.description': { like: q } }],\n } as never,\n })\n docs = (res?.docs ?? []) as PageRow[]\n } catch {\n return []\n }\n\n const results: SearchResult[] = []\n for (const doc of docs) {\n if (doc._status && doc._status !== 'published') {continue}\n if (doc.noindex || doc.meta?.noindex) {continue}\n const title = typeof doc.title === 'string' ? doc.title : undefined\n const slug = typeof doc.slug === 'string' ? doc.slug : undefined\n if (!title || !slug) {continue}\n const path = buildLocalizedPath({ config, homeSlug, locale: loc, slugs: { [loc]: slug } })\n // Prefer the richer AI summary when configured and present, else meta.description.\n const summary =\n summaryField && typeof doc[summaryField] === 'string'\n ? (doc[summaryField])\n : undefined\n const description =\n summary?.trim() ||\n (typeof doc.meta?.description === 'string' ? doc.meta.description : undefined)\n results.push({\n slug,\n title,\n url: `${origin}${path ?? `/${slug}`}`,\n ...(description ? { description } : {}),\n })\n if (results.length >= max) {break}\n }\n\n return results\n}\n"],"names":["buildLocalizedPath","getDefaultLocale","isValidLocale","searchContent","baseUrl","collection","config","homeSlug","limit","locale","payload","query","summaryField","q","trim","loc","max","Math","min","trunc","origin","replace","docs","res","find","depth","where","or","title","like","results","doc","_status","noindex","meta","undefined","slug","path","slugs","summary","description","push","url","length"],"mappings":"AAIA,SAASA,kBAAkB,EAAEC,gBAAgB,EAAEC,aAAa,QAAQ,mBAAkB;AA2CtF;;;;;;;;;CASC,GACD,OAAO,eAAeC,cAAc,EAClCC,OAAO,EACPC,aAAa,OAAO,EACpBC,MAAM,EACNC,QAAQ,EACRC,QAAQ,EAAE,EACVC,MAAM,EACNC,OAAO,EACPC,KAAK,EACLC,YAAY,EACM;IAClB,MAAMC,IAAIF,MAAMG,IAAI;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B,GAAG,CAACnB,aAAa,GAClBuB;QACN,MAAMK,cACJD,SAASzB,UACR,CAAA,OAAOiB,IAAIG,IAAI,EAAEM,gBAAgB,WAAWT,IAAIG,IAAI,CAACM,WAAW,GAAGL,SAAQ;QAC9EL,QAAQW,IAAI,CAAC;YACXL;YACAR;YACAc,KAAK,GAAGtB,SAASiB,QAAQ,CAAC,CAAC,EAAED,MAAM,EAAE;YACrC,GAAII,cAAc;gBAAEA;YAAY,IAAI,CAAC,CAAC;QACxC;QACA,IAAIV,QAAQa,MAAM,IAAI3B,KAAK;YAAC;QAAK;IACnC;IAEA,OAAOc;AACT"} \ No newline at end of file diff --git a/dist/modules/seo/buildLlmsTxt.js b/dist/modules/seo/buildLlmsTxt.js index 911c41f..224c75a 100644 --- a/dist/modules/seo/buildLlmsTxt.js +++ b/dist/modules/seo/buildLlmsTxt.js @@ -70,7 +70,7 @@ import { buildLocalizedPath } from '../i18n/index.js'; if (raw._status && raw._status !== 'published') { continue; } - if (raw.meta?.noindex) { + if (raw.noindex || raw.meta?.noindex) { continue; } const title = typeof raw.title === 'string' ? raw.title : undefined; @@ -111,7 +111,7 @@ import { buildLocalizedPath } from '../i18n/index.js'; if (raw._status && raw._status !== 'published') { continue; } - if (raw.meta?.noindex) { + if (raw.noindex || raw.meta?.noindex) { continue; } const title = typeof raw.title === 'string' ? raw.title : undefined; diff --git a/dist/modules/seo/buildLlmsTxt.js.map b/dist/modules/seo/buildLlmsTxt.js.map index fa52cc1..5367869 100644 --- a/dist/modules/seo/buildLlmsTxt.js.map +++ b/dist/modules/seo/buildLlmsTxt.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/seo/buildLlmsTxt.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { blocksToMarkdown } from '../content/blocksToMarkdown.js'\nimport { buildLocalizedPath } from '../i18n/index.js'\n\ntype BuildLlmsTxtArgs = {\n /** Absolute site URL (https://…). */\n baseUrl: string\n config: I18nConfig\n /**\n * Full-content mode (llms-full.txt). When true, each page's full body is\n * inlined as Markdown (via blocksToMarkdown) under its heading, so an agent\n * gets the whole site in one request — the llmstxt.org \"llms-full.txt\"\n * convention. Default false = the compact index (links + descriptions).\n */\n full?: boolean\n /** Field holding the block layout (full mode only). Default 'layout'. */\n layoutField?: string\n /** Locale for names/descriptions. Defaults to config.defaultLocale. */\n locale?: string\n /** Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n payload: BasePayload\n /** Site settings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n /**\n * Field holding a richer AI summary (buildSummaryField). When set and present,\n * it's used as the page description instead of meta.description.\n */\n summaryField?: string\n}\n\ntype SettingsShape = {\n siteDescription?: null | string\n siteName?: null | string\n}\n\ntype PageRow = {\n [key: string]: unknown\n _status?: string\n id: number | string\n meta?: { description?: unknown; noindex?: boolean } | null\n slug?: unknown\n title?: unknown\n}\n\n/**\n * Builds the body of /llms.txt — a Markdown file describing the site for AI\n * agents / LLM crawlers, per the llmstxt.org convention. Mirrors buildRobots /\n * buildSitemapEntries: the plugin already knows the site's name, description,\n * and pages, so it can generate this automatically.\n *\n * Structure (llmstxt.org): H1 site name, a blockquote/summary, then a list of\n * key pages as Markdown links with short descriptions. Agents read this to\n * understand the site quickly without crawling everything.\n *\n * Wire it as a route that returns text/plain:\n *\n * // app/llms.txt/route.ts\n * import { buildLlmsTxt } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * export async function GET() {\n * const body = await buildLlmsTxt({\n * payload: await getCachedPayload(),\n * config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!,\n * })\n * return new Response(body, { headers: { 'Content-Type': 'text/plain; charset=utf-8' } })\n * }\n *\n * Data comes from the panel (siteName, siteDescription, pages) — nothing\n * hardcoded. Skips drafts and noindex pages (same as the sitemap).\n */\nexport async function buildLlmsTxt({\n baseUrl,\n config,\n full = false,\n layoutField = 'layout',\n locale,\n pagesSlug = 'pages',\n payload,\n settingsSlug = 'site-settings',\n summaryField,\n}: BuildLlmsTxtArgs): Promise {\n const pickDescription = (raw: PageRow): string | undefined => {\n if (\n summaryField &&\n typeof raw[summaryField] === 'string' &&\n (raw[summaryField]).trim()\n ) {\n return (raw[summaryField]).trim()\n }\n return typeof raw.meta?.description === 'string' ? raw.meta.description : undefined\n }\n const loc = locale ?? config.defaultLocale\n const origin = baseUrl.replace(/\\/$/, '')\n\n const settings = (await payload.findGlobal({\n slug: settingsSlug as never,\n depth: 0,\n locale: loc as never,\n })) as SettingsShape\n\n const name = settings.siteName?.trim() || 'Website'\n const description = settings.siteDescription?.trim()\n\n // NO where:{_status} filter — collections without drafts enabled don't\n // register the _status field, and querying it throws\n // \"path cannot be queried: _status\" (a real bug report). Draft filtering\n // happens in memory below, which is safe for every collection. Same as\n // buildSitemapEntries and generateStaticParams.\n // Full mode needs depth:1 so block images/relations populate for the Markdown.\n const result = await payload.find({\n collection: pagesSlug as never,\n depth: full ? 1 : 0,\n limit: 1000,\n locale: loc as never,\n })\n\n const lines: string[] = [`# ${name}`, '']\n if (description) {\n lines.push(`> ${description}`, '')\n }\n\n if (full) {\n // Full-content: each published page inlined as Markdown under its heading.\n const sections: string[] = []\n for (const raw of result.docs as PageRow[]) {\n if (raw._status && raw._status !== 'published') {continue}\n if (raw.meta?.noindex) {continue}\n\n const title = typeof raw.title === 'string' ? raw.title : undefined\n const slug = typeof raw.slug === 'string' ? raw.slug : undefined\n if (!title || !slug) {continue}\n\n const path = buildLocalizedPath({ config, locale: loc, slugs: { [loc]: slug } })\n const body = blocksToMarkdown(raw[layoutField])\n const desc = pickDescription(raw)\n const parts = [`## ${title}`]\n if (path) {parts.push(`${origin}${path}`)}\n if (desc) {parts.push(`_${desc}_`)}\n if (body) {parts.push(body)}\n sections.push(parts.join('\\n\\n'))\n }\n if (sections.length > 0) {lines.push(sections.join('\\n\\n---\\n\\n'), '')}\n return lines.join('\\n')\n }\n\n const pageLinks: string[] = []\n for (const raw of result.docs as PageRow[]) {\n if (raw._status && raw._status !== 'published') {continue}\n if (raw.meta?.noindex) {continue}\n\n const title = typeof raw.title === 'string' ? raw.title : undefined\n const slug = typeof raw.slug === 'string' ? raw.slug : undefined\n if (!title || !slug) {continue}\n\n const path = buildLocalizedPath({ config, locale: loc, slugs: { [loc]: slug } })\n if (!path) {continue}\n\n const desc = pickDescription(raw)\n const pageDesc = desc ? ` — ${desc}` : ''\n pageLinks.push(`- [${title}](${origin}${path})${pageDesc}`)\n }\n\n if (pageLinks.length > 0) {\n lines.push('## Strony', '', ...pageLinks, '')\n }\n\n return lines.join('\\n')\n}\n"],"names":["blocksToMarkdown","buildLocalizedPath","buildLlmsTxt","baseUrl","config","full","layoutField","locale","pagesSlug","payload","settingsSlug","summaryField","pickDescription","raw","trim","meta","description","undefined","loc","defaultLocale","origin","replace","settings","findGlobal","slug","depth","name","siteName","siteDescription","result","find","collection","limit","lines","push","sections","docs","_status","noindex","title","path","slugs","body","desc","parts","join","length","pageLinks","pageDesc"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,iCAAgC;AACjE,SAASC,kBAAkB,QAAQ,mBAAkB;AA2CrD;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GACD,OAAO,eAAeC,aAAa,EACjCC,OAAO,EACPC,MAAM,EACNC,OAAO,KAAK,EACZC,cAAc,QAAQ,EACtBC,MAAM,EACNC,YAAY,OAAO,EACnBC,OAAO,EACPC,eAAe,eAAe,EAC9BC,YAAY,EACK;IACjB,MAAMC,kBAAkB,CAACC;QACvB,IACEF,gBACA,OAAOE,GAAG,CAACF,aAAa,KAAK,YAC7B,AAACE,GAAG,CAACF,aAAa,CAAEG,IAAI,IACxB;YACA,OAAO,AAACD,GAAG,CAACF,aAAa,CAAEG,IAAI;QACjC;QACA,OAAO,OAAOD,IAAIE,IAAI,EAAEC,gBAAgB,WAAWH,IAAIE,IA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AAG,EAAEK,MAAM,EAAE,EAAEnB,SAASoB,KAAK,CAAC,EAAEQ,UAAU;IAC5D;IAEA,IAAID,UAAUD,MAAM,GAAG,GAAG;QACxBb,MAAMC,IAAI,CAAC,aAAa,OAAOa,WAAW;IAC5C;IAEA,OAAOd,MAAMY,IAAI,CAAC;AACpB"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/seo/buildLlmsTxt.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { blocksToMarkdown } from '../content/blocksToMarkdown.js'\nimport { buildLocalizedPath } from '../i18n/index.js'\n\ntype BuildLlmsTxtArgs = {\n /** Absolute site URL (https://…). */\n baseUrl: string\n config: I18nConfig\n /**\n * Full-content mode (llms-full.txt). When true, each page's full body is\n * inlined as Markdown (via blocksToMarkdown) under its heading, so an agent\n * gets the whole site in one request — the llmstxt.org \"llms-full.txt\"\n * convention. Default false = the compact index (links + descriptions).\n */\n full?: boolean\n /** Field holding the block layout (full mode only). Default 'layout'. */\n layoutField?: string\n /** Locale for names/descriptions. Defaults to config.defaultLocale. */\n locale?: string\n /** Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n payload: BasePayload\n /** Site settings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n /**\n * Field holding a richer AI summary (buildSummaryField). When set and present,\n * it's used as the page description instead of meta.description.\n */\n summaryField?: string\n}\n\ntype SettingsShape = {\n siteDescription?: null | string\n siteName?: null | string\n}\n\ntype PageRow = {\n [key: string]: unknown\n _status?: string\n id: number | string\n meta?: { description?: unknown; noindex?: boolean } | null\n noindex?: boolean | null\n slug?: unknown\n title?: unknown\n}\n\n/**\n * Builds the body of /llms.txt — a Markdown file describing the site for AI\n * agents / LLM crawlers, per the llmstxt.org convention. Mirrors buildRobots /\n * buildSitemapEntries: the plugin already knows the site's name, description,\n * and pages, so it can generate this automatically.\n *\n * Structure (llmstxt.org): H1 site name, a blockquote/summary, then a list of\n * key pages as Markdown links with short descriptions. Agents read this to\n * understand the site quickly without crawling everything.\n *\n * Wire it as a route that returns text/plain:\n *\n * // app/llms.txt/route.ts\n * import { buildLlmsTxt } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * export async function GET() {\n * const body = await buildLlmsTxt({\n * payload: await getCachedPayload(),\n * config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!,\n * })\n * return new Response(body, { headers: { 'Content-Type': 'text/plain; charset=utf-8' } })\n * }\n *\n * Data comes from the panel (siteName, siteDescription, pages) — nothing\n * hardcoded. Skips drafts and noindex pages (same as the sitemap).\n */\nexport async function buildLlmsTxt({\n baseUrl,\n config,\n full = false,\n layoutField = 'layout',\n locale,\n pagesSlug = 'pages',\n payload,\n settingsSlug = 'site-settings',\n summaryField,\n}: BuildLlmsTxtArgs): Promise {\n const pickDescription = (raw: PageRow): string | undefined => {\n if (\n summaryField &&\n typeof raw[summaryField] === 'string' &&\n (raw[summaryField]).trim()\n ) {\n return (raw[summaryField]).trim()\n }\n return typeof raw.meta?.description === 'string' ? raw.meta.description : undefined\n }\n const loc = locale ?? config.defaultLocale\n const origin = baseUrl.replace(/\\/$/, '')\n\n const settings = (await payload.findGlobal({\n slug: settingsSlug as never,\n depth: 0,\n locale: loc as never,\n })) as SettingsShape\n\n const name = settings.siteName?.trim() || 'Website'\n const description = settings.siteDescription?.trim()\n\n // NO where:{_status} filter — collections without drafts enabled don't\n // register the _status field, and querying it throws\n // \"path cannot be queried: _status\" (a real bug report). Draft filtering\n // happens in memory below, which is safe for every collection. Same as\n // buildSitemapEntries and generateStaticParams.\n // Full mode needs depth:1 so block images/relations populate for the Markdown.\n const result = await payload.find({\n collection: pagesSlug as never,\n depth: full ? 1 : 0,\n limit: 1000,\n locale: loc as never,\n })\n\n const lines: string[] = [`# ${name}`, '']\n if (description) {\n lines.push(`> ${description}`, '')\n }\n\n if (full) {\n // Full-content: each published page inlined as Markdown under its heading.\n const sections: string[] = []\n for (const raw of result.docs as PageRow[]) {\n if (raw._status && raw._status !== 'published') {continue}\n if (raw.noindex || raw.meta?.noindex) {continue}\n\n const title = typeof raw.title === 'string' ? raw.title : undefined\n const slug = typeof raw.slug === 'string' ? raw.slug : undefined\n if (!title || !slug) {continue}\n\n const path = buildLocalizedPath({ config, locale: loc, slugs: { [loc]: slug } })\n const body = blocksToMarkdown(raw[layoutField])\n const desc = pickDescription(raw)\n const parts = [`## ${title}`]\n if (path) {parts.push(`${origin}${path}`)}\n if (desc) {parts.push(`_${desc}_`)}\n if (body) {parts.push(body)}\n sections.push(parts.join('\\n\\n'))\n }\n if (sections.length > 0) {lines.push(sections.join('\\n\\n---\\n\\n'), '')}\n return lines.join('\\n')\n }\n\n const pageLinks: string[] = []\n for (const raw of result.docs as PageRow[]) {\n if (raw._status && raw._status !== 'published') {continue}\n if (raw.noindex || raw.meta?.noindex) {continue}\n\n const title = typeof raw.title === 'string' ? raw.title : undefined\n const slug = typeof raw.slug === 'string' ? raw.slug : undefined\n if (!title || !slug) {continue}\n\n const path = buildLocalizedPath({ config, locale: loc, slugs: { [loc]: slug } })\n if (!path) {continue}\n\n const desc = pickDescription(raw)\n const pageDesc = desc ? ` — ${desc}` : ''\n pageLinks.push(`- [${title}](${origin}${path})${pageDesc}`)\n }\n\n if (pageLinks.length > 0) {\n lines.push('## Strony', '', ...pageLinks, '')\n }\n\n return lines.join('\\n')\n}\n"],"names":["blocksToMarkdown","buildLocalizedPath","buildLlmsTxt","baseUrl","config","full","layoutField","locale","pagesSlug","payload","settingsSlug","summaryField","pickDescription","raw","trim","meta","description","undefined","loc","defaultLocale","origin","replace","settings","findGlobal","slug","depth","name","siteName","siteDescription","result","find","collection","limit","lines","push","sections","docs","_status","noindex","title","path","slugs","body","desc","parts","join","length","pageLinks","pageDesc"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,iCAAgC;AACjE,SAASC,kBAAkB,QAA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AIE,IAAI,EAAEuB,SAAS;YAAC;QAAQ;QAE/C,MAAMC,QAAQ,OAAO1B,IAAI0B,KAAK,KAAK,WAAW1B,IAAI0B,KAAK,GAAGtB;QAC1D,MAAMO,OAAO,OAAOX,IAAIW,IAAI,KAAK,WAAWX,IAAIW,IAAI,GAAGP;QACvD,IAAI,CAACsB,SAAS,CAACf,MAAM;YAAC;QAAQ;QAE9B,MAAMgB,OAAOvC,mBAAmB;YAAEG;YAAQG,QAAQW;YAAKuB,OAAO;gBAAE,CAACvB,IAAI,EAAEM;YAAK;QAAE;QAC9E,IAAI,CAACgB,MAAM;YAAC;QAAQ;QAEpB,MAAMG,OAAO/B,gBAAgBC;QAC7B,MAAMmC,WAAWL,OAAO,CAAC,GAAG,EAAEA,MAAM,GAAG;QACvCI,UAAUb,IAAI,CAAC,CAAC,GAAG,EAAEK,MAAM,EAAE,EAAEnB,SAASoB,KAAK,CAAC,EAAEQ,UAAU;IAC5D;IAEA,IAAID,UAAUD,MAAM,GAAG,GAAG;QACxBb,MAAMC,IAAI,CAAC,aAAa,OAAOa,WAAW;IAC5C;IAEA,OAAOd,MAAMY,IAAI,CAAC;AACpB"} \ No newline at end of file diff --git a/dist/modules/seo/buildMetadata.d.ts b/dist/modules/seo/buildMetadata.d.ts index dc45277..c218983 100644 --- a/dist/modules/seo/buildMetadata.d.ts +++ b/dist/modules/seo/buildMetadata.d.ts @@ -53,6 +53,13 @@ type BuildMetadataArgs = { 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; /** @@ -98,5 +105,5 @@ type BuildMetadataArgs = { * pieces (meta group, site name, image URL, localized slugs) and passes them * in — the plugin composes, it doesn't fetch. */ -export declare function buildMetadata({ baseUrl, config, homeSlug, imageUrl, locale, meta, order, pageTitle, prefix, query, separator, siteDescription, siteName, slugs, }: BuildMetadataArgs): PageMetadata; +export declare function buildMetadata({ baseUrl, config, homeSlug, imageUrl, locale, meta, noindex, order, pageTitle, prefix, query, separator, siteDescription, siteName, slugs, }: BuildMetadataArgs): PageMetadata; export {}; diff --git a/dist/modules/seo/buildMetadata.js b/dist/modules/seo/buildMetadata.js index 7738aba..1e0630a 100644 --- a/dist/modules/seo/buildMetadata.js +++ b/dist/modules/seo/buildMetadata.js @@ -9,7 +9,7 @@ import { buildHreflangAlternates } from './hreflang.js'; * 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, pageTitle, prefix, query, separator, siteDescription, siteName, slugs }) { + */ export function buildMetadata({ baseUrl, config, homeSlug = 'home', imageUrl, locale, meta, noindex, order, pageTitle, prefix, query, separator, siteDescription, siteName, slugs }) { // 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') @@ -83,7 +83,7 @@ import { buildHreflangAlternates } from './hreflang.js'; // 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). - ...meta?.noindex ? { + ...noindex || meta?.noindex ? { robots: { follow: true, index: false diff --git a/dist/modules/seo/buildMetadata.js.map b/dist/modules/seo/buildMetadata.js.map index 8c24baa..197e183 100644 --- a/dist/modules/seo/buildMetadata.js.map +++ b/dist/modules/seo/buildMetadata.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/seo/buildMetadata.ts"],"sourcesContent":["import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js'\nimport type { TitleOrder } from './composeTitle.js'\nimport type { SeoMeta } from './types.js'\n\nimport { buildLocalizedPath } from '../i18n/index.js'\nimport { composeTitle } from './composeTitle.js'\nimport { buildHreflangAlternates } from './hreflang.js'\n\n/**\n * Subset of Next.js `Metadata` this helper produces. Kept local so the plugin\n * doesn't depend on `next` types; the shape is assignable to Next's Metadata.\n */\nexport type PageMetadata = {\n alternates?: {\n canonical?: string\n languages?: Record\n }\n description?: string\n openGraph?: {\n description?: string\n images?: { url: string }[]\n locale?: string\n /** Site/brand name for the OG card. */\n siteName?: string\n title: string\n /** 'website' | 'article' etc. Defaults to 'website'. */\n type?: string\n /** Canonical URL of this page. */\n url?: string\n }\n /**\n * robots directives. Indexed pages get generous snippet/preview limits by\n * default (Google shows richer results); noindex pages get index:false.\n */\n robots?: {\n follow: boolean\n index: boolean\n /** 'none' | 'standard' | 'large' — image preview size in results. */\n 'max-image-preview'?: 'large' | 'none' | 'standard'\n /** Max text snippet length; -1 = no limit. Next maps to max-snippet. */\n 'max-snippet'?: number\n /** Max video preview seconds; -1 = no limit. */\n 'max-video-preview'?: number\n }\n title: string\n}\n\ntype BuildMetadataArgs = {\n /** Absolute site origin, e.g. 'https://example.com'. */\n baseUrl?: string\n config: I18nConfig\n /** Home slug that collapses to the locale root. Defaults to 'home'. */\n homeSlug?: Record | string\n /** Resolved OG image URL (page image or site defaultShareImage). */\n imageUrl?: null | string\n /** Current locale being rendered. */\n locale: string\n /** SEO meta from the document (plugin-seo group). */\n meta?: null | SeoMeta\n /** Page title or site name first. Defaults to 'page-first'. */\n order?: TitleOrder\n /**\n * The document's own title (e.g. page.title = 'Sprzątanie biur'). Used as the\n * page-title source when meta.title is empty — the browser tab and search\n * result should show the page name, not go blank, when an editor didn't fill\n * the SEO title. Priority: titleOverride > meta.title > pageTitle.\n */\n pageTitle?: null | string\n /**\n * Localized segment the document lives under (an archive page's slugs).\n * Feeds both canonical and hreflang, so /pl/artykuly/moj-post and\n * /en/articles/my-post point at each other correctly.\n */\n prefix?: LocalizedSlugs\n /**\n * Query string appended to canonical and every hreflang, e.g. '?page=2'.\n *\n * A paginated listing must be canonical to itself — pointing page 2 at page 1\n * tells Google the entries on it don't exist. Alternates carry the same page,\n * since /pl/artykuly?page=2 corresponds to /en/articles?page=2.\n */\n query?: string\n /** Separator between page title and site name. Defaults to ' | '. */\n separator?: string\n /**\n * Global fallback description (from SiteSettings.siteDescription). Used when a\n * page has no meta.description — better than emitting no description at all\n * (Google would then scrape random on-page text for the snippet).\n */\n siteDescription?: null | string\n /** Site name for title composition and OG. */\n siteName?: null | string\n /** slug per locale for this document — drives canonical + hreflang. */\n slugs: LocalizedSlugs\n}\n\n/**\n * Assembles a Next.js-compatible Metadata object from document SEO fields and\n * site-level data. Locale-aware: canonical points at the current locale's\n * path, and hreflang alternates cover every locale the document exists in.\n *\n * Designed for use inside Next.js `generateMetadata`. The caller resolves the\n * pieces (meta group, site name, image URL, localized slugs) and passes them\n * in — the plugin composes, it doesn't fetch.\n */\nexport function buildMetadata({\n baseUrl,\n config,\n homeSlug = 'home',\n imageUrl,\n locale,\n meta,\n order,\n pageTitle,\n prefix,\n query,\n separator,\n siteDescription,\n siteName,\n slugs,\n}: BuildMetadataArgs): PageMetadata {\n // Title source priority: titleOverride (exact, wins outright) > meta.title\n // (SEO title an editor set) > pageTitle (the document's own name). This means\n // a page with no SEO title still shows its name (e.g. 'Sprzątanie biur')\n // composed with the site name, instead of just the site name or a blank.\n const override = meta?.titleOverride?.trim()\n const resolvedPageTitle = meta?.title?.trim() || pageTitle?.trim() || undefined\n const title =\n override || composeTitle({ order, pageTitle: resolvedPageTitle, separator, siteName })\n const description = meta?.description?.trim() || siteDescription?.trim() || undefined\n const origin = baseUrl?.replace(/\\/$/, '') ?? ''\n\n const suffix = query ?? ''\n\n const currentPath = buildLocalizedPath({ config, homeSlug, locale, prefix, slugs })\n const canonical = currentPath ? `${origin}${currentPath}${suffix}` : undefined\n\n const languages = buildHreflangAlternates({ baseUrl, config, homeSlug, prefix, slugs })\n if (suffix) {\n for (const code of Object.keys(languages)) {\n languages[code] = `${languages[code]}${suffix}`\n }\n }\n\n const images = imageUrl ? [{ url: imageUrl }] : undefined\n\n return {\n title,\n ...(description && { description }),\n alternates: {\n ...(canonical && { canonical }),\n ...(Object.keys(languages).length > 0 && { languages }),\n },\n openGraph: {\n title,\n ...(description && { description }),\n ...(images && { images }),\n type: 'website',\n locale,\n ...(siteName ? { siteName } : {}),\n ...(canonical ? { url: canonical } : {}),\n },\n // robots: noindex pages are excluded (follow keeps link authority). Indexed\n // pages get generous snippet/preview limits so Google can show rich results\n // (long snippets, large image previews, full video previews).\n ...(meta?.noindex\n ? { robots: { follow: true, index: false } }\n : {\n robots: {\n follow: true,\n index: true,\n 'max-image-preview': 'large' as const,\n 'max-snippet': -1,\n 'max-video-preview': -1,\n },\n }),\n }\n}\n"],"names":["buildLocalizedPath","composeTitle","buildHreflangAlternates","buildMetadata","baseUrl","config","homeSlug","imageUrl","locale","meta","order","pageTitle","prefix","query","separator","siteDescription","siteName","slugs","override","titleOverride","trim","resolvedPageTitle","title","undefined","description","origin","replace","suffix","currentPath","canonical","languages","code","Object","keys","images","url","alternates","length","openGraph","type","noindex","robots","follow","index"],"mappings":"AAIA,SAASA,kBAAkB,QAAQ,mBAAkB;AACrD,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,uBAAuB,QAAQ,gBAAe;AA0FvD;;;;;;;;CAQC,GACD,OAAO,SAASC,cAAc,EAC5BC,OAAO,EACPC,MAAM,EACNC,WAAW,MAAM,EACjBC,QAAQ,EACRC,MAAM,EACNC,IAAI,EACJC,KAAK,EACLC,SAAS,EACTC,MAAM,EACNC,KAAK,EACLC,SAAS,EACTC,eAAe,EACfC,QAAQ,EACRC,KAAK,EACa;IAClB,2EAA2E;IAC3E,8EAA8E;IAC9E,yEAAyE;IACzE,yEAAyE;IACzE,MAAMC,WAAWT,MAAMU,eAAeC;IACtC,MAAMC,oBAAoBZ,MAAMa,OAAOF,UAAUT,WAAWS,UAAUG;IACtE,MAAMD,QACJJ,YAAYjB,a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gBACrB,eAAe,CAAC;gBAChB,qBAAqB,CAAC;YACxB;QACF,CAAC;IACP;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/seo/buildMetadata.ts"],"sourcesContent":["import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js'\nimport type { TitleOrder } from './composeTitle.js'\nimport type { SeoMeta } from './types.js'\n\nimport { buildLocalizedPath } from '../i18n/index.js'\nimport { composeTitle } from './composeTitle.js'\nimport { buildHreflangAlternates } from './hreflang.js'\n\n/**\n * Subset of Next.js `Metadata` this helper produces. Kept local so the plugin\n * doesn't depend on `next` types; the shape is assignable to Next's Metadata.\n */\nexport type PageMetadata = {\n alternates?: {\n canonical?: string\n languages?: Record\n }\n description?: string\n openGraph?: {\n description?: string\n images?: { url: string }[]\n locale?: string\n /** Site/brand name for the OG card. */\n siteName?: string\n title: string\n /** 'website' | 'article' etc. Defaults to 'website'. */\n type?: string\n /** Canonical URL of this page. */\n url?: string\n }\n /**\n * robots directives. Indexed pages get generous snippet/preview limits by\n * default (Google shows richer results); noindex pages get index:false.\n */\n robots?: {\n follow: boolean\n index: boolean\n /** 'none' | 'standard' | 'large' — image preview size in results. */\n 'max-image-preview'?: 'large' | 'none' | 'standard'\n /** Max text snippet length; -1 = no limit. Next maps to max-snippet. */\n 'max-snippet'?: number\n /** Max video preview seconds; -1 = no limit. */\n 'max-video-preview'?: number\n }\n title: string\n}\n\ntype BuildMetadataArgs = {\n /** Absolute site origin, e.g. 'https://example.com'. */\n baseUrl?: string\n config: I18nConfig\n /** Home slug that collapses to the locale root. Defaults to 'home'. */\n homeSlug?: Record | string\n /** Resolved OG image URL (page image or site defaultShareImage). */\n imageUrl?: null | string\n /** Current locale being rendered. */\n locale: string\n /** SEO meta from the document (plugin-seo group). */\n meta?: null | SeoMeta\n /**\n * Top-level noindex flag (buildNoindexField). Checked alongside meta.noindex:\n * plugin-seo's meta group doesn't declare noindex, so a mirror into\n * meta.noindex is stripped on save — the top-level field is the one that\n * persists. Either being true emits robots index:false.\n */\n noindex?: boolean | null\n /** Page title or site name first. Defaults to 'page-first'. */\n order?: TitleOrder\n /**\n * The document's own title (e.g. page.title = 'Sprzątanie biur'). Used as the\n * page-title source when meta.title is empty — the browser tab and search\n * result should show the page name, not go blank, when an editor didn't fill\n * the SEO title. Priority: titleOverride > meta.title > pageTitle.\n */\n pageTitle?: null | string\n /**\n * Localized segment the document lives under (an archive page's slugs).\n * Feeds both canonical and hreflang, so /pl/artykuly/moj-post and\n * /en/articles/my-post point at each other correctly.\n */\n prefix?: LocalizedSlugs\n /**\n * Query string appended to canonical and every hreflang, e.g. '?page=2'.\n *\n * A paginated listing must be canonical to itself — pointing page 2 at page 1\n * tells Google the entries on it don't exist. Alternates carry the same page,\n * since /pl/artykuly?page=2 corresponds to /en/articles?page=2.\n */\n query?: string\n /** Separator between page title and site name. Defaults to ' | '. */\n separator?: string\n /**\n * Global fallback description (from SiteSettings.siteDescription). Used when a\n * page has no meta.description — better than emitting no description at all\n * (Google would then scrape random on-page text for the snippet).\n */\n siteDescription?: null | string\n /** Site name for title composition and OG. */\n siteName?: null | string\n /** slug per locale for this document — drives canonical + hreflang. */\n slugs: LocalizedSlugs\n}\n\n/**\n * Assembles a Next.js-compatible Metadata object from document SEO fields and\n * site-level data. Locale-aware: canonical points at the current locale's\n * path, and hreflang alternates cover every locale the document exists in.\n *\n * Designed for use inside Next.js `generateMetadata`. The caller resolves the\n * pieces (meta group, site name, image URL, localized slugs) and passes them\n * in — the plugin composes, it doesn't fetch.\n */\nexport function buildMetadata({\n baseUrl,\n config,\n homeSlug = 'home',\n imageUrl,\n locale,\n meta,\n noindex,\n order,\n pageTitle,\n prefix,\n query,\n separator,\n siteDescription,\n siteName,\n slugs,\n}: BuildMetadataArgs): PageMetadata {\n // Title source priority: titleOverride (exact, wins outright) > meta.title\n // (SEO title an editor set) > pageTitle (the document's own name). This means\n // a page with no SEO title still shows its name (e.g. 'Sprzątanie biur')\n // composed with the site name, instead of just the site name or a blank.\n const override = meta?.titleOverride?.trim()\n const resolvedPageTitle = meta?.title?.trim() || pageTitle?.trim() || undefined\n const title =\n override || composeTitle({ order, pageTitle: resolvedPageTitle, separator, siteName })\n const description = meta?.description?.trim() || siteDescription?.trim() || undefined\n const origin = baseUrl?.replace(/\\/$/, '') ?? ''\n\n const suffix = query ?? ''\n\n const currentPath = buildLocalizedPath({ config, homeSlug, locale, prefix, slugs })\n const canonical = currentPath ? `${origin}${currentPath}${suffix}` : undefined\n\n const languages = buildHreflangAlternates({ baseUrl, config, homeSlug, prefix, slugs })\n if (suffix) {\n for (const code of Object.keys(languages)) {\n languages[code] = `${languages[code]}${suffix}`\n }\n }\n\n const images = imageUrl ? [{ url: imageUrl }] : undefined\n\n return {\n title,\n ...(description && { description }),\n alternates: {\n ...(canonical && { canonical }),\n ...(Object.keys(languages).length > 0 && { languages }),\n },\n openGraph: {\n title,\n ...(description && { description }),\n ...(images && { images }),\n type: 'website',\n locale,\n ...(siteName ? { siteName } : {}),\n ...(canonical ? { url: canonical } : {}),\n },\n // robots: noindex pages are excluded (follow keeps link authority). Indexed\n // pages get generous snippet/preview limits so Google can show rich results\n // (long snippets, large image previews, full video previews).\n ...(noindex || meta?.noindex\n ? { robots: { follow: true, index: false } }\n : {\n robots: {\n follow: true,\n index: true,\n 'max-image-preview': 'large' as const,\n 'max-snippet': -1,\n 'max-video-preview': -1,\n },\n }),\n }\n}\n"],"names":["buildLocalizedPath","composeTitle","buildHreflangAlternates","buildMetadata","baseUrl","config","homeSlug","imageUrl","locale","meta","noindex","order","pageTitle","prefix","query","separator","siteDescription","siteName","slugs","override","titleOverride","trim","resolvedPageTitle","title","undefined","description","origin","replace","suffix","currentPath","canonical","languages","code","Object","keys","images","url","alternates","length","openGraph","type","robots","follow","index"],"mappings":"AAIA,SAASA,kBAAkB,QAAQ,mBAAkB;AACrD,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,uBAAuB,QAAQ,gBAAe;AAiGvD;;;;;;;;CAQC,GACD,O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AAIE,eAAe;gBAAEA;YAAY,CAAC;YAClC,GAAIU,UAAU;gBAAEA;YAAO,CAAC;YACxBK,MAAM;YACNhC;YACA,GAAIS,WAAW;gBAAEA;YAAS,IAAI,CAAC,CAAC;YAChC,GAAIa,YAAY;gBAAEM,KAAKN;YAAU,IAAI,CAAC,CAAC;QACzC;QACA,4EAA4E;QAC5E,4EAA4E;QAC5E,8DAA8D;QAC9D,GAAIpB,WAAWD,MAAMC,UACjB;YAAE+B,QAAQ;gBAAEC,QAAQ;gBAAMC,OAAO;YAAM;QAAE,IACzC;YACEF,QAAQ;gBACNC,QAAQ;gBACRC,OAAO;gBACP,qBAAqB;gBACrB,eAAe,CAAC;gBAChB,qBAAqB,CAAC;YACxB;QACF,CAAC;IACP;AACF"} \ No newline at end of file diff --git a/dist/modules/seo/buildNoindexField.d.ts b/dist/modules/seo/buildNoindexField.d.ts index 5910f4f..af4e232 100644 --- a/dist/modules/seo/buildNoindexField.d.ts +++ b/dist/modules/seo/buildNoindexField.d.ts @@ -2,29 +2,26 @@ import type { CheckboxField, Field } from 'payload'; type BuildNoindexFieldArgs = { /** Help text under the checkbox. */ description?: string; - /** Sidebar label. Default 'Wyklucz z indeksowania (noindex)'. */ + /** Sidebar label. Default 'Exclude from indexing (noindex)'. */ label?: string; - /** - * Dotted path, inside the document, that the SEO read path (metadata + - * sitemap) consumes. Default 'meta.noindex' — the plugin-seo `meta` group. - * The checkbox value is mirrored here on every save, so editors toggle one - * friendly switch and the machinery reads a stable location. - */ - metaPath?: string; /** Field name for the editor-facing checkbox. Default 'noindex'. */ name?: string; /** Extend/override the generated checkbox (position, access, etc.). */ overrides?: Partial; }; /** - * A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the - * sitemap and metadata generators actually read). Replaces the hand-rolled - * checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …` - * glue copied into every project — no `any`, one source of truth for editors, - * one stable read location for the engine. + * A top-level sidebar `noindex` checkbox. When ticked, the page is excluded from + * `sitemap.xml`, `llms.txt`, site search, and gets `robots: noindex, follow` — + * ALL automatically, no per-project filtering. * - * Idempotent and order-independent: if either the checkbox OR an existing - * `meta.noindex` is set, the page ends up noindex; the two can't drift apart. + * Why top-level (not mirrored into `meta.noindex`): plugin-seo's `meta` group + * declares only title/description/image, so Payload silently strips any extra + * key (`meta.noindex`) during sanitization — an earlier version mirrored there + * and the value vanished, leaking noindex pages into the sitemap. The value now + * lives on this top-level field, which persists; every reader in the kit + * (buildSitemapEntries, buildMetadata/createPageMetadata, buildLlmsTxt, + * searchContent) checks `doc.noindex` (and still tolerates a legacy + * `meta.noindex`). One field, one source of truth, zero project glue. * * // collections/Pages.ts * import { buildNoindexField } from '@intecion/ipal-kit' diff --git a/dist/modules/seo/buildNoindexField.js b/dist/modules/seo/buildNoindexField.js index 69fb612..40a956a 100644 --- a/dist/modules/seo/buildNoindexField.js +++ b/dist/modules/seo/buildNoindexField.js @@ -1,49 +1,23 @@ -/** Read a dotted path (e.g. 'meta.noindex') off a loosely-typed object. */ function readPath(obj, path) { - let cur = obj; - for (const key of path){ - if (cur == null || typeof cur !== 'object') { - return undefined; - } - cur = cur[key]; - } - return cur; -} -/** Write a dotted path, creating intermediate objects as needed. */ function writePath(obj, path, value) { - let cur = obj; - for(let i = 0; i < path.length - 1; i++){ - const key = path[i]; - const next = cur[key]; - if (next == null || typeof next !== 'object') { - cur[key] = {}; - } - cur = cur[key]; - } - cur[path[path.length - 1]] = value; -} /** - * A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the - * sitemap and metadata generators actually read). Replaces the hand-rolled - * checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …` - * glue copied into every project — no `any`, one source of truth for editors, - * one stable read location for the engine. + * A top-level sidebar `noindex` checkbox. When ticked, the page is excluded from + * `sitemap.xml`, `llms.txt`, site search, and gets `robots: noindex, follow` — + * ALL automatically, no per-project filtering. * - * Idempotent and order-independent: if either the checkbox OR an existing - * `meta.noindex` is set, the page ends up noindex; the two can't drift apart. + * Why top-level (not mirrored into `meta.noindex`): plugin-seo's `meta` group + * declares only title/description/image, so Payload silently strips any extra + * key (`meta.noindex`) during sanitization — an earlier version mirrored there + * and the value vanished, leaking noindex pages into the sitemap. The value now + * lives on this top-level field, which persists; every reader in the kit + * (buildSitemapEntries, buildMetadata/createPageMetadata, buildLlmsTxt, + * searchContent) checks `doc.noindex` (and still tolerates a legacy + * `meta.noindex`). One field, one source of truth, zero project glue. * * // collections/Pages.ts * import { buildNoindexField } from '@intecion/ipal-kit' * fields: [ /* … *\/ buildNoindexField() ], */ export function buildNoindexField(args = {}) { - const { name = 'noindex', description = 'Check to exclude this page from indexing (robots: noindex, follow) and from sitemap.xml.', label = 'Exclude from indexing (noindex)', metaPath = 'meta.noindex', overrides = {} } = args; - const segments = metaPath.split('.'); - const mirror = ({ data, value })=>{ - const shouldNoindex = Boolean(value ?? readPath(data, segments)); - if (data && typeof data === 'object') { - writePath(data, segments, shouldNoindex); - } - return shouldNoindex; - }; - const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides; + const { name = 'noindex', description = 'Check to exclude this page from indexing (robots: noindex, follow), the sitemap, llms.txt and site search.', label = 'Exclude from indexing (noindex)', overrides = {} } = args; + const { admin: adminOverrides, ...restOverrides } = overrides; return { name, type: 'checkbox', @@ -53,14 +27,6 @@ ...adminOverrides }, defaultValue: false, - hooks: { - ...hooksOverrides, - // mirror runs first, then any project-supplied beforeChange hooks. - beforeChange: [ - mirror, - ...hooksOverrides?.beforeChange ?? [] - ] - }, label, ...restOverrides }; diff --git a/dist/modules/seo/buildNoindexField.js.map b/dist/modules/seo/buildNoindexField.js.map index 865364b..8c0fddd 100644 --- a/dist/modules/seo/buildNoindexField.js.map +++ b/dist/modules/seo/buildNoindexField.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/seo/buildNoindexField.ts"],"sourcesContent":["import type { CheckboxField, Field, FieldHook } from 'payload'\n\ntype BuildNoindexFieldArgs = {\n /** Help text under the checkbox. */\n description?: string\n /** Sidebar label. Default 'Wyklucz z indeksowania (noindex)'. */\n label?: string\n /**\n * Dotted path, inside the document, that the SEO read path (metadata +\n * sitemap) consumes. Default 'meta.noindex' — the plugin-seo `meta` group.\n * The checkbox value is mirrored here on every save, so editors toggle one\n * friendly switch and the machinery reads a stable location.\n */\n metaPath?: string\n /** Field name for the editor-facing checkbox. Default 'noindex'. */\n name?: string\n /** Extend/override the generated checkbox (position, access, etc.). */\n overrides?: Partial\n}\n\n/** Read a dotted path (e.g. 'meta.noindex') off a loosely-typed object. */\nfunction readPath(obj: null | Record | undefined, path: string[]): unknown {\n let cur: unknown = obj\n for (const key of path) {\n if (cur == null || typeof cur !== 'object') {return undefined}\n cur = (cur as Record)[key]\n }\n return cur\n}\n\n/** Write a dotted path, creating intermediate objects as needed. */\nfunction writePath(obj: Record, path: string[], value: unknown): void {\n let cur: Record = obj\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i]\n const next = cur[key]\n if (next == null || typeof next !== 'object') {cur[key] = {}}\n cur = cur[key] as Record\n }\n cur[path[path.length - 1]] = value\n}\n\n/**\n * A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the\n * sitemap and metadata generators actually read). Replaces the hand-rolled\n * checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …`\n * glue copied into every project — no `any`, one source of truth for editors,\n * one stable read location for the engine.\n *\n * Idempotent and order-independent: if either the checkbox OR an existing\n * `meta.noindex` is set, the page ends up noindex; the two can't drift apart.\n *\n * // collections/Pages.ts\n * import { buildNoindexField } from '@intecion/ipal-kit'\n * fields: [ /* … *\\/ buildNoindexField() ],\n */\nexport function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {\n const {\n name = 'noindex',\n description = 'Check to exclude this page from indexing (robots: noindex, follow) and from sitemap.xml.',\n label = 'Exclude from indexing (noindex)',\n metaPath = 'meta.noindex',\n overrides = {},\n } = args\n\n const segments = metaPath.split('.')\n\n const mirror: FieldHook = ({ data, value }) => {\n const shouldNoindex = Boolean(value ?? readPath(data as Record, segments))\n if (data && typeof data === 'object') {\n writePath(data as Record, segments, shouldNoindex)\n }\n return shouldNoindex\n }\n\n const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides\n\n return {\n name,\n type: 'checkbox',\n admin: {\n description,\n position: 'sidebar',\n ...adminOverrides,\n },\n defaultValue: false,\n hooks: {\n ...hooksOverrides,\n // mirror runs first, then any project-supplied beforeChange hooks.\n beforeChange: [mirror, ...(hooksOverrides?.beforeChange ?? [])],\n },\n label,\n ...restOverrides,\n } as CheckboxField\n}\n"],"names":["readPath","obj","path","cur","key","undefined","writePath","value","i","length","next","buildNoindexField","args","name","description","label","metaPath","overrides","segments","split","mirror","data","shouldNoindex","Boolean","admin","adminOverrides","hooks","hooksOverrides","restOverrides","type","position","defaultValue","beforeChange"],"mappings":"AAoBA,yEAAyE,GACzE,SAASA,SAASC,GAA+C,EAAEC,IAAc;IAC/E,IAAIC,MAAeF;IACnB,KAAK,MAAMG,OAAOF,KAAM;QACtB,IAAIC,OAAO,QAAQ,OAAOA,QAAQ,UAAU;YAAC,OAAOE;QAAS;QAC7DF,MAAM,AAACA,GAA+B,CAACC,IAAI;IAC7C;IACA,OAAOD;AACT;AAEA,kEAAkE,GAClE,SAASG,UAAUL,GAA4B,EAAEC,IAAc,EAAEK,KAAc;IAC7E,IAAIJ,MAA+BF;IACnC,IAAK,IAAIO,IAAI,GAAGA,IAAIN,KAAKO,MAAM,GAAG,GAAGD,IAAK;QACxC,MAAMJ,MAAMF,IAAI,CAACM,EAAE;QACnB,MAAME,OAAOP,GAAG,CAACC,IAAI;QACrB,IAAIM,QAAQ,QAAQ,OAAOA,SAAS,UAAU;YAACP,GAAG,CAACC,IAAI,GAAG,CAAC;QAAC;QAC5DD,MAAMA,GAAG,CAACC,IAAI;IAChB;IACAD,GAAG,CAACD,IAAI,CAACA,KAAKO,MAAM,GAAG,EAAE,CAAC,GAAGF;AAC/B;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASI,kBAAkBC,OAA8B,CAAC,CAAC;IAChE,MAAM,EACJC,OAAO,SAAS,EAChBC,cAAc,0FAA0F,EACxGC,QAAQ,iCAAiC,EACzCC,WAAW,cAAc,EACzBC,YAAY,CAAC,CAAC,EACf,GAAGL;IAEJ,MAAMM,WAAWF,SAASG,KAAK,CAAC;IAEhC,MAAMC,SAAoB,CAAC,EAAEC,IAAI,EAAEd,KAAK,EAAE;QACxC,MAAMe,gBAAgBC,QAAQhB,SAASP,SAASqB,MAAiCH;QACjF,IAAIG,QAAQ,OAAOA,SAAS,UAAU;YACpCf,UAAUe,MAAiCH,UAAUI;QACvD;QACA,OAAOA;IACT;IAEA,MAAM,EAAEE,OAAOC,cAAc,EAAEC,OAAOC,cAAc,EAAE,GAAGC,eAAe,GAAGX;IAE3E,OAAO;QACLJ;QACAgB,MAAM;QACNL,OAAO;YACLV;YACAgB,UAAU;YACV,GAAGL,cAAc;QACnB;QACAM,cAAc;QACdL,OAAO;YACL,GAAGC,cAAc;YACjB,mEAAmE;YACnEK,cAAc;gBAACZ;mBAAYO,gBAAgBK,gBAAgB,EAAE;aAAE;QACjE;QACAjB;QACA,GAAGa,aAAa;IAClB;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/seo/buildNoindexField.ts"],"sourcesContent":["import type { CheckboxField, Field } from 'payload'\n\ntype BuildNoindexFieldArgs = {\n /** Help text under the checkbox. */\n description?: string\n /** Sidebar label. Default 'Exclude from indexing (noindex)'. */\n label?: string\n /** Field name for the editor-facing checkbox. Default 'noindex'. */\n name?: string\n /** Extend/override the generated checkbox (position, access, etc.). */\n overrides?: Partial\n}\n\n/**\n * A top-level sidebar `noindex` checkbox. When ticked, the page is excluded from\n * `sitemap.xml`, `llms.txt`, site search, and gets `robots: noindex, follow` —\n * ALL automatically, no per-project filtering.\n *\n * Why top-level (not mirrored into `meta.noindex`): plugin-seo's `meta` group\n * declares only title/description/image, so Payload silently strips any extra\n * key (`meta.noindex`) during sanitization — an earlier version mirrored there\n * and the value vanished, leaking noindex pages into the sitemap. The value now\n * lives on this top-level field, which persists; every reader in the kit\n * (buildSitemapEntries, buildMetadata/createPageMetadata, buildLlmsTxt,\n * searchContent) checks `doc.noindex` (and still tolerates a legacy\n * `meta.noindex`). One field, one source of truth, zero project glue.\n *\n * // collections/Pages.ts\n * import { buildNoindexField } from '@intecion/ipal-kit'\n * fields: [ /* … *\\/ buildNoindexField() ],\n */\nexport function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {\n const {\n name = 'noindex',\n description = 'Check to exclude this page from indexing (robots: noindex, follow), the sitemap, llms.txt and site search.',\n label = 'Exclude from indexing (noindex)',\n overrides = {},\n } = args\n\n const { admin: adminOverrides, ...restOverrides } = overrides\n\n return {\n name,\n type: 'checkbox',\n admin: {\n description,\n position: 'sidebar',\n ...adminOverrides,\n },\n defaultValue: false,\n label,\n ...restOverrides,\n } as CheckboxField\n}\n"],"names":["buildNoindexField","args","name","description","label","overrides","admin","adminOverrides","restOverrides","type","position","defaultValue"],"mappings":"AAaA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASA,kBAAkBC,OAA8B,CAAC,CAAC;IAChE,MAAM,EACJC,OAAO,SAAS,EAChBC,cAAc,4GAA4G,EAC1HC,QAAQ,iCAAiC,EACzCC,YAAY,CAAC,CAAC,EACf,GAAGJ;IAEJ,MAAM,EAAEK,OAAOC,cAAc,EAAE,GAAGC,eAAe,GAAGH;IAEpD,OAAO;QACLH;QACAO,MAAM;QACNH,OAAO;YACLH;YACAO,UAAU;YACV,GAAGH,cAAc;QACnB;QACAI,cAAc;QACdP;QACA,GAAGI,aAAa;IAClB;AACF"} \ No newline at end of file diff --git a/dist/modules/seo/buildSitemapEntries.js b/dist/modules/seo/buildSitemapEntries.js index a8a27f6..feaba9a 100644 --- a/dist/modules/seo/buildSitemapEntries.js +++ b/dist/modules/seo/buildSitemapEntries.js @@ -29,7 +29,11 @@ import { buildHreflangAlternates } from './hreflang.js'; if (doc._status && doc._status !== 'published') { return false; } - if (doc.meta?.noindex) { + // Check BOTH the top-level checkbox (buildNoindexField, the field that + // persists) AND meta.noindex — plugin-seo's meta group doesn't declare + // noindex, so a mirror into meta.noindex is stripped on save. Reading both + // makes exclusion automatic regardless of where the flag ended up. + if (doc.noindex || doc.meta?.noindex) { return false; } if (hasExcludedSlug(doc.slug)) { diff --git a/dist/modules/seo/buildSitemapEntries.js.map b/dist/modules/seo/buildSitemapEntries.js.map index d9f07c3..054ed80 100644 --- a/dist/modules/seo/buildSitemapEntries.js.map +++ b/dist/modules/seo/buildSitemapEntries.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/seo/buildSitemapEntries.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { ContentOption } from '../content/index.js'\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { archiveFieldName } from '../content/index.js'\nimport { buildLocalizedPath, getLocaleCodes , getLocalizedSlugs } from '../i18n/index.js'\nimport { buildHreflangAlternates } from './hreflang.js'\n\n/**\n * One sitemap entry, shaped for Next's `app/sitemap.ts`.\n *\n * `alternates.languages` is the important part for a multilingual site: Next\n * renders it as `` per URL, which is\n * exactly what Google uses to connect language versions. A sitemap without it\n * is the common, weaker kind.\n */\nexport type SitemapEntry = {\n alternates?: { languages: Record }\n changeFrequency?: 'always' | 'daily' | 'hourly' | 'monthly' | 'never' | 'weekly' | 'yearly'\n lastModified?: Date | string\n priority?: number\n url: string\n}\n\ntype CollectionEntry = {\n /** Localized segment for entries (archive page slugs), when applicable. */\n prefixSlugs?: Record\n slug: string\n}\n\ntype BuildSitemapArgs = {\n /** Absolute origin, e.g. 'https://example.com'. Required for valid sitemap URLs. */\n baseUrl: string\n changeFrequency?: SitemapEntry['changeFrequency']\n config: I18nConfig\n /** Archive-backed collections, same value as the plugin option. */\n content?: ContentOption\n /**\n * Slug of the page that is the site root (collapses to /{locale}).\n * Read from System Pages when omitted.\n */\n homeSlug?: Record | string\n /** Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n payload: BasePayload\n /** SiteSettings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n}\n\ntype DocRow = {\n _status?: string\n id: number | string\n meta?: { noindex?: boolean } | null\n slug?: unknown\n updatedAt?: string\n}\n\n/**\n * Slugs that must never appear in the sitemap — error/system pages that exist as\n * documents (e.g. a '404' page in the Pages collection) but should not be\n * indexed. A sitemap should list only real, HTTP-200 content; a '/pl/404' entry\n * is an audit finding. Matched against the slug in any locale.\n */\nconst EXCLUDED_SITEMAP_SLUGS = new Set(['404', '500', 'error', 'not-found'])\n\n/** True if the doc's slug (in any locale) is an excluded system/error slug. */\nfunction hasExcludedSlug(slug: unknown): boolean {\n if (typeof slug === 'string') {return EXCLUDED_SITEMAP_SLUGS.has(slug)}\n if (slug && typeof slug === 'object') {\n for (const value of Object.values(slug as Record)) {\n if (typeof value === 'string' && EXCLUDED_SITEMAP_SLUGS.has(value)) {return true}\n }\n }\n return false\n}\n\n/** Skip drafts, noindex, and system/error pages (404 etc.). */\nfunction isIndexable(doc: DocRow): boolean {\n if (doc._status && doc._status !== 'published') {return false}\n if (doc.meta?.noindex) {return false}\n if (hasExcludedSlug(doc.slug)) {return false}\n return true\n}\n\n/**\n * Turns one document into a sitemap entry per default locale isn't needed —\n * one entry with all languages as alternates is the correct, de-duplicated\n * shape. The `url` is the current locale's path; `alternates.languages` carries\n * every locale (including itself, per Google's guidance).\n */\nfunction entryFor(\n doc: DocRow,\n locale: string,\n config: I18nConfig,\n baseUrl: string,\n homeSlug: Record | string | undefined,\n prefix: Record | undefined,\n changeFrequency: SitemapEntry['changeFrequency'],\n): null | SitemapEntry {\n const slugs =\n doc.slug && typeof doc.slug === 'object'\n ? getLocalizedSlugs({ config, slugField: doc.slug as Record })\n : {}\n\n const path = buildLocalizedPath({ config, homeSlug, locale, prefix, slugs })\n if (!path) {return null}\n\n const origin = baseUrl.replace(/\\/$/, '')\n const languages = buildHreflangAlternates({ baseUrl, config, homeSlug, prefix, slugs })\n\n return {\n url: `${origin}${path}`,\n ...(doc.updatedAt ? { lastModified: doc.updatedAt } : {}),\n ...(changeFrequency ? { changeFrequency } : {}),\n ...(Object.keys(languages).length ? { alternates: { languages } } : {}),\n }\n}\n\n/**\n * Collects every public URL — pages and archive entries — as sitemap entries\n * with per-URL hreflang and lastmod.\n *\n * Reuses the same path/hreflang builders as page metadata, so the sitemap can't\n * drift from what the pages actually render (a classic source of sitemap bugs:\n * a URL listed one way and served another). Drafts and noindex documents are\n * omitted.\n *\n * ```ts\n * // app/sitemap.ts\n * export default async function sitemap() {\n * return buildSitemapEntries({\n * payload: await getPayload({ config }),\n * config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!,\n * content: contentConfig,\n * })\n * }\n * ```\n */\nexport async function buildSitemapEntries({\n baseUrl,\n changeFrequency = 'weekly',\n config,\n content,\n homeSlug,\n pagesSlug = 'pages',\n payload,\n settingsSlug = 'site-settings',\n}: BuildSitemapArgs): Promise {\n const locales = config.locales.map((l) => l.code)\n const defaultLocale = config.defaultLocale\n\n // Resolve homeSlug and archive prefixes from System Pages (read once, in all\n // locales so archive prefixes are available per language).\n const settings = (await payload.findGlobal({\n slug: settingsSlug as never,\n depth: 1,\n locale: 'all' as never,\n })) as Record\n\n // Home slug as a per-locale MAP so every language's homepage collapses to its\n // root in the sitemap (/pl, /de, /en) — not just the default locale. Priority:\n // caller-provided homeSlug > full map from the homepage relationship > single\n // default-locale slug > 'home'. slugMapAllLocales already builds the map (it's\n // used for archive prefixes below); reusing it here fixes /de/startseite\n // appearing in the sitemap instead of /de.\n const resolvedHomeSlug =\n homeSlug ??\n slugMapAllLocales(settings.homepage, locales) ??\n extractSlugInLocale(settings.homepage, defaultLocale) ??\n 'home'\n\n // Which collections to walk: pages (no prefix) + each content collection with\n // its archive-page slugs as the localized prefix.\n const collections: CollectionEntry[] = [{ slug: pagesSlug }]\n\n for (const c of content?.collections ?? []) {\n const archive = settings[archiveFieldName(c.slug)]\n const prefixSlugs = archive ? slugMapAllLocales(archive, locales) : undefined\n collections.push({ slug: c.slug, prefixSlugs })\n }\n\n const entries: SitemapEntry[] = []\n\n for (const collection of collections) {\n // Read every doc once, across locales, so one row yields all its language\n // alternates without re-querying per locale.\n const result = await payload.find({\n collection: collection.slug as never,\n depth: 0,\n limit: 0, // no pagination — sitemap wants everything\n locale: 'all' as never,\n pagination: false as never,\n })\n\n for (const raw of result.docs as DocRow[]) {\n if (!isIndexable(raw)) {continue}\n\n // Emit a separate for EACH locale. Google's sitemap spec for\n // localized sites requires one per language version (each with its\n // own plus xhtml:link alternates), not a single default-locale \n // with the others hidden only in alternates. Emitting only the default\n // locale makes GSC count 8 URLs instead of 8×3 — a real reporting gap.\n for (const locale of getLocaleCodes(config)) {\n const entry = entryFor(\n raw,\n locale,\n config,\n baseUrl,\n resolvedHomeSlug,\n collection.prefixSlugs,\n changeFrequency,\n )\n if (entry) {entries.push(entry)}\n }\n }\n }\n\n return entries\n}\n\n/** Pulls a slug string from a populated relationship in a specific locale. */\nfunction extractSlugInLocale(rel: unknown, locale: string): string | undefined {\n if (!rel || typeof rel !== 'object') {return undefined}\n const slug = (rel as { slug?: unknown }).slug\n if (typeof slug === 'string') {return slug}\n if (slug && typeof slug === 'object') {\n const v = (slug as Record)[locale]\n return typeof v === 'string' ? v : undefined\n }\n return undefined\n}\n\n/** Builds a locale→slug map from a populated archive relationship. */\nfunction slugMapAllLocales(rel: unknown, locales: string[]): Record | undefined {\n if (!rel || typeof rel !== 'object') {return undefined}\n const slug = (rel as { slug?: unknown }).slug\n if (!slug || typeof slug !== 'object') {return undefined}\n\n const map: Record = {}\n for (const locale of locales) {\n const v = (slug as Record)[locale]\n if (typeof v === 'string') {map[locale] = v}\n }\n return Object.keys(map).length ? map : undefined\n}\n"],"names":["archiveFieldName","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","buildHreflangAlternates","EXCLUDED_SITEMAP_SLUGS","Set","hasExcludedSlug","slug","has","value","Object","values","isIndexable","doc","_status","meta","noindex","entryFor","locale","config","baseUrl","homeSlug","prefix","changeFrequency","slugs","slugField","path","origin","replace","languages","url","updatedAt","lastModified","keys","length","alternates","buildSitemapEntries","content","pagesSlug","payload","settingsSlug","locales","map","l","code","defaultLocale","settings","findGlobal","depth","resolvedHomeSlug","slugMapAllLocales","homepage","extractSlugInLocale","collections","c","archive","prefixSlugs","undefined","push","entries","collection","result","find","limit","pagination","raw","docs","entry","rel","v"],"mappings":"AAKA,SAASA,gBAAgB,QAAQ,sBAAqB;AACtD,SAASC,kBAAkB,EAAEC,cAAc,EAAGC,iBAAiB,QAAS,mBAAkB;AAC1F,SAASC,uBAAuB,QAAQ,gBAAe;AAmDvD;;;;;CAKC,GACD,MAAMC,yBAAyB,IAAIC,IAAI;IAAC;IAAO;IAAO;IAAS;CAAY;AAE3E,6EAA6E,GAC7E,SAASC,gBAAgBC,IAAa;IACpC,IAAI,OAAOA,SAAS,UAAU;QAAC,OAAOH,uBAAuBI,GAAG,CAACD;IAAK;IACtE,IAAIA,QAAQ,OAAOA,SAAS,UAAU;QACpC,KAAK,MAAME,SAASC,OAAOC,MAAM,CAACJ,MAAkC;YAClE,IAAI,OAAOE,UAAU,YAAYL,uBAAuBI,GAAG,CAACC,QAAQ;gBAAC,OAAO;YAAI;QAClF;IACF;IACA,OAAO;AACT;AAEA,6DAA6D,GAC7D,SAASG,YAAYC,GAAW;IAC9B,IAAIA,IAAIC,OAAO,IAAID,IAAIC,OAAO,KAAK,aAAa;QAAC,OAAO;IAAK;IAC7D,IAAID,IAAIE,IAAI,EAAEC,SAAS;QAAC,OAAO;IAAK;IACpC,IAAIV,gBAAgBO,IAAIN,IAAI,GAAG;QAAC,OAAO;IAAK;IAC5C,OAAO;AACT;AAEA;;;;;CAKC,GACD,SAASU,SACPJ,GAAW,EACXK,MAAc,EACdC,MAAkB,EAClBC,OAAe,EACfC,QAAqD,EACrDC,MAA0C,EAC1CC,eAAgD;IAEhD,MAAMC,QACJX,IAAIN,IA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AOA;IAAI;IAC1C,IAAIA,QAAQ,OAAOA,SAAS,UAAU;QACpC,MAAM8D,IAAI,AAAC9D,IAAgC,CAACW,OAAO;QACnD,OAAO,OAAOmD,MAAM,WAAWA,IAAIZ;IACrC;IACA,OAAOA;AACT;AAEA,oEAAoE,GACpE,SAASP,kBAAkBkB,GAAY,EAAE3B,OAAiB;IACxD,IAAI,CAAC2B,OAAO,OAAOA,QAAQ,UAAU;QAAC,OAAOX;IAAS;IACtD,MAAMlD,OAAO,AAAC6D,IAA2B7D,IAAI;IAC7C,IAAI,CAACA,QAAQ,OAAOA,SAAS,UAAU;QAAC,OAAOkD;IAAS;IAExD,MAAMf,MAA8B,CAAC;IACrC,KAAK,MAAMxB,UAAUuB,QAAS;QAC5B,MAAM4B,IAAI,AAAC9D,IAAgC,CAACW,OAAO;QACnD,IAAI,OAAOmD,MAAM,UAAU;YAAC3B,GAAG,CAACxB,OAAO,GAAGmD;QAAC;IAC7C;IACA,OAAO3D,OAAOuB,IAAI,CAACS,KAAKR,MAAM,GAAGQ,MAAMe;AACzC"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/seo/buildSitemapEntries.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { ContentOption } from '../content/index.js'\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { archiveFieldName } from '../content/index.js'\nimport { buildLocalizedPath, getLocaleCodes , getLocalizedSlugs } from '../i18n/index.js'\nimport { buildHreflangAlternates } from './hreflang.js'\n\n/**\n * One sitemap entry, shaped for Next's `app/sitemap.ts`.\n *\n * `alternates.languages` is the important part for a multilingual site: Next\n * renders it as `` per URL, which is\n * exactly what Google uses to connect language versions. A sitemap without it\n * is the common, weaker kind.\n */\nexport type SitemapEntry = {\n alternates?: { languages: Record }\n changeFrequency?: 'always' | 'daily' | 'hourly' | 'monthly' | 'never' | 'weekly' | 'yearly'\n lastModified?: Date | string\n priority?: number\n url: string\n}\n\ntype CollectionEntry = {\n /** Localized segment for entries (archive page slugs), when applicable. */\n prefixSlugs?: Record\n slug: string\n}\n\ntype BuildSitemapArgs = {\n /** Absolute origin, e.g. 'https://example.com'. Required for valid sitemap URLs. */\n baseUrl: string\n changeFrequency?: SitemapEntry['changeFrequency']\n config: I18nConfig\n /** Archive-backed collections, same value as the plugin option. */\n content?: ContentOption\n /**\n * Slug of the page that is the site root (collapses to /{locale}).\n * Read from System Pages when omitted.\n */\n homeSlug?: Record | string\n /** Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n payload: BasePayload\n /** SiteSettings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n}\n\ntype DocRow = {\n _status?: string\n id: number | string\n meta?: { noindex?: boolean } | null\n /** Top-level checkbox (buildNoindexField) — the field that actually persists. */\n noindex?: boolean | null\n slug?: unknown\n updatedAt?: string\n}\n\n/**\n * Slugs that must never appear in the sitemap — error/system pages that exist as\n * documents (e.g. a '404' page in the Pages collection) but should not be\n * indexed. A sitemap should list only real, HTTP-200 content; a '/pl/404' entry\n * is an audit finding. Matched against the slug in any locale.\n */\nconst EXCLUDED_SITEMAP_SLUGS = new Set(['404', '500', 'error', 'not-found'])\n\n/** True if the doc's slug (in any locale) is an excluded system/error slug. */\nfunction hasExcludedSlug(slug: unknown): boolean {\n if (typeof slug === 'string') {return EXCLUDED_SITEMAP_SLUGS.has(slug)}\n if (slug && typeof slug === 'object') {\n for (const value of Object.values(slug as Record)) {\n if (typeof value === 'string' && EXCLUDED_SITEMAP_SLUGS.has(value)) {return true}\n }\n }\n return false\n}\n\n/** Skip drafts, noindex, and system/error pages (404 etc.). */\nfunction isIndexable(doc: DocRow): boolean {\n if (doc._status && doc._status !== 'published') {return false}\n // Check BOTH the top-level checkbox (buildNoindexField, the field that\n // persists) AND meta.noindex — plugin-seo's meta group doesn't declare\n // noindex, so a mirror into meta.noindex is stripped on save. Reading both\n // makes exclusion automatic regardless of where the flag ended up.\n if (doc.noindex || doc.meta?.noindex) {return false}\n if (hasExcludedSlug(doc.slug)) {return false}\n return true\n}\n\n/**\n * Turns one document into a sitemap entry per default locale isn't needed —\n * one entry with all languages as alternates is the correct, de-duplicated\n * shape. The `url` is the current locale's path; `alternates.languages` carries\n * every locale (including itself, per Google's guidance).\n */\nfunction entryFor(\n doc: DocRow,\n locale: string,\n config: I18nConfig,\n baseUrl: string,\n homeSlug: Record | string | undefined,\n prefix: Record | undefined,\n changeFrequency: SitemapEntry['changeFrequency'],\n): null | SitemapEntry {\n const slugs =\n doc.slug && typeof doc.slug === 'object'\n ? getLocalizedSlugs({ config, slugField: doc.slug as Record })\n : {}\n\n const path = buildLocalizedPath({ config, homeSlug, locale, prefix, slugs })\n if (!path) {return null}\n\n const origin = baseUrl.replace(/\\/$/, '')\n const languages = buildHreflangAlternates({ baseUrl, config, homeSlug, prefix, slugs })\n\n return {\n url: `${origin}${path}`,\n ...(doc.updatedAt ? { lastModified: doc.updatedAt } : {}),\n ...(changeFrequency ? { changeFrequency } : {}),\n ...(Object.keys(languages).length ? { alternates: { languages } } : {}),\n }\n}\n\n/**\n * Collects every public URL — pages and archive entries — as sitemap entries\n * with per-URL hreflang and lastmod.\n *\n * Reuses the same path/hreflang builders as page metadata, so the sitemap can't\n * drift from what the pages actually render (a classic source of sitemap bugs:\n * a URL listed one way and served another). Drafts and noindex documents are\n * omitted.\n *\n * ```ts\n * // app/sitemap.ts\n * export default async function sitemap() {\n * return buildSitemapEntries({\n * payload: await getPayload({ config }),\n * config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!,\n * content: contentConfig,\n * })\n * }\n * ```\n */\nexport async function buildSitemapEntries({\n baseUrl,\n changeFrequency = 'weekly',\n config,\n content,\n homeSlug,\n pagesSlug = 'pages',\n payload,\n settingsSlug = 'site-settings',\n}: BuildSitemapArgs): Promise {\n const locales = config.locales.map((l) => l.code)\n const defaultLocale = config.defaultLocale\n\n // Resolve homeSlug and archive prefixes from System Pages (read once, in all\n // locales so archive prefixes are available per language).\n const settings = (await payload.findGlobal({\n slug: settingsSlug as never,\n depth: 1,\n locale: 'all' as never,\n })) as Record\n\n // Home slug as a per-locale MAP so every language's homepage collapses to its\n // root in the sitemap (/pl, /de, /en) — not just the default locale. Priority:\n // caller-provided homeSlug > full map from the homepage relationship > single\n // default-locale slug > 'home'. slugMapAllLocales already builds the map (it's\n // used for archive prefixes below); reusing it here fixes /de/startseite\n // appearing in the sitemap instead of /de.\n const resolvedHomeSlug =\n homeSlug ??\n slugMapAllLocales(settings.homepage, locales) ??\n extractSlugInLocale(settings.homepage, defaultLocale) ??\n 'home'\n\n // Which collections to walk: pages (no prefix) + each content collection with\n // its archive-page slugs as the localized prefix.\n const collections: CollectionEntry[] = [{ slug: pagesSlug }]\n\n for (const c of content?.collections ?? []) {\n const archive = settings[archiveFieldName(c.slug)]\n const prefixSlugs = archive ? slugMapAllLocales(archive, locales) : undefined\n collections.push({ slug: c.slug, prefixSlugs })\n }\n\n const entries: SitemapEntry[] = []\n\n for (const collection of collections) {\n // Read every doc once, across locales, so one row yields all its language\n // alternates without re-querying per locale.\n const result = await payload.find({\n collection: collection.slug as never,\n depth: 0,\n limit: 0, // no pagination — sitemap wants everything\n locale: 'all' as never,\n pagination: false as never,\n })\n\n for (const raw of result.docs as DocRow[]) {\n if (!isIndexable(raw)) {continue}\n\n // Emit a separate for EACH locale. Google's sitemap spec for\n // localized sites requires one per language version (each with its\n // own plus xhtml:link alternates), not a single default-locale \n // with the others hidden only in alternates. Emitting only the default\n // locale makes GSC count 8 URLs instead of 8×3 — a real reporting gap.\n for (const locale of getLocaleCodes(config)) {\n const entry = entryFor(\n raw,\n locale,\n config,\n baseUrl,\n resolvedHomeSlug,\n collection.prefixSlugs,\n changeFrequency,\n )\n if (entry) {entries.push(entry)}\n }\n }\n }\n\n return entries\n}\n\n/** Pulls a slug string from a populated relationship in a specific locale. */\nfunction extractSlugInLocale(rel: unknown, locale: string): string | undefined {\n if (!rel || typeof rel !== 'object') {return undefined}\n const slug = (rel as { slug?: unknown }).slug\n if (typeof slug === 'string') {return slug}\n if (slug && typeof slug === 'object') {\n const v = (slug as Record)[locale]\n return typeof v === 'string' ? v : undefined\n }\n return undefined\n}\n\n/** Builds a locale→slug map from a populated archive relationship. */\nfunction slugMapAllLocales(rel: unknown, locales: string[]): Record | undefined {\n if (!rel || typeof rel !== 'object') {return undefined}\n const slug = (rel as { slug?: unknown }).slug\n if (!slug || typeof slug !== 'object') {return undefined}\n\n const map: Record = {}\n for (const locale of locales) {\n const v = (slug as Record)[locale]\n if (typeof v === 'string') {map[locale] = v}\n }\n return Object.keys(map).length ? map : undefined\n}\n"],"names":["archiveFieldName","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","buildHreflangAlternates","EXCLUDED_SITEMAP_SLUGS","Set","hasExcludedSlug","slug","has","value","Object","values","isIndexable","doc","_status","noindex","meta","entryFor","locale","config","baseUrl","homeSlug","prefix","changeFrequency","slugs","slugField","path","origin","replace","languages","url","updatedAt","lastModified","keys","length","alternates","buildSitemapEntries","content","pagesSlug","payload","settingsSlug","locales","map","l","code","defaultLocale","settings","findGlobal","depth","resolvedHomeSlug","slugMapAllLocales","homepage","extractSlugInLocale","collections","c","archive","prefixSlugs","undefined","push","entries","collection","result","find","limit","pagination","raw","docs","entry","rel","v"],"mappings":"AAKA,SAASA,gBAAgB,QAAQ,sBAAqB;AACtD,SAASC,kBAAkB,EAAEC,cAAc,EAAGC,iBAAiB,QAAS,mBAAkB;AAC1F,SAASC,uBAAuB,QAAQ,gBAAe;AAqDvD;;;;;CAKC,GACD,MAAMC,yBAAyB,IAAIC,IAAI;IAAC;IAAO;IAAO;IAAS;CAAY;AAE3E,6EAA6E,GAC7E,SAASC,gBAAgBC,IAAa;IACpC,IAAI,OAAOA,SAAS,UAAU;QAAC,OAAOH,uBAAuBI,GAAG,CAACD;IAAK;IACtE,IAAIA,QAAQ,OAAOA,SAAS,UAAU;QACpC,KAAK,MAAME,SAASC,OAAOC,MAAM,CAACJ,MAAkC;YAClE,IAAI,OAAOE,UAAU,Y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newline at end of file diff --git a/dist/modules/seo/createPageMetadata.js b/dist/modules/seo/createPageMetadata.js index 43fd99a..110de3c 100644 --- a/dist/modules/seo/createPageMetadata.js +++ b/dist/modules/seo/createPageMetadata.js @@ -90,6 +90,7 @@ import { slugsAcrossLocales } from './slugsAcrossLocales.js'; ...base, imageUrl: resolveOgImage(doc), meta: doc.meta, + noindex: doc.noindex, pageTitle: doc.title, prefix, query, diff --git a/dist/modules/seo/createPageMetadata.js.map b/dist/modules/seo/createPageMetadata.js.map index 929c8da..56be01e 100644 --- a/dist/modules/seo/createPageMetadata.js.map +++ b/dist/modules/seo/createPageMetadata.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/seo/createPageMetadata.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { ContentOption } from '../content/index.js'\nimport type { I18nConfig } from '../i18n/index.js'\nimport type { PageMetadata } from './buildMetadata.js'\nimport type { SeoMeta } from './types.js'\n\nimport { resolveRoute } from '../content/index.js'\nimport { buildMetadata } from './buildMetadata.js'\nimport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nimport { slugsAcrossLocales } from './slugsAcrossLocales.js'\n\ntype CreatePageMetadataArgs = {\n /** Absolute site origin, e.g. 'https://example.com'. */\n baseUrl?: string\n /** Collection holding pages. Defaults to 'pages'. */\n collection?: string\n config: I18nConfig\n /**\n * Archive-backed collections, same value as the plugin option. Pass it and\n * entry URLs (/pl/artykuly/moj-post) get correct canonical and hreflang;\n * omit it and only pages are handled.\n */\n content?: ContentOption\n /** SiteSettings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n /** Field on SiteSettings holding the site name. Defaults to 'siteName'. */\n siteNameField?: string\n}\n\ntype PageMetadataContext = {\n locale: string\n /**\n * Page number from ?page= on an archive listing. Pass it and page 2 gets a\n * canonical to itself; leave it out and every page claims to be page 1.\n */\n page?: number\n payload: BasePayload\n /** Route slug segments; empty/undefined means the locale root. */\n slug?: string[]\n}\n\ntype DocShape = {\n id: number | string\n meta?: null | SeoMeta\n /** The document's own title (page name), used as the fallback page title. */\n title?: null | string\n}\n\n/** plugin-seo stores the OG image as an upload relationship. */\nfunction resolveOgImage(doc: DocShape): null | string {\n const image = (doc.meta as { image?: unknown } | null | undefined)?.image\n if (image && typeof image === 'object' && 'url' in image) {\n return (image as { url: string }).url ?? null\n }\n return null\n}\n\n/**\n * Metadata for the page route, with every resolver already wired.\n *\n * `createMetadataGenerator` asks the client for resolvers because it can't know\n * their collections. But for the plugin's own conventions it does know: pages\n * live in one collection, the site name sits on SiteSettings, the OG image sits\n * on the plugin-seo `meta` group, the home page is whatever System Pages points\n * at, and — with `content` — entries live under their collection's archive page.\n * Re-declaring all that in every project is copy-paste, so this resolves it.\n *\n * Reach for `createMetadataGenerator` instead when a route doesn't follow those\n * conventions — custom image logic, a different global, hand-rolled paths.\n *\n * The plugin never calls getPayload, and Next calls generateMetadata without a\n * payload, so the client keeps a small wrapper:\n *\n * ```ts\n * const pageMetadata = createPageMetadata({ config: i18nConfig, baseUrl, content })\n *\n * export async function generateMetadata({ params }) {\n * const { locale, slug } = await params\n * return pageMetadata({ payload: await getPayload({ config }), locale, slug })\n * }\n * ```\n */\nexport function createPageMetadata(args: CreatePageMetadataArgs) {\n const {\n baseUrl,\n collection = 'pages',\n config,\n content,\n settingsSlug = 'site-settings',\n siteNameField = 'siteName',\n } = args\n\n return async function pageMetadata({\n slug,\n locale,\n page,\n payload,\n }: PageMetadataContext): Promise {\n const site = await readSiteMetaConfig({ locale, payload, settingsSlug, siteNameField })\n\n const base = {\n baseUrl,\n config,\n homeSlug: site.homeSlug,\n locale,\n order: site.order,\n separator: site.separator,\n siteName: site.siteName,\n }\n\n const route = await resolveRoute({\n content,\n locale,\n page,\n pagesSlug: collection,\n payload,\n segments: slug,\n settingsSlug,\n })\n\n // Unknown route (the page component will 404) — still return something\n // coherent rather than throwing during metadata generation.\n if (!route) {\n return buildMetadata({ ...base, meta: null, slugs: {} })\n }\n\n const doc = route.doc as DocShape\n\n // An entry sits under its archive, so its URLs need that segment — and the\n // segment differs per locale, since it's the archive page's own slug.\n const prefix =\n route.type === 'entry'\n ? await slugsAcrossLocales({\n id: (route.archive as DocShape).id,\n collection,\n config,\n payload,\n })\n : undefined\n\n const slugs = await slugsAcrossLocales({\n id: doc.id,\n collection: route.type === 'entry' ? route.collection : collection,\n config,\n payload,\n })\n\n // Page 2 of a listing is its own URL, not a variant of page 1.\n const query = route.type === 'archive' && route.page > 1 ? `?page=${route.page}` : undefined\n\n return buildMetadata({\n ...base,\n imageUrl: resolveOgImage(doc),\n meta: doc.meta,\n pageTitle: doc.title,\n prefix,\n query,\n slugs,\n })\n }\n}\n"],"names":["resolveRoute","buildMetadata","readSiteMetaConfig","slugsAcrossLocales","resolveOgImage","doc","image","meta","url","createPageMetadata","args","baseUrl","collection","config","content","settingsSlug","siteNameField","pageMetadata","slug","locale","page","payload","site","base","homeSlug","order","separator","siteName","route","pagesSlug","segments","slugs","prefix","type","id","archive","undefined","query","imageUrl","pageTitle","title"],"mappings":"AAOA,SAASA,YAAY,QAAQ,sBAAqB;AAClD,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,kBAAkB,QAAQ,0BAAyB;AAuC5D,8DAA8D,GAC9D,SAASC,eAAeC,GAAa;IACnC,MAAMC,QAASD,IAAIE,IAAI,EAA6CD;IACpE,IAAIA,SAAS,OAAOA,UAAU,YAAY,SAASA,OAAO;QACxD,OAAO,AAACA,MAA0BE,GAAG,IAAI;IAC3C;IACA,OAAO;AACT;AAEA;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GACD,OAAO,SAASC,mBAAmBC,IAA4B;IAC7D,MAAM,EACJC,OAAO,EACPC,aAAa,OAAO,EACpBC,MAAM,EACNC,OAAO,EACPC,eAAe,eAAe,EAC9BC,gBAAgB,UAAU,EAC3B,GAAGN;IAEJ,OAAO,eAAeO,aAAa,EACjCC,IAAI,EACJC,MAAM,EACNC,IAAI,EACJC,OAAO,EACa;QACpB,MAAMC,OAAO,MAAMpB,mBAAmB;YAAEiB;YAAQE;YAASN;YAAcC;QAAc;QAErF,MAAMO,OAAO;YACXZ;YACAE;YACAW,UAAUF,KAAKE,QAAQ;YACvBL;YACAM,OAAOH,KAAKG,KAAK;YACjBC,WAAWJ,KAAKI,SAAS;YACzBC,UAAUL,KAAKK,QAAQ;QACzB;QAEA,MAAMC,QAAQ,MAAM5B,aAAa;YAC/Bc;YACAK;YACAC;YACAS,WAAWjB;YACXS;YACAS,UAAUZ;YACVH;QACF;QAEA,uEAAuE;QACvE,4DAA4D;QAC5D,IAAI,CAACa,OAAO;YACV,OAAO3B,cAAc;gBAAE,GAAGsB,IAAI;gBAAEhB,MAAM;gBAAMwB,OAAO,CAAC;YAAE;QACxD;QAEA,MAAM1B,MAAMuB,MAAMvB,GAAG;QAErB,2EAA2E;QAC3E,sEAAsE;QACtE,MAAM2B,SACJJ,MAAMK,IAAI,KAAK,UACX,MAAM9B,mBAAmB;YACvB+B,IAAI,AAACN,MAAMO,OAAO,CAAcD,EAAE;YAClCtB;YACAC;YACAQ;QACF,KACAe;QAEN,MAAML,QAAQ,MAAM5B,mBAAmB;YACrC+B,IAAI7B,IAAI6B,EAAE;YACVtB,YAAYgB,MAAMK,IAAI,KAAK,UAAUL,MAAMhB,UAAU,GAAGA;YACxDC;YACAQ;QACF;QAEA,+DAA+D;QAC/D,MAAMgB,QAAQT,MAAMK,IAAI,KAAK,aAAaL,MAAMR,IAAI,GAAG,IAAI,CAAC,MAAM,EAAEQ,MAAMR,IAAI,EAAE,GAAGgB;QAEnF,OAAOnC,cAAc;YACnB,GAAGsB,IAAI;YACPe,UAAUlC,eAAeC;YACzBE,MAAMF,IAAIE,IAAI;YACdgC,WAAWlC,IAAImC,KAAK;YACpBR;YACAK;YACAN;QACF;IACF;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/seo/createPageMetadata.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { ContentOption } from '../content/index.js'\nimport type { I18nConfig } from '../i18n/index.js'\nimport type { PageMetadata } from './buildMetadata.js'\nimport type { SeoMeta } from './types.js'\n\nimport { resolveRoute } from '../content/index.js'\nimport { buildMetadata } from './buildMetadata.js'\nimport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nimport { slugsAcrossLocales } from './slugsAcrossLocales.js'\n\ntype CreatePageMetadataArgs = {\n /** Absolute site origin, e.g. 'https://example.com'. */\n baseUrl?: string\n /** Collection holding pages. Defaults to 'pages'. */\n collection?: string\n config: I18nConfig\n /**\n * Archive-backed collections, same value as the plugin option. Pass it and\n * entry URLs (/pl/artykuly/moj-post) get correct canonical and hreflang;\n * omit it and only pages are handled.\n */\n content?: ContentOption\n /** SiteSettings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n /** Field on SiteSettings holding the site name. Defaults to 'siteName'. */\n siteNameField?: string\n}\n\ntype PageMetadataContext = {\n locale: string\n /**\n * Page number from ?page= on an archive listing. Pass it and page 2 gets a\n * canonical to itself; leave it out and every page claims to be page 1.\n */\n page?: number\n payload: BasePayload\n /** Route slug segments; empty/undefined means the locale root. */\n slug?: string[]\n}\n\ntype DocShape = {\n id: number | string\n meta?: null | SeoMeta\n /** Top-level noindex checkbox (buildNoindexField) — the field that persists. */\n noindex?: boolean | null\n /** The document's own title (page name), used as the fallback page title. */\n title?: null | string\n}\n\n/** plugin-seo stores the OG image as an upload relationship. */\nfunction resolveOgImage(doc: DocShape): null | string {\n const image = (doc.meta as { image?: unknown } | null | undefined)?.image\n if (image && typeof image === 'object' && 'url' in image) {\n return (image as { url: string }).url ?? null\n }\n return null\n}\n\n/**\n * Metadata for the page route, with every resolver already wired.\n *\n * `createMetadataGenerator` asks the client for resolvers because it can't know\n * their collections. But for the plugin's own conventions it does know: pages\n * live in one collection, the site name sits on SiteSettings, the OG image sits\n * on the plugin-seo `meta` group, the home page is whatever System Pages points\n * at, and — with `content` — entries live under their collection's archive page.\n * Re-declaring all that in every project is copy-paste, so this resolves it.\n *\n * Reach for `createMetadataGenerator` instead when a route doesn't follow those\n * conventions — custom image logic, a different global, hand-rolled paths.\n *\n * The plugin never calls getPayload, and Next calls generateMetadata without a\n * payload, so the client keeps a small wrapper:\n *\n * ```ts\n * const pageMetadata = createPageMetadata({ config: i18nConfig, baseUrl, content })\n *\n * export async function generateMetadata({ params }) {\n * const { locale, slug } = await params\n * return pageMetadata({ payload: await getPayload({ config }), locale, slug })\n * }\n * ```\n */\nexport function createPageMetadata(args: CreatePageMetadataArgs) {\n const {\n baseUrl,\n collection = 'pages',\n config,\n content,\n settingsSlug = 'site-settings',\n siteNameField = 'siteName',\n } = args\n\n return async function pageMetadata({\n slug,\n locale,\n page,\n payload,\n }: PageMetadataContext): Promise {\n const site = await readSiteMetaConfig({ locale, payload, settingsSlug, siteNameField })\n\n const base = {\n baseUrl,\n config,\n homeSlug: site.homeSlug,\n locale,\n order: site.order,\n separator: site.separator,\n siteName: site.siteName,\n }\n\n const route = await resolveRoute({\n content,\n locale,\n page,\n pagesSlug: collection,\n payload,\n segments: slug,\n settingsSlug,\n })\n\n // Unknown route (the page component will 404) — still return something\n // coherent rather than throwing during metadata generation.\n if (!route) {\n return buildMetadata({ ...base, meta: null, slugs: {} })\n }\n\n const doc = route.doc as DocShape\n\n // An entry sits under its archive, so its URLs need that segment — and the\n // segment differs per locale, since it's the archive page's own slug.\n const prefix =\n route.type === 'entry'\n ? await slugsAcrossLocales({\n id: (route.archive as DocShape).id,\n collection,\n config,\n payload,\n })\n : undefined\n\n const slugs = await slugsAcrossLocales({\n id: doc.id,\n collection: route.type === 'entry' ? route.collection : collection,\n config,\n payload,\n })\n\n // Page 2 of a listing is its own URL, not a variant of page 1.\n const query = route.type === 'archive' && route.page > 1 ? `?page=${route.page}` : undefined\n\n return buildMetadata({\n ...base,\n imageUrl: resolveOgImage(doc),\n meta: doc.meta,\n noindex: doc.noindex,\n pageTitle: doc.title,\n prefix,\n query,\n slugs,\n })\n }\n}\n"],"names":["resolveRoute","buildMetadata","readSiteMetaConfig","slugsAcrossLocales","resolveOgImage","doc","image","meta","url","createPageMetadata","args","baseUrl","collection","config","content","settingsSlug","siteNameField","pageMetadata","slug","locale","page","payload","site","base","homeSlug","order","separator","siteName","route","pagesSlug","segments","slugs","prefix","type","id","archive","undefined","query","imageUrl","noindex","pageTitle","title"],"mappings":"AAOA,SAASA,YAAY,QAAQ,sBAAqB;AAClD,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,kBAAkB,QAAQ,0BAAyB;AAyC5D,8DAA8D,GAC9D,SAASC,eAAeC,GAAa;IACnC,MAAMC,QAASD,IAAIE,IAAI,EAA6CD;IACpE,IAAIA,SAAS,OAAOA,UAAU,YAAY,SAASA,OAAO;QACxD,OAAO,AAACA,MAA0BE,GAAG,IAAI;IAC3C;IACA,OAAO;AACT;AAEA;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GACD,OAAO,SAASC,mBAAmBC,IAA4B;IAC7D,MAAM,EACJC,OAAO,EACPC,aAAa,OAAO,EACpBC,MAAM,EACNC,OAAO,EACPC,eAAe,eAAe,EAC9BC,gBAAgB,UAAU,EAC3B,GAAGN;IAEJ,OAAO,eAAeO,aAAa,EACjCC,IAAI,EACJC,MAAM,EACNC,IAAI,EACJC,OAAO,EACa;QACpB,MAAMC,OAAO,MAAMpB,mBAAmB;YAAEiB;YAAQE;YAASN;YAAcC;QAAc;QAErF,MAAMO,OAAO;YACXZ;YACAE;YACAW,UAAUF,KAAKE,QAAQ;YACvBL;YACAM,OAAOH,KAAKG,KAAK;YACjBC,WAAWJ,KAAKI,SAAS;YACzBC,UAAUL,KAAKK,QAAQ;QACzB;QAEA,MAAMC,QAAQ,MAAM5B,aAAa;YAC/Bc;YACAK;YACAC;YACAS,WAAWjB;YACXS;YACAS,UAAUZ;YACVH;QACF;QAEA,uEAAuE;QACvE,4DAA4D;QAC5D,IAAI,CAACa,OAAO;YACV,OAAO3B,cAAc;gBAAE,GAAGsB,IAAI;gBAAEhB,MAAM;gBAAMwB,OAAO,CAAC;YAAE;QACxD;QAEA,MAAM1B,MAAMuB,MAAMvB,GAAG;QAErB,2EAA2E;QAC3E,sEAAsE;QACtE,MAAM2B,SACJJ,MAAMK,IAAI,KAAK,UACX,MAAM9B,mBAAmB;YACvB+B,IAAI,AAACN,MAAMO,OAAO,CAAcD,EAAE;YAClCtB;YACAC;YACAQ;QACF,KACAe;QAEN,MAAML,QAAQ,MAAM5B,mBAAmB;YACrC+B,IAAI7B,IAAI6B,EAAE;YACVtB,YAAYgB,MAAMK,IAAI,KAAK,UAAUL,MAAMhB,UAAU,GAAGA;YACxDC;YACAQ;QACF;QAEA,+DAA+D;QAC/D,MAAMgB,QAAQT,MAAMK,IAAI,KAAK,aAAaL,MAAMR,IAAI,GAAG,IAAI,CAAC,MAAM,EAAEQ,MAAMR,IAAI,EAAE,GAAGgB;QAEnF,OAAOnC,cAAc;YACnB,GAAGsB,IAAI;YACPe,UAAUlC,eAAeC;YACzBE,MAAMF,IAAIE,IAAI;YACdgC,SAASlC,IAAIkC,OAAO;YACpBC,WAAWnC,IAAIoC,KAAK;YACpBT;YACAK;YACAN;QACF;IACF;AACF"} \ No newline at end of file diff --git a/docs/seo.md b/docs/seo.md index fefb207..fb9f402 100644 --- a/docs/seo.md +++ b/docs/seo.md @@ -731,9 +731,9 @@ Alternatywnie: dodaj `noindex` do System Pages o rolach prawnych automatycznie. ### buildNoindexField — przyjazny checkbox w sidebarze -Zamiast własnego checkboxa + hooka z `(data as any).meta.noindex = …` użyj -gotowego pola. Jeden przełącznik dla redaktora, zgrany z `meta.noindex` (to -czyta sitemap i metadata), bez `any`, bez rozjazdu między dwoma miejscami: +Jeden przełącznik w sidebarze. Zaznaczony → strona **automatycznie** wypada z: +`sitemap.xml`, `llms.txt`, wyszukiwarki, i dostaje `robots: noindex, follow` — +bez żadnego ręcznego filtrowania w projekcie. ```ts import { buildNoindexField } from '@intecion/ipal-kit' @@ -743,10 +743,22 @@ export const Pages: CollectionConfig = { } ``` -Idempotentne: jeśli ustawiony checkbox LUB istniejące `meta.noindex` — strona -wychodzi `noindex`; nie da się ich rozjechać. Opcje: `name` (domyślnie -`'noindex'`), `label`, `description`, `metaPath` (domyślnie `'meta.noindex'`), -`overrides` (pozycja, access itp.). +**Pole jest top-level (`doc.noindex`), NIE mirrorowane do `meta.noindex`.** +Dlaczego: grupa `meta` z plugin-seo deklaruje tylko title/description/image, więc +Payload przy sanityzacji **po cichu wycina** każdy dodatkowy klucz (`meta.noindex`) +— wcześniejsza wersja mirrorowała tam wartość i znikała, przez co strony noindex +trafiały do sitemapy. Teraz wartość żyje na polu top-level (które się zapisuje), a +wszystkie czytniki kitu (`buildSitemapEntries`, `buildMetadata`/ +`createPageMetadata`, `buildLlmsTxt`, `searchContent`) sprawdzają `doc.noindex` +(oraz, dla zgodności wstecznej, ewentualne `meta.noindex`). Jedno pole, jedno +źródło prawdy, zero kleju w projekcie. + +Opcje: `name` (domyślnie `'noindex'`), `label`, `description`, `overrides` +(pozycja, access itp.). + +> Naprawione w 1.7.5 — wcześniej (mirror do `meta.noindex`) strony noindex +> potrafiły wyciekać do sitemapy. Po aktualizacji `app/sitemap.xml/route.ts` +> wraca do czystej jednolinijki, bez ręcznego filtrowania. ## robots.txt — blokada parametrów (crawl budget) @@ -1129,4 +1141,4 @@ const speakable = buildSpeakableJsonLd({ W markupie projektu oznacz pasujące elementy (np. `className="speakable"` albo sekcja `.lead` ze streszczeniem). Selektory nietrafiające w nic są ignorowane — nie wskazuj nawigacji ani boilerplate'u, tylko samodzielny, czytelny tekst. -Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony. \ No newline at end of file +Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony. \ No newline at end of file diff --git a/package.json b/package.json index 8d01a67..d46d25c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@intecion/ipal-kit", - "version": "1.7.4", + "version": "1.7.5", "description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.", "license": "MIT", "repository": { diff --git a/src/modules/content/searchContent.ts b/src/modules/content/searchContent.ts index 6f7000e..d2d5627 100644 --- a/src/modules/content/searchContent.ts +++ b/src/modules/content/searchContent.ts @@ -40,6 +40,7 @@ type PageRow = { _status?: string id: number | string meta?: { description?: unknown; noindex?: boolean } | null + noindex?: boolean | null slug?: unknown title?: unknown } @@ -91,7 +92,7 @@ export async function searchContent({ const results: SearchResult[] = [] for (const doc of docs) { if (doc._status && doc._status !== 'published') {continue} - if (doc.meta?.noindex) {continue} + if (doc.noindex || doc.meta?.noindex) {continue} const title = typeof doc.title === 'string' ? doc.title : undefined const slug = typeof doc.slug === 'string' ? doc.slug : undefined if (!title || !slug) {continue} diff --git a/src/modules/seo/buildLlmsTxt.ts b/src/modules/seo/buildLlmsTxt.ts index 42be1a3..5eb2a12 100644 --- a/src/modules/seo/buildLlmsTxt.ts +++ b/src/modules/seo/buildLlmsTxt.ts @@ -42,6 +42,7 @@ type PageRow = { _status?: string id: number | string meta?: { description?: unknown; noindex?: boolean } | null + noindex?: boolean | null slug?: unknown title?: unknown } @@ -131,7 +132,7 @@ export async function buildLlmsTxt({ const sections: string[] = [] for (const raw of result.docs as PageRow[]) { if (raw._status && raw._status !== 'published') {continue} - if (raw.meta?.noindex) {continue} + if (raw.noindex || raw.meta?.noindex) {continue} const title = typeof raw.title === 'string' ? raw.title : undefined const slug = typeof raw.slug === 'string' ? raw.slug : undefined @@ -153,7 +154,7 @@ export async function buildLlmsTxt({ const pageLinks: string[] = [] for (const raw of result.docs as PageRow[]) { if (raw._status && raw._status !== 'published') {continue} - if (raw.meta?.noindex) {continue} + if (raw.noindex || raw.meta?.noindex) {continue} const title = typeof raw.title === 'string' ? raw.title : undefined const slug = typeof raw.slug === 'string' ? raw.slug : undefined diff --git a/src/modules/seo/buildMetadata.ts b/src/modules/seo/buildMetadata.ts index c7d0e28..0d64f27 100644 --- a/src/modules/seo/buildMetadata.ts +++ b/src/modules/seo/buildMetadata.ts @@ -57,6 +57,13 @@ type BuildMetadataArgs = { 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 /** @@ -110,6 +117,7 @@ export function buildMetadata({ imageUrl, locale, meta, + noindex, order, pageTitle, prefix, @@ -163,7 +171,7 @@ export function buildMetadata({ // 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). - ...(meta?.noindex + ...(noindex || meta?.noindex ? { robots: { follow: true, index: false } } : { robots: { diff --git a/src/modules/seo/buildNoindexField.ts b/src/modules/seo/buildNoindexField.ts index d613921..34aca8a 100644 --- a/src/modules/seo/buildNoindexField.ts +++ b/src/modules/seo/buildNoindexField.ts @@ -1,54 +1,29 @@ -import type { CheckboxField, Field, FieldHook } from 'payload' +import type { CheckboxField, Field } from 'payload' type BuildNoindexFieldArgs = { /** Help text under the checkbox. */ description?: string - /** Sidebar label. Default 'Wyklucz z indeksowania (noindex)'. */ + /** Sidebar label. Default 'Exclude from indexing (noindex)'. */ label?: string - /** - * Dotted path, inside the document, that the SEO read path (metadata + - * sitemap) consumes. Default 'meta.noindex' — the plugin-seo `meta` group. - * The checkbox value is mirrored here on every save, so editors toggle one - * friendly switch and the machinery reads a stable location. - */ - metaPath?: string /** Field name for the editor-facing checkbox. Default 'noindex'. */ name?: string /** Extend/override the generated checkbox (position, access, etc.). */ overrides?: Partial } -/** Read a dotted path (e.g. 'meta.noindex') off a loosely-typed object. */ -function readPath(obj: null | Record | undefined, path: string[]): unknown { - let cur: unknown = obj - for (const key of path) { - if (cur == null || typeof cur !== 'object') {return undefined} - cur = (cur as Record)[key] - } - return cur -} - -/** Write a dotted path, creating intermediate objects as needed. */ -function writePath(obj: Record, path: string[], value: unknown): void { - let cur: Record = obj - for (let i = 0; i < path.length - 1; i++) { - const key = path[i] - const next = cur[key] - if (next == null || typeof next !== 'object') {cur[key] = {}} - cur = cur[key] as Record - } - cur[path[path.length - 1]] = value -} - /** - * A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the - * sitemap and metadata generators actually read). Replaces the hand-rolled - * checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …` - * glue copied into every project — no `any`, one source of truth for editors, - * one stable read location for the engine. + * A top-level sidebar `noindex` checkbox. When ticked, the page is excluded from + * `sitemap.xml`, `llms.txt`, site search, and gets `robots: noindex, follow` — + * ALL automatically, no per-project filtering. * - * Idempotent and order-independent: if either the checkbox OR an existing - * `meta.noindex` is set, the page ends up noindex; the two can't drift apart. + * Why top-level (not mirrored into `meta.noindex`): plugin-seo's `meta` group + * declares only title/description/image, so Payload silently strips any extra + * key (`meta.noindex`) during sanitization — an earlier version mirrored there + * and the value vanished, leaking noindex pages into the sitemap. The value now + * lives on this top-level field, which persists; every reader in the kit + * (buildSitemapEntries, buildMetadata/createPageMetadata, buildLlmsTxt, + * searchContent) checks `doc.noindex` (and still tolerates a legacy + * `meta.noindex`). One field, one source of truth, zero project glue. * * // collections/Pages.ts * import { buildNoindexField } from '@intecion/ipal-kit' @@ -57,23 +32,12 @@ function writePath(obj: Record, path: string[], value: unknown) export function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field { const { name = 'noindex', - description = 'Check to exclude this page from indexing (robots: noindex, follow) and from sitemap.xml.', + description = 'Check to exclude this page from indexing (robots: noindex, follow), the sitemap, llms.txt and site search.', label = 'Exclude from indexing (noindex)', - metaPath = 'meta.noindex', overrides = {}, } = args - const segments = metaPath.split('.') - - const mirror: FieldHook = ({ data, value }) => { - const shouldNoindex = Boolean(value ?? readPath(data as Record, segments)) - if (data && typeof data === 'object') { - writePath(data as Record, segments, shouldNoindex) - } - return shouldNoindex - } - - const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides + const { admin: adminOverrides, ...restOverrides } = overrides return { name, @@ -84,11 +48,6 @@ export function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field { ...adminOverrides, }, defaultValue: false, - hooks: { - ...hooksOverrides, - // mirror runs first, then any project-supplied beforeChange hooks. - beforeChange: [mirror, ...(hooksOverrides?.beforeChange ?? [])], - }, label, ...restOverrides, } as CheckboxField diff --git a/src/modules/seo/buildSitemapEntries.ts b/src/modules/seo/buildSitemapEntries.ts index ac86842..63014dc 100644 --- a/src/modules/seo/buildSitemapEntries.ts +++ b/src/modules/seo/buildSitemapEntries.ts @@ -52,6 +52,8 @@ type DocRow = { _status?: string id: number | string meta?: { noindex?: boolean } | null + /** Top-level checkbox (buildNoindexField) — the field that actually persists. */ + noindex?: boolean | null slug?: unknown updatedAt?: string } @@ -78,7 +80,11 @@ function hasExcludedSlug(slug: unknown): boolean { /** Skip drafts, noindex, and system/error pages (404 etc.). */ function isIndexable(doc: DocRow): boolean { if (doc._status && doc._status !== 'published') {return false} - if (doc.meta?.noindex) {return false} + // Check BOTH the top-level checkbox (buildNoindexField, the field that + // persists) AND meta.noindex — plugin-seo's meta group doesn't declare + // noindex, so a mirror into meta.noindex is stripped on save. Reading both + // makes exclusion automatic regardless of where the flag ended up. + if (doc.noindex || doc.meta?.noindex) {return false} if (hasExcludedSlug(doc.slug)) {return false} return true } diff --git a/src/modules/seo/createPageMetadata.ts b/src/modules/seo/createPageMetadata.ts index 7f43138..744b80f 100644 --- a/src/modules/seo/createPageMetadata.ts +++ b/src/modules/seo/createPageMetadata.ts @@ -43,6 +43,8 @@ type PageMetadataContext = { type DocShape = { id: number | string meta?: null | SeoMeta + /** Top-level noindex checkbox (buildNoindexField) — the field that persists. */ + noindex?: boolean | null /** The document's own title (page name), used as the fallback page title. */ title?: null | string } @@ -153,6 +155,7 @@ export function createPageMetadata(args: CreatePageMetadataArgs) { ...base, imageUrl: resolveOgImage(doc), meta: doc.meta, + noindex: doc.noindex, pageTitle: doc.title, prefix, query,