/**
* publicDocsSeo.js — ADR-190-A: request-time SSR-lite for a public space's
* documentation hub (`/s/:slug`, `/s/:slug/docs`, `/s/:slug/docs/:docSlug`)
* plus that hub's contribution to `/sitemap.xml`.
*
* ADR-190 did this for `/blog/*`; the docs hub has the same problem and gets
* the same cure, built out of the same primitives — `esc`, `safeUrl`, `jsonLd`,
* `injectHead`, `injectRoot`, `loadTemplate`, `renderMarkdown` are all imported
* from blogSeo.js, and the data comes from the loaders public.js already
* exports for the anonymous MCP mount. No new SQL here, no new dependency, no
* new public API surface.
*
* WHAT IS DIFFERENT FROM THE BLOG: the blog is a single hard-coded table, this
* is per-space and opt-in. Nothing is rendered unless the space passes BOTH
* hard guards (ADR-190-A D2) and its owner has switched `indexable` on:
*
* 1. visibility = 'external' (enforced in getPublicSpaceBySlug SQL)
* 2. public_password_hash IS NULL (a gated space must never leak to an index)
* 3. settings.public_seo.indexable (opt-in — sharing ≠ indexing)
*
* A space that fails any of them falls through to the SPA catch-all untouched,
* so `/s/*` behaves exactly as it did before this module existed.
*
* SECURITY: identical contract to ADR-190. Every value below is authored
* content and is treated as untrusted — text/attributes through `esc()`, URLs
* through `safeUrl()`, body markdown through markdown-it with `html:false`,
* JSON-LD through `jsonLd()`'s ``-breakout escape.
*/
import {
DEFAULT_SITE_ORIGIN,
esc,
safeUrl,
jsonLd,
isoDate,
injectHead,
injectRoot,
loadTemplate,
noCache,
renderMarkdown,
} from './blogSeo.js';
import {
getPublicSpaceBySlug,
readPublicSeoPrefs,
listIndexableSpaces,
} from './SpaceVisibilityService.js';
import { loadPublicDocumentsRegistry, loadPublicDocument } from '../routes/v3/public.js';
import { apiLogger } from '../utils/logger.js';
const log = apiLogger.child({ module: 'public-docs-seo' });
/** Meta descriptions past ~300 chars are truncated by every consumer anyway. */
const DESCRIPTION_MAX = 300;
// ── resolution ──────────────────────────────────────────────────────────────
/**
* ADR-190-A D5 — origin resolution, in order:
* 1. the space's own `public_seo.site_origin`,
* 2. `process.env.PUBLIC_SITE_ORIGIN`,
* 3. the compiled default.
* Steps 2–3 are already folded into `DEFAULT_SITE_ORIGIN` (blogSeo.js), which
* is why the blog cannot regress when a space sets its own origin (AC-8).
*/
function resolveOrigin(seo) {
// Absolute http(s) only — `safeUrl` also passes root-relative paths, and a
// space configured with `site_origin: "/"` would otherwise build `//s/help`
// (a protocol-relative URL) as its canonical.
const configured = /^https?:\/\//i.test(String(seo.site_origin || '').trim())
? safeUrl(seo.site_origin)
: '';
return (configured || DEFAULT_SITE_ORIGIN).replace(/\/+$/, '');
}
/**
* The two hard guards of D2 + the opt-in, in one place. Returns
* `{ space, seo, origin }` for a renderable space, or null — and null always
* means "fall through to the SPA", never "error".
*/
async function resolveIndexableSpace(slug) {
// Query is `visibility = 'external'` only — guard 1.
const space = await getPublicSpaceBySlug(slug);
if (!space) return null;
// Guard 2: a password-protected space is force-noindex whatever config says.
if (space.has_password) return null;
const seo = readPublicSeoPrefs(space.settings);
if (!seo.indexable) return null;
return { space, seo, origin: resolveOrigin(seo) };
}
/** Guard 3: only `status = 'published'` rows are ever rendered (D2). */
async function loadPublishedDocs(spaceId) {
const { documents = [] } = await loadPublicDocumentsRegistry(spaceId);
return documents.filter((d) => d && d.status === 'published' && !!d.slug);
}
/**
* Listable = published AND not individually opted out. `seo_noindex` keeps a
* chapter out of the sitemap and the hub's ItemList, but the page itself still
* renders (with `robots: noindex`) — a 404 would be a lie to a human reader.
*/
const isListable = (doc) => doc.seo_noindex !== true;
// ── copy resolution (fallback chains from D3) ───────────────────────────────
/** `title_template` carries a single `%s`. Function replacement so a `$&` in a
* document title is inserted literally instead of being read as a backref. */
function applyTemplate(template, value) {
return template.includes('%s') ? template.replace('%s', () => value) : value;
}
function clamp(text, max = DESCRIPTION_MAX) {
const s = String(text ?? '').replace(/\s+/g, ' ').trim();
if (s.length <= max) return s;
const cut = s.slice(0, max);
const lastSpace = cut.lastIndexOf(' ');
return `${(lastSpace > max * 0.6 ? cut.slice(0, lastSpace) : cut).trimEnd()}…`;
}
/** seo_title → title_template % name → name. */
function docTitle(doc, seo) {
if (doc.seo_title) return doc.seo_title;
return applyTemplate(seo.title_template, doc.name || doc.slug);
}
/** seo_description → registry description → space default_description. */
function docDescription(doc, seo) {
return clamp(doc.seo_description || doc.description || seo.default_description);
}
/** OG images must be absolute; a configured root-relative path is resolved. */
function absoluteImage(seo, origin) {
const url = safeUrl(seo.og_image);
if (!url) return '';
return url.startsWith('/') ? `${origin}${url}` : url;
}
// ── head + body builders (pure — unit-tested) ──────────────────────────────
function headTags({ title, description, canonical, ogType, image, noindex, lds }) {
return [
noindex ? '' : '',
`
${esc(title)}`,
``,
``,
``,
``,
``,
``,
image ? `` : '',
``,
``,
``,
...lds.map((ld) => ``),
].filter(Boolean).join('\n ');
}
/** Declare the language actually served (D6 — one indexed language, no hreflang). */
function setHtmlLang(html, lang) {
// Both replacements take a function — `lang` is owner-configured text and a
// `$&`/`` $` `` in it would otherwise be read as a substitution pattern.
return html.replace(/]*?\slang="[^"]*"/i, (m) =>
m.replace(/lang="[^"]*"/i, () => `lang="${esc(lang)}"`));
}
function breadcrumbs(items) {
return {
'@context': 'https://schema.org',
'@type': 'BreadcrumbList',
itemListElement: items.map((it, i) => ({
'@type': 'ListItem', position: i + 1, name: it.name, item: it.url,
})),
};
}
const publisher = (seo) => ({ '@type': 'Organization', name: seo.site_name });
export function renderDocHead({ doc, seo, origin, slug, hubUrl }) {
const title = docTitle(doc, seo);
const description = docDescription(doc, seo);
const canonical = `${origin}/s/${slug}/docs/${doc.slug}`;
const article = {
'@context': 'https://schema.org',
'@type': 'TechArticle',
headline: doc.seo_title || doc.name || doc.slug,
description: description || undefined,
url: canonical,
inLanguage: seo.default_lang,
datePublished: isoDate(doc.created_at) || undefined,
dateModified: isoDate(doc.updated_at) || undefined,
author: publisher(seo),
publisher: publisher(seo),
isPartOf: { '@type': 'CollectionPage', '@id': hubUrl },
mainEntityOfPage: { '@type': 'WebPage', '@id': canonical },
};
return headTags({
title,
description,
canonical,
ogType: 'article',
image: absoluteImage(seo, origin),
noindex: doc.seo_noindex === true,
lds: [article, breadcrumbs([
{ name: seo.site_name, url: `${origin}/` },
{ name: 'Docs', url: hubUrl },
{ name: doc.seo_title || doc.name || doc.slug, url: canonical },
])],
});
}
/**
* Atoms → crawler-readable markup. `level` drives the tag (h1/h2/h3 headings,
* `divider` → , everything else → a markdown-rendered paragraph block);
* language falls back to the other column when the requested one is empty, so
* an RU-only chapter still has a body instead of an empty .
*/
export function renderDocBody(doc, items, lang) {
const pickText = (item) => {
const en = typeof item.content_en === 'string' ? item.content_en : '';
const ru = typeof item.content_ru === 'string' ? item.content_ru : '';
return (lang === 'ru' ? (ru || en) : (en || ru)).trim();
};
const blocks = (items || []).map((item) => {
const level = String(item.level || 'text');
if (level === 'divider') return '';
const text = pickText(item);
if (!text) return '';
if (level === 'h1' || level === 'h2' || level === 'h3') {
return `<${level}>${esc(text)}${level}>`;
}
return renderMarkdown(text);
}).filter(Boolean).join('');
return ''
+ `