diff --git a/apps/web/content/docs/content-engine/seo.mdx b/apps/web/content/docs/content-engine/seo.mdx index 463829e602..1714c8b398 100644 --- a/apps/web/content/docs/content-engine/seo.mdx +++ b/apps/web/content/docs/content-engine/seo.mdx @@ -136,7 +136,7 @@ The resolve route reports the choice under `openGraph.image`: } ``` -Colours, fonts, templates per content type and caching are covered in [Social images](/docs/dev/social-images). +Colours, fonts, templates per content type and caching are covered in [Social images](/docs/dev/seo/social-images) and [Social card templates](/docs/dev/seo/social-image-templates). ## Hide a record from search engines @@ -176,7 +176,36 @@ delivery: { ## Sitemap -`delivery.sitemap` adds a public route that lists every published URL of the content type, oldest record first. Pass `true` or `{ changeFrequency, priority }`. It needs `publication: true`, since a sitemap lists only what readers can reach. +`delivery.sitemap` puts every published record of the content type in the site's `/sitemap.xml`. Pass `true` or `{ changeFrequency, priority }`. It needs `publication: true`, since a sitemap lists only what readers can reach. + +```ts title="plugins/newsroom/src/content/story.ts" +delivery: { + sitemap: { changeFrequency: 'weekly', priority: 0.7 }, // [!code ++] +}, +``` + +That is all a plugin author writes. When an app turns on [site SEO](/docs/dev/seo/setup), its build finds every content type with `delivery.sitemap` in the configured plugins and writes them to `src/sitemap-sources.gen.ts`. `withSeo` then reads each one's route as a guest and publishes one child file per language, such as `/sitemap-stories-1.xml` or `/sitemap-blog-pl-1.xml`. A content type whose public API path is shared with another plugin's gets the plugin id in its file name, and two names that would still collide fail the build. + +### Check that a record is listed + +With the newsroom plugin and `seo: { indexing: true }`: + +1. Publish a story, then open the index and the story file: + + ```bash + curl -s http://localhost:3000/sitemap.xml + curl -s http://localhost:3000/sitemap-stories-1.xml | grep hello-content-engine + ``` + + The story's `` is there, with ``, `` and ``. + +2. Set the story's `noIndexField` to `true` (`newsroom.story` calls it `noIndex`), or [hide](/docs/content-engine/content-visibility) the story, and run the second command again. It prints nothing: the change expired the file, and the new copy leaves the record out. + +A translation appears in its own language's file only once it is published, and the XML is the same when a signed-in admin requests it. + +### Read the sitemap route yourself + +The generated sitemap reads a public route that every content type with `delivery.sitemap` gets. Use it directly when you assemble XML in an app that does not use `withSeo`. ```bash curl "http://localhost:3000/api/newsroom/content/stories/delivery/sitemap?cursor=1&limit=1" @@ -224,7 +253,7 @@ curl "http://localhost:3000/api/@vitnode/blog/content/blog/delivery/sitemap?loca } ``` -The app's `/sitemap.xml` does not read these routes for you, so add the entries where you build it. `contentSitemapXml` from `@vitnode/core/content` writes the XML: +To build the XML yourself, `contentSitemapXml` from `@vitnode/core/content` writes it: ```ts import { diff --git a/apps/web/content/docs/dev/configuration.mdx b/apps/web/content/docs/dev/configuration.mdx index 982373d18a..2dc42a57ce 100644 --- a/apps/web/content/docs/dev/configuration.mdx +++ b/apps/web/content/docs/dev/configuration.mdx @@ -13,7 +13,7 @@ files, filled in with working defaults. | File | Holds | Runs in | Section | | :----------------------------- | :----------------------------------------------------------------- | :------------------------------------- | :-------------------------------------------- | | `src/vitnode.config.ts` | Locales, metadata, logo, menus, theme, enabled plugins | Browser, server **and** your Vite build | [Shared config](#shared-config) | -| `src/vitnode.server.config.ts` | Message loaders | Server only | [Server config](#server-config) | +| `src/vitnode.server.config.ts` | Message loaders, SEO policy | Server only | [Server config](#server-config) | | `src/start.ts` | The request middleware | Server | [Request pipeline](#request-pipeline) | | `vite.config.ts` | The `vitnode()` Vite plugin and its options | Vite (dev and build) | [Vite config](#vite-config) | @@ -56,7 +56,7 @@ export const vitNodeConfig = buildConfig({ | Name | Type | Required | Default | Description | | :---------------- | :----------------------- | :------- | :------------- | :----------------------------------------------------------------------------------------------- | | `i18n` | object | Yes | - | Languages and locale routing. See [Languages & Localization](/docs/dev/i18n) | -| `metadata` | object | Yes | - | Site title, used in page titles as `{page} - {shortTitle ?? title}`. `metadata.ogImage` sets the default social image and `metadata.twitterSite` the X handle, see [Social images](/docs/dev/social-images) | +| `metadata` | object | Yes | - | Site title, used in page titles as `{page} - {shortTitle ?? title}`. `metadata.ogImage` sets the default social image and `metadata.twitterSite` the X handle, see [Social images](/docs/dev/seo/social-images) | | `plugins` | `buildPlugin()` results | Yes | - | The installed plugins' frontend factories. See [Enabled plugins](#enabled-plugins) | | `editor` | object | No | - | Settings shared by every `Editor` in the app | | `logo` | component | No | VitNode logo | The header logo. See [Logo](#logo) | @@ -191,6 +191,7 @@ of those modules, and that is the part worth knowing: | `src/blocks.gen.ts` | the plugin's `widgets` module | only by routes that render blocks | | `src/package-messages.gen.ts` | the factory's `localeFiles` | per request, one locale at a time | | `src/page-cache.gen.ts` | route `cache` options | by `src/server.ts`, to pick each page's HTML cache policy | +| `src/sitemap-sources.gen.ts` | content types' `delivery.sitemap` | by `src/server.ts`, to list their records in `/sitemap.xml` | | `src/api-registry.gen.ts` | the plugin's `config.api` | never. Type-only, it teaches the fetcher which plugins exist | | `src/plugin-inventory.gen.ts` | the factory's `metadata` | by the API only, through `buildApiConfig({ frontendPlugins })` | @@ -261,6 +262,29 @@ export const loadIntlMessages = createIntlMessagesLoader(vitNodeServerConfig) where you reword a string a package translates differently to how you want it. [Languages & Localization](/docs/dev/i18n) covers both. +### Options + +| Name | Type | Required | Default | Description | +| ----------------- | ----------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------- | +| `config` | `VitNodeConfig` | Yes | - | The shared config from `src/vitnode.config.ts`. | +| `messages` | `AppMessagesMap` | No | - | The app's own translations, merged over the packages' strings. | +| `packageMessages` | `Record` | No | - | The generated `src/package-messages.gen.ts`. | +| `seo` | `VitNodeSeoConfig` | No | `{ indexing: true }` | Search indexing, `/robots.txt`, `/sitemap.xml` and AI crawler rules, served by `withSeo`. | + +`seo` is served by `withSeo` in `src/server.ts` and defaults `indexing` to `true`: + +```ts title="apps/web/src/vitnode.server.config.ts" +export const vitNodeServerConfig = buildServerConfig({ + config: vitNodeConfig, + messages: appMessages, + packageMessages, + seo: { sitemap: { paths: ['/', '/plugins'] } }, // [!code ++] +}) +``` + +[Set up SEO](/docs/dev/seo/setup) turns it on, and the [SEO reference](/docs/dev/seo/reference) +lists every option. + `src/vitnode.api.config.ts` configures the Hono app at `/api/*` - the database, storage, email, Redis. In a single app it reads `vitNodeConfig.i18n` diff --git a/apps/web/content/docs/dev/i18n/localized-urls-advanced.mdx b/apps/web/content/docs/dev/i18n/localized-urls-advanced.mdx index b026527369..a2f46e9790 100644 --- a/apps/web/content/docs/dev/i18n/localized-urls-advanced.mdx +++ b/apps/web/content/docs/dev/i18n/localized-urls-advanced.mdx @@ -1,6 +1,6 @@ --- title: Advanced localized URLs -description: Serve each language of a VitNode app from its own domain, see how a request's language is chosen, add hreflang and canonical links and fix URL errors. +description: Serve each language of a VitNode app from its own domain, see how a request's language is chosen, how Content Engine URLs follow along and fix URL errors. icon: Globe2 --- @@ -113,78 +113,7 @@ Adding a translation doesn't break links people already shared. The old English ## hreflang and canonical links -A plugin page declares its alternates from `head()`, as **internal** paths, meaning the English route with each language's own values filled in. Only include translations that are actually published. - -This example assumes an articles plugin whose `fetchArticle` helper returns one article: - -```tsx title="plugins/articles/src/pages/article-page.tsx" -export const route = defineRoute({ - load: async ({ params }) => await fetchArticle(params.slug), - head: ({ loaderData }) => ({ - title: loaderData?.title, - // [!code ++:4] - alternates: { - en: '/articles/hello-world', - pl: '/articles/witaj-swiecie', - }, - }), -}) -``` - -VitNode turns that into a `canonical` link, one `alternate` per language and an `x-default` for the default locale, all absolute and spelled for each language: `https://vitnode.pl/artykuly/witaj-swiecie` with domains, or your `VITNODE_WEB_URL` plus `/pl/artykuly/witaj-swiecie` without them. - - - Pass `/articles/witaj-swiecie`, not `/pl/artykuly/witaj-swiecie`. VitNode - always reads `alternates` as internal paths, so a public one would be - translated a second time. The delivery API gives you both. Each alternate has a public - `path` and an `internalPath`, and metadata has `canonicalInternalPath`. - - -A page backed by the Content System doesn't write any of this by hand. `@vitnode/core/tanstack/content` turns a delivery response into page data and a head. That covers redirects, 404s, the SEO title and description, and the internal alternates of every published translation. Blog's own post page is built this way (excerpt): - -```tsx title="plugins/blog/src/pages/post-page.tsx" -import { - contentDeliveryPage, - contentDeliveryPageHead, -} from '@vitnode/core/tanstack/content' -import { defineRoute } from '@vitnode/core/tanstack/plugin-routes' - -import { blogPostQueryOptions } from './post-query' - -export const route = defineRoute({ - load: async ({ context, params }) => - contentDeliveryPage( - await context.queryClient.query( - blogPostQueryOptions({ locale: context.locale, slug: params.slug }), - ), - ), - head: ({ loaderData }) => - contentDeliveryPageHead(loaderData?.metadata, { - title: loaderData?.item.title, - }), -}) -``` - -`blogPostQueryOptions` calls the content type's public routes, `/delivery/resolve/{slug}` and `/{slug}` under `module: 'content/blog'`, and returns the resolution and the localized item that `contentDeliveryPage` expects. - -A retired slug answers with a 308 to the current one, and an unknown slug is a 404. - -App routes can do the same with `pageHead` or `localeAlternateLinks` from `@vitnode/core/tanstack/metadata`: - -```tsx title="apps/web/src/routes/pricing.tsx" -import { localeAlternateLinks } from '@vitnode/core/tanstack/metadata' - -export const Route = createFileRoute('/pricing')({ - head: ({ match }) => ({ - links: localeAlternateLinks({ - internalPathname: '/pricing', - locale: match.context.locale, - }), - }), -}) -``` - -`internalPathname` means "the same page in every locale". Pass `alternates: { en: '...', pl: '...' }` instead when the path differs per language. +A translated page declares its other languages with `alternates` in its `head`, as internal paths, and VitNode writes the canonical, `hreflang` and `x-default` links spelled with these rules. See [Canonical and hreflang](/docs/dev/seo/hreflang). ## Translated segments vs localized slugs diff --git a/apps/web/content/docs/dev/meta.json b/apps/web/content/docs/dev/meta.json index 7d4d9f8978..bd0f52db4d 100644 --- a/apps/web/content/docs/dev/meta.json +++ b/apps/web/content/docs/dev/meta.json @@ -26,7 +26,7 @@ "i18n", "navigation", "mobile-navigation", - "social-images", + "seo", "performance", "---Extend VitNode---", "widgets", diff --git a/apps/web/content/docs/dev/routing/route-module.mdx b/apps/web/content/docs/dev/routing/route-module.mdx index 5d70d30bab..f3a9590b95 100644 --- a/apps/web/content/docs/dev/routing/route-module.mdx +++ b/apps/web/content/docs/dev/routing/route-module.mdx @@ -78,11 +78,11 @@ Throw `notFound()` or `redirect()` from `@tanstack/react-router` to answer with | `title` | `string` | The page's own title, already translated. VitNode suffixes it with the site name from `buildConfig({ metadata })`. | | `description` | `string` | The ``. | | `robots` | `'index, follow' \| 'noindex, follow' \| 'noindex, nofollow'` | What a crawler may do. `noindex, follow` keeps a filtered list out of the index while its links still count. | -| `alternates` | `Record` | Internal paths of the page in each language, for canonical and `hreflang` links. See [Advanced localized URLs](/docs/dev/i18n/localized-urls-advanced#hreflang-and-canonical-links). | +| `alternates` | `Record` | Internal paths of the page in each language, for canonical and `hreflang` links. See [Advanced localized URLs](/docs/dev/seo/hreflang). | | `canonical` | `string` | The canonical URL, absolute or a path on the site, for a page without `alternates`. Also becomes `og:url`. | -| `openGraph` | `{ title?, description?, type?, image? }` | Overrides for link previews. `type` is `article`, `profile` or `website` (the default). `image` is `{ url, width?, height?, type?, alt? }`. See [Social images](/docs/dev/social-images). | +| `openGraph` | `{ title?, description?, type?, image? }` | Overrides for link previews. `type` is `article`, `profile` or `website` (the default). `image` is `{ url, width?, height?, type?, alt? }`. See [Social images](/docs/dev/seo/social-images). | -Return only these fields. VitNode turns them into the full set of tags with the app's site metadata. A page with a `title` also gets Open Graph and `twitter:card` tags, with the site's [social image](/docs/dev/social-images) when it sets no `openGraph.image`. +Return only these fields. VitNode turns them into the full set of tags with the app's site metadata. A page with a `title` also gets Open Graph and `twitter:card` tags, with the site's [social image](/docs/dev/seo/social-images) when it sets no `openGraph.image`. ## Translated metadata diff --git a/apps/web/content/docs/dev/seo/ai-crawlers.mdx b/apps/web/content/docs/dev/seo/ai-crawlers.mdx new file mode 100644 index 0000000000..c6dc0818ab --- /dev/null +++ b/apps/web/content/docs/dev/seo/ai-crawlers.mdx @@ -0,0 +1,97 @@ +--- +title: AI crawlers +description: Allow or block OpenAI, Anthropic and Google AI crawlers separately for search and training with seo.crawlers in VitNode's generated robots.txt. +icon: Sparkles +--- + +`seo.crawlers` adds a `User-agent` group to the generated [robots.txt](/docs/dev/seo/robots-txt) for each AI crawler you name. Use it to stay in AI search results while opting out of training, or the other way round. + +This guide assumes [SEO is set up](/docs/dev/seo/setup). + +## Choose per bot + +Each bot you leave out follows `User-agent: *`. Set a bot to `false` to give it its own `Disallow: /` group, or to `true` to give it an explicit allow group: + +```ts title="src/vitnode.server.config.ts" +seo: { + indexing: true, + crawlers: { + openai: { search: true, training: false }, + anthropic: { search: true, training: false }, + googleExtended: false, + }, +}, +``` + +| Option | Bot | Used for | +| ----------------------------- | ------------------ | --------------------------------------------------------- | +| `crawlers.openai.search` | `OAI-SearchBot` | ChatGPT search results | +| `crawlers.openai.training` | `GPTBot` | OpenAI training data | +| `crawlers.anthropic.search` | `Claude-SearchBot` | Claude search results | +| `crawlers.anthropic.training` | `ClaudeBot` | Anthropic training data | +| `crawlers.googleExtended` | `Google-Extended` | Gemini training and grounding, as Google describes it | + +## What robots.txt gets + +The config above adds these groups after `User-agent: *`, shown for a site with English and Polish: + +```txt +User-agent: OAI-SearchBot +Allow: / +Disallow: /admin +Disallow: /settings +Disallow: /pl/settings +Disallow: /modcp +Disallow: /pl/modcp +Disallow: /files +Disallow: /pl/files +Disallow: /login +Disallow: /pl/login +Disallow: /register +Disallow: /pl/register + +User-agent: GPTBot +Disallow: / + +User-agent: Claude-SearchBot +Allow: / +Disallow: /admin +Disallow: /settings +Disallow: /pl/settings +Disallow: /modcp +Disallow: /pl/modcp +Disallow: /files +Disallow: /pl/files +Disallow: /login +Disallow: /pl/login +Disallow: /register +Disallow: /pl/register + +User-agent: ClaudeBot +Disallow: / + +User-agent: Google-Extended +Disallow: / +``` + +An allowed bot gets the same `Disallow` lines as `User-agent: *` because a crawler obeys only the most specific group that names it. Without them, `Allow: /` alone would open the AdminCP to that bot. + +## What these rules can't do + +Crawler rules state a policy that well-behaved bots follow. They do not block HTTP requests, and they do not cover fetches a person starts, such as asking an assistant to open one page. `Google-Extended` never changes how Google Search crawls or ranks the site. + +On Cloudflare, check that the zone's managed robots.txt does not add conflicting rules; see [robots.txt](/docs/dev/seo/robots-txt#check-the-result). + +## Check the result + +Restart the app and look for the group of one bot: + +```bash +curl -s http://localhost:3000/robots.txt | grep -A1 'User-agent: GPTBot' +``` + +With `openai.training: false` it prints `User-agent: GPTBot` followed by `Disallow: /`. + +## Related + +- [SEO reference](/docs/dev/seo/reference#seo-options): every `seo` option and its default. diff --git a/apps/web/content/docs/dev/seo/hreflang.mdx b/apps/web/content/docs/dev/seo/hreflang.mdx new file mode 100644 index 0000000000..d3cf07d0da --- /dev/null +++ b/apps/web/content/docs/dev/seo/hreflang.mdx @@ -0,0 +1,111 @@ +--- +title: Canonical and hreflang +description: Add canonical and hreflang alternate links to translated VitNode pages, so search engines show each reader the page in their language. +icon: Languages +--- + +When a page exists in several languages, `hreflang` links tell search engines which URL serves which language, and the canonical link names the original of each. VitNode writes both from one `alternates` object, spelled with your [localized URL rules](/docs/dev/i18n/localized-urls). + +## Declare alternates on a plugin page + +A plugin page declares its alternates from `head()`, as **internal** paths: the English route with each language's own values filled in. Only include translations that are actually published. + +This example assumes an articles plugin whose `fetchArticle` helper returns one article: + +```tsx title="plugins/articles/src/pages/article-page.tsx" +export const route = defineRoute({ + load: async ({ params }) => await fetchArticle(params.slug), + head: ({ loaderData }) => ({ + title: loaderData?.title, + // [!code ++:4] + alternates: { + en: '/articles/hello-world', + pl: '/articles/witaj-swiecie', + }, + }), +}) +``` + +VitNode turns that into a `canonical` link, one `alternate` per language and an `x-default` for the default locale, all absolute and spelled for each language: `https://vitnode.pl/artykuly/witaj-swiecie` with [a domain per language](/docs/dev/i18n/localized-urls-advanced#a-domain-per-language), or your `VITNODE_WEB_URL` plus `/pl/artykuly/witaj-swiecie` without one. + + + Pass `/articles/witaj-swiecie`, not `/pl/artykuly/witaj-swiecie`. VitNode + always reads `alternates` as internal paths, so a public one would be + translated a second time. The delivery API gives you both. Each alternate has + a public `path` and an `internalPath`, and metadata has + `canonicalInternalPath`. + + +## Content Engine pages + +A page backed by the Content Engine doesn't write any of this by hand. `@vitnode/core/tanstack/content` turns a delivery response into page data and a head. That covers redirects, 404s, the SEO title and description, and the internal alternates of every published translation. Blog's own post page is built this way (excerpt): + +```tsx title="plugins/blog/src/pages/post-page.tsx" +import { + contentDeliveryPage, + contentDeliveryPageHead, +} from '@vitnode/core/tanstack/content' +import { defineRoute } from '@vitnode/core/tanstack/plugin-routes' + +import { blogPostQueryOptions } from './post-query' + +export const route = defineRoute({ + load: async ({ context, params }) => + contentDeliveryPage( + await context.queryClient.query( + blogPostQueryOptions({ locale: context.locale, slug: params.slug }), + ), + ), + head: ({ loaderData }) => + contentDeliveryPageHead(loaderData?.metadata, { + title: loaderData?.item.title, + }), +}) +``` + +`blogPostQueryOptions` calls the content type's public routes, `/delivery/resolve/{slug}` and `/{slug}` under `module: 'content/blog'`, and returns the resolution and the localized item that `contentDeliveryPage` expects. + +A retired slug answers with a `308` to the current one, and an unknown slug is a `404`. [Content SEO](/docs/content-engine/seo#localized-alternates-and-hreflang) shows the links a localized record gets. + +## App routes + +App routes do the same with `pageHead` or `localeAlternateLinks` from `@vitnode/core/tanstack/metadata`: + +```tsx title="apps/web/src/routes/pricing.tsx" +import { localeAlternateLinks } from '@vitnode/core/tanstack/metadata' + +export const Route = createFileRoute('/pricing')({ + head: ({ match }) => ({ + links: localeAlternateLinks({ + internalPathname: '/pricing', + locale: match.context.locale, + }), + }), +}) +``` + +`internalPathname` means "the same page in every locale". Pass `alternates: { en: '...', pl: '...' }` instead when the path differs per language. + +A page in one language only needs no alternates. Give it a `canonical` in its [page metadata](/docs/dev/seo/page-metadata#point-to-the-canonical-url). + +## Check the result + +Print the links of a translated page: + +```bash +curl -s http://localhost:3000/blog/article/english-title | grep -oE ']*rel="(canonical|alternate)"[^>]*>' +``` + +```html + + + + +``` + +The canonical link is the page's own language, and every alternate opens a published translation. + +## Related + +- [Advanced localized URLs](/docs/dev/i18n/localized-urls-advanced): domains per language and translated segments. +- [Sitemap](/docs/dev/seo/sitemap#add-your-own-pages): the same alternates in `/sitemap.xml`. diff --git a/apps/web/content/docs/dev/seo/index.mdx b/apps/web/content/docs/dev/seo/index.mdx new file mode 100644 index 0000000000..94d7dc275d --- /dev/null +++ b/apps/web/content/docs/dev/seo/index.mdx @@ -0,0 +1,40 @@ +--- +title: SEO +description: How a VitNode site works with search engines, AI crawlers and link previews - indexing, robots.txt, sitemaps, page metadata, hreflang and social images. +icon: SearchCheck +--- + +VitNode handles SEO in two layers. A site-wide policy in `vitnode.server.config.ts` decides whether the deployment is indexable and serves `/robots.txt` and `/sitemap.xml`. Each page's `head` sets its own title, description, robots tag, canonical link and social image. + +## Site-wide policy + +Set once per app with the `seo` block and the `withSeo` server entry. + +| I want to... | Guide | +| ----------------------------------------------------- | --------------------------------------------- | +| Turn on generated robots.txt and sitemaps | [Set up SEO](/docs/dev/seo/setup) | +| Keep a preview deployment out of search results | [Indexing](/docs/dev/seo/indexing) | +| See which paths crawlers are kept out of | [robots.txt](/docs/dev/seo/robots-txt) | +| Allow AI search but block AI training | [AI crawlers](/docs/dev/seo/ai-crawlers) | +| List my pages and content in `/sitemap.xml` | [Sitemap](/docs/dev/seo/sitemap) | +| Look up an option, default or startup error | [SEO reference](/docs/dev/seo/reference) | + +## Page by page + +Set in each route's `head`. Works with or without the `seo` block. + +| I want to... | Guide | +| ----------------------------------------------------- | -------------------------------------------------------------- | +| Set a page's title, description or `noindex` | [Page metadata](/docs/dev/seo/page-metadata) | +| Link the translations of a page | [Canonical and hreflang](/docs/dev/seo/hreflang) | +| Control the picture in link previews | [Social images](/docs/dev/seo/social-images) | +| Design my own preview card | [Social card templates](/docs/dev/seo/social-image-templates) | + +## Content Engine records + +Pages built from Content Engine records get their title, description, `noindex`, Open Graph tags, `hreflang` links and sitemap entries from the content type's `delivery.seo` and `delivery.sitemap`. Plugin authors set those fields once; see [Content SEO](/docs/content-engine/seo). + +## Related + +- [Content SEO](/docs/content-engine/seo): SEO fields of a content type. +- [Localized URLs](/docs/dev/i18n/localized-urls): how each language's URL is spelled. diff --git a/apps/web/content/docs/dev/seo/indexing.mdx b/apps/web/content/docs/dev/seo/indexing.mdx new file mode 100644 index 0000000000..2c861cc646 --- /dev/null +++ b/apps/web/content/docs/dev/seo/indexing.mdx @@ -0,0 +1,70 @@ +--- +title: Indexing +description: Let search engines index a production VitNode site and keep preview deployments out of search results with seo.indexing, X-Robots-Tag and noindex. +icon: Eye +--- + +`seo.indexing` decides whether search engines may index a whole deployment. It defaults to `true`, so set it to `false` on previews and staging, and a test site never shows up next to the real one in search results. + +This guide assumes [SEO is set up](/docs/dev/seo/setup). + +## What each value does + +| `indexing` | Pages | Sitemap | +| ---------- | ----------------------------------------------- | ------------------------------------ | +| `true` | Indexable, each page keeps its own `robots` tag | `/sitemap.xml` and a `Sitemap:` line | +| `false` | `X-Robots-Tag: noindex` on every HTML response | `404`, no `Sitemap:` line | + +With `indexing: false` the pages stay crawlable on purpose. A search engine has to fetch a page to read its `noindex`, so blocking it in robots.txt would hide the very signal that removes it. `/robots.txt` keeps the same rules and only loses the `Sitemap:` line. + +`indexing: false` also hides the sitemap, whatever `sitemap.enabled` says. A sitemap invites crawlers to index what it lists, so the two cannot disagree. + +## Pick the value per deployment + +`indexing` defaults to `true`, so check `VITNODE_WEB_URL` (or any host-provided environment variable) to turn it off outside production: + +```ts title="src/vitnode.server.config.ts" +const PRODUCTION_ORIGIN = 'https://example.com' + +seo: { + indexing: process.env.VITNODE_WEB_URL === PRODUCTION_ORIGIN, +}, +``` + +| Deployment | `VITNODE_WEB_URL` | Result | +| ---------- | ----------------------------- | --------------------------------------------------------- | +| Production | `https://example.com` | Indexable pages, `/sitemap.xml`, `Sitemap:` in robots.txt | +| Preview | `https://preview.example.com` | `X-Robots-Tag: noindex` on every page, sitemap `404` | + +Any boolean expression works - VitNode reads the value you pass, not an environment variable of its own. + + + [Prerendered pages](/docs/dev/deployments/prerendering) are written at build + time and served as files, without the server. When `indexing` is `false` + during the build, VitNode writes `` + into each of them; the server adds `X-Robots-Tag: noindex` to everything it + renders. Give the build and the running server the same value, or the two + kinds of page will disagree. + + +## Page-level robots still apply + +`indexing: false` keeps a page's own robots tag. A page that already sends `noindex, nofollow` keeps it. With `indexing: true`, a page can still opt out: set `robots` in its [page metadata](/docs/dev/seo/page-metadata), or set a Content Engine record's [`noIndexField`](/docs/content-engine/seo#hide-a-record-from-search-engines). + +## Check the result + +On a preview deployment, look at the headers and HTML of any page: + +```bash +curl -sI https://preview.example.com/ | grep -i x-robots-tag +curl -s https://preview.example.com/ | grep -o '' +``` + +The first line shows `x-robots-tag: noindex` for a server-rendered page. The second matches only on a prerendered page, which a host serves as a file without the header. `/sitemap.xml` answers `404`. + +Switching a live site from `false` to `true` takes effect with the next deployment. Search engines then need days to weeks to recrawl and reprocess pages, and removing a page from results is not instant either. + +## Related + +- [robots.txt](/docs/dev/seo/robots-txt): what crawlers may request. +- [Page metadata](/docs/dev/seo/page-metadata): `noindex` for a single page. diff --git a/apps/web/content/docs/dev/seo/meta.json b/apps/web/content/docs/dev/seo/meta.json new file mode 100644 index 0000000000..9e23dd3355 --- /dev/null +++ b/apps/web/content/docs/dev/seo/meta.json @@ -0,0 +1,18 @@ +{ + "title": "SEO", + "description": "Indexing, robots.txt, sitemaps, page metadata, hreflang and social images", + "icon": "SearchCheck", + "pages": [ + "index", + "setup", + "indexing", + "robots-txt", + "ai-crawlers", + "sitemap", + "page-metadata", + "hreflang", + "social-images", + "social-image-templates", + "reference" + ] +} diff --git a/apps/web/content/docs/dev/seo/page-metadata.mdx b/apps/web/content/docs/dev/seo/page-metadata.mdx new file mode 100644 index 0000000000..02486021cd --- /dev/null +++ b/apps/web/content/docs/dev/seo/page-metadata.mdx @@ -0,0 +1,105 @@ +--- +title: Page metadata +description: Set the title, meta description, robots tag and canonical URL of VitNode pages from a plugin route's head or an app route's pageHead. +icon: Tags +--- + +Every VitNode page builds its ``, meta description, `robots` tag and canonical link from one small object returned by the route's `head`. VitNode adds the site name, the Open Graph tags and the X card tags for you. + +## Name the site + +The site name comes from `metadata` in `src/vitnode.config.ts`. Each page title is `{page} - {shortTitle ?? title}`: + +```ts title="src/vitnode.config.ts" +export const vitNodeConfig = buildConfig({ + metadata: { + title: 'Acme Community', + shortTitle: 'Acme', // [!code ++] + }, + // ... +}) +``` + +A page titled `Pricing` then gets `<title>Pricing - Acme`. + +## Set metadata on a plugin page + +A plugin page returns plain fields from `head` in its page module. `head` runs after `load`, so it can use the loaded data, and `t` translates keys from the route's `messages`: + +```tsx title="plugins/site-notes/src/pages/note-page.tsx" +import { defineRoute } from '@vitnode/core/tanstack/plugin-routes' + +export const route = defineRoute({ + load: async ({ params }) => await fetchNote(params.id), + head: ({ loaderData, t }) => ({ + title: loaderData?.title ?? t('site-notes.note.not_found'), + description: loaderData?.summary, + }), +}) +``` + +`fetchNote` stands for your own query. Write `head` after `load`: TypeScript infers `loaderData` from `load` and reads members in order. [Route module](/docs/dev/routing/route-module#head-arguments-and-result) lists every field `head` accepts. + +## Set metadata on an app route + +An app's own file routes call `pageHead` from `@vitnode/core/tanstack/metadata`, which takes the same fields and returns TanStack Router's `meta` and `links`: + +```tsx title="apps/web/src/routes/_main/pricing.tsx" +import { createFileRoute } from '@tanstack/react-router' +import { pageHead } from '@vitnode/core/tanstack/metadata' + +import { PRICING_DESCRIPTION, PRICING_TITLE } from '@/site/pricing/metadata' + +export const Route = createFileRoute('/_main/pricing')({ + head: () => + pageHead({ + title: PRICING_TITLE, + description: PRICING_DESCRIPTION, + canonical: '/pricing', + }), +}) +``` + +Keep the strings in a leaf file without UI imports, so `head` does not pull components into the client entry bundle. See [Performance](/docs/dev/performance#1-isolate-metadata-in-file-routes). + +## Keep a page out of search results + +Set `robots` to one of three values: + +| Value | Use it for | +| ------------------- | ----------------------------------------------------------------------- | +| `index, follow` | A normal public page. Same as leaving `robots` out. | +| `noindex, follow` | A view of other pages, such as a filtered or sorted list: its links still count | +| `noindex, nofollow` | A page with nothing for search, such as a member's own files | + +```tsx title="plugins/site-notes/src/pages/notes-page.tsx" +export const route = defineRoute({ + head: ({ search, t }) => ({ + title: t('site-notes.notes.title'), + robots: search.tag ? 'noindex, follow' : 'index, follow', // [!code ++] + }), +}) +``` + +A deeper route's `robots` replaces its parent's. On a preview deployment, [`seo.indexing: false`](/docs/dev/seo/indexing) adds `noindex` on top of whatever a page says. + +Don't also block such a page in robots.txt: a crawler has to fetch the page to read its `noindex`. + +## Point to the canonical URL + +`canonical` tells search engines which URL is the original when the same page is reachable at several, for example with query parameters. Pass an absolute URL or a path on the site; it also becomes `og:url`. A page that exists in several languages sets `alternates` instead, which writes the canonical link and the `hreflang` links together. See [Canonical and hreflang](/docs/dev/seo/hreflang). + +## Check the result + +Print the tags of a page: + +```bash +curl -s http://localhost:3000/pricing | grep -oE '[^<]*|]*name="(description|robots)"[^>]*>|]*rel="canonical"[^>]*>' +``` + +You should see the suffixed title, the description, the canonical link and, when set, the `robots` tag. The same page also carries `og:*` and `twitter:*` tags; see [Social images](/docs/dev/seo/social-images). + +## Related + +- [Route module](/docs/dev/routing/route-module#translated-metadata): translate titles with `t`. +- [Content SEO](/docs/content-engine/seo): metadata for Content Engine record pages. diff --git a/apps/web/content/docs/dev/seo/reference.mdx b/apps/web/content/docs/dev/seo/reference.mdx new file mode 100644 index 0000000000..b44b18bfe4 --- /dev/null +++ b/apps/web/content/docs/dev/seo/reference.mdx @@ -0,0 +1,105 @@ +--- +title: SEO reference +description: Every option of VitNode's seo server config and the withSeo server entry, with types, defaults, sitemap list source shapes and configuration errors. +icon: BookOpen +--- + +import { TypeTable } from 'fumadocs-ui/components/type-table' + +This page lists the options of `buildServerConfig({ seo })` and `withSeo`. To turn the feature on, follow [Set up SEO](/docs/dev/seo/setup). + +## `seo` options + +Set in `src/vitnode.server.config.ts`. Read when the server starts. + + + +Leaving `seo` out is the same as `seo: { indexing: true }`. To serve your own robots.txt and sitemap, leave `withSeo` out of the server entry instead. + +## `withSeo` options + +`withSeo(entry, options)` from `@vitnode/core/tanstack/seo/server` wraps the server entry, outside `withPageCache`. Server-only. + +| Name | Type | Required | Default | Description | +| --------- | -------------------------------- | -------- | ------- | ------------------------------------------------------------------------ | +| `config` | `VitNodeServerConfig` | Yes | - | The app's `vitNodeServerConfig`. `seo`, `i18n` and `pageCache.storage` are read from it. | +| `sitemap` | `SeoSitemapManifest` | Yes | - | `sitemapManifest` from the generated `src/sitemap-sources.gen.ts`. | +| `sources` | `readonly SeoSitemapListSource[]` | No | `[]` | App-owned URL lists, each published as `/sitemap-{id}-{n}.xml`. | + +`withSeo` answers `/robots.txt`, `/sitemap.xml`, `/sitemap-*.xml` and `POST /api/vitnode/content/revalidate` itself, and passes every other request to `entry`. + +## `SeoSitemapListSource` + +| Name | Type | Description | +| ------ | --------------------------------------------------------- | ------------------------------------------------------------------------ | +| `id` | `string` | The file stem: lowercase letters, digits and dashes. `pages` is reserved. | +| `urls` | `() => Promise \| readonly SeoSitemapUrl[]` | Read once per server process and host. | + +Each `SeoSitemapUrl`: + +| Name | Type | Required | Description | +| -------------- | -------------------------------- | -------- | ------------------------------------------------------------------- | +| `path` | `string` | Yes | The canonical pathname, e.g. `/docs/dev`. | +| `origin` | `string` | No | A configured origin. Defaults to the web origin; any other host is dropped. | +| `lastModified` | `Date \| null` | No | Leave it out when there is no reliable modification date. | +| `alternates` | `{ locale, path, origin? }[]` | No | One per language, `locale` may be `x-default`. | + +## Errors + +An invalid `seo` value stops the server at startup with a `SeoConfigError` whose message starts with `[VitNode SEO]` and names the option: + +| Message contains | Fix | +| ------------------------------------------------ | ---------------------------------------------------------- | +| `` `seo.indexing` must be `true` or `false` `` | Pass a boolean, not a string such as `"true"`. | +| `... is not an option. Use ...` | Remove or rename the unknown key. | +| `seo.sitemap.paths entry "..." must be a path on this site` | Start the path with a single `/`. | +| `... is under /admin or /api` | Remove the path; those are never public pages. | +| `... starts with the locale "pl"` | List the unlocalized path; every language is added for you. | + +## Related + +- [robots.txt](/docs/dev/seo/robots-txt): what the generated file contains. +- [Sitemap](/docs/dev/seo/sitemap): how each source is published. diff --git a/apps/web/content/docs/dev/seo/robots-txt.mdx b/apps/web/content/docs/dev/seo/robots-txt.mdx new file mode 100644 index 0000000000..50be806e31 --- /dev/null +++ b/apps/web/content/docs/dev/seo/robots-txt.mdx @@ -0,0 +1,74 @@ +--- +title: robots.txt +description: What the robots.txt VitNode generates contains, which private paths it excludes in every language, and how to check it after a deployment. +icon: Bot +--- + +With [SEO set up](/docs/dev/seo/setup), VitNode answers `/robots.txt` from config alone: no API call, no session and no database. It lets crawlers read the site, keeps them out of private areas and points them at the sitemap. + +## What the file contains + +With `seo: { indexing: true }` on a site with English and Polish: + +```txt title="https://example.com/robots.txt" +User-agent: * +Allow: / +Disallow: /admin +Disallow: /settings +Disallow: /pl/settings +Disallow: /modcp +Disallow: /pl/modcp +Disallow: /files +Disallow: /pl/files +Disallow: /login +Disallow: /pl/login +Disallow: /register +Disallow: /pl/register + +Sitemap: https://example.com/sitemap.xml +``` + +- `Allow: /` opens everything that is not excluded below it. +- The `Sitemap:` line appears only while the [sitemap](/docs/dev/seo/sitemap) is published. With `indexing: false` it is gone and the rules stay. +- `HEAD /robots.txt` returns the same headers with no body. + +## Excluded paths + +| Path | Why | +| ----------- | ---------------------------------------------------------------------- | +| `/admin` | The AdminCP. Never locale-prefixed. | +| `/settings` | A member's account settings. Needs sign-in. | +| `/modcp` | The moderator control panel. Needs sign-in. | +| `/files` | A member's uploaded files. Needs sign-in. | +| `/login` | Sign-in, plus password reset, email verification and SSO callbacks, whose links carry one-time tokens | +| `/register` | Registration. Nothing to index. | + +Every path except `/admin` is excluded in each language's URL, including translated [route paths](/docs/dev/i18n/localized-urls): with `routePaths: { pl: { '/settings': '/ustawienia' } }` the Polish line is `Disallow: /pl/ustawienia`. With a [domain per language](/docs/dev/i18n/localized-urls-advanced#a-domain-per-language), each domain's file lists only the languages that domain serves. + +Rules match by prefix, as robots.txt always does, so `Disallow: /files` also covers `/files/2`. Those pages are still protected by their own sign-in checks; the rules only stop well-behaved crawlers from asking. + +The list is fixed. To keep one of your own pages out of search results, don't block it here. Give it `robots: 'noindex, follow'` in its [page metadata](/docs/dev/seo/page-metadata) instead: a crawler must be able to fetch a page to see its `noindex`. + +## Check the result + +After a deployment, fetch the live file: + +```bash +curl -i https://example.com/robots.txt +``` + +Expect `200`, `content-type: text/plain; charset=utf-8`, the rules above and exactly one `Sitemap:` line with your origin. + + + Cloudflare's managed robots.txt feature (in the zone's AI crawler and bot + settings) prepends Cloudflare's own rules to the file visitors receive. If it + is on, `curl` your live `/robots.txt` after deploying and turn the setting off + when its rules conflict with [`seo.crawlers`](/docs/dev/seo/ai-crawlers). + Static files in `public/` are also served before the Worker runs, so remove + any old `public/robots.txt`. + + +## Related + +- [AI crawlers](/docs/dev/seo/ai-crawlers): separate rules for search and training bots. +- [Indexing](/docs/dev/seo/indexing): keep a preview deployment out of search results. diff --git a/apps/web/content/docs/dev/seo/setup.mdx b/apps/web/content/docs/dev/seo/setup.mdx new file mode 100644 index 0000000000..6e53554806 --- /dev/null +++ b/apps/web/content/docs/dev/seo/setup.mdx @@ -0,0 +1,101 @@ +--- +title: Set up SEO +description: Turn on VitNode's generated robots.txt, sitemap and noindex handling with the withSeo server entry, and change the defaults with the seo block. +icon: Power +--- + +VitNode can serve your site's `/robots.txt`, a `/sitemap.xml` index and a deployment-wide `noindex`. This page turns them on. Each feature then has its own guide. + +The defaults need no config: once the server entry is wrapped with `withSeo`, the site is indexable, robots.txt keeps crawlers out of private areas and the sitemap lists your content. Apps created with `create-vitnode-app` already wrap it. + + + + +### Wrap the server entry with `withSeo` + +`withSeo` from `@vitnode/core/tanstack/seo/server` goes **outside** `withPageCache` in `src/server.ts`, so pages served from the [page cache](/docs/dev/cache/pages) get the same policy as fresh renders: + +```ts title="src/server.ts" +import handler from '@tanstack/react-start/server-entry' +import { withPageCache } from '@vitnode/core/tanstack/page-cache/server' +import { withSeo } from '@vitnode/core/tanstack/seo/server' + +import { pageCacheBuildId, pageCacheRoutes } from '@/page-cache.gen' +import { sitemapManifest } from '@/sitemap-sources.gen' +import { vitNodeConfig } from '@/vitnode.config' +import { vitNodeServerConfig } from '@/vitnode.server.config' + +export default withSeo( + withPageCache(handler, { + buildId: pageCacheBuildId, + config: vitNodeConfig, + routes: pageCacheRoutes, + }), + { config: vitNodeServerConfig, sitemap: sitemapManifest }, +) +``` + +VitNode's Vite plugin writes `src/sitemap-sources.gen.ts` on every `vitnode dev` and `vitnode build`, like the other `*.gen.ts` files. It lists the content types whose records go into the [sitemap](/docs/dev/seo/sitemap). + + + + +### Remove static robots and sitemap files + +Delete `public/robots.txt` and any `public/sitemap*.xml`. Hosts serve files from `public/` before your server runs, so those files would replace the generated ones. The build prints a warning while one is still there. + + + + +### Change the defaults (optional) + +Leaving `seo` out of `buildServerConfig` is the same as `seo: { indexing: true }`. Add the block in `src/vitnode.server.config.ts` only to change something, such as your own [sitemap pages](/docs/dev/seo/sitemap#add-your-own-pages) or the [AI crawler rules](/docs/dev/seo/ai-crawlers): + +```ts title="src/vitnode.server.config.ts" +import '@tanstack/react-start/server-only' +import { buildServerConfig } from '@vitnode/core/vitnode.config' + +import { appMessages } from '@/locales/app' +import { packageMessages } from '@/package-messages.gen' +import { vitNodeConfig } from '@/vitnode.config' + +export const vitNodeServerConfig = buildServerConfig({ + config: vitNodeConfig, + messages: appMessages, + packageMessages, + // [!code ++:3] + seo: { + sitemap: { paths: ['/', '/about'] }, + }, +}) +``` + +Set `indexing: false` on preview and staging deployments, so they stay out of search results. [Indexing](/docs/dev/seo/indexing) shows how to pick the value per deployment. + + + + +To serve your own robots.txt and sitemap instead, leave `withSeo` out of `src/server.ts`. + +## Which origin URLs use + +Every URL VitNode writes uses `VITNODE_WEB_URL`, or a language's own origin from [`i18n.domains`](/docs/dev/i18n/localized-urls-advanced#a-domain-per-language) when the request is for that host. The request's `Host` header only picks between those configured origins, so nobody can make your sitemap point at another domain. + +Set `VITNODE_WEB_URL` to the public origin wherever the server runs. Without it, URLs fall back to `http://localhost:3000`. + +## Check the result + +Start the app and request the generated file: + +```bash +curl -i http://localhost:3000/robots.txt +``` + +Expect `200`, `content-type: text/plain; charset=utf-8` and exactly one `Sitemap:` line with your origin. [robots.txt](/docs/dev/seo/robots-txt) explains every line. + +The config is read when the server starts, so a change takes effect with the next restart or deployment. + +## Related + +- [SEO reference](/docs/dev/seo/reference): every `seo` and `withSeo` option. +- [Configuration](/docs/dev/configuration#server-config): every file that configures a web app. diff --git a/apps/web/content/docs/dev/seo/sitemap.mdx b/apps/web/content/docs/dev/seo/sitemap.mdx new file mode 100644 index 0000000000..d2eda290bb --- /dev/null +++ b/apps/web/content/docs/dev/seo/sitemap.mdx @@ -0,0 +1,121 @@ +--- +title: Sitemap +description: Publish a generated /sitemap.xml for a VitNode site with your own pages, Content Engine records and app-owned URL lists, kept fresh automatically. +icon: Network +--- + +With [SEO set up](/docs/dev/seo/setup) and `indexing: true`, VitNode publishes `/sitemap.xml`: a sitemap index that lists your app's pages, every published Content Engine record and any other URL list you add. It refreshes itself when content changes. + +## What the sitemap lists + +`/sitemap.xml` is a sitemap index. Each child file sits at the site root, so it may list any URL on the host: + +| Child file | Source | +| ------------------------ | ----------------------------------------------------------------------- | +| `/sitemap-pages-1.xml` | `seo.sitemap.paths`, once per language, with `hreflang` alternates | +| `/sitemap-blog-pl-1.xml` | A content type with `delivery.sitemap`, one file per language and part | +| `/sitemap-docs-1.xml` | A list source you pass to `withSeo`, such as your own docs | + +The sitemap is off while `indexing` is `false`, and `sitemap: { enabled: false }` turns it off on an indexable site too. Then `/sitemap.xml` answers `404` and robots.txt has no `Sitemap:` line. + +## Add your own pages + +List canonical, public, indexable pages in `seo.sitemap.paths`, without a language prefix: + +```ts title="src/vitnode.server.config.ts" +seo: { + indexing: true, + sitemap: { paths: ['/', '/about', '/plugins'] }, // [!code ++] +}, +``` + +VitNode adds each language's URL through your [locale routing](/docs/dev/i18n/localized-urls): `"/plugins"` becomes `/plugins` and `/pl/plugins`, each with `xhtml:link` alternates and an `x-default`. + +- A path starts with `/` and has no query, hash, `..` segment or language prefix. `/admin` and `/api` paths are refused. +- A trailing slash is dropped and duplicates are merged. +- App paths get no `lastmod`, since VitNode has no real modification date for them. + +An invalid path stops the server at startup with a `SeoConfigError` that names the entry. + +## Content Engine records + +A plugin author only adds `delivery.sitemap` to a content type. At build time VitNode finds every such type in your configured plugins, writes it to `src/sitemap-sources.gen.ts` and lists its published records, one file per language. See [Content SEO](/docs/content-engine/seo#sitemap) for what a record needs to appear. + +VitNode reads each type's `/delivery/sitemap` route as a guest, sending no cookie or `Authorization` header, so the XML is the same when a signed-in admin opens it. Drafts, hidden and restricted records, unpublished translations and records marked `noindex` stay out. + +## App-owned lists + +Pass any other bounded list of URLs as a source. vitnode.com publishes its documentation pages this way: + +```ts title="apps/web/src/docs/sitemap.server.ts" +import '@tanstack/react-start/server-only' + +import type { SeoSitemapListSource } from '@vitnode/core/tanstack/seo/server' + +export const docsSitemapSource: SeoSitemapListSource = { + id: 'docs', + urls: async () => { + const { source } = await import('./source.server') + + return source.getPages().map((page) => ({ path: page.url })) + }, +} +``` + +Then add it to `withSeo` in `src/server.ts`: + +```ts title="src/server.ts (excerpt)" +export default withSeo(entry, { + config: vitNodeServerConfig, + sitemap: sitemapManifest, + sources: [docsSitemapSource], // [!code ++] +}) +``` + +The list is read once per server process. A URL may carry `lastModified` and `alternates`; one on a host you have not configured is dropped. + +## How the sitemap stays fresh + +Generated XML is kept in the page cache's store, configured by [`pageCache.storage`](/docs/dev/cache/pages): one process's memory by default, or Redis shared by every instance. Nothing else needs setting up. + +- A child file holds at most 1,000 URLs and stays under the protocol's 50 MB limit. +- A content file is cached for an hour. A publish, edit, slug change, delete, hide, or a change to a record's `noindex` field expires it at once. Removals are hard: XML that lists a removed URL is never served again. Additions may take one more request to appear. +- The index lives for 10 minutes and is rebuilt as soon as any file it lists changes, so every child it links to exists. +- A large content type is built a few API pages per request and finished in the background. Until every part is ready, the previous complete sitemap is served. A crawler gets `503` with `Retry-After` only while there is no complete, valid copy, for example right after a deployment or a removal. Failures are never cached. + +In a [separate front end](/docs/content-engine/caching#notify-a-separate-front-end), list its origin in the API's `content.revalidateOrigins`. `withSeo` answers that `POST /api/vitnode/content/revalidate` itself, checks `CRON_SECRET` and expires the affected sitemap files. Give the front end the same `CRON_SECRET` as the API. + +## Check the result + + + + +### Open the index and one child + +```bash +curl -s https://example.com/sitemap.xml +curl -s https://example.com/sitemap-pages-1.xml | head -n 20 +``` + +Both answer `application/xml; charset=utf-8`. Every `` in the index opens a child file on the same host. + + + + +### Publish and hide a record + +Publish an article, then request its file again. Its URL appears. With the blog plugin: + +```bash +curl -s https://example.com/sitemap-blog-en-1.xml | grep english-title +``` + +Set the record's `noIndexField` to `true`, or hide it, and the same command prints nothing. + + + + +## Related + +- [Content SEO](/docs/content-engine/seo#sitemap): `delivery.sitemap` and the per-type sitemap route. +- [SEO reference](/docs/dev/seo/reference): `sitemap` options and the list source types. diff --git a/apps/web/content/docs/dev/seo/social-image-templates.mdx b/apps/web/content/docs/dev/seo/social-image-templates.mdx new file mode 100644 index 0000000000..0d2af8ccc2 --- /dev/null +++ b/apps/web/content/docs/dev/seo/social-image-templates.mdx @@ -0,0 +1,101 @@ +--- +title: Social card templates +description: Design your own VitNode social card with an OgImageTemplate, register it for a content type or the whole site, and draw cards from your own API route. +icon: PenTool +--- + +VitNode's built-in [social images](/docs/dev/seo/social-images) cover most sites with a colour and a logo. When you want your own layout, write a template: a function that returns JSX, drawn to a 1200 × 630 PNG by the API. + +Theme colours, the logo and fonts set in `ogImage` reach every template through its props, so set those first. + +## Write your own template + +A template is a function that takes the card's props and returns JSX. VitNode calls it as a plain function, so it cannot use hooks or context. The renderer understands inline `style` objects and flexbox. Give every element with more than one child `display: "flex"`. + +```tsx title="plugins/newsroom/src/api/og/story-card.tsx" +import type { OgImageTemplate } from "@vitnode/api/lib/og-image"; + +export const StoryCard: OgImageTemplate = ({ siteName, theme, title }) => ( +
+ {siteName} · Story + {title} +
+); +``` + +The props are `title`, `description`, `siteName`, `domain`, `locale`, `theme`, `logo` and `kind` (`content`, `profile` or `site`), plus `contentTypeId` and `pluginId` on a content card and `avatar` on a profile card. `logo` is `{ src, width, height, wordmark }`, ready for an ``. A template that puts the logo on a background other than `theme.background` recolors its `currentColor` with `ogImageLogoSrc(logo, "#18181b")` from `@vitnode/api/lib/og-image`. + +A plugin registers templates for its own content types in `buildApiPlugin`: + +```ts title="plugins/newsroom/src/config.api.ts (excerpt)" +import { StoryCard } from "./api/og/story-card"; + +export const newsroomApiPlugin = () => + buildApiPlugin({ + manifest, + // [!code ++] + ogImageTemplates: { "newsroom.story": StoryCard }, + // ... + }); +``` + +An app replaces any card in `buildApiConfig`. `ogImage.templates` overrides a plugin's template for a content type, and `ogImage.template` draws everything no other template covers, profiles and the site card included. A template registered for an id no plugin defines stops the API at startup. + +## Draw a card from your own route + +For a page outside the Content Engine, answer from an API route with `ogImageResponse` and point the page head at it. Check that the data is public first, because the card is shown to everyone: + +```ts title="plugins/events/src/api/modules/events/routes/og.route.ts" +import { + ogImageBaseProps, + ogImageResponse, + ogImageVersion, +} from "@vitnode/api/lib/og-image"; + +import { buildRoute } from "@/api/builders"; + +export const eventOgRoute = buildRoute({ + route: { method: "get", path: "/og/{slug}" /* params, responses */ }, + handler: async c => { + const event = await findPublicEvent(c, c.req.param("slug")); + if (!event) return c.json({ error: "Not found" }, 404); + + return await ogImageResponse( + c, + { + ...ogImageBaseProps(c), + description: event.summary, + kind: "content", + locale: null, + title: event.title, + }, + { version: ogImageVersion(c, [event.title, event.summary]) }, + ); + }, +}); +``` + +`buildRoute` is your plugin's bound builder from `src/api/builders.ts`, and `findPublicEvent` stands for your own query. In the page's `head`, return `openGraph: { image: { url, width: 1200, height: 630, type: "image/png" } }`, with `url` built from the route and the same `v`. See [`head` arguments and result](/docs/dev/routing/route-module#head-arguments-and-result). + +## Check the result + +Restart the API, then open a card URL in the browser, such as a story's `og:image` from the [social images check](/docs/dev/seo/social-images#check-the-result). A `200` with `Content-Type: image/png` showing your layout means the template is used. A `503` means the renderer failed, and the reason is in **AdminCP → Debug Panel → Log explorer** (`/admin/core/debug`). + +Raise `ogImage.version` in the API config after changing a template, so crawlers and CDNs fetch the new cards instead of cached ones. + +## Related + +- [Social images](/docs/dev/seo/social-images#options-reference): every `ogImage` option. +- [Route module](/docs/dev/routing/route-module#head-arguments-and-result): the `openGraph` field of a page's `head`. diff --git a/apps/web/content/docs/dev/social-images-card.webp b/apps/web/content/docs/dev/seo/social-images-card.webp similarity index 100% rename from apps/web/content/docs/dev/social-images-card.webp rename to apps/web/content/docs/dev/seo/social-images-card.webp diff --git a/apps/web/content/docs/dev/social-images.mdx b/apps/web/content/docs/dev/seo/social-images.mdx similarity index 76% rename from apps/web/content/docs/dev/social-images.mdx rename to apps/web/content/docs/dev/seo/social-images.mdx index dee7712cb9..f6eaf08794 100644 --- a/apps/web/content/docs/dev/social-images.mdx +++ b/apps/web/content/docs/dev/seo/social-images.mdx @@ -181,86 +181,9 @@ export const vitNodeApiConfig = buildApiConfig({ TTF, OTF, WOFF and WOFF2 all work. Cloudflare Workers have no file system, so there you bundle the bytes into the code instead, for example as a base64 string. That is how VitNode ships Geist. -## Write your own template - -A template is a function that takes the card's props and returns JSX. VitNode calls it as a plain function, so it cannot use hooks or context. The renderer understands inline `style` objects and flexbox. Give every element with more than one child `display: "flex"`. - -```tsx title="plugins/newsroom/src/api/og/story-card.tsx" -import type { OgImageTemplate } from "@vitnode/api/lib/og-image"; - -export const StoryCard: OgImageTemplate = ({ siteName, theme, title }) => ( -
- {siteName} · Story - {title} -
-); -``` - -The props are `title`, `description`, `siteName`, `domain`, `locale`, `theme`, `logo` and `kind` (`content`, `profile` or `site`), plus `contentTypeId` and `pluginId` on a content card and `avatar` on a profile card. `logo` is `{ src, width, height, wordmark }`, ready for an ``. A template that puts the logo on a background other than `theme.background` recolors its `currentColor` with `ogImageLogoSrc(logo, "#18181b")` from `@vitnode/api/lib/og-image`. - -A plugin registers templates for its own content types in `buildApiPlugin`: - -```ts title="plugins/newsroom/src/config.api.ts (excerpt)" -import { StoryCard } from "./api/og/story-card"; - -export const newsroomApiPlugin = () => - buildApiPlugin({ - manifest, - // [!code ++] - ogImageTemplates: { "newsroom.story": StoryCard }, - // ... - }); -``` - -An app replaces any card in `buildApiConfig`. `ogImage.templates` overrides a plugin's template for a content type, and `ogImage.template` draws everything no other template covers, profiles and the site card included. A template registered for an id no plugin defines stops the API at startup. - -## Draw a card from your own route - -For a page outside the Content Engine, answer from an API route with `ogImageResponse` and point the page head at it. Check that the data is public first, because the card is shown to everyone: - -```ts title="plugins/events/src/api/modules/events/routes/og.route.ts" -import { - ogImageBaseProps, - ogImageResponse, - ogImageVersion, -} from "@vitnode/api/lib/og-image"; - -import { buildRoute } from "@/api/builders"; - -export const eventOgRoute = buildRoute({ - route: { method: "get", path: "/og/{slug}" /* params, responses */ }, - handler: async c => { - const event = await findPublicEvent(c, c.req.param("slug")); - if (!event) return c.json({ error: "Not found" }, 404); - - return await ogImageResponse( - c, - { - ...ogImageBaseProps(c), - description: event.summary, - kind: "content", - locale: null, - title: event.title, - }, - { version: ogImageVersion(c, [event.title, event.summary]) }, - ); - }, -}); -``` +## Draw your own cards -`buildRoute` is your plugin's bound builder from `src/api/builders.ts`, and `findPublicEvent` stands for your own query. In the page's `head`, return `openGraph: { image: { url, width: 1200, height: 630, type: "image/png" } }`, with `url` built from the route and the same `v`. See [`head` arguments and result](/docs/dev/routing/route-module#head-arguments-and-result). +A plugin can register its own card template for its content types, an app can replace any card, and a page outside the Content Engine can serve a card from its own API route. See [Social card templates](/docs/dev/seo/social-image-templates). ## Turn cards off @@ -297,5 +220,6 @@ The real output has more tags, and your `v` differs. Open the `og:image` URL in ## Related -- [SEO for Content Engine pages](/docs/content-engine/seo) -- [Plugin page `head`](/docs/dev/routing/route-module#head-arguments-and-result) +- [Social card templates](/docs/dev/seo/social-image-templates): your own card design. +- [Content SEO](/docs/content-engine/seo#social-images): a record's cover as `og:image`. +- [Page metadata](/docs/dev/seo/page-metadata): the title and description a card shows. diff --git a/apps/web/public/robots.txt b/apps/web/public/robots.txt deleted file mode 100644 index 7418a79cc1..0000000000 --- a/apps/web/public/robots.txt +++ /dev/null @@ -1,6 +0,0 @@ -User-agent: * -Allow: / -Disallow: /admin -Disallow: /settings - -Sitemap: https://vitnode.com/sitemap.xml diff --git a/apps/web/public/sitemap.xml b/apps/web/public/sitemap.xml deleted file mode 100644 index b35258839e..0000000000 --- a/apps/web/public/sitemap.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - https://vitnode.com/weekly1.0 - https://vitnode.com/pluginsmonthly0.8 - https://vitnode.com/solutionsmonthly0.8 - https://vitnode.com/solutions/help-centermonthly0.7 - https://vitnode.com/solutions/membership-sitemonthly0.7 - https://vitnode.com/solutions/open-source-hubmonthly0.7 - https://vitnode.com/solutions/multilingual-magazinemonthly0.7 - https://vitnode.com/solutions/gaming-guildmonthly0.7 - https://vitnode.com/docs/devweekly0.9 - https://vitnode.com/docs/dev/setupweekly0.8 - https://vitnode.com/docs/guides/first-pluginmonthly0.7 - https://vitnode.com/docs/dev/plugins/createmonthly0.7 - https://vitnode.com/docs/dev/content-enginemonthly0.7 - https://vitnode.com/docs/dev/plugins/adminmonthly0.6 - https://vitnode.com/docs/dev/deployments/self-hostedmonthly0.6 - diff --git a/apps/web/src/docs/redirects.ts b/apps/web/src/docs/redirects.ts index 643049cf93..a86829c7ae 100644 --- a/apps/web/src/docs/redirects.ts +++ b/apps/web/src/docs/redirects.ts @@ -14,6 +14,7 @@ const RENAMED_PAGES: Readonly> = { 'content-engine/relations-and-advanced-modeling': 'content-engine/relations', 'content-engine/services-and-api': 'content-engine/services', 'dev/plugins/navigation': 'dev/navigation', + 'dev/social-images': 'dev/seo/social-images', 'ui/editor-images': 'ui/editor', } diff --git a/apps/web/src/docs/sitemap.server.ts b/apps/web/src/docs/sitemap.server.ts new file mode 100644 index 0000000000..7e739719f2 --- /dev/null +++ b/apps/web/src/docs/sitemap.server.ts @@ -0,0 +1,17 @@ +import '@tanstack/react-start/server-only' + +import type { SeoSitemapListSource } from '@vitnode/core/tanstack/seo/server' + +/** + * Every docs page at its canonical URL, for `/sitemap-docs-{n}.xml`. Docs are + * English-only: a `/pl/docs/...` URL canonicalizes to the English page, so it + * is not listed. Loaded on the first sitemap request, not at startup. + */ +export const docsSitemapSource: SeoSitemapListSource = { + id: 'docs', + urls: async () => { + const { source } = await import('./source.server') + + return source.getPages().map((page) => ({ path: page.url })) + }, +} diff --git a/apps/web/src/server.ts b/apps/web/src/server.ts index eaaf6a4ddb..7dcd17425a 100644 --- a/apps/web/src/server.ts +++ b/apps/web/src/server.ts @@ -1,11 +1,24 @@ import handler from '@tanstack/react-start/server-entry' import { withPageCache } from '@vitnode/core/tanstack/page-cache/server' +import { withSeo } from '@vitnode/core/tanstack/seo/server' +import { docsSitemapSource } from './docs/sitemap.server' import { pageCacheBuildId, pageCacheRoutes } from './page-cache.gen' +import { sitemapManifest } from './sitemap-sources.gen' import { vitNodeConfig } from './vitnode.config' +import { vitNodeServerConfig } from './vitnode.server.config' -export default withPageCache(handler, { - buildId: pageCacheBuildId, - config: vitNodeConfig, - routes: pageCacheRoutes, -}) +// `withSeo` sits outside the page cache, so a cached page gets the same +// indexing policy as a fresh render. +export default withSeo( + withPageCache(handler, { + buildId: pageCacheBuildId, + config: vitNodeConfig, + routes: pageCacheRoutes, + }), + { + config: vitNodeServerConfig, + sitemap: sitemapManifest, + sources: [docsSitemapSource], + }, +) diff --git a/apps/web/src/site/marketing/marketing.css b/apps/web/src/site/marketing/marketing.css index c3e79eea1e..bf5ac45446 100644 --- a/apps/web/src/site/marketing/marketing.css +++ b/apps/web/src/site/marketing/marketing.css @@ -371,6 +371,9 @@ body:has(.mk-final-cta) .mk-footer-rule { --mk-isles-cyan: oklch(0.62 0.12 215); --mk-isles-amber: oklch(0.72 0.15 55); --mk-isles-ink: oklch(0.5 0.17 262); + --mk-isles-sky-a: oklch(0.685 0.169 237); + --mk-isles-sky-b: oklch(0.707 0.165 255); + --mk-isles-sky-c: oklch(0.623 0.214 260); --mk-isles-line: rgb(0 0 0 / 0.08); --mk-isles-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.04), 0 1px 3px 0 rgb(0 0 0 / 0.05); @@ -381,6 +384,9 @@ body:has(.mk-final-cta) .mk-footer-rule { --mk-isles-cyan: oklch(0.78 0.11 215); --mk-isles-amber: oklch(0.82 0.13 55); --mk-isles-ink: oklch(0.74 0.13 262); + --mk-isles-sky-a: oklch(0.42 0.13 240); + --mk-isles-sky-b: oklch(0.45 0.15 258); + --mk-isles-sky-c: oklch(0.4 0.17 262); --mk-isles-line: var(--border); --mk-isles-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.3); } @@ -389,12 +395,23 @@ body:has(.mk-final-cta) .mk-footer-rule { position: absolute; inset: 0; z-index: -1; - background: linear-gradient( - to bottom, - color-mix(in oklab, var(--primary) 9%, var(--background)), - color-mix(in oklab, var(--mk-isles-cyan) 7%, var(--background)) 55%, - var(--background) - ); + background: + radial-gradient( + ellipse 55% 60% at 80% 35%, + color-mix(in oklab, var(--mk-isles-sky-a) 28%, transparent), + transparent 70% + ), + radial-gradient( + ellipse 50% 45% at 10% 0%, + color-mix(in oklab, var(--mk-isles-sky-b) 24%, transparent), + transparent 70% + ), + linear-gradient( + to bottom, + color-mix(in oklab, var(--mk-isles-sky-c) 22%, var(--background)), + color-mix(in oklab, var(--mk-isles-sky-a) 14%, var(--background)) 60%, + var(--background) + ); pointer-events: none; } @@ -416,12 +433,16 @@ body:has(.mk-final-cta) .mk-footer-rule { ); --mk-isles-cloud: white; --mk-isles-cloud-shade: color-mix(in oklab, var(--primary) 22%, transparent); + --mk-isles-cloud-alpha: 0.95; + --mk-isles-cloud-alpha-hover: 1; container-type: inline-size; } .dark .mk-isles { - --mk-isles-cloud: color-mix(in oklab, var(--card) 90%, var(--mk-isles-cyan)); + --mk-isles-cloud: oklch(0.97 0.01 240); --mk-isles-cloud-shade: transparent; + --mk-isles-cloud-alpha: 0.35; + --mk-isles-cloud-alpha-hover: 0.5; } .mk-isles-scene { @@ -518,7 +539,7 @@ body:has(.mk-final-cta) .mk-footer-rule { var(--mk-isles-cloud) 70%, transparent ); - opacity: 0.95; + opacity: var(--mk-isles-cloud-alpha); filter: drop-shadow(0 4px 8px var(--mk-isles-cloud-shade)); transition: scale 150ms ease-out; } @@ -1182,7 +1203,7 @@ body:has(.mk-final-cta) .mk-footer-rule { } .mk-isles-cloud:hover i { - opacity: 1; + opacity: var(--mk-isles-cloud-alpha-hover); } } diff --git a/apps/web/src/sitemap-sources.gen.ts b/apps/web/src/sitemap-sources.gen.ts new file mode 100644 index 0000000000..e99bc73e44 --- /dev/null +++ b/apps/web/src/sitemap-sources.gen.ts @@ -0,0 +1,26 @@ +/* oxlint-disable */ + +// This file is generated by VitNode. Do not edit it, and do not format it. +// +// It is rewritten by the `vitnode:plugin-routes` Vite plugin on every +// `vite dev` and `vite build`: every content type of a configured plugin that +// lists its records in the sitemap (`delivery.sitemap`), with the public +// route the site's `/sitemap.xml` reads them from. `src/server.ts` hands it +// to `withSeo`. +// +// `sitemapManifest.revision` is replaced at build time with an id unique to +// that build, so two deployments sharing one cache never serve each other's +// sitemaps. + +import type { SeoSitemapManifest } from '@vitnode/core/tanstack/seo/server' + +export const sitemapManifest: SeoSitemapManifest = { + revision: import.meta.env.VITNODE_BUILD_ID, + sources: [ + { contentTypeId: 'blog.post', file: 'blog', localized: true, module: 'content/blog', path: '/delivery/sitemap', pluginId: '@vitnode/blog' }, + { contentTypeId: 'forum.topic', file: 'topics', localized: false, module: 'content/topics', path: '/delivery/sitemap', pluginId: '@vitnode/forum' }, + { contentTypeId: 'newsroom.event', file: 'events', localized: true, module: 'content/events', path: '/delivery/sitemap', pluginId: 'newsroom' }, + { contentTypeId: 'newsroom.explainer', file: 'explainers', localized: true, module: 'content/explainers', path: '/delivery/sitemap', pluginId: 'newsroom' }, + { contentTypeId: 'newsroom.story', file: 'stories', localized: false, module: 'content/stories', path: '/delivery/sitemap', pluginId: 'newsroom' }, + ], +} diff --git a/apps/web/src/vitnode.server.config.ts b/apps/web/src/vitnode.server.config.ts index 64b0fe60c2..9625f5bc7b 100644 --- a/apps/web/src/vitnode.server.config.ts +++ b/apps/web/src/vitnode.server.config.ts @@ -3,10 +3,14 @@ import { buildServerConfig } from '@vitnode/core/vitnode.config' import { appMessages } from '@/locales/app' import { packageMessages } from '@/package-messages.gen' +import { PRERENDERED_PATHS } from '@/site/prerender' import { vitNodeConfig } from '@/vitnode.config' export const vitNodeServerConfig = buildServerConfig({ config: vitNodeConfig, messages: appMessages, packageMessages, + seo: { + sitemap: { paths: PRERENDERED_PATHS }, + }, }) diff --git a/packages/api/src/content/index.ts b/packages/api/src/content/index.ts index c676931628..9299007dd7 100644 --- a/packages/api/src/content/index.ts +++ b/packages/api/src/content/index.ts @@ -543,7 +543,11 @@ export { contentSitemapXml, escapeXml, } from "./sitemap"; -export type { ContentSitemapEntry, ContentSitemapIndexEntry } from "./sitemap"; +export type { + ContentSitemapEntry, + ContentSitemapIndexEntry, + ContentSitemapXmlEntry, +} from "./sitemap"; export { slugify } from "./slug"; export { contentTarget } from "./target"; export type { ContentTarget } from "./target"; diff --git a/packages/api/src/content/server/index.ts b/packages/api/src/content/server/index.ts index 93a4896a1c..3940e28d88 100644 --- a/packages/api/src/content/server/index.ts +++ b/packages/api/src/content/server/index.ts @@ -260,6 +260,8 @@ export { contentListPageCacheTags, contentPublicStateOf, contentRecordPageCacheTags, + contentSitemapInvalidationMode, + contentSitemapPageCacheTags, } from "./page-cache"; export type { ContentPublicState } from "./page-cache"; export { diff --git a/packages/api/src/content/server/page-cache.test.ts b/packages/api/src/content/server/page-cache.test.ts index 325d07df80..f5a6743a40 100644 --- a/packages/api/src/content/server/page-cache.test.ts +++ b/packages/api/src/content/server/page-cache.test.ts @@ -5,23 +5,58 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { EventEmitResult } from "@/models/events"; import type { PageCacheStore } from "@/page-cache/store.server"; +import { defineContentType } from "@/content/define"; +import { field } from "@/content/fields"; import { configurePageCacheStore, createMemoryPageCacheStore, latestPageCacheInvalidation, resetPageCacheStore, } from "@/page-cache/store.server"; -import { testPostContentType } from "@/tests/content-fixtures"; +import { + testDeliveredLocalizedContentType, + testDeliveredPostContentType, + testDuplicableArticleContentType, + testPostContentType, +} from "@/tests/content-fixtures"; import type { ContentEventAction } from "../events"; -import { contentPublicItemTag, contentPublicListTag } from "../cache"; +import { + contentDeliverySitemapTag, + contentPublicItemTag, + contentPublicListTag, +} from "../cache"; import { emitContentEvent } from "./emit"; -import { contentPageInvalidationMode } from "./page-cache"; +import { + contentPageInvalidationMode, + contentSitemapInvalidationMode, + contentSitemapPageCacheTags, +} from "./page-cache"; const RECORD_TAG = contentPublicItemTag(testPostContentType.id, 7); const LIST_TAG = contentPublicListTag(testPostContentType.id); +/** A type whose noindex flag sits in a group, `seo.noIndex`. */ +const nestedNoIndexType = defineContentType({ + id: "test.nested-noindex", + tableName: "test_nested_noindex", + fields: { + title: field.text({ required: true, maxLength: 200 }), + slug: field.slug({ source: "title" }), + seo: field.group({ + fields: { noIndex: field.boolean({ defaultValue: false }) }, + }), + }, + publication: true, + publicApi: { + path: "nested-noindex", + fields: ["id", "title", "slug", "seo.noIndex", "publishedAt"], + defaultOrderBy: "publishedAt", + }, + delivery: { seo: { noIndexField: "seo.noIndex" }, sitemap: true }, +}); + describe("contentPageInvalidationMode", () => { it.each< [ContentEventAction, Record, "hard" | "soft" | null] @@ -49,6 +84,96 @@ describe("contentPageInvalidationMode", () => { }); }); +describe("contentSitemapInvalidationMode", () => { + it.each< + [ + string, + Parameters[0], + ContentEventAction, + Record, + "hard" | "soft" | null, + ] + >([ + [ + "noindex toggled", + testDeliveredPostContentType, + "updated", + { changedFields: ["hidden"] }, + "hard", + ], + [ + "noindex toggled through its parent path", + testDeliveredPostContentType, + "updated", + { changedFields: ["data.hidden"] }, + "hard", + ], + [ + "another field", + testDeliveredPostContentType, + "updated", + { changedFields: ["title"] }, + "soft", + ], + [ + "a field that only starts like it", + testDeliveredPostContentType, + "updated", + { changedFields: ["hiddenAt"] }, + "soft", + ], + ["a removal", testDeliveredPostContentType, "deleted", {}, "hard"], + [ + "no invalidation", + testDeliveredPostContentType, + "scheduled", + { changedFields: ["hidden"] }, + null, + ], + [ + "the group holding the flag", + nestedNoIndexType, + "updated", + { changedFields: ["seo"] }, + "hard", + ], + [ + "the nested flag", + nestedNoIndexType, + "updated", + { changedFields: ["seo.noIndex"] }, + "hard", + ], + [ + "no noIndexField", + testDeliveredLocalizedContentType, + "updated", + { changedFields: ["seo"] }, + "soft", + ], + ])("%s → %s", (_, definition, action, payload, mode) => { + expect(contentSitemapInvalidationMode(definition, action, payload)).toBe( + mode, + ); + }); +}); + +describe("contentSitemapPageCacheTags", () => { + it.each< + [string, Parameters[0], string[]] + >([ + [ + "delivery.sitemap", + testDeliveredPostContentType, + [contentDeliverySitemapTag(testDeliveredPostContentType.id)], + ], + ["delivery without a sitemap", testDuplicableArticleContentType, []], + ["no delivery", testPostContentType, []], + ])("%s", (_, definition, tags) => { + expect(contentSitemapPageCacheTags(definition)).toEqual(tags); + }); +}); + describe("emitContentEvent invalidates cached pages", () => { const EMITTED: EventEmitResult = { delivered: 1, @@ -101,6 +226,36 @@ describe("emitContentEvent invalidates cached pages", () => { expect(await stamp(RECORD_TAG, "hard")).toBe(0); }); + it("hard-invalidates the sitemap of an edit that toggles noindex", async () => { + const recordTag = contentPublicItemTag(testDeliveredPostContentType.id, 7); + const sitemapTag = contentDeliverySitemapTag( + testDeliveredPostContentType.id, + ); + + await emitContentEvent(context(), testDeliveredPostContentType, "updated", { + changedFields: ["hidden"], + contentId: 7, + }); + + expect(await stamp(sitemapTag, "hard")).toBeGreaterThan(0); + expect(await stamp(recordTag, "soft")).toBeGreaterThan(0); + expect(await stamp(recordTag, "hard")).toBe(0); + }); + + it("expires the sitemap with the pages for an ordinary edit", async () => { + const sitemapTag = contentDeliverySitemapTag( + testDeliveredPostContentType.id, + ); + + await emitContentEvent(context(), testDeliveredPostContentType, "updated", { + changedFields: ["title"], + contentId: 7, + }); + + expect(await stamp(sitemapTag, "soft")).toBeGreaterThan(0); + expect(await stamp(sitemapTag, "hard")).toBe(0); + }); + it("reports a store that could not be written with the event's failures", async () => { vi.spyOn(store.tags, "set").mockRejectedValue(new Error("redis down")); diff --git a/packages/api/src/content/server/page-cache.ts b/packages/api/src/content/server/page-cache.ts index be441307a7..9c5e4580a1 100644 --- a/packages/api/src/content/server/page-cache.ts +++ b/packages/api/src/content/server/page-cache.ts @@ -7,7 +7,11 @@ import type { ContentId } from "../ids"; import type { AnyContentTypeDefinition } from "../types"; import { invalidatePageCacheTags } from "../../page-cache/store.server"; -import { contentPublicItemTag, contentPublicListTag } from "../cache"; +import { + contentDeliverySitemapTag, + contentPublicItemTag, + contentPublicListTag, +} from "../cache"; import { contentDependentDefinitions } from "./parent-visibility"; import { bumpContentPublicGeneration } from "./public-cache"; import { isContentBaseRowPublic } from "./visibility"; @@ -78,6 +82,17 @@ export const contentListPageCacheTags = ( definition: AnyContentTypeDefinition, ): string[] => [contentPublicListTag(definition.id)]; +/** + * What a content type's sitemap files depend on: every record of it, in every + * locale. Empty for a type that lists nothing in a sitemap. + */ +export const contentSitemapPageCacheTags = ( + definition: AnyContentTypeDefinition, +): string[] => + definition.delivery.enabled && definition.delivery.sitemap.enabled + ? [contentDeliverySitemapTag(definition.id)] + : []; + /** Changes after which a page must not be served again, even once. */ const HARD_ACTIONS: ReadonlySet = new Set([ "deleted", @@ -120,6 +135,51 @@ const slugChanged = ( ); }; +const noIndexChanged = ( + definition: AnyContentTypeDefinition, + payload: ContentPagePayload, +): boolean => { + const field = definition.delivery.enabled + ? definition.delivery.seo.noIndexField + : null; + if (field === null) return false; + + const { changedFields } = payload; + + return ( + Array.isArray(changedFields) && + changedFields.some( + changed => + typeof changed === "string" && + (changed === field || + field.startsWith(`${changed}.`) || + changed.endsWith(`.${field}`)), + ) + ); +}; + +/** + * How the sitemap files of a content type expire after one change: as the + * pages do, except that toggling the record's `noIndexField` is a hard + * invalidation - a record that left the sitemap must not be listed again. + */ +export const contentSitemapInvalidationMode = ( + definition: AnyContentTypeDefinition, + action: ContentEventAction, + payload: ContentPagePayload, + publicState?: ContentPublicState, +): null | PageCacheInvalidationMode => { + const mode = contentPageInvalidationMode( + definition, + action, + payload, + publicState, + ); + if (mode === null) return null; + + return noIndexChanged(definition, payload) ? "hard" : mode; +}; + export const contentPageInvalidationMode = ( definition: AnyContentTypeDefinition, action: ContentEventAction, @@ -177,14 +237,30 @@ export const invalidateContentPages = async ( // runs from `emitContentEvent`, after the write committed - a bump before the // commit would let a reader store the old row under the new generation. const dependents = contentDependentDefinitions(c, definition); + // The site's sitemap files are cached with the HTML and expire on the same + // write, so a record that left the public site leaves its sitemap too. + const sitemapMode = noIndexChanged(definition, payload) ? "hard" : mode; + const sitemapTags = [definition, ...dependents].flatMap(target => + contentSitemapPageCacheTags(target), + ); const [result, generation] = await Promise.all([ - invalidatePageCacheTags( - [ - ...contentRecordPageCacheTags(definition, recordIdOf(payload)), - ...contentListPageCacheTags(definition), - ...dependents.flatMap(dependent => contentListPageCacheTags(dependent)), - ], - { mode }, + Promise.all([ + invalidatePageCacheTags( + [ + ...contentRecordPageCacheTags(definition, recordIdOf(payload)), + ...contentListPageCacheTags(definition), + ...dependents.flatMap(dependent => + contentListPageCacheTags(dependent), + ), + ...(sitemapMode === mode ? sitemapTags : []), + ], + { mode }, + ), + sitemapMode === mode || sitemapTags.length === 0 + ? Promise.resolve({ status: "done" as const }) + : invalidatePageCacheTags(sitemapTags, { mode: sitemapMode }), + ]).then(([pages, sitemaps]) => + sitemaps.status === "failed" ? sitemaps : pages, ), Promise.all( [definition, ...dependents].map( diff --git a/packages/api/src/content/sitemap.test.ts b/packages/api/src/content/sitemap.test.ts index ebb172ebc5..b6a50493b8 100644 --- a/packages/api/src/content/sitemap.test.ts +++ b/packages/api/src/content/sitemap.test.ts @@ -66,6 +66,20 @@ describe("contentSitemapXml", () => { expect(xml).toContain("https://example.com/articles/my-article"); }); + it.each<[string, Date | null | undefined]>([ + ["absent", undefined], + ["null", null], + ["an invalid date", new Date("not a date")], + ])("omits lastmod when lastModified is %s", (_, lastModified) => { + const xml = contentSitemapXml({ + entries: [{ itemId: 1, lastModified, path: "/about" }], + origin: "https://example.com", + }); + + expect(xml).not.toContain("lastmod"); + expect(xml).toContain("https://example.com/about"); + }); + it("drops an entry whose path will not resolve rather than emitting a bad loc", () => { const xml = contentSitemapXml({ entries: [entry(), entry({ itemId: 2, path: "http://" })], @@ -143,6 +157,10 @@ describe("contentSitemapIndexXml", () => { path: "/sitemaps/blog.article-1.xml", }, { path: "/sitemaps/blog.article-2.xml" }, + { + lastModified: new Date("not a date"), + path: "/sitemaps/blog.article-3.xml", + }, ], origin: "https://example.com", }); @@ -153,7 +171,7 @@ describe("contentSitemapIndexXml", () => { "https://example.com/sitemaps/blog.article-1.xml", ); expect(xml).toContain("2026-01-02T03:04:05.000Z"); - // The second entry has no timestamp, so it carries no `lastmod` element. + // The others have no valid timestamp, so they carry no `lastmod` element. expect(xml.match(//g)).toHaveLength(1); }); }); diff --git a/packages/api/src/content/sitemap.ts b/packages/api/src/content/sitemap.ts index fc9f8aada9..6333796456 100644 --- a/packages/api/src/content/sitemap.ts +++ b/packages/api/src/content/sitemap.ts @@ -20,6 +20,23 @@ export interface ContentSitemapEntry { priority: null | number; } +/** + * One `` element for {@link contentSitemapXml}. A {@link ContentSitemapEntry} + * is one; a URL that is not a content record - an app's own page - leaves out + * what it has no reliable value for, `lastModified` included. + */ +export interface ContentSitemapXmlEntry { + changeFrequency?: ContentSitemapChangeFrequency | null; + /** Keys `alternates`; any value unique within one document. */ + itemId: ContentId; + /** Omit it, or pass `null`, when there is no reliable modification date. */ + lastModified?: Date | null; + locale?: null | string; + origin?: string; + path: string; + priority?: null | number; +} + export const escapeXml = (value: string): string => value .replace(/&/g, "&") @@ -36,13 +53,17 @@ const absolute = (origin: string, path: string): null | string => { } }; +const isValidDate = (value: Date | null | undefined): value is Date => + value instanceof Date && !Number.isNaN(value.getTime()); + /** `priority` at the one precision the protocol illustrates, without a float tail. */ const formatPriority = (priority: number): string => priority.toFixed(1); /** * A `` sitemap document from sitemap entries. Paths resolve against * the entry's own `origin` or `origin`; an entry whose URL cannot be built is - * skipped. `changefreq` and `priority` are left out when `null`. + * skipped. `lastmod`, `changefreq` and `priority` are left out when absent or + * `null`. */ export const contentSitemapXml = ({ alternates, @@ -57,7 +78,7 @@ export const contentSitemapXml = ({ ContentId, readonly { locale: string; origin?: string; path: string }[] >; - entries: readonly ContentSitemapEntry[]; + entries: readonly ContentSitemapXmlEntry[]; origin: string; }): string => { const withAlternates = alternates !== undefined && alternates.size > 0; @@ -74,13 +95,15 @@ export const contentSitemapXml = ({ lines.push(" "); lines.push(` ${escapeXml(loc)}`); - lines.push( - ` ${escapeXml(entry.lastModified.toISOString())}`, - ); - if (entry.changeFrequency !== null) { + if (isValidDate(entry.lastModified)) { + lines.push( + ` ${escapeXml(entry.lastModified.toISOString())}`, + ); + } + if (entry.changeFrequency !== null && entry.changeFrequency !== undefined) { lines.push(` ${entry.changeFrequency}`); } - if (entry.priority !== null) { + if (entry.priority !== null && entry.priority !== undefined) { lines.push(` ${formatPriority(entry.priority)}`); } @@ -135,7 +158,7 @@ export const contentSitemapIndexXml = ({ lines.push(" "); lines.push(` ${escapeXml(loc)}`); - if (entry.lastModified !== undefined) { + if (isValidDate(entry.lastModified)) { lines.push( ` ${escapeXml(entry.lastModified.toISOString())}`, ); diff --git a/packages/create-vitnode-app/copy-of-vitnode-app/root/src/server.ts b/packages/create-vitnode-app/copy-of-vitnode-app/root/src/server.ts index 8cee26f864..3f56aa8a3d 100644 --- a/packages/create-vitnode-app/copy-of-vitnode-app/root/src/server.ts +++ b/packages/create-vitnode-app/copy-of-vitnode-app/root/src/server.ts @@ -1,13 +1,21 @@ import handler from "@tanstack/react-start/server-entry"; import { withPageCache } from "@vitnode/core/tanstack/page-cache/server"; +import { withSeo } from "@vitnode/core/tanstack/seo/server"; import { pageCacheBuildId, pageCacheRoutes } from "@/page-cache.gen"; +import { sitemapManifest } from "@/sitemap-sources.gen"; import { vitNodeConfig } from "@/vitnode.config"; +import { vitNodeServerConfig } from "@/vitnode.server.config"; // Serves pages whose route declares a `cache` policy from VitNode's HTML cache. -// Routes without one pass straight through. -export default withPageCache(handler, { - buildId: pageCacheBuildId, - config: vitNodeConfig, - routes: pageCacheRoutes, -}); +// Routes without one pass straight through. `withSeo` wraps it, so cached and +// fresh pages get the same indexing policy, and it serves `/robots.txt` and +// `/sitemap.xml` from `seo` in `vitnode.server.config.ts`. +export default withSeo( + withPageCache(handler, { + buildId: pageCacheBuildId, + config: vitNodeConfig, + routes: pageCacheRoutes, + }), + { config: vitNodeServerConfig, sitemap: sitemapManifest }, +); diff --git a/packages/create-vitnode-app/copy-of-vitnode-app/root/src/vitnode.server.config.ts b/packages/create-vitnode-app/copy-of-vitnode-app/root/src/vitnode.server.config.ts index 3578eaae84..f641c9b3cd 100644 --- a/packages/create-vitnode-app/copy-of-vitnode-app/root/src/vitnode.server.config.ts +++ b/packages/create-vitnode-app/copy-of-vitnode-app/root/src/vitnode.server.config.ts @@ -9,4 +9,7 @@ export const vitNodeServerConfig = buildServerConfig({ config: vitNodeConfig, messages: appMessages, packageMessages, + seo: { + sitemap: { paths: ["/"] }, + }, }); diff --git a/packages/vitnode/src/content/index.ts b/packages/vitnode/src/content/index.ts index 78310d6863..9a12154bed 100644 --- a/packages/vitnode/src/content/index.ts +++ b/packages/vitnode/src/content/index.ts @@ -607,6 +607,7 @@ export { export type { ContentSitemapEntry, ContentSitemapIndexEntry, + ContentSitemapXmlEntry, } from "@vitnode/api/content/sitemap"; export { slugify } from "@vitnode/api/content/slug"; export { contentTarget } from "@vitnode/api/content/target"; diff --git a/packages/vitnode/src/framework/sitemap-sources/generate.test.ts b/packages/vitnode/src/framework/sitemap-sources/generate.test.ts new file mode 100644 index 0000000000..8412a31ebd --- /dev/null +++ b/packages/vitnode/src/framework/sitemap-sources/generate.test.ts @@ -0,0 +1,181 @@ +import { defineContentType } from "@vitnode/api/content/define"; +import { field } from "@vitnode/api/content/fields"; +import { describe, expect, it } from "vitest"; + +import type { ContentUrlSource } from "../plugin-routes/content-urls.js"; + +import { contentSitemapSourcesFrom, SitemapSourcesError } from "./generate.js"; + +const contentType = ({ + delivery = true, + id, + localized = false, + publicPath, + sitemap = true, +}: { + delivery?: boolean; + id: string; + localized?: boolean; + publicPath?: string; + sitemap?: boolean; +}) => + defineContentType({ + id, + tableName: id.replace(/\W/g, "_"), + ...(localized + ? { localization: { defaultLocale: "en", fallback: "default" } } + : {}), + fields: { + title: field.text({ localized, required: true, maxLength: 200 }), + slug: field.slug({ localized, source: "title" }), + }, + publication: true, + ...(publicPath === undefined + ? {} + : { + publicApi: { + path: publicPath, + fields: ["id", "title", "slug", "publishedAt"], + defaultOrderBy: "publishedAt", + }, + }), + ...(delivery ? { delivery: { sitemap } } : {}), + }); + +const plugin = ( + pluginId: string, + ...contentTypes: ReturnType[] +): ContentUrlSource => ({ contentTypes, pluginId }); + +describe("contentSitemapSourcesFrom", () => { + it("lists only types with a public API, delivery and delivery.sitemap", () => { + const sources = contentSitemapSourcesFrom({ + contentUrls: [ + plugin( + "@vitnode/blog", + contentType({ id: "blog.post", publicPath: "blog" }), + contentType({ + id: "blog.draft", + sitemap: false, + publicPath: "drafts", + }), + contentType({ + delivery: false, + id: "blog.note", + publicPath: "notes", + }), + contentType({ delivery: false, id: "blog.private" }), + ), + ], + locales: ["en"], + }); + + expect(sources).toEqual([ + { + contentTypeId: "blog.post", + file: "blog", + localized: false, + module: "content/blog", + path: "/delivery/sitemap", + pluginId: "@vitnode/blog", + }, + ]); + }); + + it("names the file after the public path and marks localized types", () => { + const [source] = contentSitemapSourcesFrom({ + contentUrls: [ + plugin( + "@vitnode/docs", + contentType({ + id: "docs.page", + localized: true, + publicPath: "docs-pages", + }), + ), + ], + locales: ["en", "pl"], + }); + + expect(source).toMatchObject({ + file: "docs-pages", + localized: true, + module: "content/docs-pages", + }); + }); + + it("prefixes the plugin when two plugins share a public path", () => { + const sources = contentSitemapSourcesFrom({ + contentUrls: [ + plugin( + "@acme/news", + contentType({ id: "news.post", publicPath: "posts" }), + ), + plugin( + "@vitnode/blog", + contentType({ id: "blog.post", publicPath: "posts" }), + ), + plugin( + "@vitnode/wiki", + contentType({ id: "wiki.page", publicPath: "wiki" }), + ), + ], + locales: ["en"], + }); + + expect(sources.map(source => source.file)).toEqual([ + "acme-news-posts", + "vitnode-blog-posts", + "wiki", + ]); + }); + + it("prefixes the plugin for a reserved file name", () => { + const [source] = contentSitemapSourcesFrom({ + contentUrls: [ + plugin( + "@vitnode/cms", + contentType({ id: "cms.page", publicPath: "pages" }), + ), + ], + locales: ["en"], + }); + + expect(source.file).toBe("vitnode-cms-pages"); + }); + + it("throws when a locale file would collide with another type's file", () => { + expect(() => + contentSitemapSourcesFrom({ + contentUrls: [ + plugin( + "@vitnode/blog", + contentType({ id: "blog.post", localized: true, publicPath: "x" }), + contentType({ id: "blog.polish", publicPath: "x-pl" }), + ), + ], + locales: ["en", "pl"], + }), + ).toThrow(SitemapSourcesError); + }); + + it("sorts by plugin and content type, whatever the input order", () => { + const blog = plugin( + "@vitnode/blog", + contentType({ id: "blog.z", publicPath: "z" }), + contentType({ id: "blog.a", publicPath: "a" }), + ); + const docs = plugin( + "@vitnode/docs", + contentType({ id: "docs.page", publicPath: "docs" }), + ); + + const ids = (contentUrls: ContentUrlSource[]) => + contentSitemapSourcesFrom({ contentUrls, locales: ["en"] }).map( + source => source.contentTypeId, + ); + + expect(ids([docs, blog])).toEqual(["blog.a", "blog.z", "docs.page"]); + expect(ids([blog, docs])).toEqual(ids([docs, blog])); + }); +}); diff --git a/packages/vitnode/src/framework/sitemap-sources/generate.ts b/packages/vitnode/src/framework/sitemap-sources/generate.ts new file mode 100644 index 0000000000..3486648949 --- /dev/null +++ b/packages/vitnode/src/framework/sitemap-sources/generate.ts @@ -0,0 +1,180 @@ +import type { SeoContentSitemapSource } from "../../tanstack/seo/manifest.js"; +import type { ContentUrlSource } from "../plugin-routes/content-urls.js"; + +import { + SEO_SITEMAP_FILE_PATTERN, + seoSitemapSlug, +} from "../../tanstack/seo/manifest.js"; +import { toSingleQuotedLiteral } from "../plugin-routes/resolve.js"; + +const ERROR_PREFIX = "[VitNode sitemap sources]"; + +/** Child sitemap stems VitNode keeps for itself. */ +const RESERVED_FILES: ReadonlySet = new Set(["index", "pages"]); + +export class SitemapSourcesError extends Error { + constructor(message: string) { + super(`${ERROR_PREFIX} ${message}`); + this.name = "SitemapSourcesError"; + } +} + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +interface Candidate { + contentTypeId: string; + localized: boolean; + pluginId: string; + publicPath: string; +} + +/** + * The content types a sitemap lists, read off the definitions the plugin + * route check already loaded and validated - so a type whose delivery URL + * has no page has already failed the build. A type is listed only with a + * public API, `delivery` and `delivery.sitemap`. + */ +const candidatesFrom = (sources: readonly ContentUrlSource[]): Candidate[] => + sources.flatMap(source => + source.contentTypes.flatMap((definition): Candidate[] => { + const raw: unknown = definition; + if (!isRecord(raw)) return []; + const { delivery, localization, publicApi } = raw; + if ( + !isRecord(delivery) || + !isRecord(publicApi) || + delivery.enabled !== true || + publicApi.enabled !== true || + !isRecord(delivery.sitemap) || + delivery.sitemap.enabled !== true || + typeof publicApi.path !== "string" || + publicApi.path === "" + ) { + return []; + } + + return [ + { + contentTypeId: definition.id, + localized: isRecord(localization) && localization.enabled === true, + publicPath: publicApi.path, + pluginId: source.pluginId, + }, + ]; + }), + ); + +/** + * The generated sitemap sources: one per listed content type, with a child + * file stem that is unique in the app. The stem is the type's public API + * path (`blog`), or the plugin id and the path together when two plugins + * share a path. Sorted by plugin and content type, so the same plugins give + * the same bytes. + * + * @throws {SitemapSourcesError} When two content types, or a type and one of + * its locales, would share a child sitemap file name. + */ +export const contentSitemapSourcesFrom = ({ + contentUrls, + locales, +}: { + contentUrls: readonly ContentUrlSource[]; + /** Every locale code the app configures, for the per-locale file names. */ + locales: readonly string[]; +}): SeoContentSitemapSource[] => { + const candidates = candidatesFrom(contentUrls).sort((a, b) => + a.pluginId === b.pluginId + ? a.contentTypeId.localeCompare(b.contentTypeId) + : a.pluginId.localeCompare(b.pluginId), + ); + const counts = new Map(); + for (const candidate of candidates) { + const stem = seoSitemapSlug(candidate.publicPath); + counts.set(stem, (counts.get(stem) ?? 0) + 1); + } + + const sources = candidates.map((candidate): SeoContentSitemapSource => { + const stem = seoSitemapSlug(candidate.publicPath); + const file = + (counts.get(stem) ?? 0) > 1 || RESERVED_FILES.has(stem) + ? seoSitemapSlug(`${candidate.pluginId}-${candidate.publicPath}`) + : stem; + + return { + contentTypeId: candidate.contentTypeId, + file, + localized: candidate.localized, + module: `content/${candidate.publicPath}`, + path: "/delivery/sitemap", + pluginId: candidate.pluginId, + }; + }); + + const owners = new Map(); + const claim = (name: string, owner: string): void => { + if (!SEO_SITEMAP_FILE_PATTERN.test(name)) { + throw new SitemapSourcesError( + `Content type "${owner}" would publish the sitemap file "sitemap-${name}-1.xml", which is not a valid file name. Give its public API a path of letters, digits and dashes.`, + ); + } + const existing = owners.get(name); + if (existing !== undefined) { + throw new SitemapSourcesError( + `Content types "${existing}" and "${owner}" would both publish "/sitemap-${name}-1.xml". Rename one public API path (\`publicApi.path\`) so their sitemap files differ.`, + ); + } + owners.set(name, owner); + }; + + for (const source of sources) { + if (source.localized) { + for (const locale of locales) { + claim( + `${source.file}-${seoSitemapSlug(locale)}`, + `${source.contentTypeId} (${locale})`, + ); + } + } else { + claim(source.file, source.contentTypeId); + } + } + + return sources; +}; + +const HEADER = `/* oxlint-disable */ + +// This file is generated by VitNode. Do not edit it, and do not format it. +// +// It is rewritten by the \`vitnode:plugin-routes\` Vite plugin on every +// \`vite dev\` and \`vite build\`: every content type of a configured plugin that +// lists its records in the sitemap (\`delivery.sitemap\`), with the public +// route the site's \`/sitemap.xml\` reads them from. \`src/server.ts\` hands it +// to \`withSeo\`. +// +// \`sitemapManifest.revision\` is replaced at build time with an id unique to +// that build, so two deployments sharing one cache never serve each other's +// sitemaps. + +import type { SeoSitemapManifest } from '@vitnode/core/tanstack/seo/server' + +`; + +export const generateSitemapSourcesSource = ( + sources: readonly SeoContentSitemapSource[], +): string => { + const entries = sources + .map( + source => + ` { contentTypeId: ${toSingleQuotedLiteral(source.contentTypeId)}, file: ${toSingleQuotedLiteral(source.file)}, localized: ${String(source.localized)}, module: ${toSingleQuotedLiteral(source.module)}, path: '/delivery/sitemap', pluginId: ${toSingleQuotedLiteral(source.pluginId)} },\n`, + ) + .join(""); + + return `${HEADER}export const sitemapManifest: SeoSitemapManifest = { + revision: import.meta.env.VITNODE_BUILD_ID, + sources: [ +${entries} ], +} +`; +}; diff --git a/packages/vitnode/src/framework/sitemap-sources/index.ts b/packages/vitnode/src/framework/sitemap-sources/index.ts new file mode 100644 index 0000000000..8441c71547 --- /dev/null +++ b/packages/vitnode/src/framework/sitemap-sources/index.ts @@ -0,0 +1,5 @@ +export { + contentSitemapSourcesFrom, + generateSitemapSourcesSource, + SitemapSourcesError, +} from "./generate.js"; diff --git a/packages/vitnode/src/framework/vite/plugin-routes.ts b/packages/vitnode/src/framework/vite/plugin-routes.ts index 5748cbbc3d..e464134332 100644 --- a/packages/vitnode/src/framework/vite/plugin-routes.ts +++ b/packages/vitnode/src/framework/vite/plugin-routes.ts @@ -63,6 +63,10 @@ import { pluginsFromLoadedConfig, routeDeclarationsFromRoutesModule, } from "../plugin-routes"; +import { + contentSitemapSourcesFrom, + generateSitemapSourcesSource, +} from "../sitemap-sources"; import { createGenerationQueue } from "./generation-queue"; import { versionedModuleUrl } from "./module-version"; import { buildRouteReport } from "./route-report"; @@ -125,6 +129,8 @@ const pathsFor = (appRoot: string) => ({ registry: join(appRoot, "src", "plugin-routes.gen.ts"), + sitemapSources: join(appRoot, "src", "sitemap-sources.gen.ts"), + staleManifest: join(appRoot, "src", "plugin-route-manifest.gen.ts"), /** The file-based router's config, read only for where the routes are. */ routerConfig: join(appRoot, "tsr.config.json"), @@ -605,6 +611,11 @@ const discover = async ( pluginRoutes: compiled.manifest, }); + const sitemapSources = contentSitemapSourcesFrom({ + contentUrls, + locales: i18n?.locales.map(locale => locale.code) ?? [], + }); + return { adminNav: adminNav.modules, apiRegistry: apiRegistry.modules, @@ -621,6 +632,7 @@ const discover = async ( packageMessages, pageCache, pageCacheRoutes, + sitemapSources, watch, }; }; @@ -646,7 +658,7 @@ type DiscoveredRoutes = Omit< pageCacheRoutes: ResolvedPageCacheRoute[]; }; -/** All nine generated files, from one discovery pass. */ +/** All ten generated files, from one discovery pass. */ const writeGenerated = async ( appRoot: string, options: VitNodePluginRoutesOptions, @@ -666,6 +678,7 @@ const writeGenerated = async ( packageMessages, pageCache, pageCacheRoutes, + sitemapSources, } = await discover(appRoot, options, onLoaded); await Promise.all([ @@ -696,6 +709,10 @@ const writeGenerated = async ( paths.pluginInventory, generatePluginInventorySource(inventory), ), + writeIfChanged( + paths.sitemapSources, + generateSitemapSourcesSource(sitemapSources), + ), removeIfPresent(paths.staleManifest), ]); @@ -726,16 +743,26 @@ const SERVER_ENTRY_FILES = [ "server.mjs", ]; -/** Whether `src/server.*` - TanStack Start's custom server entry - uses the page cache. */ -const serverEntryUsesPageCache = (appRoot: string): boolean => - SERVER_ENTRY_FILES.some(name => { - const file = join(appRoot, "src", name); +const serverEntryUses = (appRoot: string, name: string): boolean => + SERVER_ENTRY_FILES.some(entry => { + const file = join(appRoot, "src", entry); - return ( - existsSync(file) && readFileSync(file, "utf8").includes("withPageCache") - ); + return existsSync(file) && readFileSync(file, "utf8").includes(name); }); +/** + * Static files a host serves before the server entry runs, so they would + * shadow what `withSeo` generates for the same URLs. + */ +const shadowedSeoAssets = (appRoot: string): string[] => { + const publicDir = join(appRoot, "public"); + if (!existsSync(publicDir)) return []; + + return readdirSync(publicDir).filter( + name => name === "robots.txt" || /^sitemap.*\.xml$/.test(name), + ); +}; + /** * Identifies one build, so deployments sharing a cache never serve each other's * HTML. `VITNODE_BUILD_ID` at build time wins - a commit SHA, say. @@ -747,8 +774,8 @@ const newBuildId = (): string => /** * Generates the app's `src/*.gen.ts` registries from the plugins configured in * `src/vitnode.config.ts` - plugin routes, API registry, AdminCP navigation and - * content registry, widgets, package messages, page cache and plugin - * inventory - and regenerates them in `vite dev` when a plugin changes. + * content registry, widgets, package messages, page cache, sitemap sources + * and plugin inventory - and regenerates them in `vite dev` when a plugin changes. * * Fails `vite dev` and `vite build` when plugin routes collide with each other * or the app's routes, translated route paths are invalid, or a public content @@ -765,7 +792,7 @@ export const vitNodePluginRoutes = ( return { api: { - pageCacheServed: () => serverEntryUsesPageCache(appRoot), + pageCacheServed: () => serverEntryUses(appRoot, "withPageCache"), pageCacheStorage: () => discovered?.pageCache.enabled === true ? discovered.pageCache.storage @@ -795,6 +822,16 @@ export const vitNodePluginRoutes = ( }; }, + configResolved: resolved => { + if (!serverEntryUses(appRoot, "withSeo")) return; + const shadowed = shadowedSeoAssets(appRoot); + if (shadowed.length === 0) return; + + resolved.logger.warn( + `${ERROR_PREFIX} public/${shadowed.join(", public/")} is served as a static file before \`withSeo\` runs, so it replaces the generated one. Delete it to serve the generated file.`, + ); + }, + configureServer: server => { const watched = new Set([configPath]); diff --git a/packages/vitnode/src/tanstack/fetcher/server.ts b/packages/vitnode/src/tanstack/fetcher/server.ts index 23a39bd7bd..ac1d628b5d 100644 --- a/packages/vitnode/src/tanstack/fetcher/server.ts +++ b/packages/vitnode/src/tanstack/fetcher/server.ts @@ -181,6 +181,40 @@ export const rawFetcher = async ({ return response; }; +/** + * An anonymous server-side API call, for work no visitor may influence - + * public data rendered once for everybody, such as sitemaps. Unlike + * {@link rawFetcher} it sends no cookie, no `Authorization`, no visitor IP or + * user agent, and never relays `Set-Cookie`: the API answers as it would a + * guest, even while a signed-in admin is the one asking. It keeps the same + * transport choice: in process when the API is mounted here, else + * `VITNODE_API_URL` or `VITNODE_WEB_URL` over the network. Server-only. + */ +export const guestRawFetcher = async ({ + localTransport, + options, + origin, + ...args +}: Omit & { + /** + * Answers the request in this process when the API is served here but its + * direct handler is not registered yet - the app's own server entry, say. + */ + localTransport?: ApiTransport; +}): Promise => + await rawApiFetch( + { + ...args, + additionalHeaders: { accept: "application/json" }, + options, + origin: origin ?? resolveApiOrigin(), + }, + inProcessTransport(origin) ?? + (origin === undefined && isApiOnThisOrigin() + ? localTransport + : undefined), + ); + /** What the server-only {@link fetcher} accepts besides the route and `args`. */ export type FetcherServerOptions = FetcherRequestOptions & { /** diff --git a/packages/vitnode/src/tanstack/seo/cache.server.test.ts b/packages/vitnode/src/tanstack/seo/cache.server.test.ts new file mode 100644 index 0000000000..459034c857 --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/cache.server.test.ts @@ -0,0 +1,86 @@ +import { PAGE_CACHE_CLOCK_SKEW_MS } from "@vitnode/api/page-cache/store.server"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import type { SeoSitemapCache } from "./cache.server"; + +import { seoCachedState } from "./cache.server"; + +const NOW = new Date("2026-01-01T00:00:00Z").getTime(); +const STARTED = NOW - 60_000; + +const cacheWith = ({ + bypassUntil = 0, + hard = 0, + soft = 0, +}: { + bypassUntil?: number; + hard?: number; + soft?: number; +}): SeoSitemapCache => ({ + bypassUntil: () => bypassUntil, + delete: async () => {}, + ensure: () => {}, + get: async () => await Promise.resolve(null), + invalidatedAt: async (_, mode) => + await Promise.resolve(mode === "hard" ? hard : soft), + set: async () => {}, +}); + +beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(NOW); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("seoCachedState", () => { + it.each<[string, Parameters[0], string]>([ + ["nothing invalidated", {}, "fresh"], + [ + "invalidated long before the read", + { hard: STARTED - 60_000, soft: STARTED - 60_000 }, + "fresh", + ], + ["soft after the read", { soft: STARTED + 1 }, "stale"], + ["hard after the read", { hard: STARTED + 1 }, "invalid"], + // A hard invalidation inside the skew allowance may have happened after the + // read by another server's clock, so the read is never trusted. + [ + "hard just inside the skew window", + { hard: STARTED - PAGE_CACHE_CLOCK_SKEW_MS }, + "invalid", + ], + [ + "hard just outside the skew window", + { hard: STARTED - PAGE_CACHE_CLOCK_SKEW_MS - 1 }, + "fresh", + ], + [ + "soft just inside the skew window", + { soft: STARTED - PAGE_CACHE_CLOCK_SKEW_MS }, + "stale", + ], + [ + "hard wins over soft", + { hard: STARTED + 1, soft: STARTED + 1 }, + "invalid", + ], + [ + "a failed invalidation still bypassing the cache", + { bypassUntil: NOW + 1 }, + "invalid", + ], + ])("%s → %s", async (_, stamps, state) => { + expect(await seoCachedState(cacheWith(stamps), ["tag"], STARTED)).toBe( + state, + ); + }); + + it("is fresh for data that depends on no tag", async () => { + expect(await seoCachedState(cacheWith({ hard: NOW }), [], STARTED)).toBe( + "fresh", + ); + }); +}); diff --git a/packages/vitnode/src/tanstack/seo/cache.server.ts b/packages/vitnode/src/tanstack/seo/cache.server.ts new file mode 100644 index 0000000000..0bf651a35e --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/cache.server.ts @@ -0,0 +1,133 @@ +import type { PageCacheStorageKind } from "@vitnode/api/page-cache/config"; +import type { + PageCacheInvalidationMode, + PageCacheStore, +} from "@vitnode/api/page-cache/store.server"; + +import { + configurePageCacheStore, + createMemoryPageCacheStore, + latestPageCacheInvalidation, + PAGE_CACHE_CLOCK_SKEW_MS, + pageCacheRuntime, + pageCacheStoreFor, +} from "@vitnode/api/page-cache/store.server"; + +/** How long a completed generation of one child sitemap may be served. */ +export const SEO_SITEMAP_TTL_SECONDS = 60 * 60; + +/** How long the index is kept: shorter than the files it lists. */ +export const SEO_SITEMAP_INDEX_TTL_SECONDS = 10 * 60; + +/** How long an unfinished generation's progress is kept. */ +export const SEO_SITEMAP_BUILD_TTL_SECONDS = 15 * 60; + +/** + * Where generated sitemaps live, and when their data was last invalidated. + * Internal: the default reads the page cache's store, so sitemap XML is + * shared (Redis) or local (memory) exactly as cached pages are, and the + * content invalidations that expire pages reach it too. + */ +export interface SeoSitemapCache { + /** In ms. While in the future, nothing cached may be served. */ + bypassUntil: () => number; + delete: (key: string) => Promise; + /** Registers the store, so invalidations reach it before the first read. */ + ensure: () => void; + get: (key: string) => Promise; + /** The latest invalidation of any of `tags` in one mode, in ms, or `0`. */ + invalidatedAt: ( + tags: readonly string[], + mode: PageCacheInvalidationMode, + ) => Promise; + set: (key: string, value: unknown, ttlSeconds: number) => Promise; +} + +/** `fresh` serves; `stale` serves while a refresh runs; `invalid` never serves. */ +export type SeoCachedState = "fresh" | "invalid" | "stale"; + +/** + * Whether data read at `startedAt` is still good. A hard invalidation within + * the clock-skew allowance of it counts as after it, so a read that raced a + * hidden record is never trusted. + */ +export const seoCachedState = async ( + cache: SeoSitemapCache, + tags: readonly string[], + startedAt: number, +): Promise => { + if (cache.bypassUntil() > Date.now()) return "invalid"; + if (tags.length === 0) return "fresh"; + + const [hard, soft] = await Promise.all([ + cache.invalidatedAt(tags, "hard"), + cache.invalidatedAt(tags, "soft"), + ]); + if (hard >= startedAt - PAGE_CACHE_CLOCK_SKEW_MS) return "invalid"; + if (soft >= startedAt - PAGE_CACHE_CLOCK_SKEW_MS) return "stale"; + + return "fresh"; +}; + +const PREFIX = "seo:"; + +/** How long one serialized child part and its invalidation stamps stay in cache. */ +export const SEO_SITEMAP_PART_TTL_SECONDS = + SEO_SITEMAP_TTL_SECONDS * 2 + + SEO_SITEMAP_INDEX_TTL_SECONDS + + SEO_SITEMAP_BUILD_TTL_SECONDS; + +let warnedFallback = false; + +/** + * The process's page cache store, registered by `withPageCache` - or, when + * the page cache is off, one opened here from `pageCache.storage` and + * registered the same way, so `invalidatePageCacheTags` still reaches the + * sitemaps. Read per call: a dev server can register a new store at any time. + */ +const runtimeStore = (storage: PageCacheStorageKind): PageCacheStore => { + const runtime = pageCacheRuntime(); + if (runtime) { + if (runtime.maxLifetime < SEO_SITEMAP_PART_TTL_SECONDS) { + runtime.maxLifetime = SEO_SITEMAP_PART_TTL_SECONDS; + } + + return runtime.store; + } + + let store = pageCacheStoreFor(storage); + if (store === null) { + if (!warnedFallback) { + warnedFallback = true; + // oxlint-disable-next-line no-console + console.error( + `[vitnode seo] pageCache.storage is "${storage}" but REDIS_URL is not set, so sitemaps are cached in this process only.`, + ); + } + store = createMemoryPageCacheStore(); + } + configurePageCacheStore(store, { maxLifetime: SEO_SITEMAP_PART_TTL_SECONDS }); + + return store; +}; + +export const createSeoSitemapCache = ( + storage: PageCacheStorageKind, +): SeoSitemapCache => ({ + bypassUntil: () => pageCacheRuntime()?.bypassUntil ?? 0, + delete: async key => { + await runtimeStore(storage).entries.set(`${PREFIX}${key}`, null); + }, + ensure: () => { + runtimeStore(storage); + }, + get: async (key: string) => + await runtimeStore(storage).entries.get(`${PREFIX}${key}`), + invalidatedAt: async (tags, mode) => + await latestPageCacheInvalidation(runtimeStore(storage), tags, mode), + set: async (key, value, ttlSeconds) => { + await runtimeStore(storage).entries.set(`${PREFIX}${key}`, value, { + ttl: Math.max(1, Math.ceil(ttlSeconds)), + }); + }, +}); diff --git a/packages/vitnode/src/tanstack/seo/content-transport.server.test.ts b/packages/vitnode/src/tanstack/seo/content-transport.server.test.ts new file mode 100644 index 0000000000..6eee4e5c01 --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/content-transport.server.test.ts @@ -0,0 +1,166 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import type { SeoContentSitemapSource } from "./manifest"; + +import { + createContentSitemapFetch, + readContentSitemapPage, + SeoSitemapSourceError, +} from "./content-transport.server"; + +const SOURCE: SeoContentSitemapSource = { + contentTypeId: "blog.post", + file: "blog", + localized: true, + module: "content/blog", + path: "/delivery/sitemap", + pluginId: "@vitnode/blog", +}; + +const json = (body: unknown, status = 200): Response => + new Response(JSON.stringify(body), { + headers: { "content-type": "application/json" }, + status, + }); + +beforeEach(() => { + // A non-2xx answer is logged by the shared fetch core. + vi.spyOn(console, "error").mockImplementation(() => undefined); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("createContentSitemapFetch", () => { + it("asks the delivery route as a guest and returns the cursor opaque", async () => { + const sent: Request[] = []; + const fetchPage = createContentSitemapFetch({ + localTransport: async request => { + sent.push(request); + + return await Promise.resolve( + json({ + entries: [{ path: "/blog/hello" }], + nextCursor: 1000, + }), + ); + }, + }); + + const page = await fetchPage({ + cursor: "opaque:500", + limit: 1000, + locale: "pl", + source: SOURCE, + }); + + expect(page.nextCursor).toBe("1000"); + expect(sent).toHaveLength(1); + const [request] = sent; + const url = new URL(request.url); + expect(request.method).toBe("GET"); + expect(url.pathname).toBe( + "/api/@vitnode/blog/content/blog/delivery/sitemap", + ); + expect(Object.fromEntries(url.searchParams)).toEqual({ + cursor: "opaque:500", + limit: "1000", + locale: "pl", + }); + expect(request.headers.get("cookie")).toBeNull(); + expect(request.headers.get("authorization")).toBeNull(); + expect(request.headers.get("x-forwarded-for")).toBeNull(); + }); + + it("leaves out the cursor and locale of a first page of an unlocalized type", async () => { + const urls: URL[] = []; + const fetchPage = createContentSitemapFetch({ + localTransport: async request => { + urls.push(new URL(request.url)); + + return await Promise.resolve(json({ entries: [], nextCursor: null })); + }, + }); + + await expect( + fetchPage({ cursor: null, limit: 1000, locale: null, source: SOURCE }), + ).resolves.toEqual({ entries: [], nextCursor: null }); + expect(urls.map(url => Object.fromEntries(url.searchParams))).toEqual([ + { limit: "1000" }, + ]); + }); + + it.each<[string, Response]>([ + ["a 404", json({ entries: [], nextCursor: null }, 404)], + ["a 503", new Response("down", { status: 503 })], + ["a body that is not a page", json({ items: [] })], + ])("throws on %s", async (_, response) => { + const fetchPage = createContentSitemapFetch({ + localTransport: async () => await Promise.resolve(response), + }); + + await expect( + fetchPage({ cursor: null, limit: 1000, locale: null, source: SOURCE }), + ).rejects.toBeInstanceOf(SeoSitemapSourceError); + }); +}); + +describe("readContentSitemapPage", () => { + it.each<[string, unknown]>([ + ["null", null], + ["an array", []], + ["no entries", { nextCursor: null }], + ["an object cursor", { entries: [], nextCursor: { id: 1 } }], + ["a missing cursor", { entries: [] }], + ["an entry without a path", { entries: [{ loc: "/x" }], nextCursor: null }], + ])("rejects %s", (_, body) => { + expect(() => readContentSitemapPage(body, "blog")).toThrow( + SeoSitemapSourceError, + ); + }); + + it("keeps valid optional fields and drops invalid ones", () => { + expect( + readContentSitemapPage( + { + entries: [ + { + changeFrequency: "weekly", + lastModified: "2026-01-02T03:04:05.000Z", + origin: "https://example.pl", + path: "/a", + priority: 0.5, + }, + { + changeFrequency: "sometimes", + lastModified: "not a date", + origin: 7, + path: "/b", + priority: 2, + }, + ], + nextCursor: "next", + }, + "blog", + ), + ).toEqual({ + entries: [ + { + changeFrequency: "weekly", + lastModified: new Date("2026-01-02T03:04:05.000Z"), + origin: "https://example.pl", + path: "/a", + priority: 0.5, + }, + { + changeFrequency: null, + lastModified: null, + path: "/b", + priority: null, + }, + ], + nextCursor: "next", + }); + }); +}); diff --git a/packages/vitnode/src/tanstack/seo/content-transport.server.ts b/packages/vitnode/src/tanstack/seo/content-transport.server.ts new file mode 100644 index 0000000000..76698d8a93 --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/content-transport.server.ts @@ -0,0 +1,155 @@ +import type { ContentSitemapChangeFrequency } from "@vitnode/api/content/types"; + +import { isContentSitemapChangeFrequency } from "@vitnode/api/content/const"; + +import type { SeoContentSitemapSource } from "./manifest"; + +import { guestRawFetcher } from "../fetcher/server"; + +/** One URL of a content sitemap page, as the delivery route reports it. */ +export interface SeoContentSitemapEntry { + changeFrequency: ContentSitemapChangeFrequency | null; + lastModified: Date | null; + origin?: string; + path: string; + priority: null | number; +} + +export interface SeoContentSitemapPage { + entries: SeoContentSitemapEntry[]; + /** Opaque: only ever passed back as `cursor`. `null` on the last page. */ + nextCursor: null | string; +} + +export interface SeoContentSitemapPageRequest { + cursor: null | string; + limit: number; + /** `null` for a content type that is not localized. */ + locale: null | string; + signal?: AbortSignal; + source: SeoContentSitemapSource; +} + +/** + * Reads one page of a content type's `/delivery/sitemap` route. Internal: the + * default is {@link createContentSitemapFetch}; tests and unusual deployments + * pass their own to `withSeo`. + * + * @throws When the source cannot confirm its answer - a network failure, a + * non-`2xx` status or a body of the wrong shape. Never resolves with an empty + * page it did not receive. + */ +export type SeoContentSitemapFetch = ( + request: SeoContentSitemapPageRequest, +) => Promise; + +/** Thrown when a sitemap source answers with something that is not a page. */ +export class SeoSitemapSourceError extends Error { + constructor(message: string) { + super(`[VitNode SEO] ${message}`); + this.name = "SeoSitemapSourceError"; + } +} + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +const REQUEST_TIMEOUT_MS = 10_000; + +const readEntry = (value: unknown, where: string): SeoContentSitemapEntry => { + if (!isRecord(value) || typeof value.path !== "string") { + throw new SeoSitemapSourceError( + `${where} returned an entry without a path.`, + ); + } + const lastModified = + typeof value.lastModified === "string" + ? new Date(value.lastModified) + : null; + + return { + changeFrequency: isContentSitemapChangeFrequency(value.changeFrequency) + ? value.changeFrequency + : null, + lastModified: + lastModified && !Number.isNaN(lastModified.getTime()) + ? lastModified + : null, + ...(typeof value.origin === "string" ? { origin: value.origin } : {}), + path: value.path, + priority: + typeof value.priority === "number" && + value.priority >= 0 && + value.priority <= 1 + ? value.priority + : null, + }; +}; + +export const readContentSitemapPage = ( + body: unknown, + where: string, +): SeoContentSitemapPage => { + if (!isRecord(body) || !Array.isArray(body.entries)) { + throw new SeoSitemapSourceError(`${where} did not return a sitemap page.`); + } + const { nextCursor } = body; + if ( + nextCursor !== null && + typeof nextCursor !== "string" && + typeof nextCursor !== "number" + ) { + throw new SeoSitemapSourceError(`${where} returned an invalid nextCursor.`); + } + + return { + entries: body.entries.map(entry => readEntry(entry, where)), + nextCursor: nextCursor === null ? null : String(nextCursor), + }; +}; + +/** + * The default {@link SeoContentSitemapFetch}: an anonymous request with no + * cookie or `Authorization`, in process when the API is mounted here and + * over the network to `VITNODE_API_URL` otherwise. The API keeps its own + * publication, visibility, locale and `noindex` filtering. + * + * In a single app the API's direct handler is registered only once its + * route module loads, so `localTransport` - the app's own server entry - + * answers the first requests in process instead of over the network. + */ +export const createContentSitemapFetch = + ({ + localTransport, + }: { + /** Serves `/api/*` in this process when the API is mounted here. */ + localTransport?: (request: Request) => Promise; + } = {}): SeoContentSitemapFetch => + async ({ cursor, limit, locale, signal, source }) => { + const where = `${source.pluginId} ${source.module}${source.path}`; + const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS); + const response = await guestRawFetcher({ + localTransport, + method: "get", + module: source.module, + options: { + signal: signal ? AbortSignal.any([signal, timeout]) : timeout, + }, + path: source.path, + pluginId: source.pluginId, + query: { + cursor: cursor ?? undefined, + limit: String(limit), + locale: locale ?? undefined, + }, + }); + + if (!response.ok) { + await response.body?.cancel(); + throw new SeoSitemapSourceError( + `${where} answered ${String(response.status)}.`, + ); + } + + return readContentSitemapPage(await response.json(), where); + }; diff --git a/packages/vitnode/src/tanstack/seo/html.server.test.ts b/packages/vitnode/src/tanstack/seo/html.server.test.ts new file mode 100644 index 0000000000..2a0dd6fda0 --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/html.server.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from "vitest"; + +import { + injectNoIndexMeta, + withNoIndexDocument, + withNoIndexHeader, +} from "./html.server"; + +const META = ''; + +const page = (robots?: string): Response => + new Response("Hi", { + headers: { + "content-type": "text/html; charset=utf-8", + ...(robots === undefined ? {} : { "x-robots-tag": robots }), + }, + status: 200, + }); + +describe("withNoIndexHeader", () => { + it.each<[string | undefined, string]>([ + [undefined, "noindex"], + ["nofollow", "nofollow, noindex"], + ["noindex, nofollow", "noindex, nofollow"], + ["NoIndex", "NoIndex"], + ["none", "none"], + ])("%j → %j", (existing, expected) => { + expect(withNoIndexHeader(page(existing)).headers.get("x-robots-tag")).toBe( + expected, + ); + }); + + it("keeps the status and body", async () => { + const response = withNoIndexHeader( + new Response("

gone

", { + headers: { "content-type": "text/html" }, + status: 404, + }), + ); + + expect(response.status).toBe(404); + expect(await response.text()).toBe("

gone

"); + }); +}); + +describe("injectNoIndexMeta", () => { + it.each<[string, string]>([ + [ + "x", + `${META}x`, + ], + [ + 'x', + `${META}x`, + ], + [`${META}`, `${META}`], + [ + "
no head
", + "
no head
", + ], + ])("%j", (html, expected) => { + expect(injectNoIndexMeta(html)).toBe(expected); + }); +}); + +describe("withNoIndexDocument", () => { + it("adds the meta and the header and drops a stale content-length", async () => { + const source = page("nofollow"); + source.headers.set("content-length", "10"); + + const response = await withNoIndexDocument(source); + + expect(await response.text()).toContain(`${META}`); + expect(response.headers.get("x-robots-tag")).toBe("nofollow, noindex"); + expect(response.headers.get("content-length")).toBeNull(); + }); +}); diff --git a/packages/vitnode/src/tanstack/seo/html.server.ts b/packages/vitnode/src/tanstack/seo/html.server.ts new file mode 100644 index 0000000000..4c95b753ee --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/html.server.ts @@ -0,0 +1,65 @@ +const ROBOTS_HEADER = "x-robots-tag"; + +const saysNoIndex = (value: string): boolean => + value + .split(",") + .map(part => part.trim().toLowerCase()) + .some(part => part === "noindex" || part === "none"); + +export const isHtmlResponse = (response: Response): boolean => + (response.headers.get("content-type") ?? "") + .toLowerCase() + .startsWith("text/html"); + +/** + * Adds `X-Robots-Tag: noindex` to an HTML response, keeping any directive it + * already carries - a record's own `noindex, nofollow`, say. The page stays + * crawlable, which is what lets a search engine read the directive. + */ +export const withNoIndexHeader = (response: Response): Response => { + const existing = response.headers.get(ROBOTS_HEADER); + if (existing !== null && saysNoIndex(existing)) return response; + + const headers = new Headers(response.headers); + headers.append(ROBOTS_HEADER, "noindex"); + + return new Response(response.body, { + headers, + status: response.status, + statusText: response.statusText, + }); +}; + +const ROBOTS_META = '<meta name="robots" content="noindex"/>'; + +/** + * Writes a robots `noindex` meta tag into a document, right after `<head>`. + * For prerendered pages, which a host serves as static files without the + * server that would add `X-Robots-Tag`. Other robots tags stay: a crawler + * applies the most restrictive one. + */ +export const injectNoIndexMeta = (html: string): string => { + if (html.includes(ROBOTS_META)) return html; + + const head = /<head(?:\s[^>]*)?>/i.exec(html); + if (!head) return html; + const at = head.index + head[0].length; + + return `${html.slice(0, at)}${ROBOTS_META}${html.slice(at)}`; +}; + +/** {@link withNoIndexHeader} plus {@link injectNoIndexMeta}, for a prerender. */ +export const withNoIndexDocument = async ( + response: Response, +): Promise<Response> => { + const tagged = withNoIndexHeader(response); + const headers = new Headers(tagged.headers); + headers.delete("content-length"); + const html = injectNoIndexMeta(await tagged.text()); + + return new Response(html, { + headers, + status: tagged.status, + statusText: tagged.statusText, + }); +}; diff --git a/packages/vitnode/src/tanstack/seo/manifest.ts b/packages/vitnode/src/tanstack/seo/manifest.ts new file mode 100644 index 0000000000..7edf328acb --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/manifest.ts @@ -0,0 +1,53 @@ +/** + * One content type whose records the generated sitemap lists, as the VitNode + * Vite plugin writes it into `src/sitemap-sources.gen.ts`: every content type + * of a configured plugin with a public API, `delivery` and `delivery.sitemap`. + */ +export interface SeoContentSitemapSource { + /** The content type's id, e.g. `blog.post`. Its cache tags are keyed on it. */ + contentTypeId: string; + /** + * The child sitemap name stem, unique in the app: `blog` gives + * `/sitemap-blog-1.xml`, or `/sitemap-blog-pl-1.xml` per locale. + */ + file: string; + /** Whether each locale is its own file, read with `?locale=`. */ + localized: boolean; + /** The public API module, `content/<publicApi.path>`. */ + module: string; + /** The delivery sitemap route within `module`. */ + path: "/delivery/sitemap"; + /** The plugin id the module is mounted under, e.g. `@vitnode/blog`. */ + pluginId: string; +} + +/** What `src/sitemap-sources.gen.ts` exports. */ +export interface SeoSitemapManifest { + /** Changes with every build, so a deployment never serves another's XML. */ + revision: string; + sources: readonly SeoContentSitemapSource[]; +} + +/** A child sitemap name stem: lowercase letters, digits and single dashes. */ +export const SEO_SITEMAP_FILE_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; + +/** `/sitemap-{file}-{part}.xml`, `part` counted from 1. */ +export const seoSitemapChildPath = (file: string, part: number): string => + `/sitemap-${file}-${String(part)}.xml`; + +/** The `{file}` and `{part}` of a child sitemap path, or `null`. */ +export const parseSeoSitemapChildPath = ( + pathname: string, +): null | { file: string; part: number } => { + const match = /^\/sitemap-([a-z0-9-]+)-([1-9]\d{0,5})\.xml$/.exec(pathname); + if (!match) return null; + + return { file: match[1], part: Number(match[2]) }; +}; + +/** `"@vitnode/blog"` -> `"vitnode-blog"`, `"Content/Blog_Posts"` -> `"content-blog-posts"`. */ +export const seoSitemapSlug = (value: string): string => + value + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); diff --git a/packages/vitnode/src/tanstack/seo/policy.server.test.ts b/packages/vitnode/src/tanstack/seo/policy.server.test.ts new file mode 100644 index 0000000000..b0a646e3ed --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/policy.server.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from "vitest"; + +import { + normalizeSeoSitemapPath, + resolveSeoPolicy, + SeoConfigError, +} from "./policy.server"; + +const LOCALES = ["en", "pl"]; + +describe("resolveSeoPolicy", () => { + it.each<[string, unknown]>([ + ["`seo` left out", undefined], + ["`indexing` left out", {}], + ])("defaults to indexing on with %s", (_, value) => { + expect(resolveSeoPolicy(value)).toEqual( + resolveSeoPolicy({ indexing: true }), + ); + expect(resolveSeoPolicy(value).indexing).toBe(true); + }); + + it.each<[string, unknown]>([ + ["not an object", "yes"], + ["string indexing", { indexing: "true" }], + ["unknown top-level key", { indexing: true, robots: true }], + ["unknown sitemap key", { indexing: true, sitemap: { files: [] } }], + [ + "non-boolean sitemap.enabled", + { indexing: true, sitemap: { enabled: 1 } }, + ], + ["non-array sitemap.paths", { indexing: true, sitemap: { paths: "/" } }], + ["unknown crawler vendor", { crawlers: { bing: true }, indexing: true }], + [ + "unknown crawler use", + { crawlers: { openai: { ads: true } }, indexing: true }, + ], + [ + "non-boolean crawler", + { crawlers: { anthropic: { search: "no" } }, indexing: true }, + ], + [ + "non-boolean googleExtended", + { crawlers: { googleExtended: null }, indexing: true }, + ], + ])("throws SeoConfigError for %s", (_, value) => { + expect(() => resolveSeoPolicy(value)).toThrow(SeoConfigError); + }); + + it.each<[string, unknown, boolean]>([ + ["indexing on, sitemap left out", { indexing: true }, true], + ["indexing off, sitemap left out", { indexing: false }, false], + [ + "indexing on, sitemap off", + { indexing: true, sitemap: { enabled: false } }, + false, + ], + [ + "indexing off forces the sitemap off", + { indexing: false, sitemap: { enabled: true } }, + false, + ], + [ + "indexing on, sitemap object without enabled", + { indexing: true, sitemap: {} }, + true, + ], + ])("%s → sitemap.enabled %s", (_, value, enabled) => { + expect(resolveSeoPolicy(value).sitemap.enabled).toBe(enabled); + }); + + it("normalizes and deduplicates sitemap paths in declaration order", () => { + expect( + resolveSeoPolicy( + { + indexing: true, + sitemap: { paths: ["/about/", "/", "/about", "/plugins"] }, + }, + { locales: LOCALES }, + ).sitemap.paths, + ).toEqual(["/about", "/", "/plugins"]); + }); + + it("rejects a sitemap path that starts with a configured locale", () => { + expect(() => + resolveSeoPolicy( + { indexing: true, sitemap: { paths: ["/pl/about"] } }, + { locales: LOCALES }, + ), + ).toThrow(SeoConfigError); + }); +}); + +describe("normalizeSeoSitemapPath", () => { + it.each<[string, string]>([ + ["/", "/"], + ["/about", "/about"], + ["/about/", "/about"], + ["/docs/dev", "/docs/dev"], + ["/administrator", "/administrator"], + ["/english", "/english"], + ])("%j → %j", (value, expected) => { + expect(normalizeSeoSitemapPath(value, LOCALES)).toBe(expected); + }); + + it.each<[string, unknown]>([ + ["non-string", 42], + ["empty string", ""], + ["relative path", "about"], + ["protocol-relative URL", "//evil.com/about"], + ["absolute URL", "https://example.com/about"], + ["empty segment", "/docs//dev"], + ["query", "/search?q=x"], + ["hash", "/about#team"], + ["whitespace", "/about us"], + ["backslash", "/about\\team"], + ["dot segment", "/docs/./dev"], + ["parent segment", "/docs/../admin"], + ["/admin", "/admin"], + ["/admin subpath", "/admin/core/users"], + ["/api subpath", "/API/users"], + ["locale prefix", "/pl"], + ["locale-prefixed path", "/en/about"], + ])("rejects %s", (_, value) => { + expect(() => normalizeSeoSitemapPath(value, LOCALES)).toThrow( + SeoConfigError, + ); + }); +}); diff --git a/packages/vitnode/src/tanstack/seo/policy.server.ts b/packages/vitnode/src/tanstack/seo/policy.server.ts new file mode 100644 index 0000000000..4756a519db --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/policy.server.ts @@ -0,0 +1,236 @@ +import type { LocaleRouting } from "@vitnode/api/lib/i18n/locale-routing"; + +/** Thrown when `buildServerConfig({ seo })` holds an invalid value. */ +export class SeoConfigError extends Error { + constructor(message: string) { + super(`[VitNode SEO] ${message}`); + this.name = "SeoConfigError"; + } +} + +/** One named `User-agent` group the config adds to `/robots.txt`. */ +export interface SeoCrawlerRule { + /** `true` allows the site with the baseline exclusions; `false` is `Disallow: /`. */ + allow: boolean; + token: string; +} + +export interface ResolvedSeoPolicy { + crawlers: readonly SeoCrawlerRule[]; + indexing: boolean; + sitemap: { + enabled: boolean; + /** Normalized, deduplicated, unlocalized paths. */ + paths: readonly string[]; + }; +} + +const isRecord = (value: unknown): value is Record<string, unknown> => + typeof value === "object" && value !== null && !Array.isArray(value); + +const SEO_KEYS: ReadonlySet<string> = new Set([ + "crawlers", + "indexing", + "sitemap", +]); +const SITEMAP_KEYS: ReadonlySet<string> = new Set(["enabled", "paths"]); +const CRAWLERS_KEYS: ReadonlySet<string> = new Set([ + "anthropic", + "googleExtended", + "openai", +]); +const CRAWLER_PAIR_KEYS: ReadonlySet<string> = new Set(["search", "training"]); + +const assertKeys = ( + value: Record<string, unknown>, + allowed: ReadonlySet<string>, + where: string, +): void => { + for (const key of Object.keys(value)) { + if (!allowed.has(key)) { + throw new SeoConfigError( + `${where}.${key} is not an option. Use ${[...allowed].map(name => `\`${name}\``).join(", ")}.`, + ); + } + } +}; + +const optionalBoolean = ( + value: unknown, + where: string, +): boolean | undefined => { + if (value === undefined) return undefined; + if (typeof value !== "boolean") { + throw new SeoConfigError(`${where} must be \`true\` or \`false\`.`); + } + + return value; +}; + +const CRAWLER_TOKENS = { + anthropic: { search: "Claude-SearchBot", training: "ClaudeBot" }, + googleExtended: "Google-Extended", + openai: { search: "OAI-SearchBot", training: "GPTBot" }, +} as const; + +const resolveCrawlers = (value: unknown): SeoCrawlerRule[] => { + if (value === undefined) return []; + if (!isRecord(value)) { + throw new SeoConfigError("`seo.crawlers` must be an object."); + } + assertKeys(value, CRAWLERS_KEYS, "seo.crawlers"); + + const rules: SeoCrawlerRule[] = []; + for (const vendor of ["openai", "anthropic"] as const) { + const pair = value[vendor]; + if (pair === undefined) continue; + const where = `seo.crawlers.${vendor}`; + if (!isRecord(pair)) + throw new SeoConfigError(`${where} must be an object.`); + assertKeys(pair, CRAWLER_PAIR_KEYS, where); + + for (const use of ["search", "training"] as const) { + const allow = optionalBoolean(pair[use], `${where}.${use}`); + if (allow !== undefined) { + rules.push({ allow, token: CRAWLER_TOKENS[vendor][use] }); + } + } + } + + const gemini = optionalBoolean( + value.googleExtended, + "seo.crawlers.googleExtended", + ); + if (gemini !== undefined) { + rules.push({ allow: gemini, token: CRAWLER_TOKENS.googleExtended }); + } + + return rules; +}; + +const RESERVED_PREFIXES = ["/admin", "/api"]; +const PATH_BASE = "https://vitnode.invalid"; + +/** + * One `seo.sitemap.paths` entry as a canonical unlocalized path, or a thrown + * {@link SeoConfigError} saying why it cannot be one. + */ +export const normalizeSeoSitemapPath = ( + value: unknown, + locales: readonly string[] = [], +): string => { + const where = `seo.sitemap.paths entry ${JSON.stringify(value)}`; + if (typeof value !== "string" || value === "") { + throw new SeoConfigError(`${where} must be a non-empty string.`); + } + if (!value.startsWith("/") || value.startsWith("//")) { + throw new SeoConfigError( + `${where} must be a path on this site starting with a single "/", like "/about".`, + ); + } + if (/[\\?#\s]/.test(value)) { + throw new SeoConfigError( + `${where} must not hold a query, a hash, whitespace or a backslash. List canonical URLs only.`, + ); + } + if (value.split("/").some(segment => segment === "." || segment === "..")) { + throw new SeoConfigError(`${where} must not hold "." or ".." segments.`); + } + if (/\/{2,}/.test(value)) { + throw new SeoConfigError(`${where} must not hold empty segments ("//").`); + } + + let pathname: string; + try { + pathname = new URL(value, PATH_BASE).pathname; + } catch { + throw new SeoConfigError(`${where} is not a valid URL path.`); + } + if (pathname.length > 1 && pathname.endsWith("/")) { + pathname = pathname.slice(0, -1); + } + + const lower = pathname.toLowerCase(); + if ( + RESERVED_PREFIXES.some( + prefix => lower === prefix || lower.startsWith(`${prefix}/`), + ) + ) { + throw new SeoConfigError( + `${where} is under /admin or /api, which are never public pages.`, + ); + } + + const [, first] = pathname.split("/"); + if (first !== undefined && locales.includes(first)) { + throw new SeoConfigError( + `${where} starts with the locale "${first}". List the unlocalized path - every locale's URL is added for you.`, + ); + } + + return pathname; +}; + +/** + * Checks `buildServerConfig({ seo })` and fills in its defaults. `seo` left + * out is `{ indexing: true }`, and so is an `indexing` left out. Server-only. + * + * @throws {SeoConfigError} When a value is invalid. + */ +export const resolveSeoPolicy = ( + value: unknown = {}, + { locales = [] }: { locales?: readonly string[] } = {}, +): ResolvedSeoPolicy => { + if (!isRecord(value)) throw new SeoConfigError("`seo` must be an object."); + assertKeys(value, SEO_KEYS, "seo"); + + const indexing = optionalBoolean(value.indexing, "seo.indexing") ?? true; + + let sitemapEnabled = indexing; + let paths: string[] = []; + if (value.sitemap !== undefined) { + if (!isRecord(value.sitemap)) { + throw new SeoConfigError("`seo.sitemap` must be an object."); + } + assertKeys(value.sitemap, SITEMAP_KEYS, "seo.sitemap"); + sitemapEnabled = + optionalBoolean(value.sitemap.enabled, "seo.sitemap.enabled") ?? indexing; + + const declared = value.sitemap.paths ?? []; + if (!Array.isArray(declared)) { + throw new SeoConfigError("`seo.sitemap.paths` must be an array."); + } + paths = [ + ...new Set(declared.map(path => normalizeSeoSitemapPath(path, locales))), + ]; + } + + return { + crawlers: resolveCrawlers(value.crawlers), + indexing, + // Indexing off wins: a sitemap invites crawlers to index what it lists. + sitemap: { enabled: indexing && sitemapEnabled, paths }, + }; +}; + +/** + * The trusted origin a request is served for: a configured locale domain when + * the request's host is one, else the web origin (`VITNODE_WEB_URL`). The + * request's own `Host` or forwarding headers only ever pick among configured + * origins; they never become a URL. + */ +export const trustedOriginFor = ( + url: URL, + routing: LocaleRouting, + webOrigin: string, +): string => routing.domainForHost(url.host)?.origin ?? webOrigin; + +/** The locales whose canonical URLs live on `origin`. */ +export const localesOnOrigin = ( + routing: LocaleRouting, + origin: string, + webOrigin: string, +): string[] => + routing.locales.filter( + locale => (routing.domainForLocale(locale)?.origin ?? webOrigin) === origin, + ); diff --git a/packages/vitnode/src/tanstack/seo/revalidate.server.test.ts b/packages/vitnode/src/tanstack/seo/revalidate.server.test.ts new file mode 100644 index 0000000000..83779975a2 --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/revalidate.server.test.ts @@ -0,0 +1,150 @@ +import type { PageCacheStore } from "@vitnode/api/page-cache/store.server"; + +import { + contentDeliverySitemapTag, + contentPublicItemTag, + contentPublicListTag, +} from "@vitnode/api/content/cache"; +import { + CONTENT_REVALIDATE_PATH, + CONTENT_REVALIDATE_TIMESTAMP_HEADER, +} from "@vitnode/api/content/server/revalidate-bridge"; +import { INSECURE_DEFAULT_CRON_SECRET } from "@vitnode/api/lib/config"; +import { + configurePageCacheStore, + createMemoryPageCacheStore, + latestPageCacheInvalidation, + resetPageCacheStore, +} from "@vitnode/api/page-cache/store.server"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { handleContentRevalidation } from "./revalidate.server"; + +const SECRET = "test-revalidation-secret"; +const TYPE = "blog.post"; + +let store: PageCacheStore; + +const ensure = () => { + configurePageCacheStore(store, { maxLifetime: 3600 }); +}; + +const body = (overrides: Record<string, unknown> = {}) => ({ + contentTypeId: TYPE, + delivery: { sitemap: { contentChanged: true, indexChanged: false } }, + id: 7, + isPublic: false, + mode: "immediate", + slugs: ["hello"], + wasPublic: true, + ...overrides, +}); + +const post = async ({ + bearer = SECRET, + payload = body(), + sentAt = Date.now(), +}: { + bearer?: null | string; + payload?: unknown; + sentAt?: number; +} = {}): Promise<number> => { + const response = await handleContentRevalidation( + new Request(new URL(CONTENT_REVALIDATE_PATH, "https://example.com"), { + body: typeof payload === "string" ? payload : JSON.stringify(payload), + headers: { + ...(bearer === null ? {} : { authorization: `Bearer ${bearer}` }), + [CONTENT_REVALIDATE_TIMESTAMP_HEADER]: String(sentAt), + "content-type": "application/json", + }, + method: "POST", + }), + ensure, + ); + + return response.status; +}; + +const stamp = async (tag: string, mode: "hard" | "soft") => + await latestPageCacheInvalidation(store, [tag], mode); + +beforeEach(() => { + vi.stubEnv("CRON_SECRET", SECRET); + store = createMemoryPageCacheStore(); + resetPageCacheStore(); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + resetPageCacheStore(); +}); + +describe("handleContentRevalidation", () => { + it.each<[string, Parameters<typeof post>[0]]>([ + ["no bearer", { bearer: null }], + ["a wrong bearer", { bearer: "not-the-secret" }], + ["a stale timestamp", { sentAt: Date.now() - 6 * 60 * 1000 }], + ["a timestamp from the future", { sentAt: Date.now() + 6 * 60 * 1000 }], + ])("answers 403 to %s", async (_, request) => { + expect(await post(request)).toBe(403); + expect(await stamp(contentDeliverySitemapTag(TYPE), "hard")).toBe(0); + }); + + it("answers 403 while CRON_SECRET is still the insecure default", async () => { + vi.stubEnv("CRON_SECRET", INSECURE_DEFAULT_CRON_SECRET); + + expect(await post({ bearer: INSECURE_DEFAULT_CRON_SECRET })).toBe(403); + }); + + it.each<[string, unknown]>([ + ["a body that is not JSON", "{not json"], + ["an unknown mode", body({ mode: "later" })], + ["a missing id", body({ id: undefined })], + ["a malformed delivery", body({ delivery: { sitemap: true } })], + ["malformed locales", body({ locales: [{ locale: "pl" }] })], + ])("answers 400 to %s", async (_, payload) => { + expect(await post({ payload })).toBe(400); + }); + + it("hard-invalidates only the sitemap tags for an immediate change", async () => { + expect(await post()).toBe(204); + + expect( + await stamp(contentDeliverySitemapTag(TYPE), "hard"), + ).toBeGreaterThan(0); + expect(await stamp(contentDeliverySitemapTag(TYPE), "soft")).toBe(0); + for (const tag of [ + contentPublicListTag(TYPE), + contentPublicItemTag(TYPE, 7), + ]) { + expect(await stamp(tag, "hard")).toBe(0); + expect(await stamp(tag, "soft")).toBe(0); + } + }); + + it("soft-invalidates a stale-while-revalidate change, per locale", async () => { + expect( + await post({ + payload: body({ + delivery: { sitemap: { contentChanged: true, indexChanged: false } }, + locales: [ + { isPublic: true, locale: "pl", slugs: ["witaj"], wasPublic: true }, + ], + mode: "stale-while-revalidate", + }), + }), + ).toBe(204); + + expect( + await stamp(contentDeliverySitemapTag(TYPE, "pl"), "soft"), + ).toBeGreaterThan(0); + expect(await stamp(contentDeliverySitemapTag(TYPE, "pl"), "hard")).toBe(0); + // The locale-less tag is the index of locale files: unchanged here. + expect(await stamp(contentDeliverySitemapTag(TYPE), "soft")).toBe(0); + }); + + it("answers 204 without touching the store when no sitemap is affected", async () => { + expect(await post({ payload: body({ delivery: undefined }) })).toBe(204); + expect(await stamp(contentDeliverySitemapTag(TYPE), "hard")).toBe(0); + }); +}); diff --git a/packages/vitnode/src/tanstack/seo/revalidate.server.ts b/packages/vitnode/src/tanstack/seo/revalidate.server.ts new file mode 100644 index 0000000000..e8a7e2d538 --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/revalidate.server.ts @@ -0,0 +1,193 @@ +import type { ContentLocaleInvalidation } from "@vitnode/api/content/cache"; +import type { ContentRevalidationRequest } from "@vitnode/api/content/server/revalidate-bridge"; + +import { + contentDeliverySitemapTag, + contentInvalidationTags, +} from "@vitnode/api/content/cache"; +import { + CONTENT_REVALIDATE_MAX_SKEW_MS, + CONTENT_REVALIDATE_TIMESTAMP_HEADER, +} from "@vitnode/api/content/server/revalidate-bridge"; +import { CONFIG, isCronSecretRejected } from "@vitnode/api/lib/config"; +import { invalidatePageCacheTags } from "@vitnode/api/page-cache/store.server"; + +const isRecord = (value: unknown): value is Record<string, unknown> => + typeof value === "object" && value !== null && !Array.isArray(value); + +const isStringArray = (value: unknown): value is string[] => + Array.isArray(value) && value.every(item => typeof item === "string"); + +const digest = async (value: string): Promise<Uint8Array> => + new Uint8Array( + await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)), + ); + +/** Compares two secrets in constant time, through fixed-length digests. */ +const sameSecret = async ( + given: string, + expected: string, +): Promise<boolean> => { + const [a, b] = await Promise.all([digest(given), digest(expected)]); + let difference = 0; + for (let index = 0; index < a.length; index += 1) { + difference |= a[index] ^ b[index]; + } + + return difference === 0; +}; + +/** Whether a request carries the shared `CRON_SECRET` and a recent timestamp. */ +export const isTrustedContentRevalidation = async ( + request: Request, + secret: string = CONFIG.cronJobSecret, +): Promise<boolean> => { + if (isCronSecretRejected(secret)) return false; + + const bearer = /^Bearer (.+)$/.exec( + request.headers.get("authorization") ?? "", + )?.[1]; + if (bearer === undefined || !(await sameSecret(bearer, secret))) { + return false; + } + + const sentAt = Number( + request.headers.get(CONTENT_REVALIDATE_TIMESTAMP_HEADER), + ); + + return ( + Number.isFinite(sentAt) && + Math.abs(Date.now() - sentAt) <= CONTENT_REVALIDATE_MAX_SKEW_MS + ); +}; + +const readLocaleInvalidation = ( + entry: unknown, +): ContentLocaleInvalidation | null => { + if ( + !isRecord(entry) || + typeof entry.locale !== "string" || + typeof entry.isPublic !== "boolean" || + typeof entry.wasPublic !== "boolean" || + !isStringArray(entry.slugs) + ) { + return null; + } + + return { + isPublic: entry.isPublic, + locale: entry.locale, + slugs: entry.slugs, + wasPublic: entry.wasPublic, + }; +}; + +/** The body `dispatchContentRevalidation` posts, or `null`. */ +export const readContentRevalidation = ( + body: unknown, +): ContentRevalidationRequest | null => { + if ( + !isRecord(body) || + typeof body.contentTypeId !== "string" || + (typeof body.id !== "string" && typeof body.id !== "number") || + typeof body.isPublic !== "boolean" || + typeof body.wasPublic !== "boolean" || + !isStringArray(body.slugs) || + (body.mode !== "immediate" && body.mode !== "stale-while-revalidate") + ) { + return null; + } + + let locales: ContentLocaleInvalidation[] | undefined; + if (body.locales !== undefined) { + if (!Array.isArray(body.locales)) return null; + locales = []; + for (const entry of body.locales) { + const parsed = readLocaleInvalidation(entry); + if (parsed === null) return null; + locales.push(parsed); + } + } + + let delivery: ContentRevalidationRequest["delivery"]; + if (body.delivery !== undefined) { + if ( + !isRecord(body.delivery) || + !isRecord(body.delivery.sitemap) || + typeof body.delivery.sitemap.contentChanged !== "boolean" || + typeof body.delivery.sitemap.indexChanged !== "boolean" + ) { + return null; + } + delivery = { + sitemap: { + contentChanged: body.delivery.sitemap.contentChanged, + indexChanged: body.delivery.sitemap.indexChanged, + }, + }; + } + + return { + contentTypeId: body.contentTypeId, + ...(delivery === undefined ? {} : { delivery }), + id: body.id, + isPublic: body.isPublic, + ...(locales === undefined ? {} : { locales }), + mode: body.mode, + slugs: body.slugs, + wasPublic: body.wasPublic, + }; +}; + +/** + * The sitemap tags one revalidation expires: the same tags + * `contentInvalidationTags` lists for it, narrowed to the content type's + * sitemap files. + */ +export const contentRevalidationSitemapTags = ( + input: ContentRevalidationRequest, +): string[] => { + const sitemapTags = new Set([ + contentDeliverySitemapTag(input.contentTypeId), + ...(input.locales ?? []).map(entry => + contentDeliverySitemapTag(input.contentTypeId, entry.locale), + ), + ]); + + return contentInvalidationTags(input).filter(tag => sitemapTags.has(tag)); +}; + +const answer = (status: number): Response => + new Response(null, { headers: { "cache-control": "no-store" }, status }); + +/** + * Answers `POST /api/vitnode/content/revalidate` from an API that lists this + * site in `content.revalidateOrigins`: checks the bearer `CRON_SECRET` in + * constant time and the timestamp, then expires the affected sitemap files. + * `immediate` is a hard invalidation - the old XML is never served again. + */ +export const handleContentRevalidation = async ( + request: Request, + ensureStore: () => void, +): Promise<Response> => { + if (!(await isTrustedContentRevalidation(request))) return answer(403); + + let body: unknown; + try { + body = await request.json(); + } catch { + return answer(400); + } + const input = readContentRevalidation(body); + if (input === null) return answer(400); + + const tags = contentRevalidationSitemapTags(input); + if (tags.length === 0) return answer(204); + + ensureStore(); + const result = await invalidatePageCacheTags(tags, { + mode: input.mode === "immediate" ? "hard" : "soft", + }); + + return answer(result.status === "failed" ? 503 : 204); +}; diff --git a/packages/vitnode/src/tanstack/seo/robots.server.test.ts b/packages/vitnode/src/tanstack/seo/robots.server.test.ts new file mode 100644 index 0000000000..6c8e3a5776 --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/robots.server.test.ts @@ -0,0 +1,131 @@ +import { createLocaleRouting } from "@vitnode/api/lib/i18n/locale-routing"; +import { describe, expect, it } from "vitest"; + +import { resolveSeoPolicy } from "./policy.server"; +import { seoRobotsTxt } from "./robots.server"; + +const ORIGIN = "https://example.com"; + +const routing = createLocaleRouting({ + defaultLocale: "en", + locales: ["en", "pl"], +}); + +const robots = ( + seo: unknown, + { origin = ORIGIN, locales = routing } = {}, +): string => + seoRobotsTxt({ + origin, + policy: resolveSeoPolicy(seo), + routing: locales, + webOrigin: ORIGIN, + }); + +/** The `User-agent` group for one token, as its lines. */ +const groupOf = (txt: string, token: string): string[] | undefined => + txt + .trimEnd() + .split("\n\n") + .map(block => block.split("\n")) + .find(lines => lines[0] === `User-agent: ${token}`); + +const BASELINE = [ + "Allow: /", + "Disallow: /admin", + ...["/settings", "/modcp", "/files", "/login", "/register"].flatMap(path => [ + `Disallow: ${path}`, + `Disallow: /pl${path}`, + ]), +]; + +describe("seoRobotsTxt", () => { + it("allows the site and excludes the AdminCP and every locale's private areas", () => { + expect(robots({ indexing: true, sitemap: { enabled: false } })).toBe( + `${["User-agent: *", ...BASELINE].join("\n")}\n`, + ); + }); + + it("is deterministic", () => { + const seo = { + crawlers: { anthropic: { training: false }, googleExtended: true }, + indexing: true, + }; + + expect(robots(seo)).toBe(robots(seo)); + }); + + it.each<[boolean, boolean | undefined, boolean]>([ + [true, undefined, true], + [true, true, true], + [true, false, false], + [false, undefined, false], + [false, true, false], + [false, false, false], + ])( + "indexing %s, sitemap.enabled %s → Sitemap line %s", + (indexing, enabled, listed) => { + const txt = robots({ + indexing, + ...(enabled === undefined ? {} : { sitemap: { enabled } }), + }); + + expect(txt.match(/^Sitemap: .*$/gm)).toEqual( + listed ? [`Sitemap: ${ORIGIN}/sitemap.xml`] : null, + ); + // Indexing off never blocks crawling: the noindex header must be readable. + expect(groupOf(txt, "*")).toEqual(["User-agent: *", ...BASELINE]); + }, + ); + + it("adds no bot group for a crawler left out", () => { + const txt = robots({ indexing: true }); + + expect(txt.match(/^User-agent: /gm)).toEqual(["User-agent: "]); + }); + + it.each<[string, (allow: boolean) => Record<string, unknown>]>([ + ["OAI-SearchBot", allow => ({ openai: { search: allow } })], + ["GPTBot", allow => ({ openai: { training: allow } })], + ["Claude-SearchBot", allow => ({ anthropic: { search: allow } })], + ["ClaudeBot", allow => ({ anthropic: { training: allow } })], + ["Google-Extended", allow => ({ googleExtended: allow })], + ])("toggles %s on its own", (token, crawlers) => { + const blocked = robots({ crawlers: crawlers(false), indexing: true }); + const allowed = robots({ crawlers: crawlers(true), indexing: true }); + + expect(groupOf(blocked, token)).toEqual([ + `User-agent: ${token}`, + "Disallow: /", + ]); + // A bot obeys only its own group, so an allow group repeats the exclusions. + expect(groupOf(allowed, token)).toEqual([ + `User-agent: ${token}`, + ...BASELINE, + ]); + for (const txt of [blocked, allowed]) { + expect(txt.match(/^User-agent: /gm)).toHaveLength(2); + } + }); + + it("excludes translated settings paths", () => { + const txt = robots( + { indexing: true }, + { + locales: createLocaleRouting({ + defaultLocale: "en", + locales: ["en", "pl"], + routePaths: { pl: { "/settings": "/ustawienia" } }, + }), + }, + ); + + expect(groupOf(txt, "*")).toEqual( + expect.arrayContaining([ + "Disallow: /settings", + "Disallow: /pl/ustawienia", + ]), + ); + expect(groupOf(txt, "*")).not.toContain("Disallow: /pl/settings"); + }); +}); diff --git a/packages/vitnode/src/tanstack/seo/robots.server.ts b/packages/vitnode/src/tanstack/seo/robots.server.ts new file mode 100644 index 0000000000..3384fa3ad8 --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/robots.server.ts @@ -0,0 +1,94 @@ +import type { LocaleRouting } from "@vitnode/api/lib/i18n/locale-routing"; + +import type { ResolvedSeoPolicy } from "./policy.server"; + +import { localesOnOrigin } from "./policy.server"; + +/** Never locale-prefixed: the AdminCP. */ +const UNLOCALIZED_EXCLUSIONS = ["/admin"]; + +/** + * Locale-routed core areas with nothing to index, and every locale's URL of + * them: the signed-in pages (account settings, the ModCP, the member's files) + * and the sign-in flows, whose reset, verification and SSO URLs carry + * one-time tokens. + */ +const LOCALIZED_EXCLUSIONS = [ + "/settings", + "/modcp", + "/files", + "/login", + "/register", +]; + +/** + * The paths `User-agent: *` disallows on one origin: the AdminCP, the + * signed-in areas and the sign-in flows, with each locale's prefix and + * translated path that origin serves. Pages there are protected by their own + * authorization; this only keeps crawlers from asking. + */ +export const seoBaselineExclusions = ({ + origin, + routing, + webOrigin, +}: { + origin: string; + routing: LocaleRouting; + webOrigin: string; +}): string[] => { + const host = new URL(origin).host; + const locales = localesOnOrigin(routing, origin, webOrigin); + const served = locales.length > 0 ? locales : routing.locales; + + return [ + ...new Set([ + ...UNLOCALIZED_EXCLUSIONS, + ...LOCALIZED_EXCLUSIONS.flatMap(path => [ + path, + ...served.map(locale => + routing.localizePathname(path, locale, { host }), + ), + ]), + ]), + ]; +}; + +/** + * `/robots.txt` for one trusted origin. Deterministic: the same policy and + * origin always give the same bytes. + * + * - `User-agent: *` allows the site and disallows the baseline exclusions. + * - Each configured bot gets its own group: `Disallow: /` when it is turned + * off, or the baseline rules again when it is turned on - a crawler obeys + * only its most specific group, so an allow group without them would open + * the AdminCP to it. + * - Exactly one absolute `Sitemap:` line when the sitemap is published. + */ +export const seoRobotsTxt = ({ + origin, + policy, + routing, + webOrigin, +}: { + origin: string; + policy: ResolvedSeoPolicy; + routing: LocaleRouting; + webOrigin: string; +}): string => { + const exclusions = seoBaselineExclusions({ origin, routing, webOrigin }); + const baseline = ["Allow: /", ...exclusions.map(path => `Disallow: ${path}`)]; + const groups = [ + ["User-agent: *", ...baseline], + ...policy.crawlers.map(rule => [ + `User-agent: ${rule.token}`, + ...(rule.allow ? baseline : ["Disallow: /"]), + ]), + ]; + const blocks = groups.map(lines => lines.join("\n")); + + if (policy.sitemap.enabled) { + blocks.push(`Sitemap: ${new URL("/sitemap.xml", origin).href}`); + } + + return `${blocks.join("\n\n")}\n`; +}; diff --git a/packages/vitnode/src/tanstack/seo/server.test.ts b/packages/vitnode/src/tanstack/seo/server.test.ts new file mode 100644 index 0000000000..b5dfe51c94 --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/server.test.ts @@ -0,0 +1,214 @@ +import type { LocaleConfig } from "@vitnode/api/lib/i18n/types"; + +import { resetPageCacheStore } from "@vitnode/api/page-cache/store.server"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import type { VitNodeConfig } from "@/vitnode.config"; + +import type { SeoContentSitemapFetch } from "./content-transport.server"; +import type { VitNodeSeoConfig } from "./types"; + +import { createSeoSitemapCache } from "./cache.server"; +import { createSeoHandler } from "./server"; + +const WEB = "https://example.com"; + +const I18N: VitNodeConfig["i18n"] = { + defaultLocale: "en", + domains: [ + { defaultLocale: "en", origin: WEB }, + { defaultLocale: "pl", origin: "https://example.pl" }, + ], + locales: [ + { code: "en", name: "English" }, + { code: "pl", name: "Polski" }, + ] satisfies LocaleConfig[], +}; + +const HTML = "<!doctype html><html><head><title>Hi"; + +const setup = (seo?: VitNodeSeoConfig) => { + const render = vi.fn(async (request: Request) => { + const { pathname } = new URL(request.url); + if (pathname === "/data.json") { + return await Promise.resolve(Response.json({ ok: true })); + } + + return await Promise.resolve( + new Response(HTML, { + headers: { "content-type": "text/html; charset=utf-8" }, + }), + ); + }); + const fetchPage: SeoContentSitemapFetch = async () => + await Promise.reject(new Error("No content source in this test.")); + const handler = createSeoHandler( + render, + { + config: { + config: { i18n: I18N, metadata: { title: "Test" }, plugins: [] }, + ...(seo === undefined ? {} : { seo }), + }, + sitemap: { revision: "test", sources: [] }, + }, + { cache: createSeoSitemapCache("memory"), fetchPage, webOrigin: WEB }, + ); + + const request = async (url: string, init: RequestInit = {}) => { + const response = await handler(new Request(new URL(url, WEB), init)); + + return { body: await response.text(), response }; + }; + + return { render, request }; +}; + +beforeEach(() => { + resetPageCacheStore(); +}); + +afterEach(() => { + resetPageCacheStore(); +}); + +describe("seo left out", () => { + it("serves the indexable defaults", async () => { + const { request } = setup(); + + const [robots, page] = await Promise.all([ + request("/robots.txt"), + request("/blog"), + ]); + + expect(robots.body.match(/^Sitemap: .*$/gm)).toEqual([ + `Sitemap: ${WEB}/sitemap.xml`, + ]); + expect(page.body).toBe(HTML); + expect(page.response.headers.get("x-robots-tag")).toBeNull(); + }); +}); + +describe("/robots.txt", () => { + it("is plain text generated without rendering the app", async () => { + const { render, request } = setup({ indexing: true }); + + const { body, response } = await request("/robots.txt"); + + expect(render).not.toHaveBeenCalled(); + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toBe( + "text/plain; charset=utf-8", + ); + expect(response.headers.get("content-length")).toBe( + String(new TextEncoder().encode(body).byteLength), + ); + expect(body).toContain("User-agent: *"); + }); + + it("answers HEAD with the headers and no body", async () => { + const { request } = setup({ indexing: true }); + + const { body, response } = await request("/robots.txt", { + method: "HEAD", + }); + + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toBe( + "text/plain; charset=utf-8", + ); + expect(Number(response.headers.get("content-length"))).toBeGreaterThan(0); + expect(body).toBe(""); + }); + + it.each<[string, string]>([ + [`${WEB}/robots.txt`, `${WEB}/sitemap.xml`], + // Any other Host - spoofed, a preview alias - never becomes a URL. + ["https://evil.test/robots.txt", `${WEB}/sitemap.xml`], + ["http://localhost:3000/robots.txt", `${WEB}/sitemap.xml`], + // A configured locale domain gets its own origin. + ["https://example.pl/robots.txt", "https://example.pl/sitemap.xml"], + ])("%s lists %s", async (url, sitemap) => { + const { request } = setup({ indexing: true }); + + const { body } = await request(url); + + expect(body.match(/^Sitemap: .*$/gm)).toEqual([`Sitemap: ${sitemap}`]); + }); + + it("excludes only the locales a domain serves", async () => { + const { request } = setup({ indexing: true }); + + const [main, pl] = await Promise.all([ + request(`${WEB}/robots.txt`), + request("https://example.pl/robots.txt"), + ]); + + const unprefixed = [ + "Disallow: /admin", + "Disallow: /settings", + "Disallow: /modcp", + "Disallow: /files", + "Disallow: /login", + "Disallow: /register", + ]; + expect(main.body.match(/^Disallow: .*$/gm)).toEqual(unprefixed); + expect(pl.body.match(/^Disallow: .*$/gm)).toEqual(unprefixed); + }); +}); + +describe("indexing: false", () => { + it("adds X-Robots-Tag to HTML only", async () => { + const { request } = setup({ indexing: false }); + + const [page, data] = await Promise.all([ + request("/blog"), + request("/data.json"), + ]); + + expect(page.response.headers.get("x-robots-tag")).toBe("noindex"); + expect(page.body).toBe(HTML); + expect(data.response.headers.get("x-robots-tag")).toBeNull(); + }); + + it("writes a robots meta into a prerendered page", async () => { + const { request } = setup({ indexing: false }); + + const { body, response } = await request("/blog", { + headers: { "x-nitro-prerender": "/blog" }, + }); + + expect(body).toContain(''); + expect(response.headers.get("x-robots-tag")).toBe("noindex"); + }); + + it("leaves pages alone while indexing is on", async () => { + const { request } = setup({ indexing: true }); + + const { body, response } = await request("/blog", { + headers: { "x-nitro-prerender": "/blog" }, + }); + + expect(body).toBe(HTML); + expect(response.headers.get("x-robots-tag")).toBeNull(); + }); +}); + +describe("sitemap turned off", () => { + it.each<[string, VitNodeSeoConfig]>([ + ["indexing off", { indexing: false, sitemap: { paths: ["/"] } }], + [ + "sitemap.enabled false", + { indexing: true, sitemap: { enabled: false, paths: ["/"] } }, + ], + ])("answers 404 for every sitemap URL with %s", async (_, seo) => { + const { render, request } = setup(seo); + + for (const path of ["/sitemap.xml", "/sitemap-pages-1.xml"]) { + const { response } = await request(path); + + expect(response.status).toBe(404); + expect(response.headers.get("cache-control")).toBe("no-store"); + } + expect(render).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/vitnode/src/tanstack/seo/server.ts b/packages/vitnode/src/tanstack/seo/server.ts new file mode 100644 index 0000000000..673124fbab --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/server.ts @@ -0,0 +1,314 @@ +import "@tanstack/react-start/server-only"; +import type { LocaleConfig } from "@vitnode/api/lib/i18n/types"; + +import { CONTENT_REVALIDATE_PATH } from "@vitnode/api/content/server/revalidate-bridge"; +import { executionContextOf } from "@vitnode/api/lib/after-response"; +import { CONFIG } from "@vitnode/api/lib/config"; +import { localeRoutingFromConfig } from "@vitnode/api/lib/i18n/locale-routing"; +import { resolvePageCacheConfig } from "@vitnode/api/page-cache/config"; + +import type { VitNodeServerConfig } from "@/vitnode.config"; + +import type { SeoSitemapCache } from "./cache.server"; +import type { SeoContentSitemapFetch } from "./content-transport.server"; +import type { SeoSitemapManifest } from "./manifest"; +import type { + SeoBackground, + SeoSitemapListSource, + SeoSitemapResult, +} from "./sitemap.server"; + +import { createSeoSitemapCache } from "./cache.server"; +import { createContentSitemapFetch } from "./content-transport.server"; +import { + isHtmlResponse, + withNoIndexDocument, + withNoIndexHeader, +} from "./html.server"; +import { parseSeoSitemapChildPath } from "./manifest"; +import { resolveSeoPolicy, trustedOriginFor } from "./policy.server"; +import { handleContentRevalidation } from "./revalidate.server"; +import { seoRobotsTxt } from "./robots.server"; +import { createSeoSitemapEngine } from "./sitemap.server"; + +export type { SeoContentSitemapSource, SeoSitemapManifest } from "./manifest"; +export { SeoConfigError } from "./policy.server"; +export type { + SeoSitemapAlternate, + SeoSitemapListSource, + SeoSitemapUrl, +} from "./sitemap.server"; +export type { + VitNodeSeoConfig, + VitNodeSeoCrawlerPair, + VitNodeSeoCrawlersConfig, + VitNodeSeoSitemapConfig, +} from "./types"; + +/** The server entry's request handler, as `withPageCache` passes it on. */ +export type SeoRender = ( + request: Request, + ...rest: never[] +) => Promise | Response; + +export interface SeoHandlerOptions< + AppLocales extends LocaleConfig[] = LocaleConfig[], +> { + /** + * The app's `vitNodeServerConfig`. `seo` is read from it - left out, it is + * `{ indexing: true }` - along with `i18n` and `pageCache.storage` from the + * shared config. + */ + config: VitNodeServerConfig; + /** `sitemapManifest` from the generated `src/sitemap-sources.gen.ts`. */ + sitemap: SeoSitemapManifest; + /** + * App-owned URL lists beyond `seo.sitemap.paths` - the app's own docs, for + * example - each published as `/sitemap-{id}-{n}.xml`. Keep them to + * canonical, public, indexable pages. Defaults to none. + */ + sources?: readonly SeoSitemapListSource[]; +} + +/** + * Seams for tests and unusual deployments. Not part of the public contract. + * + * @internal + */ +export interface SeoHandlerInternals { + cache?: SeoSitemapCache; + fetchPage?: SeoContentSitemapFetch; + /** Replaces `VITNODE_WEB_URL`. */ + webOrigin?: string; +} + +const ROBOTS_CACHE_CONTROL = "public, max-age=300"; + +const textResponse = ( + request: Request, + body: string, + status: number, + headers: Record, +): Response => + new Response(request.method === "HEAD" ? null : body, { + headers: { + ...headers, + "content-length": String(new TextEncoder().encode(body).byteLength), + }, + status, + }); + +const sitemapResponse = ( + request: Request, + result: SeoSitemapResult, +): Response => { + if (result.status === 404) { + return textResponse(request, "Not Found\n", 404, { + "cache-control": "no-store", + "content-type": "text/plain; charset=utf-8", + }); + } + if (result.status === 503) { + return textResponse(request, "Sitemap temporarily unavailable\n", 503, { + "cache-control": "no-store", + "content-type": "text/plain; charset=utf-8", + "retry-after": "60", + }); + } + + const headers = { + // Caches must ask again: a record that left the public site leaves the + // sitemap at once, not when a downstream copy expires. + "cache-control": "no-cache", + "content-type": "application/xml; charset=utf-8", + etag: result.etag, + }; + const match = request.headers.get("if-none-match"); + if ( + match !== null && + match.split(",").some(tag => tag.trim() === result.etag) + ) { + return new Response(null, { headers, status: 304 }); + } + + return textResponse(request, result.xml, 200, headers); +}; + +const backgroundFor = (request: Request): SeoBackground => { + const executionCtx = executionContextOf(request); + + return task => { + const running = task().catch((error: unknown) => { + // oxlint-disable-next-line no-console + console.error( + "[vitnode seo] A background sitemap refresh failed.", + error, + ); + }); + executionCtx?.waitUntil(running); + }; +}; + +/** + * Wraps a server entry's `fetch` with the site's SEO policy, from + * `buildServerConfig({ seo })`. See `withSeo` for what it serves. + * + * @throws {SeoConfigError} When `seo` is invalid - at startup, not per request. + */ +export const createSeoHandler = ( + render: SeoRender, + { config, sitemap, sources = [] }: SeoHandlerOptions, + internals: SeoHandlerInternals = {}, +): SeoRender => { + const { i18n, pageCache } = config.config; + const policy = resolveSeoPolicy(config.seo, { + locales: i18n.locales.map(locale => locale.code), + }); + + const routing = localeRoutingFromConfig(i18n); + const cache = + internals.cache ?? + createSeoSitemapCache(resolvePageCacheConfig(pageCache).storage); + const engine = policy.sitemap.enabled + ? createSeoSitemapEngine({ + cache, + fetchPage: + internals.fetchPage ?? + createContentSitemapFetch({ + localTransport: async request => await render(request), + }), + listSources: sources, + manifest: sitemap, + policy, + routing, + }) + : null; + const webOriginOf = (): string => + internals.webOrigin === undefined + ? CONFIG.web.origin + : new URL(internals.webOrigin).origin; + + return async (request, ...rest) => { + const url = new URL(request.url); + const { pathname } = url; + + if (request.method === "GET" || request.method === "HEAD") { + if (pathname === "/robots.txt") { + const webOrigin = webOriginOf(); + + return textResponse( + request, + seoRobotsTxt({ + origin: trustedOriginFor(url, routing, webOrigin), + policy, + routing, + webOrigin, + }), + 200, + { + "cache-control": ROBOTS_CACHE_CONTROL, + "content-type": "text/plain; charset=utf-8", + }, + ); + } + + const child = parseSeoSitemapChildPath(pathname); + if (pathname === "/sitemap.xml" || child !== null) { + if (engine === null) return sitemapResponse(request, { status: 404 }); + + const webOrigin = webOriginOf(); + const origin = trustedOriginFor(url, routing, webOrigin); + const background = backgroundFor(request); + const result = + child === null + ? await engine.index({ background, origin, webOrigin }) + : await engine.child({ + background, + file: child.file, + origin, + part: child.part, + webOrigin, + }); + + return sitemapResponse(request, result); + } + } + + if (pathname === CONTENT_REVALIDATE_PATH && request.method === "POST") { + return await handleContentRevalidation(request, cache.ensure); + } + + const response = await render(request, ...rest); + if (policy.indexing || !isHtmlResponse(response)) return response; + + // Prerendered pages are served as files, past this handler, so the + // directive goes into the document itself as well. + return request.headers.has("x-nitro-prerender") + ? await withNoIndexDocument(response) + : withNoIndexHeader(response); + }; +}; + +/** A TanStack Start server entry, as `withPageCache` returns it. */ +export interface SeoServerEntry { + fetch: (request: Request, ...rest: never[]) => Promise | Response; +} + +/** + * Applies `buildServerConfig({ seo })` to every response. Compose it outside + * `withPageCache`, so the policy also reaches pages served from the HTML + * cache. With `seo` left out the site is indexable (`{ indexing: true }`). + * Server-only. + * + * - `/robots.txt`: `User-agent: *` with the AdminCP, the signed-in areas and + * the sign-in flows excluded (every locale's path), one group per configured bot, and an + * absolute `Sitemap:` line while the sitemap is published. Generated from + * config alone - no API, session or database. + * - `/sitemap.xml`: a sitemap index of `/sitemap-{file}-{n}.xml` children - + * `seo.sitemap.paths`, the `sources` given here, and every content type + * with `delivery.sitemap`, read as a guest. Cached with the page cache's + * store and expired by content changes. `404` while the sitemap is off, + * `503` while no complete generation can be served. + * - `indexing: false`: `X-Robots-Tag: noindex` on HTML responses, and a robots + * `` in prerendered pages. + * - `POST /api/vitnode/content/revalidate`: expires sitemap files when a + * separate API lists this site in `content.revalidateOrigins`. + * + * URLs only ever use configured origins: `VITNODE_WEB_URL`, or an + * `i18n.domains` origin when the request is for that host. + * + * @throws {SeoConfigError} When `seo` is invalid. + * + * @example + * ```ts + * // src/server.ts + * import handler from "@tanstack/react-start/server-entry"; + * import { withPageCache } from "@vitnode/core/tanstack/page-cache/server"; + * import { withSeo } from "@vitnode/core/tanstack/seo/server"; + * + * import { pageCacheBuildId, pageCacheRoutes } from "@/page-cache.gen"; + * import { sitemapManifest } from "@/sitemap-sources.gen"; + * import { vitNodeConfig } from "@/vitnode.config"; + * import { vitNodeServerConfig } from "@/vitnode.server.config"; + * + * export default withSeo( + * withPageCache(handler, { + * buildId: pageCacheBuildId, + * config: vitNodeConfig, + * routes: pageCacheRoutes, + * }), + * { config: vitNodeServerConfig, sitemap: sitemapManifest }, + * ); + * ``` + */ +export const withSeo = ( + entry: SeoServerEntry, + options: SeoHandlerOptions, +): SeoServerEntry => { + const fetch = createSeoHandler( + async (request, ...rest) => await entry.fetch(request, ...rest), + options, + ); + + return { fetch }; +}; diff --git a/packages/vitnode/src/tanstack/seo/sitemap.server.test.ts b/packages/vitnode/src/tanstack/seo/sitemap.server.test.ts new file mode 100644 index 0000000000..33f6c83eca --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/sitemap.server.test.ts @@ -0,0 +1,595 @@ +import type { LocaleConfig } from "@vitnode/api/lib/i18n/types"; + +import { contentDeliverySitemapTag } from "@vitnode/api/content/cache"; +import { + invalidatePageCacheTags, + resetPageCacheStore, +} from "@vitnode/api/page-cache/store.server"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import type { VitNodeConfig } from "@/vitnode.config"; + +import type { SeoSitemapCache } from "./cache.server"; +import type { + SeoContentSitemapEntry, + SeoContentSitemapFetch, + SeoContentSitemapPageRequest, +} from "./content-transport.server"; +import type { SeoContentSitemapSource } from "./manifest"; +import type { SeoSitemapListSource } from "./sitemap.server"; +import type { VitNodeSeoConfig } from "./types"; + +import { createSeoSitemapCache } from "./cache.server"; +import { SeoConfigError } from "./policy.server"; +import { createSeoHandler } from "./server"; + +const WEB = "https://example.com"; +const NOW = new Date("2026-03-01T00:00:00Z"); + +const POSTS: SeoContentSitemapSource = { + contentTypeId: "blog.post", + file: "blog", + localized: false, + module: "content/blog", + path: "/delivery/sitemap", + pluginId: "@vitnode/blog", +}; + +const DOCS: SeoContentSitemapSource = { + contentTypeId: "docs.page", + file: "docs", + localized: true, + module: "content/docs", + path: "/delivery/sitemap", + pluginId: "@vitnode/docs", +}; + +const LOCALES = [ + { code: "en", name: "English" }, + { code: "pl", name: "Polski" }, +] satisfies LocaleConfig[]; + +const PREFIXED: VitNodeConfig["i18n"] = { + defaultLocale: "en", + locales: LOCALES, +}; + +const DOMAINS: VitNodeConfig["i18n"] = { + defaultLocale: "en", + domains: [ + { defaultLocale: "en", origin: WEB }, + { defaultLocale: "pl", origin: "https://example.pl" }, + ], + locales: LOCALES, +}; + +const post = (index: number): SeoContentSitemapEntry => ({ + changeFrequency: null, + lastModified: new Date(Date.UTC(2026, 0, 1, 0, 0, index)), + path: `/blog/post-${String(index)}`, + priority: null, +}); + +/** + * A delivery route over `count()` records, numbered from 1, with the offset as + * its cursor. `count` is read per call, so a test can change the data. + */ +const pagedSource = ( + count: () => number, + entry: (index: number) => SeoContentSitemapEntry = post, +) => + vi.fn( + async ({ cursor, limit }: SeoContentSitemapPageRequest) => { + const start = cursor === null ? 0 : Number(cursor); + const end = Math.min(start + limit, count()); + const entries = Array.from({ length: Math.max(0, end - start) }, (_, i) => + entry(start + i + 1), + ); + + return await Promise.resolve({ + entries, + nextCursor: end < count() ? String(end) : null, + }); + }, + ); + +const deferred = () => { + let resolve: () => void = () => undefined; + const promise = new Promise(done => { + resolve = done; + }); + + return { promise, resolve }; +}; + +/** Background generation the handler started, drained before each test ends. */ +const background: Promise[] = []; + +/** Lets background generation finish. */ +const settle = async () => { + while (background.length > 0) await background.shift(); +}; + +const setup = ({ + cache = createSeoSitemapCache("memory"), + fetchPage = pagedSource(() => 0), + i18n = PREFIXED, + seo = { indexing: true }, + sources = [POSTS], + lists = [], +}: { + cache?: SeoSitemapCache; + fetchPage?: SeoContentSitemapFetch; + i18n?: VitNodeConfig["i18n"]; + lists?: SeoSitemapListSource[]; + seo?: VitNodeSeoConfig; + sources?: SeoContentSitemapSource[]; +} = {}) => { + const handler = createSeoHandler( + async () => await Promise.resolve(new Response("app", { status: 404 })), + { + config: { + config: { i18n, metadata: { title: "Test" }, plugins: [] }, + seo, + }, + sitemap: { revision: "test", sources }, + sources: lists, + }, + { cache, fetchPage, webOrigin: WEB }, + ); + + const request = async (url: string, init: RequestInit = {}) => { + const incoming = Object.assign(new Request(new URL(url, WEB), init), { + waitUntil: (promise: Promise) => { + background.push(promise); + }, + }); + const response = await handler(incoming); + + return { body: await response.text(), response }; + }; + + return { request, settle }; +}; + +const locs = (xml: string): string[] => + [...xml.matchAll(/([^<]*)<\/loc>/g)].map(match => match[1]); + +beforeEach(() => { + resetPageCacheStore(); + vi.useFakeTimers(); + vi.setSystemTime(NOW); + vi.spyOn(console, "error").mockImplementation(() => undefined); +}); + +afterEach(async () => { + await settle(); + vi.useRealTimers(); + vi.restoreAllMocks(); + resetPageCacheStore(); +}); + +describe("the sitemap index", () => { + it("lists the app pages, list sources and content files", async () => { + const { request } = setup({ + fetchPage: pagedSource(() => 3), + lists: [{ id: "guides", urls: () => [{ path: "/guides/start" }] }], + seo: { indexing: true, sitemap: { paths: ["/", "/about"] } }, + }); + + const { body, response } = await request("/sitemap.xml"); + + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toBe( + "application/xml; charset=utf-8", + ); + expect(body).toContain(" { + const { request } = setup({ fetchPage: pagedSource(() => 2_500) }); + + const index = await request("/sitemap.xml"); + const parts = await Promise.all( + [1, 2, 3].map( + async part => await request(`/sitemap-blog-${String(part)}.xml`), + ), + ); + + expect(locs(index.body)).toEqual([ + `${WEB}/sitemap-blog-1.xml`, + `${WEB}/sitemap-blog-2.xml`, + `${WEB}/sitemap-blog-3.xml`, + ]); + expect(parts.map(({ body }) => locs(body).length)).toEqual([ + 1_000, 1_000, 500, + ]); + expect(locs(parts[1].body)[0]).toBe(`${WEB}/blog/post-1001`); + }); + + it("dates each file by its newest URL and leaves undated files without lastmod", async () => { + const { request } = setup({ + fetchPage: pagedSource(() => 1_200), + lists: [{ id: "guides", urls: () => [{ path: "/guides/start" }] }], + }); + + const { body } = await request("/sitemap.xml"); + + expect(body.match(/[^<]*<\/lastmod>/g)).toEqual([ + "2026-01-01T00:16:40.000Z", + "2026-01-01T00:20:00.000Z", + ]); + }); + + it("is generated once and then served from the cache", async () => { + const fetchPage = pagedSource(() => 2_500); + const { request } = setup({ fetchPage }); + + const first = await request("/sitemap.xml"); + await request("/sitemap-blog-2.xml"); + const second = await request("/sitemap.xml"); + await request("/sitemap-blog-2.xml"); + + expect(fetchPage).toHaveBeenCalledTimes(3); + expect(second.body).toBe(first.body); + }); + + it("answers a matching If-None-Match with 304", async () => { + const { request } = setup({ fetchPage: pagedSource(() => 1) }); + const first = await request("/sitemap.xml"); + const etag = first.response.headers.get("etag") ?? ""; + + const again = await request("/sitemap.xml", { + headers: { "if-none-match": `"other", ${etag}` }, + }); + + expect(etag).not.toBe(""); + expect(first.response.headers.get("cache-control")).toBe("no-cache"); + expect(again.response.status).toBe(304); + expect(again.body).toBe(""); + }); +}); + +describe("child files", () => { + it.each([ + "/sitemap-nope-1.xml", + "/sitemap-blog-4.xml", + "/sitemap-pages-1.xml", + "/sitemap-docs-en-1.xml", + ])("answers 404 for %s", async path => { + const { request } = setup({ fetchPage: pagedSource(() => 2_500) }); + + const { response } = await request(path); + + expect(response.status).toBe(404); + }); + + it("escapes URLs for XML", async () => { + const { request } = setup({ + fetchPage: pagedSource( + () => 1, + () => ({ + changeFrequency: null, + lastModified: null, + path: "/search?a=1&b=<2>", + priority: null, + }), + ), + }); + + const { body } = await request("/sitemap-blog-1.xml"); + + expect(locs(body)).toEqual([`${WEB}/search?a=1&b=%3C2%3E`]); + }); + + it("drops list URLs on untrusted origins and repeated URLs", async () => { + const { request } = setup({ + lists: [ + { + id: "guides", + urls: () => [ + { path: "/guides/a" }, + { path: "/guides/a" }, + { origin: "https://evil.test", path: "/guides/b" }, + { path: "/guides/c?x=1&y=2" }, + ], + }, + ], + sources: [], + }); + + const { body } = await request("/sitemap-guides-1.xml"); + + expect(locs(body)).toEqual([ + `${WEB}/guides/a`, + `${WEB}/guides/c?x=1&y=2`, + ]); + }); + + it("lists each app path once per locale with hreflang alternates", async () => { + const { request } = setup({ + seo: { indexing: true, sitemap: { paths: ["/about"] } }, + sources: [], + }); + + const { body } = await request("/sitemap-pages-1.xml"); + + expect(locs(body)).toEqual([`${WEB}/about`, `${WEB}/pl/about`]); + expect(body).toContain( + ``, + ); + }); + + it.each<[string, SeoSitemapListSource]>([ + ["reserved id", { id: "pages", urls: () => [] }], + ["invalid id", { id: "My_Docs", urls: () => [] }], + ])("rejects a list source with a %s at startup", (_, source) => { + expect(() => setup({ lists: [source] })).toThrow(SeoConfigError); + }); +}); + +describe("one origin per host", () => { + const docs = () => + vi.fn( + async request => + await Promise.resolve({ + entries: [ + { + changeFrequency: null, + lastModified: null, + origin: request.locale === "pl" ? "https://example.pl" : WEB, + path: `/docs/${request.locale ?? "x"}`, + priority: null, + }, + { + changeFrequency: null, + lastModified: null, + origin: "https://evil.test", + path: "/docs/elsewhere", + priority: null, + }, + ], + nextCursor: null, + }), + ); + + it("lists only the locales a host serves", async () => { + const { request } = setup({ + fetchPage: docs(), + i18n: DOMAINS, + sources: [DOCS, POSTS], + }); + + const [main, pl] = await Promise.all([ + request(`${WEB}/sitemap.xml`), + request("https://example.pl/sitemap.xml"), + ]); + + expect(locs(main.body)).toEqual([ + `${WEB}/sitemap-docs-en-1.xml`, + `${WEB}/sitemap-blog-1.xml`, + ]); + expect(locs(pl.body)).toEqual(["https://example.pl/sitemap-docs-pl-1.xml"]); + expect( + (await request("https://example.pl/sitemap-docs-en-1.xml")).response + .status, + ).toBe(404); + }); + + it("drops entries that belong to another origin", async () => { + const { request } = setup({ + fetchPage: docs(), + i18n: DOMAINS, + sources: [DOCS], + }); + + const [main, pl] = await Promise.all([ + request(`${WEB}/sitemap-docs-en-1.xml`), + request("https://example.pl/sitemap-docs-pl-1.xml"), + ]); + + expect(locs(main.body)).toEqual([`${WEB}/docs/en`]); + expect(locs(pl.body)).toEqual(["https://example.pl/docs/pl"]); + }); + + it("serves an untrusted Host the web origin's sitemap", async () => { + const { request } = setup({ fetchPage: pagedSource(() => 1) }); + + const { body } = await request("https://evil.test/sitemap.xml"); + + expect(locs(body)).toEqual([`${WEB}/sitemap-blog-1.xml`]); + }); +}); + +describe("evicted parts", () => { + /** A cache that can lose every stored part, as an LRU under pressure would. */ + const evictableCache = () => { + const cache = createSeoSitemapCache("memory"); + let evicting = false; + + return { + cache: { + ...cache, + get: async (key: string) => + evicting && key.includes(":x:") ? null : await cache.get(key), + } satisfies SeoSitemapCache, + evict: () => { + evicting = true; + }, + }; + }; + + it("re-reads only that part, from the cursor it starts at", async () => { + const { cache, evict } = evictableCache(); + const fetchPage = pagedSource(() => 2_500); + const { request } = setup({ cache, fetchPage }); + await request("/sitemap.xml"); + evict(); + fetchPage.mockClear(); + + const { body, response } = await request("/sitemap-blog-3.xml"); + + expect(response.status).toBe(200); + expect(fetchPage).toHaveBeenCalledTimes(1); + expect(fetchPage.mock.calls[0][0].cursor).toBe("2000"); + expect(locs(body)).toHaveLength(500); + }); + + it("answers 503, uncached, when the data moved under the part", async () => { + const { cache, evict } = evictableCache(); + let count = 2_500; + const { request } = setup({ cache, fetchPage: pagedSource(() => count) }); + await request("/sitemap.xml"); + evict(); + count = 1_800; + + const { response } = await request("/sitemap-blog-2.xml"); + + expect(response.status).toBe(503); + expect(response.headers.get("retry-after")).toBe("60"); + expect(response.headers.get("cache-control")).toBe("no-store"); + }); +}); + +describe("failures and invalidation", () => { + it("answers 503 and caches nothing while the source fails", async () => { + let failing = true; + const working = pagedSource(() => 2); + const fetchPage = vi.fn(async request => { + if (failing) throw new Error("API down"); + + return await working(request); + }); + const { request } = setup({ fetchPage }); + + const [index, child] = await Promise.all([ + request("/sitemap.xml"), + request("/sitemap-blog-1.xml"), + ]); + failing = false; + const recovered = await request("/sitemap.xml"); + + expect([index.response.status, child.response.status]).toEqual([503, 503]); + expect(recovered.response.status).toBe(200); + expect(locs(recovered.body)).toEqual([`${WEB}/sitemap-blog-1.xml`]); + }); + + it("answers 503 for a source that hands back the cursor it was given", async () => { + const fetchPage = vi.fn( + async () => + await Promise.resolve({ entries: [post(1)], nextCursor: "stuck" }), + ); + const { request } = setup({ fetchPage }); + + const { response } = await request("/sitemap.xml"); + + expect(response.status).toBe(503); + expect(fetchPage).toHaveBeenCalledTimes(2); + }); + + it("keeps serving the last generation when a refresh fails", async () => { + let failing = false; + const working = pagedSource(() => 2); + const fetchPage = vi.fn(async request => { + if (failing) throw new Error("API down"); + + return await working(request); + }); + const { request, settle } = setup({ fetchPage }); + const first = await request("/sitemap-blog-1.xml"); + await vi.advanceTimersByTimeAsync(5_000); + await invalidatePageCacheTags( + [contentDeliverySitemapTag(POSTS.contentTypeId)], + { + mode: "soft", + }, + ); + failing = true; + fetchPage.mockClear(); + + const stale = await request("/sitemap-blog-1.xml"); + await settle(); + const after = await request("/sitemap-blog-1.xml"); + + expect(fetchPage).toHaveBeenCalled(); + expect(stale.response.status).toBe(200); + expect(stale.body).toBe(first.body); + expect(after.body).toBe(first.body); + }); + + it("stops listing a removed URL after a hard invalidation", async () => { + let count = 3; + const { request } = setup({ fetchPage: pagedSource(() => count) }); + const before = await request("/sitemap-blog-1.xml"); + await vi.advanceTimersByTimeAsync(5_000); + + count = 2; + await invalidatePageCacheTags( + [contentDeliverySitemapTag(POSTS.contentTypeId)], + { + mode: "hard", + }, + ); + await vi.advanceTimersByTimeAsync(1); + const after = await request("/sitemap-blog-1.xml"); + + expect(locs(before.body)).toContain(`${WEB}/blog/post-3`); + expect(after.response.status).toBe(200); + expect(locs(after.body)).toEqual([ + `${WEB}/blog/post-1`, + `${WEB}/blog/post-2`, + ]); + }); + + it("never publishes a build that a hard invalidation overtook", async () => { + // Nine delivery pages: more than one request reads, so the build is kept + // in the cache and finished in the background. + let renamed = false; + const gate = deferred(); + const paged = pagedSource( + () => 8_500, + index => + index === 1 && renamed + ? { ...post(1), path: "/blog/renamed" } + : post(index), + ); + const fetchPage = vi.fn(async request => { + if (request.cursor === "8000") await gate.promise; + + return await paged(request); + }); + const { request, settle } = setup({ fetchPage }); + + const first = await request("/sitemap.xml"); + // Page one, already read, lists the old URL; then the slug changes. + renamed = true; + await vi.advanceTimersByTimeAsync(10); + await invalidatePageCacheTags( + [contentDeliverySitemapTag(POSTS.contentTypeId)], + { mode: "hard" }, + ); + await vi.advanceTimersByTimeAsync(1); + gate.resolve(); + await settle(); + + const served: string[] = []; + for (const wait of [0, 3_000, 0]) { + await vi.advanceTimersByTimeAsync(wait); + const { body, response } = await request("/sitemap-blog-1.xml"); + await settle(); + if (response.status === 200) served.push(body); + } + + expect(first.response.status).toBe(503); + expect(served.length).toBeGreaterThan(0); + for (const body of served) { + expect(locs(body)).not.toContain(`${WEB}/blog/post-1`); + expect(locs(body)).toContain(`${WEB}/blog/renamed`); + } + }); +}); diff --git a/packages/vitnode/src/tanstack/seo/sitemap.server.ts b/packages/vitnode/src/tanstack/seo/sitemap.server.ts new file mode 100644 index 0000000000..244b05ebc6 --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/sitemap.server.ts @@ -0,0 +1,921 @@ +import type { LocaleRouting } from "@vitnode/api/lib/i18n/locale-routing"; + +import { contentDeliverySitemapTag } from "@vitnode/api/content/cache"; +import { fingerprint } from "@vitnode/api/content/hash"; +import { + contentSitemapIndexXml, + contentSitemapXml, +} from "@vitnode/api/content/sitemap"; + +import type { SeoSitemapCache } from "./cache.server"; +import type { + SeoContentSitemapEntry, + SeoContentSitemapFetch, +} from "./content-transport.server"; +import type { SeoContentSitemapSource, SeoSitemapManifest } from "./manifest"; +import type { ResolvedSeoPolicy } from "./policy.server"; + +import { + SEO_SITEMAP_BUILD_TTL_SECONDS, + SEO_SITEMAP_INDEX_TTL_SECONDS, + SEO_SITEMAP_PART_TTL_SECONDS, + SEO_SITEMAP_TTL_SECONDS, + seoCachedState, +} from "./cache.server"; +import { SeoSitemapSourceError } from "./content-transport.server"; +import { + SEO_SITEMAP_FILE_PATTERN, + seoSitemapChildPath, + seoSitemapSlug, +} from "./manifest"; +import { localesOnOrigin, SeoConfigError } from "./policy.server"; + +/** URLs per child file: well under the protocol's 50,000, cheap on Workers. */ +export const SEO_SITEMAP_PART_SIZE = 1_000; + +/** The protocol's size limit for one uncompressed file. */ +export const SEO_SITEMAP_MAX_BYTES = 50 * 1024 * 1024; + +/** The protocol's limit on files in one index (and on URLs in one file). */ +export const SEO_SITEMAP_MAX_FILES = 50_000; + +/** Longer URLs are rejected by search engines, so they are left out. */ +const MAX_URL_LENGTH = 2_048; + +/** Delivery pages one request may read before answering. */ +const INLINE_PAGE_BUDGET = 8; + +/** Delivery pages one background run may read. */ +const BACKGROUND_PAGE_BUDGET = 200; + +/** Index files whose generations are resolved side by side. */ +const SOURCE_CONCURRENCY = 2; + +/** How long one instance owns an unfinished generation. */ +const BUILD_LEASE_MS = 60_000; + +/** One alternate of an app-owned URL, for `xhtml:link hreflang`. */ +export interface SeoSitemapAlternate { + /** A locale code, or `x-default`. */ + locale: string; + /** A trusted origin; defaults to the web origin. */ + origin?: string; + path: string; +} + +/** One app-owned URL a {@link SeoSitemapListSource} lists. */ +export interface SeoSitemapUrl { + alternates?: readonly SeoSitemapAlternate[]; + /** Leave it out when there is no reliable modification date. */ + lastModified?: Date | null; + /** + * A configured origin (`VITNODE_WEB_URL` or an `i18n.domains` origin). + * Defaults to the web origin; a URL on any other host is dropped. + */ + origin?: string; + /** The canonical pathname, e.g. `/docs/dev`. */ + path: string; +} + +/** + * A bounded, app-owned list of canonical URLs - the app's documentation, say + * - published as `/sitemap-{id}-{n}.xml`. Read once per process and host, + * since it only changes with a deployment. + */ +export interface SeoSitemapListSource { + /** The file stem: lowercase letters, digits and dashes; not `pages`. */ + id: string; + urls: () => Promise | readonly SeoSitemapUrl[]; +} + +interface ListFile { + file: string; + kind: "list"; + source: SeoSitemapListSource; +} + +interface ContentFile { + file: string; + kind: "content"; + locale: null | string; + source: SeoContentSitemapSource; + tags: string[]; +} + +type SitemapFile = ContentFile | ListFile; + +interface PartRecord { + /** The cursor after this part, `null` for the last. */ + end: null | string; + lastmod: null | string; + /** The cursor this part starts from, `null` for the first. */ + start: null | string; + urls: number; +} + +/** A completed generation of one content file: what its parts are. */ +interface GenerationRecord { + /** After this, in ms, the generation is served while it is refreshed. */ + freshUntil: number; + gen: string; + parts: PartRecord[]; + startedAt: number; +} + +/** An unfinished generation, built a few delivery pages at a time. */ +interface BuildRecord { + gen: string; + leaseUntil: number; + next: null | string; + owner: string; + parts: PartRecord[]; + startedAt: number; +} + +interface IndexRecord { + /** The generation of every content file the index was built from. */ + gens: Record; + xml: string; +} + +interface ListPart { + lastmod: Date | null; + urls: number; + xml: string; +} + +/** What a sitemap request answers. */ +export type SeoSitemapResult = + | { etag: string; status: 200; xml: string } + | { status: 404 } + | { status: 503 }; + +/** Lets background work outlive the response. */ +export type SeoBackground = (task: () => Promise) => void; + +interface Budget { + pages: number; +} + +const log = (message: string, error?: unknown): void => { + // oxlint-disable-next-line no-console + console.error(`[vitnode seo] ${message}`, error ?? ""); +}; + +const randomId = (): string => + `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`; + +const absoluteUrl = (origin: string, path: string): null | URL => { + try { + const url = new URL(path, origin); + if (url.href.length > MAX_URL_LENGTH) return null; + + return url; + } catch { + return null; + } +}; + +const latest = (dates: readonly (Date | null | undefined)[]): Date | null => { + let max: Date | null = null; + for (const date of dates) { + if (!date || Number.isNaN(date.getTime())) continue; + if (max === null || date > max) max = date; + } + + return max; +}; + +const mapLimit = async ( + items: readonly T[], + limit: number, + run: (item: T) => Promise, +): Promise => { + const results: R[] = Array.from({ length: items.length }); + let next = 0; + const worker = async (): Promise => { + while (next < items.length) { + const index = next; + next += 1; + results[index] = await run(items[index]); + } + }; + await Promise.all( + Array.from({ length: Math.min(limit, items.length) }, worker), + ); + + return results; +}; + +/** + * Serializes `entries` into one or more `` documents, each within the + * byte limit: a document over it is split in half until every half fits. + */ +const serializeWithinLimit = ( + entries: readonly T[], + serialize: (slice: readonly T[]) => string, +): string[] => { + const xml = serialize(entries); + if (new TextEncoder().encode(xml).byteLength <= SEO_SITEMAP_MAX_BYTES) { + return [xml]; + } + if (entries.length <= 1) { + throw new SeoSitemapSourceError( + "One sitemap URL is larger than the 50 MB file limit.", + ); + } + const half = Math.ceil(entries.length / 2); + + return [ + ...serializeWithinLimit(entries.slice(0, half), serialize), + ...serializeWithinLimit(entries.slice(half), serialize), + ]; +}; + +export interface SeoSitemapEngineOptions { + cache: SeoSitemapCache; + fetchPage: SeoContentSitemapFetch; + listSources: readonly SeoSitemapListSource[]; + manifest: SeoSitemapManifest; + policy: ResolvedSeoPolicy; + routing: LocaleRouting; +} + +/** + * Generates and caches the site's sitemap index and child files. + * + * - App paths and list sources are deterministic per deployment, so they are + * chunked once per process and host. + * - Each content file (content type, locale, host) is a *generation*: its + * delivery pages are read in cursor order, each page stored as one part, + * and the generation's part list is published only once every part is + * stored. A request reads at most a few pages; the rest continue in the + * background, and until a generation is complete the previous one is + * served - unless it was hard-invalidated, which answers `503` rather than + * listing a URL that left the public site. + * - A child request reads its part directly from the published part list, + * never walking the cursors before it. + * - The index records which generation of each file it lists, so it is + * rebuilt as soon as any of them changes. + */ +export const createSeoSitemapEngine = ({ + cache, + fetchPage, + listSources, + manifest, + policy, + routing, +}: SeoSitemapEngineOptions) => { + const owner = randomId(); + const revision = manifest.revision; + const inflight = new Map>(); + const listParts = new Map>(); + const filesByOrigin = new Map(); + + for (const source of listSources) { + if (!SEO_SITEMAP_FILE_PATTERN.test(source.id) || source.id === "pages") { + throw new SeoConfigError( + `Sitemap source id "${source.id}" must be lowercase letters, digits and dashes, and not "pages".`, + ); + } + } + + const pagesSource: SeoSitemapListSource = { + id: "pages", + urls: () => + policy.sitemap.paths.flatMap(path => { + const alternates = routing.alternatesFor(path); + const fallback = alternates.find( + alternate => alternate.locale === routing.defaultLocale, + ); + const links: SeoSitemapAlternate[] = [ + ...alternates.map(alternate => ({ + locale: alternate.locale, + ...(alternate.origin === undefined + ? {} + : { origin: alternate.origin }), + path: alternate.pathname, + })), + ...(fallback && alternates.length > 1 + ? [ + { + locale: "x-default", + ...(fallback.origin === undefined + ? {} + : { origin: fallback.origin }), + path: fallback.pathname, + }, + ] + : []), + ]; + + return alternates.map(alternate => ({ + alternates: alternates.length > 1 ? links : [], + ...(alternate.origin === undefined + ? {} + : { origin: alternate.origin }), + path: alternate.pathname, + })); + }), + }; + + const trustedOrigins = (webOrigin: string): Set => + new Set([webOrigin, ...routing.domains.map(domain => domain.origin)]); + + const filesFor = (origin: string, webOrigin: string): SitemapFile[] => { + const known = filesByOrigin.get(origin); + if (known) return known; + + const files: SitemapFile[] = [ + ...(policy.sitemap.paths.length > 0 + ? [{ file: "pages", kind: "list" as const, source: pagesSource }] + : []), + ...listSources.map(source => ({ + file: source.id, + kind: "list" as const, + source, + })), + ]; + const locales = localesOnOrigin(routing, origin, webOrigin); + const defaultOrigin = + routing.domainForLocale(routing.defaultLocale)?.origin ?? webOrigin; + + for (const source of manifest.sources) { + if (source.localized) { + for (const locale of locales) { + files.push({ + file: `${source.file}-${seoSitemapSlug(locale)}`, + kind: "content", + locale, + source, + tags: [ + contentDeliverySitemapTag(source.contentTypeId), + contentDeliverySitemapTag(source.contentTypeId, locale), + ], + }); + } + } else if (defaultOrigin === origin) { + files.push({ + file: source.file, + kind: "content", + locale: null, + source, + tags: [contentDeliverySitemapTag(source.contentTypeId)], + }); + } + } + + const seen = new Set(); + for (const { file } of files) { + if (!SEO_SITEMAP_FILE_PATTERN.test(file) || seen.has(file)) { + throw new SeoConfigError( + `Two sitemap sources would publish "/sitemap-${file}-1.xml". Rename the app's sitemap source.`, + ); + } + seen.add(file); + } + + filesByOrigin.set(origin, files); + + return files; + }; + + const buildListParts = async ( + file: ListFile, + origin: string, + webOrigin: string, + ): Promise => { + const trusted = trustedOrigins(webOrigin); + const urls = await file.source.urls(); + const seen = new Set(); + const entries: { + alternates: SeoSitemapAlternate[]; + lastModified: Date | null; + loc: URL; + }[] = []; + + for (const url of urls) { + const own = url.origin ?? webOrigin; + if (own !== origin || !trusted.has(own)) continue; + const loc = absoluteUrl(own, url.path); + if (loc === null || seen.has(loc.href)) continue; + seen.add(loc.href); + entries.push({ + alternates: (url.alternates ?? []).filter(alternate => + trusted.has(alternate.origin ?? webOrigin), + ), + lastModified: url.lastModified ?? null, + loc, + }); + } + + const parts: ListPart[] = []; + for ( + let start = 0; + start < entries.length; + start += SEO_SITEMAP_PART_SIZE + ) { + const slice = entries.slice(start, start + SEO_SITEMAP_PART_SIZE); + for (const xml of serializeWithinLimit(slice, chunk => + contentSitemapXml({ + alternates: new Map( + chunk.flatMap((entry, index) => + entry.alternates.length > 0 + ? [ + [ + index, + entry.alternates.map(alternate => ({ + locale: alternate.locale, + origin: alternate.origin ?? webOrigin, + path: alternate.path, + })), + ] as const, + ] + : [], + ), + ), + entries: chunk.map((entry, index) => ({ + itemId: index, + lastModified: entry.lastModified, + origin: entry.loc.origin, + path: `${entry.loc.pathname}${entry.loc.search}`, + })), + origin, + }), + )) { + parts.push({ + lastmod: latest(slice.map(entry => entry.lastModified)), + urls: slice.length, + xml, + }); + } + } + + return parts; + }; + + const listPartsFor = async ( + file: ListFile, + origin: string, + webOrigin: string, + ): Promise => { + const key = `${origin}|${file.file}`; + let pending = listParts.get(key); + if (!pending) { + pending = buildListParts(file, origin, webOrigin).catch( + (error: unknown) => { + listParts.delete(key); + throw error; + }, + ); + listParts.set(key, pending); + } + + return await pending; + }; + + const keyOf = (kind: string, origin: string, file: string): string => + `${revision}:${kind}:${encodeURIComponent(origin)}:${file}`; + const partKey = ( + origin: string, + file: string, + gen: string, + part: number, + ): string => `${keyOf("x", origin, file)}:${gen}:${String(part)}`; + + const serializeContentPart = ( + entries: readonly SeoContentSitemapEntry[], + origin: string, + webOrigin: string, + ): { lastmod: Date | null; urls: number; xml: string } => { + const seen = new Set(); + const kept: (SeoContentSitemapEntry & { loc: URL })[] = []; + for (const entry of entries) { + // Each host lists only its own URLs: a locale served from another + // domain is in that domain's sitemap. + if ((entry.origin ?? webOrigin) !== origin) continue; + const loc = absoluteUrl(origin, entry.path); + if (loc === null || seen.has(loc.href)) continue; + seen.add(loc.href); + kept.push({ ...entry, loc }); + } + const [xml, ...rest] = serializeWithinLimit(kept, chunk => + contentSitemapXml({ + entries: chunk.map((entry, index) => ({ + changeFrequency: entry.changeFrequency, + itemId: index, + lastModified: entry.lastModified, + path: `${entry.loc.pathname}${entry.loc.search}`, + priority: entry.priority, + })), + origin, + }), + ); + if (rest.length > 0) { + throw new SeoSitemapSourceError( + "One delivery page does not fit in one 50 MB sitemap file.", + ); + } + + return { + lastmod: latest(kept.map(entry => entry.lastModified)), + urls: kept.length, + xml, + }; + }; + + /** + * Reads up to `budget.pages` delivery pages of `file`'s current generation + * and stores each as a part. Publishes the generation once its last page is + * stored, unless the file was invalidated after it started - an older read + * never replaces a newer invalidation. + */ + const advance = async ( + file: ContentFile, + origin: string, + webOrigin: string, + budget: Budget, + ): Promise => { + const buildKey = keyOf("b", origin, file.file); + const manifestKey = keyOf("m", origin, file.file); + let stored = await cache.get(buildKey); + + if (stored) { + const state = await seoCachedState(cache, file.tags, stored.startedAt); + if (state !== "fresh") { + stored = null; + } else if (stored.owner !== owner && stored.leaseUntil > Date.now()) { + // Another instance is building it; serve what there is meanwhile. + return null; + } + } + + const build: BuildRecord = stored + ? { ...stored, owner, parts: [...stored.parts] } + : { + gen: randomId(), + leaseUntil: 0, + next: null, + owner, + parts: [], + startedAt: Date.now(), + }; + + let done = false; + while (budget.pages > 0) { + budget.pages -= 1; + const page = await fetchPage({ + cursor: build.next, + limit: SEO_SITEMAP_PART_SIZE, + locale: file.locale, + source: file.source, + }); + if (page.nextCursor !== null && page.nextCursor === build.next) { + throw new SeoSitemapSourceError( + `${file.source.contentTypeId} returned the cursor it was given; its sitemap cannot advance.`, + ); + } + + const part = serializeContentPart(page.entries, origin, webOrigin); + build.parts.push({ + end: page.nextCursor, + lastmod: part.lastmod?.toISOString() ?? null, + start: build.next, + urls: part.urls, + }); + await cache.set( + partKey(origin, file.file, build.gen, build.parts.length), + part.xml, + SEO_SITEMAP_PART_TTL_SECONDS, + ); + build.next = page.nextCursor; + + if (page.nextCursor === null) { + done = true; + break; + } + if (build.parts.length >= SEO_SITEMAP_MAX_FILES) { + throw new SeoSitemapSourceError( + `${file.source.contentTypeId} needs more than ${String(SEO_SITEMAP_MAX_FILES)} sitemap files.`, + ); + } + } + + if (!done) { + build.leaseUntil = Date.now() + BUILD_LEASE_MS; + await cache.set(buildKey, build, SEO_SITEMAP_BUILD_TTL_SECONDS); + + return null; + } + + await cache.delete(buildKey); + const [state, current] = await Promise.all([ + seoCachedState(cache, file.tags, build.startedAt), + cache.get(manifestKey), + ]); + if (current && current.startedAt > build.startedAt) return current; + + const record: GenerationRecord = { + freshUntil: build.startedAt + SEO_SITEMAP_TTL_SECONDS * 1000, + gen: build.gen, + parts: build.parts, + startedAt: build.startedAt, + }; + if (state !== "fresh") { + // Invalidated around the time it started. Read entirely after a hard + // invalidation by this clock, it may answer the request that built it, + // but it is not published: another server's clock may disagree. + const hardAt = await cache.invalidatedAt(file.tags, "hard"); + + return hardAt < build.startedAt ? record : null; + } + + const lifetime = + SEO_SITEMAP_TTL_SECONDS * 2 - (Date.now() - build.startedAt) / 1000; + if (lifetime <= 0) return null; + await cache.set(manifestKey, record, lifetime); + + return record; + }; + + /** One advance per file at a time in this process. */ + const advanceOnce = async ( + file: ContentFile, + origin: string, + webOrigin: string, + budget: Budget, + ): Promise => { + const key = keyOf("b", origin, file.file); + const running = inflight.get(key); + if (running) return await running; + + const task = advance(file, origin, webOrigin, budget).finally(() => { + inflight.delete(key); + }); + inflight.set(key, task); + + return await task; + }; + + const continueInBackground = ( + background: SeoBackground, + file: ContentFile, + origin: string, + webOrigin: string, + ): void => { + background(async () => { + const budget = { pages: BACKGROUND_PAGE_BUDGET }; + while (budget.pages > 0) { + const before = budget.pages; + const record = await advanceOnce(file, origin, webOrigin, budget); + if (record !== null || budget.pages === before) return; + } + }); + }; + + /** + * The generation of `file` that may be served now, or `null` when there is + * none: no completed generation, or only one a hard invalidation retired. + */ + const usableGeneration = async ( + file: ContentFile, + origin: string, + webOrigin: string, + budget: Budget, + background: SeoBackground, + ): Promise => { + const current = await cache.get( + keyOf("m", origin, file.file), + ); + if (current) { + const state = await seoCachedState(cache, file.tags, current.startedAt); + if (state === "fresh" && current.freshUntil > Date.now()) return current; + if (state !== "invalid") { + continueInBackground(background, file, origin, webOrigin); + + return current; + } + } + + try { + const built = await advanceOnce(file, origin, webOrigin, budget); + if (built) return built; + } catch (error) { + log(`The ${file.file} sitemap could not be generated.`, error); + + return null; + } + continueInBackground(background, file, origin, webOrigin); + + return null; + }; + + const servableIndex = async ( + origin: string, + webOrigin: string, + background: SeoBackground, + ): Promise => { + const files = filesFor(origin, webOrigin); + const budget = { pages: INLINE_PAGE_BUDGET }; + type Resolved = + | { file: ContentFile; generation: GenerationRecord | null } + | { file: ListFile; parts: ListPart[] }; + const resolved = await mapLimit( + files, + SOURCE_CONCURRENCY, + async (file): Promise => + file.kind === "list" + ? { + file, + parts: await listPartsFor(file, origin, webOrigin), + } + : { + file, + generation: await usableGeneration( + file, + origin, + webOrigin, + budget, + background, + ), + }, + ); + + const gens: Record = {}; + const entries: { lastModified?: Date; path: string }[] = []; + for (const item of resolved) { + if ("parts" in item) { + if (item.parts.every(part => part.urls === 0)) continue; + item.parts.forEach((part, index) => { + entries.push({ + ...(part.lastmod ? { lastModified: part.lastmod } : {}), + path: seoSitemapChildPath(item.file.file, index + 1), + }); + }); + continue; + } + // An index without one of its sources would quietly drop its URLs. + if (item.generation === null) return { status: 503 }; + gens[item.file.file] = item.generation.gen; + if (item.generation.parts.every(part => part.urls === 0)) continue; + item.generation.parts.forEach((part, index) => { + entries.push({ + ...(part.lastmod ? { lastModified: new Date(part.lastmod) } : {}), + path: seoSitemapChildPath(item.file.file, index + 1), + }); + }); + } + if (entries.length > SEO_SITEMAP_MAX_FILES) { + log( + `The sitemap index for ${origin} would list more than ${String(SEO_SITEMAP_MAX_FILES)} files.`, + ); + + return { status: 503 }; + } + + const gensKey = JSON.stringify(gens); + const etag = `W/"${fingerprint(`${revision}|${gensKey}`)}"`; + const indexKey = keyOf("i", origin, "index"); + const cached = await cache.get(indexKey); + if (cached && JSON.stringify(cached.gens) === gensKey) { + return { etag, status: 200, xml: cached.xml }; + } + + const xml = contentSitemapIndexXml({ entries, origin }); + await cache.set( + indexKey, + { gens, xml } satisfies IndexRecord, + SEO_SITEMAP_INDEX_TTL_SECONDS, + ); + + return { etag, status: 200, xml }; + }; + + const servableChild = async ( + origin: string, + webOrigin: string, + name: string, + part: number, + background: SeoBackground, + ): Promise => { + const file = filesFor(origin, webOrigin).find( + candidate => candidate.file === name, + ); + if (!file) return { status: 404 }; + + if (file.kind === "list") { + const parts = await listPartsFor(file, origin, webOrigin); + const found = parts[part - 1]; + if (!found) { + // A list with nothing on this host still answers its first file. + return part === 1 && parts.length === 0 + ? { + etag: `W/"${fingerprint(`${revision}|${name}|empty`)}"`, + status: 200, + xml: contentSitemapXml({ entries: [], origin }), + } + : { status: 404 }; + } + + return { + etag: `W/"${fingerprint(`${revision}|${name}|${String(part)}`)}"`, + status: 200, + xml: found.xml, + }; + } + + const budget = { pages: INLINE_PAGE_BUDGET }; + const generation = await usableGeneration( + file, + origin, + webOrigin, + budget, + background, + ); + if (generation === null) return { status: 503 }; + + const record = generation.parts[part - 1]; + if (!record) return { status: 404 }; + + const etag = `W/"${fingerprint(`${revision}|${generation.gen}|${String(part)}`)}"`; + const key = partKey(origin, file.file, generation.gen, part); + const cached = await cache.get(key); + if (cached !== null) return { etag, status: 200, xml: cached }; + + // Evicted: read just this part again from the cursor it starts at. A + // different end cursor means the data moved under the generation, so it + // is retired rather than served with gaps or duplicates. + try { + const page = await fetchPage({ + cursor: record.start, + limit: SEO_SITEMAP_PART_SIZE, + locale: file.locale, + source: file.source, + }); + if (page.nextCursor !== record.end) { + await cache.delete(keyOf("m", origin, file.file)); + continueInBackground(background, file, origin, webOrigin); + + return { status: 503 }; + } + const { xml } = serializeContentPart(page.entries, origin, webOrigin); + await cache.set(key, xml, SEO_SITEMAP_PART_TTL_SECONDS); + + return { etag, status: 200, xml }; + } catch (error) { + log( + `Part ${String(part)} of the ${name} sitemap could not be read.`, + error, + ); + + return { status: 503 }; + } + }; + + return { + /** `/sitemap.xml` for one trusted origin. */ + index: async ({ + background, + origin, + webOrigin, + }: { + background: SeoBackground; + origin: string; + webOrigin: string; + }): Promise => { + try { + return await servableIndex(origin, webOrigin, background); + } catch (error) { + if (error instanceof SeoConfigError) throw error; + log(`The sitemap index for ${origin} could not be generated.`, error); + + return { status: 503 }; + } + }, + /** `/sitemap-{file}-{part}.xml` for one trusted origin. */ + child: async ({ + background, + file, + origin, + part, + webOrigin, + }: { + background: SeoBackground; + file: string; + origin: string; + part: number; + webOrigin: string; + }): Promise => { + try { + return await servableChild(origin, webOrigin, file, part, background); + } catch (error) { + if (error instanceof SeoConfigError) throw error; + log(`The ${file} sitemap could not be generated.`, error); + + return { status: 503 }; + } + }, + }; +}; + +export type SeoSitemapEngine = ReturnType; diff --git a/packages/vitnode/src/tanstack/seo/types.ts b/packages/vitnode/src/tanstack/seo/types.ts new file mode 100644 index 0000000000..93a3e6e57f --- /dev/null +++ b/packages/vitnode/src/tanstack/seo/types.ts @@ -0,0 +1,83 @@ +/** + * Search and AI-training crawler choices for one vendor that runs separate + * bots for search and for training. `true` adds a group for that bot that + * allows the site with the same exclusions as `User-agent: *`; `false` adds + * `Disallow: /` for it; leaving it out adds no group, so the bot follows + * `User-agent: *`. + */ +export interface VitNodeSeoCrawlerPair { + /** The vendor's search crawler (results and citations). */ + search?: boolean; + /** The vendor's crawler that collects training data. */ + training?: boolean; +} + +/** + * Per-bot rules written to `/robots.txt`. Directives express a policy that + * well-behaved crawlers follow; they do not block HTTP access. User-initiated + * fetches (a person asking an assistant to open a page) are outside this + * contract. + */ +export interface VitNodeSeoCrawlersConfig { + /** Anthropic: `search` maps to `Claude-SearchBot`, `training` to `ClaudeBot`. */ + anthropic?: VitNodeSeoCrawlerPair; + /** + * Google's `Google-Extended` token: whether Gemini may use the site for + * training and grounding, as Google describes it. It never changes Google + * Search crawling or ranking. + */ + googleExtended?: boolean; + /** OpenAI: `search` maps to `OAI-SearchBot`, `training` to `GPTBot`. */ + openai?: VitNodeSeoCrawlerPair; +} + +/** The generated sitemap: `/sitemap.xml` and its child files. */ +export interface VitNodeSeoSitemapConfig { + /** + * Publishes `/sitemap.xml` and the `Sitemap:` line in `/robots.txt`. + * Defaults to the value of `indexing`; `indexing: false` always hides it. + */ + enabled?: boolean; + /** + * The app's own canonical, public, indexable pages, as unlocalized paths + * (`"/"`, `"/plugins"`). Each is listed once per locale with its locale + * prefix or domain applied and `hreflang` alternates. Content Engine + * records with `delivery.sitemap` are added on their own - do not list them. + * A path must start with `/` and carry no query, hash, `.`/`..` segment or + * locale prefix, and must not be under `/admin` or `/api`; a trailing slash + * is dropped and duplicates are merged. Defaults to `[]`. + */ + paths?: readonly string[]; +} + +/** + * Site-wide search indexing, sitemap and crawler policy, set in + * `buildServerConfig({ seo })` and served by `withSeo` from + * `@vitnode/core/tanstack/seo/server`. Changes apply on the next deployment. + * + * Leaving `seo` out is `{ indexing: true }`: `withSeo` serves the generated + * `/robots.txt` and sitemap, and pages are indexable. An app without `withSeo` + * in its server entry gets none of this. + * + * @example + * ```ts + * seo: { + * sitemap: { paths: ["/", "/about"] }, + * crawlers: { openai: { training: false } }, + * } + * ``` + */ +export interface VitNodeSeoConfig { + /** Per-bot rules. Each omitted bot follows `User-agent: *`. */ + crawlers?: VitNodeSeoCrawlersConfig; + /** + * `true` lets search engines index the site. `false` adds + * `X-Robots-Tag: noindex` to every HTML response (and a robots `` to + * prerendered pages), hides the sitemap and keeps pages crawlable so search + * engines can read the directive. Set it to `false` on preview and staging + * deployments. Defaults to `true`. + */ + indexing?: boolean; + /** The generated sitemap. See {@link VitNodeSeoSitemapConfig}. */ + sitemap?: VitNodeSeoSitemapConfig; +} diff --git a/packages/vitnode/src/vitnode.config.ts b/packages/vitnode/src/vitnode.config.ts index d4090ef8fc..d3eee4525c 100644 --- a/packages/vitnode/src/vitnode.config.ts +++ b/packages/vitnode/src/vitnode.config.ts @@ -12,10 +12,11 @@ import type { VitNodeLogo } from "./components/logo-context"; import type { ThemeProviderProps } from "./components/theme-provider"; import type { NavigationConfig } from "./lib/navigation"; import type { BuildPluginReturn } from "./lib/plugin"; +import type { VitNodeSeoConfig } from "./tanstack/seo/types"; import { assertNavigationConfig } from "./lib/navigation"; -export type { LocaleConfig }; +export type { LocaleConfig, VitNodeSeoConfig }; /** * An app's frontend configuration, written in `src/vitnode.config.ts` with @@ -82,6 +83,26 @@ export interface VitNodeServerConfig< /** Each package's message loaders - the generated `src/package-messages.gen.ts`. */ packageMessages?: Record; + + /** + * Search indexing, `/robots.txt`, the sitemap and AI crawler rules, served + * by `withSeo` from `@vitnode/core/tanstack/seo/server`. Defaults to + * `{ indexing: true }`: the site is indexable, the sitemap is on while + * indexing is on, and each omitted crawler follows `User-agent: *`. Set + * `indexing: false` on preview deployments. Read when the server starts, so + * a change takes effect with the next deployment. See + * {@link VitNodeSeoConfig}. + * + * @example + * ```ts + * seo: { + * indexing: true, + * sitemap: { paths: ["/", "/about"] }, + * crawlers: { openai: { search: true, training: false } }, + * } + * ``` + */ + seo?: VitNodeSeoConfig; } const DEFAULT_TIME_ZONE = "UTC"; @@ -138,8 +159,8 @@ export function buildConfig( /** * Declares the server-only part of the frontend configuration: app message - * overrides and the generated package message loaders. Import it only from - * server code. + * overrides, the generated package message loaders and the site's `seo` + * policy. Import it only from server code. */ export function buildServerConfig( args: VitNodeServerConfig,