feat: CMS head and one JSON-LD graph on every server-rendered page (tracer)

- Nitro middleware resolves page requests once and hands the answer to the
  render (event.context.seo); the route middleware reuses it
- useCmsSeo: html lang, hreflang links, og:locale and exactly one JSON-LD
  script with one @graph (CMS nodes plus useSchemaNode nodes, merged by @id)
- local module (configKey seo): cms (alias of public.seo.enabled),
  breadcrumbs, links.newTabHint, rootFiles, resolveFiles
- GET /api/__seo__/resolve for client navigation through the Nuxt server
- smoke harness: count=, exact header=, noheader=, reqheader=, repeated
  options, resolves/apicalls/noreport lines, --no-site; v0.1.1 suite runs
  unchanged against a backend without /site
This commit is contained in:
Jakub Zych
2026-11-04 09:15:26 +01:00
parent 7d52c5d2e5
commit 160b53b2f5
25 changed files with 1074 additions and 140 deletions

View File

@@ -1,20 +1,31 @@
// A small node:http stand-in for the SEO plugin's public API
// (/_seo/api/v1):
// (/_seo/api/v1) and the Go binary's root files:
//
// GET /resolve?url=… the answer for that exact url from
// <dir>/resolve.json, else not_found
// POST /notfound 204 with `Authorization: Bearer <token>`,
// 401 with another token, 404 without one
// GET /verification/<name> <dir>/verification/<name>, else 404
// GET /_seo/api/v1/resolve?url=… the answer for that exact url from
// <dir>/seo/resolve.json, then
// <dir>/resolve.json, else not_found
// GET /_seo/api/v1/site <dir>/seo/site.json (404 without the
// file or with { site: false }: an
// older backend)
// POST /_seo/api/v1/notfound 204 with `Authorization: Bearer <token>`,
// 401 with another token, 404 without one
// GET /_seo/api/v1/verification/<name> <dir>/verification/<name> or
// <dir>/seo/verification/<name>, else 404
// GET /robots.txt, /llms.txt, <dir>/seo/root/<name>, else 404
// /sitemap.xml
// GET /_sitemap/files/<file> <dir>/seo/root/<file>, else 404;
// sitemap-fail-*.xml answers 500
// GET /_sitemap/indexnow/<key>.txt <dir>/seo/indexnow/<key>.txt, else 404
//
// It records every request (with the parsed JSON body of a POST) so a smoke
// run can assert header forwarding and the 404 reports.
// run can assert header forwarding, resolve counts and the 404 reports.
// `reload()` reads the fixture files again (purge-check changes them).
//
// Plain .mjs with JSDoc types: Node does not strip TypeScript under
// node_modules, and consuming apps may import this file from there.
import { createServer } from 'node:http'
import { readFileSync } from 'node:fs'
import { existsSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
const PREFIX = '/_seo/api/v1'
@@ -24,26 +35,58 @@ export const FIXTURE_NOTFOUND_TOKEN = 'fixture-seo-notfound-token-0123456789'
/**
* @typedef {{ method: string, url: string, xff: string | null, authorization: string | null, body: unknown }} FixtureRequest
* @typedef {{ url: string, requests: FixtureRequest[], close: () => Promise<void> }} FixtureApi
* @typedef {{ url: string, requests: FixtureRequest[], resolveCount: (target?: string) => number, reload: () => void, close: () => Promise<void> }} FixtureApi
*/
/** @param {string} file @returns {any} */
function readJson(file) {
return existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : null
}
/** @param {string} name */
function contentType(name) {
if (name.endsWith('.xml')) return 'application/xml; charset=utf-8'
if (name.endsWith('.html')) return 'text/html; charset=utf-8'
return 'text/plain; charset=utf-8'
}
/**
* Starts the fixture API on 127.0.0.1.
* @param {{ dir: string, port?: number, token?: string }} opts
* @param {{ dir: string, port?: number, token?: string, site?: boolean }} opts
* @returns {Promise<FixtureApi>}
*/
export function startFixtureApi({ dir, port = 0, token = FIXTURE_NOTFOUND_TOKEN }) {
export function startFixtureApi({ dir, port = 0, token = FIXTURE_NOTFOUND_TOKEN, site = true }) {
/** @type {FixtureRequest[]} */
const requests = []
/** @type {Record<string, unknown>} */
const answers = JSON.parse(readFileSync(join(dir, 'resolve.json'), 'utf8'))
let answers = {}
/** @type {unknown} */
let siteAnswer = null
const load = () => {
answers = { ...(readJson(join(dir, 'resolve.json')) ?? {}), ...(readJson(join(dir, 'seo', 'resolve.json')) ?? {}) }
siteAnswer = site ? readJson(join(dir, 'seo', 'site.json')) : null
}
load()
/** @param {string} file @param {string} name */
const fileAnswer = (file, name) => {
if (/^sitemap-fail-/.test(name)) return { status: 500, text: 'backend failure', type: 'text/plain' }
if (!existsSync(file)) return { status: 404, body: { error: 'not_found' } }
return { status: 200, text: readFileSync(file, 'utf8'), type: contentType(name), robots: name.startsWith('sitemap-') || name === 'llms.txt' ? 'noindex' : undefined }
}
/**
* @param {import('node:http').IncomingMessage} req
* @returns {{ status: number, body?: unknown, text?: string, type?: string }}
* @returns {{ status: number, body?: unknown, text?: string, type?: string, robots?: string }}
*/
const route = (req) => {
const url = new URL(req.url ?? '/', 'http://fixture.local')
const root = /^\/(robots\.txt|llms\.txt|sitemap\.xml)$/.exec(url.pathname)
if (root && req.method === 'GET') return fileAnswer(join(dir, 'seo', 'root', root[1]), root[1])
const files = /^\/_sitemap\/files\/(sitemap-[a-z0-9-]+\.xml)$/.exec(url.pathname)
if (files && req.method === 'GET') return fileAnswer(join(dir, 'seo', 'root', files[1]), files[1])
const key = /^\/_sitemap\/indexnow\/([A-Za-z0-9-]{8,128}\.txt)$/.exec(url.pathname)
if (key && req.method === 'GET') return fileAnswer(join(dir, 'seo', 'indexnow', key[1]), key[1])
if (!url.pathname.startsWith(PREFIX + '/')) return { status: 404, body: { error: 'not_found' } }
const path = url.pathname.slice(PREFIX.length)
if (path === '/resolve' && req.method === 'GET') {
@@ -53,17 +96,19 @@ export function startFixtureApi({ dir, port = 0, token = FIXTURE_NOTFOUND_TOKEN
if (hit) return { status: 200, body: hit }
return { status: 200, body: { action: 'not_found', status: 404, url: target, locale: '', staging: false, seo: null } }
}
if (path === '/site' && req.method === 'GET') {
return siteAnswer ? { status: 200, body: siteAnswer } : { status: 404, body: { error: 'not_found' } }
}
if (path === '/notfound' && req.method === 'POST') {
if (!token) return { status: 404, body: { error: 'not_found' } }
return req.headers.authorization === `Bearer ${token}` ? { status: 204 } : { status: 401, body: { error: 'unauthorized' } }
}
const v = /^\/verification\/([A-Za-z0-9._-]+)$/.exec(path)
if (v && req.method === 'GET') {
try {
return { status: 200, text: readFileSync(join(dir, 'verification', v[1]), 'utf8'), type: 'text/html; charset=utf-8' }
} catch {
return { status: 404, body: { error: 'not_found' } }
for (const file of [join(dir, 'verification', v[1]), join(dir, 'seo', 'verification', v[1])]) {
if (existsSync(file)) return { status: 200, text: readFileSync(file, 'utf8'), type: 'text/html; charset=utf-8' }
}
return { status: 404, body: { error: 'not_found' } }
}
return { status: 404, body: { error: 'not_found' } }
}
@@ -91,7 +136,7 @@ export function startFixtureApi({ dir, port = 0, token = FIXTURE_NOTFOUND_TOKEN
out = { status: 500, body: { error: String(err) } }
}
if (out.text !== undefined) {
res.writeHead(out.status, { 'content-type': out.type ?? 'text/plain' })
res.writeHead(out.status, { 'content-type': out.type ?? 'text/plain', ...(out.robots ? { 'x-robots-tag': out.robots } : {}) })
res.end(out.text)
return
}
@@ -100,6 +145,14 @@ export function startFixtureApi({ dir, port = 0, token = FIXTURE_NOTFOUND_TOKEN
})
})
/** Resolve calls so far, for one target url or (without one) all of them. @param {string} [target] */
const resolveCount = (target) =>
requests.filter((r) => {
if (r.method !== 'GET') return false
const u = new URL(r.url, 'http://fixture.local')
return u.pathname === `${PREFIX}/resolve` && (target === undefined || u.searchParams.get('url') === target)
}).length
return new Promise((resolve, reject) => {
server.once('error', reject)
server.listen(port, '127.0.0.1', () => {
@@ -107,6 +160,8 @@ export function startFixtureApi({ dir, port = 0, token = FIXTURE_NOTFOUND_TOKEN
resolve({
url: `http://127.0.0.1:${addr.port}`,
requests,
resolveCount,
reload: load,
close: () => new Promise((done) => server.close(() => done())),
})
})