From dc761164d9909ef63d9202f7856a8ab753236d13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:13:57 +0200 Subject: [PATCH] SEO: project overrides (sitemapEntries, sitemapOptions, underConstructionSeo, searchSettings fn); seo-check follows sitemap index - createContentHelpers: sitemapEntries transform has the last word, sitemapOptions passes maxUrls/cacheControl/memoSeconds to sitemapRoute, underConstructionSeo: false turns the construction filter off - seo.searchSettings accepts a function over the default fields - ipal-seo-check: reads sitemap index parts, reports 503 sitemap, warns on missing Google/Bing verification (skip key: verification) - docs/seo.md updated Co-Authored-By: Claude Opus 5.5 --- docs/agent/skills/ipal-seo-check/SKILL.md | 13 +++++-- .../ipal-seo-check/scripts/seo-check.mjs | 34 ++++++++++++++++--- docs/seo.md | 18 ++++++++-- src/modules/frontend/createContentHelpers.ts | 31 +++++++++++++---- src/modules/seo/types.ts | 7 ++-- src/plugin.ts | 9 ++++- test/seoIntegration.test.ts | 14 ++++++++ test/seoSearch.test.ts | 9 +++++ 8 files changed, 117 insertions(+), 18 deletions(-) diff --git a/docs/agent/skills/ipal-seo-check/SKILL.md b/docs/agent/skills/ipal-seo-check/SKILL.md index 037ef1b..af5b1b6 100644 --- a/docs/agent/skills/ipal-seo-check/SKILL.md +++ b/docs/agent/skills/ipal-seo-check/SKILL.md @@ -1,6 +1,6 @@ --- name: ipal-seo-check -description: Checks a running ipal-kit site the way Googlebot and AI agents see it — metadata inside (not streamed to body), title, description, self canonical, hreflang with x-default, noindex pages leaking into the sitemap, error pages in the sitemap, robots.txt, soft 404s, favicon, JSON-LD, and GEO (llms.txt, llms-full.txt, Markdown version, text/markdown alternate, MCP server, AI bots in robots, health). Use after building pages, before handing over, after deploys, after an ipal-kit upgrade, and whenever SEO, indexing, Search Console or "Google doesn't see" problems come up. +description: Checks a running ipal-kit site the way Googlebot and AI agents see it — metadata inside (not streamed to body), title, description, self canonical, hreflang with x-default, noindex pages leaking into the sitemap, error pages in the sitemap, sitemap index parts, Search Console / Bing verification tags, robots.txt, soft 404s, favicon, JSON-LD, and GEO (llms.txt, llms-full.txt, Markdown version, text/markdown alternate, MCP server, AI bots in robots, health). Use after building pages, before handing over, after deploys, after an ipal-kit upgrade, and whenever SEO, indexing, Search Console or "Google doesn't see" problems come up. --- # ipal-seo-check @@ -31,11 +31,18 @@ Sprawdza **działającą** aplikację, nie kod — dokładnie to, co dostaje Goo | no JSON-LD structured data | brak `` / `` w `[locale]/layout.tsx` albo pusta nazwa w Site Settings | | `/llms.txt` / `/llms-full.txt` → 404 | brak trasy (`export { llmsRoute as GET }` / `llmsFullRoute` z `lib/content`) | | Markdown version `/md/…` → 404 | brak `src/app/md/[locale]/[[...slug]]/route.ts`; strona noindex/draft | +| `sitemap.xml → 503` | baza niedostępna przy budowaniu sitemapy (`sitemapRoute` zwraca 503 + Retry-After zamiast pustej) — sprawdź `DATABASE_URL` / zdrowie bazy | +| sitemap index parts not 200 | serwis > `maxUrls` (10 000) → `/sitemap.xml` to index; części `?part=N` muszą odpowiadać 200 — własna trasa bez obsługi `part` albo cache CDN ze starą liczbą części | | MCP not answering initialize | brak `src/app/api/mcp/route.ts` albo Cloudflare Access bez Bypass (mcp.md) | -3. `[WARNING]` oceń: brak opisu / zduplikowane tytuły to **treść w panelu** — +3. `no search-console verification meta tag` (WARNING) — wklej kod w **Site Settings → + Search & AI** (Google Search Console, Bing Webmaster). Weryfikacja przez DNS → dopisz + `verification` do `ipal-audit-skip:` w `AGENTS.md`. + `robots.txt blocks AI bots` — sprawdź też Site Settings → Search & AI → AI crawlers + (gdy projekt używa `getRobots`, redaktor mógł zmienić politykę). +4. `[WARNING]` oceń: brak opisu / zduplikowane tytuły to **treść w panelu** — uzupełnij z briefu albo wypisz w raporcie dla klienta. -4. Uruchom ponownie aż `0 error(s)`. +5. Uruchom ponownie aż `0 error(s)`. ## Czego skrypt nie sprawdzi Search Console (indeksacja, ręczne działania), Core Web Vitals, poprawność diff --git a/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs b/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs index 10e8d95..110341c 100644 --- a/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs +++ b/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs @@ -73,14 +73,30 @@ else { const sitemap = await get('/sitemap.xml') let urls = [] let hasAlternates = false -if (sitemap.res.status !== 200) report('ERROR', `sitemap.xml → ${sitemap.res.status}`, 'export sitemap from lib/content + force-dynamic') +const locs = (xml) => [...xml.matchAll(/\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1].replace(/&/g, '&')) +if (sitemap.res.status === 503) report('ERROR', 'sitemap.xml → 503', 'the database was unreachable while building it (sitemapRoute answers 503 + Retry-After) — check DATABASE_URL / DB health') +else if (sitemap.res.status !== 200) report('ERROR', `sitemap.xml → ${sitemap.res.status}`, 'export sitemapRoute (or sitemap) from lib/content + force-dynamic') else { - urls = [...new Set([...sitemap.text.matchAll(/\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1]))] - hasAlternates = /hreflang=/.test(sitemap.text) + let xml = sitemap.text + // Large sites: /sitemap.xml is a of parts (?part=N) — read every part. + if (/ null) + if (!r || r.res.status !== 200) broken.push(`${part} → ${r?.res.status ?? 'unreachable'}`) + else xml += r.text + } + console.log(`sitemap index: ${parts.length} part(s)`) + if (broken.length) report('ERROR', 'sitemap index parts not 200', 'every must answer 200 (seo.md → Duży serwis)', broken) + } + urls = [...new Set(locs(xml))] + hasAlternates = /hreflang=/.test(xml) if (urls.length === 0) report('ERROR', 'sitemap.xml is empty', 'DB unreachable at build without force-dynamic, or no published pages') const foreign = urls.filter((u) => !u.startsWith('http') || /localhost|127\.0\.0\.1/.test(u) !== /localhost|127\.0\.0\.1/.test(origin)) if (foreign.length) report('ERROR', 'sitemap URLs relative or on another host', 'NEXT_PUBLIC_SERVER_URL / baseUrl', foreign.slice(0, 5)) - if (/(\/404|\/500|not-found)(\/|<|$)/.test(sitemap.text)) report('ERROR', 'error pages listed in the sitemap', 'pages.md — 404 page is excluded by ID') + if (/(\/404|\/500|not-found)(\/|<|$)/.test(xml)) report('ERROR', 'error pages listed in the sitemap', 'pages.md — 404 page is excluded by ID') } // --- 4. sampled pages ----------------------------------------------------- @@ -209,6 +225,16 @@ if (issues.noLinks.length) report('WARNING', 'pages without internal links', 'li if (!skipped('jsonld') && issues.jsonLd.length) report('ERROR', 'no JSON-LD structured data', ' WebSite + Organization in [locale]/layout.tsx (AGENT.md §0b.4)', issues.jsonLd.slice(0, 5)) if (!skipped('markdown') && issues.mdAlt.length) report('WARNING', 'no text/markdown alternate link in head', 'createContentHelpers({ markdownAlternate: true }) (AGENT.md §0b.6)', issues.mdAlt.slice(0, 3)) +// --- 4b. Search Console / Bing verification (Site Settings → Search & AI) ---- +if (!skipped('verification') && sample.length) { + const page = await get(sample[0]).catch(() => null) + const head = page?.text.split(/<\/head>/i)[0] ?? '' + const missing = [['google-site-verification', 'Google Search Console'], ['msvalidate.01', 'Bing Webmaster Tools']] + .filter(([name]) => !new RegExp(`]+name="${name}"`, 'i').test(head)) + .map(([, label]) => label) + if (missing.length) report('WARNING', 'no search-console verification meta tag', 'paste the code in Site Settings → Search & AI (or verify by DNS and add `verification` to ipal-audit-skip)', missing) +} + // --- 5. 404 --------------------------------------------------------------- const firstLocale = [...byLocale.keys()].find((l) => l && l.length <= 5) ?? '' for (const path of [`/${firstLocale ? firstLocale + '/' : ''}ipal-seo-check-${Date.now()}`]) { diff --git a/docs/seo.md b/docs/seo.md index d588502..8a6d9bd 100644 --- a/docs/seo.md +++ b/docs/seo.md @@ -345,9 +345,21 @@ z każdego URL-a kilka linii): | `memoSeconds` | `300` | ile sekund proces trzyma zbudowaną listę (index i części nie budują jej od nowa); `0` = wyłączone | ```ts -createSitemapRouteHandler(sitemap, { maxUrls: 5000, memoSeconds: 0 }) +createContentHelpers({ …, sitemapOptions: { maxUrls: 5000, memoSeconds: 0 } }) // sitemapRoute +createSitemapRouteHandler(sitemap, { maxUrls: 5000, memoSeconds: 0 }) // własna trasa ``` +Ostatnie słowo ma projekt — `sitemapEntries` dostaje wpisy pluginu i zwraca listę do +publikacji (dodaj adresy własnych tras, usuń, ustaw `priority`): + +```ts +createContentHelpers({ …, + sitemapEntries: (entries) => [...entries, { url: `${origin}/kalkulator`, lastModified: new Date() }], +}) +``` + +Filtr „Under construction” w sitemapie i llms.txt wyłączasz `underConstructionSeo: false`. + Błąd bazy w runtime → **503 + `Retry-After: 300`** (crawler wróci), nie pusta sitemapa z 200 („strona nie ma podstron”). Pusta odpowiedź i błąd nigdy nie idą z cache. Wyjątek: `next build` (`NEXT_PHASE=phase-production-build`) dalej dostaje pustą, @@ -1236,7 +1248,9 @@ Oba tak samo dobre dla Google — to kwestia czytelności dla człowieka, nie SE ## Search & AI — weryfikacja Search Console, boty AI, notka llms.txt (1.13) Zakładka **Site Settings → Search & AI** (włączona domyślnie; puste pola nic nie -zmieniają; `ipalKit({ seo: { …, searchSettings: false } })` ją usuwa): +zmieniają; `ipalKit({ seo: { …, searchSettings: false } })` ją usuwa; funkcja +`searchSettings: (fields) => fields` dostaje pola pluginu i zwraca własne — dodaj, usuń, +zmień etykiety; nazwy `searchVerification` / `aiCrawlers` / `llmsIntro` czytają helpery): | Pole | Gdzie trafia | |---|---| diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index f4404a8..9ac9eae 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -11,7 +11,7 @@ import type { I18nConfig } from '../i18n/index.js' import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js' import type { CreateMcpRouteArgs } from '../mcp/createMcpRoute.js' import type { FormNotificationTexts } from '../notifications/types.js' -import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapStyleOptions } from '../seo/index.js' +import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapRouteOptions, SitemapStyleOptions } from '../seo/index.js' import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js' import { getConsentTexts } from '../consent/getConsentTexts.js' @@ -96,8 +96,19 @@ type CreateContentHelpersArgs = { * LocalBusiness from the Company global); `false` = none. */ siteJsonLd?: ((ctx: { baseUrl: string; locale: string; settings: Record }) => Promise[]> | Record[]) | false + /** + * Last word on the sitemap: gets the plugin's entries (after the construction + * filter) and returns the list to publish — add URLs from your own routes, + * drop or reorder some, set priority. Used by `sitemap` and `sitemapRoute`. + */ + sitemapEntries?: (entries: SitemapEntry[]) => Promise | SitemapEntry[] /** Image URLs of a document for the sitemap (Google Images). Default: its SEO share image. */ sitemapImages?: (doc: Record) => (null | string | undefined)[] + /** + * `sitemapRoute` behaviour: `maxUrls` (split into an index, default 10 000), + * `cacheControl` (string or false), `memoSeconds` (default 300, 0 = off). + */ + sitemapOptions?: Pick /** * Browser look of `sitemapRoute` (/sitemap.xml). Default: built-in style, * header "XML Sitemap", credit "Technology by Intecion.com". `false` = raw XML. @@ -105,6 +116,11 @@ type CreateContentHelpersArgs = { sitemapStyle?: false | SitemapStyleOptions /** Field with the AI summary (buildSummaryField) — llms.txt and MCP prefer it. */ summaryField?: string + /** + * While Site Settings → Under construction is on, the sitemap and llms.txt + * list only the pages still open. Default true; false lists everything. + */ + underConstructionSeo?: boolean } /** What an entry's own JSON-LD builder gets (PageJsonLdOptions.entries). */ @@ -182,9 +198,12 @@ export function createContentHelpers({ robots: robotsOptions, settingsSlug = 'site-settings', siteJsonLd, + sitemapEntries: transformSitemap, sitemapImages, + sitemapOptions, sitemapStyle, summaryField, + underConstructionSeo = true, }: CreateContentHelpersArgs) { const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '' const getCachedPayload = cache( @@ -447,9 +466,9 @@ export function createContentHelpers({ // Under construction: list only the pages visitors can still open — the // rest redirect to the homepage notice, which crawlers would index. const open = await constructionPaths() - if (!open) {return entries} - const allowed = new Set(open.map(normalizePath)) - return entries.filter((e) => allowed.has(normalizePath(pathOf(e.url)))) + const allowed = open ? new Set(open.map(normalizePath)) : null + const visible = allowed ? entries.filter((e) => allowed.has(normalizePath(pathOf(e.url)))) : entries + return transformSitemap ? await transformSitemap(visible) : visible } catch (error) { // At runtime a failure is an error (the sitemap route answers 503, so // crawlers retry) — an empty sitemap would read as "no pages". @@ -636,7 +655,7 @@ export function createContentHelpers({ * export { sitemapRoute as GET } from '@/lib/content' * export const dynamic = 'force-dynamic' */ - const sitemapRoute = createSitemapRouteHandler(sitemap, { style: sitemapStyle ?? {} }) + const sitemapRoute = createSitemapRouteHandler(sitemap, { ...sitemapOptions, style: sitemapStyle ?? {} }) const needI18n = (what: string): I18nConfig => { if (!i18n) {throw new Error(`[ipal] createContentHelpers: pass \`i18n\` to use ${what}.`)} @@ -737,7 +756,7 @@ export function createContentHelpers({ * null when the site is open or the setting can't be read. */ const constructionPaths = async (): Promise => { - if (!i18n) {return null} + if (!i18n || !underConstructionSeo) {return null} try { const mode = await getConstructionMode(i18n.defaultLocale) return mode.enabled ? mode.allowedPaths : null diff --git a/src/modules/seo/types.ts b/src/modules/seo/types.ts index bbcc8d6..be15a84 100644 --- a/src/modules/seo/types.ts +++ b/src/modules/seo/types.ts @@ -39,9 +39,12 @@ export type SeoOption = { /** * Site Settings → "Search & AI" tab: Search Console / Bing / Yandex * verification, AI crawler policy for robots.txt (getRobots), llms.txt note. - * On by default (empty fields change nothing); false removes the tab. + * On by default (empty fields change nothing); false removes the tab; a + * function gets the plugin's fields and returns the tab's fields (add, drop, + * relabel). Keep the field names the readers use (searchVerification, + * aiCrawlers, llmsIntro) or read your own fields in your routes. */ - searchSettings?: false + searchSettings?: ((defaults: Field[]) => Field[]) | false } /** diff --git a/src/plugin.ts b/src/plugin.ts index 6e04014..d42ec02 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -219,7 +219,14 @@ export const ipalKit = (options: IpalOptions): Plugin => { additionalFields: options.siteSettingsFields, ...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}), ...(options.forms?.emailLayout ? { emailFields: emailSettingsFields } : {}), - ...(options.seo?.searchSettings === false ? {} : { searchFields: searchSettingsFields }), + ...(options.seo?.searchSettings === false + ? {} + : { + searchFields: + typeof options.seo?.searchSettings === 'function' + ? options.seo.searchSettings(searchSettingsFields) + : searchSettingsFields, + }), systemPageFields, }), buildSiteIntegrations({ additionalFields: options.integrationsFields }), diff --git a/test/seoIntegration.test.ts b/test/seoIntegration.test.ts index 498d916..53687d6 100644 --- a/test/seoIntegration.test.ts +++ b/test/seoIntegration.test.ts @@ -71,6 +71,18 @@ describe('SEO outputs against a real database', () => { expect(await urls()).toEqual(['https://acme.pl/en', 'https://acme.pl/en/about', 'https://acme.pl/pl', 'https://acme.pl/pl/o-nas']) }) + test('project overrides: sitemapEntries has the last word', async () => { + const h = createContentHelpers({ + baseUrl: 'https://acme.pl', + config: configPromise, + i18n, + sitemapEntries: (entries) => [...entries.filter((e) => !e.url.endsWith('/en')), { url: 'https://acme.pl/custom' }], + }) + const list = (await h.sitemap()).map((e) => e.url) + expect(list).toContain('https://acme.pl/custom') + expect(list).not.toContain('https://acme.pl/en') + }) + test('verification codes and AI crawler rules from Site Settings → Search & AI', async () => { await payload.updateGlobal({ slug: 'site-settings' as never, @@ -98,6 +110,8 @@ describe('SEO outputs against a real database', () => { expect(await urls()).toEqual(['https://acme.pl/en', 'https://acme.pl/pl']) const llms = await (await helpers().llmsRoute()).text() expect(llms).not.toContain('o-nas') + const unfiltered = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, underConstructionSeo: false }) + expect(await unfiltered.sitemap()).toHaveLength(4) await payload.updateGlobal({ slug: 'site-settings' as never, data: { construction: { enabled: false } } as never, locale: 'pl' as never }) expect(await urls()).toHaveLength(4) }) diff --git a/test/seoSearch.test.ts b/test/seoSearch.test.ts index bd5c2eb..2fa829e 100644 --- a/test/seoSearch.test.ts +++ b/test/seoSearch.test.ts @@ -307,5 +307,14 @@ describe('plugin: Search & AI tab', () => { twoFactor: false, })(base()) expect(tabs(off)).not.toContain('Search & AI') + const custom = await ipalKit({ + access: { authCollection: 'users' }, + i18n: config, + seo: { collections: [], searchSettings: (fields) => fields.filter((f) => 'name' in f && f.name !== 'llmsIntro') }, + twoFactor: false, + })(base()) + const settings = custom.globals?.find((g) => g.slug === 'site-settings') + const tab = (settings?.fields[0] as { tabs: { fields: { name?: string }[]; label: string }[] }).tabs.find((t) => t.label === 'Search & AI') + expect(tab?.fields.map((f) => f.name)).toEqual(['searchVerification', 'aiCrawlers']) }) })