Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ Operating guide for agents (and humans) working in this repository.

## SEO and link previews

- `book/.vitepress/seo.mjs` adds per-page head tags in VitePress's `transformHead`: `meta description` from the chapter text, canonical, `hreflang` and Open Graph/Twitter tags. `sitemap.xml` is VitePress's own, with an x-default alternate added.
- `book/.vitepress/seo.mjs` adds per-page head tags in VitePress's `transformHead`: `meta description`, canonical, `hreflang` and Open Graph/Twitter tags. `sitemap.xml` is VitePress's own, with an x-default alternate added.
- The description is written into the page's frontmatter by a markdown-it plugin while the page renders, not computed in `transformHead`: the VitePress client rewrites `meta description` to the frontmatter description (or the site's) on hydration. A `description:` in a page's frontmatter overrides it. A locale page with no prose (the table of contents) takes its locale home page's description.
- VitePress keeps one `meta` per key (its `id`, else its first attribute besides `content`), so a repeated meta such as `og:locale:alternate` needs a distinct `id` on each tag.
- The public URL, base path and preview image live in `book/.vitepress/config.mjs`; change `BASE_URL` and `base` there when the site moves to its own domain.
- The description is the first paragraph of a pattern's intent section, or an anti-pattern's problem section; other pages use their first paragraph, skipping an all-italic note. The section heading ids per locale are `descriptionSections` in the same config: add the id there when a new chapter kind opens differently. That paragraph should state the chapter's point on its own.
- Preview cards are `book/assets/og/<locale>.png`, rendered from `book/.vitepress/og-card.html`; the command to rerender one is at the top of that file.
Expand Down
2 changes: 2 additions & 0 deletions book/.vitepress/config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ export default defineConfig({
anchor: { slugify: (text) => slugid(text.trim()) },
config: (md) => {
md.use(mermaidMarkdown);
md.use(seo.markdown);
const linkOpen = md.renderer.rules.link_open;
md.renderer.rules.link_open = (tokens, index, options, env, self) => {
const token = tokens[index];
Expand Down Expand Up @@ -209,6 +210,7 @@ export default defineConfig({
transformItems: seo.sitemapItems
},

transformPageData: seo.transformPageData,
transformHead: seo.transformHead,

// Shared files (preview cards, chapter samples) keep their plain URLs under
Expand Down
95 changes: 77 additions & 18 deletions book/.vitepress/seo.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,16 @@
// the chapter itself, canonical and hreflang links, and Open Graph and Twitter
// card tags. The sitemap is VitePress's own; `sitemapItems` only adds the
// x-default alternate and keeps the language picker out of the locale groups.
//
// The description lives in the page's frontmatter, filled while the Markdown
// renders, because the VitePress client rewrites <meta name="description"> to
// the frontmatter description (or the site's) as soon as the page hydrates.

import fs from 'node:fs';
import path from 'node:path';

import * as cheerio from 'cheerio';
import { createMarkdownRenderer } from 'vitepress';

const DESCRIPTION_LENGTH = 160;

Expand All @@ -17,7 +25,8 @@ const OG_LOCALES = { ru: 'ru_RU', en: 'en_US', es: 'es_ES' };
* @typedef {object} SeoOptions
* @property {string} baseUrl public URL of the site root, ending in "/"
* @property {string} siteName
* @property {string} siteDescription stands in on the language picker
* @property {string} siteDescription stands in when a page and its locale's
* home page have no prose to describe them
* @property {string[]} locales
* @property {string} defaultLocale the x-default and the picker's language
* @property {string} image preview card path under baseUrl; "{locale}" is replaced
Expand Down Expand Up @@ -48,13 +57,13 @@ export function truncate(text) {
* problem). Other pages use their first paragraph, skipping an all-italic note
* such as a tool chapter's "checked on" line.
*
* @param {string} html the page's rendered content
* @param {string} html the page's rendered Markdown
* @param {string[]} sections heading ids, most preferred first
* @returns {string}
*/
export function describe(html, sections) {
const $ = cheerio.load(html);
const content = $('.vp-doc > div').first();
const $ = cheerio.load(html, null, false);
const content = $.root();

/** @param {import('cheerio').Cheerio<any>} paragraphs */
const firstProse = (paragraphs) =>
Expand Down Expand Up @@ -125,8 +134,56 @@ export function createSeo(options) {
Object.entries(tags).map(([name, content]) => ['meta', { [key]: name, content }]);

return {
/**
* markdown-it plugin: describe each page from its rendered content, unless
* its frontmatter already has a description.
*
* @param {import('vitepress').MarkdownRenderer} md
*/
markdown(md) {
const render = md.renderer.render.bind(md.renderer);
md.renderer.render = (tokens, markdownOptions, env) => {
const html = render(tokens, markdownOptions, env);
env.frontmatter ??= {};
if (!env.frontmatter.description) {
const description = describe(html, options.descriptionSections);
if (description) {
env.frontmatter.description = description;
}
}
return html;
};
},

/**
* A locale page with no prose of its own (the table of contents) takes the
* description of the locale's home page.
*
* @type {NonNullable<import('vitepress').UserConfig['transformPageData']>}
*/
async transformPageData(pageData, { siteConfig }) {
const [locale] = pageData.relativePath.split('/');
const home = `${locale}/index.md`;
if (pageData.description || !locales.includes(locale) || pageData.relativePath === home) {
return;
}
const source = siteConfig.rewrites.inv[home] || home;
const file = path.join(siteConfig.srcDir, source);
const md = await createMarkdownRenderer(
siteConfig.srcDir,
siteConfig.markdown,
siteConfig.site.base,
siteConfig.logger
);
/** @type {import('vitepress').MarkdownEnv} */
const env = { path: file, relativePath: home, cleanUrls: siteConfig.cleanUrls };
await md.renderAsync(fs.readFileSync(file, 'utf8'), env);
const description = env.frontmatter?.description;
return description ? { description } : undefined;
},

/** @type {(context: import('vitepress').TransformContext) => import('vitepress').HeadConfig[]} */
transformHead({ page, siteConfig, pageData, content }) {
transformHead({ page, siteConfig, pageData }) {
if (page === '404.md') {
return [];
}
Expand All @@ -138,9 +195,7 @@ export function createSeo(options) {
const alternates = alternatesFor(siteConfig).get(slug) || [];
const url = baseUrl + pathFor(page);
const title = isPicker ? options.siteName : pageData.title;
const description =
describe(content, options.descriptionSections) ||
(isPicker ? truncate(options.siteDescription) : '');
const description = pageData.description || truncate(options.siteDescription);
const image = baseUrl + options.image.replace('{locale}', locale);

/** @type {import('vitepress').HeadConfig[]} */
Expand All @@ -162,28 +217,32 @@ export function createSeo(options) {
'og:site_name': options.siteName,
'og:title': title,
'og:url': url,
'og:locale': OG_LOCALES[locale] || locale
'og:locale': OG_LOCALES[locale] || locale,
'og:description': description,
'og:image': image,
'og:image:alt': options.siteName,
'og:image:width': String(options.imageWidth),
'og:image:height': String(options.imageHeight)
};
if (description) {
og['og:description'] = description;
}
og['og:image'] = image;
og['og:image:alt'] = options.siteName;
og['og:image:width'] = String(options.imageWidth);
og['og:image:height'] = String(options.imageHeight);

return [
// Replaces the site-wide description VitePress would otherwise emit.
// Replaces the tag VitePress emits, which falls back to the site description.
['meta', { name: 'description', content: description }],
...links,
...meta(og, 'property'),
// VitePress keeps one meta per key (its id, else its first attribute
// besides content), so repeated og:locale:alternate tags each need an id.
...alternates
.filter((alternate) => alternate !== locale)
.map(
(alternate) =>
/** @type {import('vitepress').HeadConfig} */ ([
'meta',
{ property: 'og:locale:alternate', content: OG_LOCALES[alternate] || alternate }
{
id: `og-locale-alternate-${alternate}`,
property: 'og:locale:alternate',
content: OG_LOCALES[alternate] || alternate
}
])
),
...meta({ 'twitter:card': 'summary_large_image' }, 'name')
Expand Down
139 changes: 99 additions & 40 deletions tests/seo.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,54 @@ import { test } from 'node:test';

import { createSeo, describe, truncate } from '../book/.vitepress/seo.mjs';

/** @param {string} body */
const page = (body) => `<div class="VPDoc"><div class="vp-doc _x"><div>${body}</div></div></div>`;
const newSeo = () =>
createSeo({
baseUrl: 'https://example.org/book/',
siteName: 'Book',
siteDescription: 'About the book',
locales: ['ru', 'en', 'es'],
defaultLocale: 'en',
image: 'assets/og/{locale}.png',
imageWidth: 1200,
imageHeight: 630,
descriptionSections: ['назначение']
});

/**
* @param {string} page
* @param {string[]} pages
* @param {Record<string, unknown>} pageData
*/
const headFor = (page, pages, pageData) =>
// The page list is read once per instance, so each case gets its own.
newSeo().transformHead(
/** @type {any} */ ({
page,
siteConfig: { pages, rewrites: { map: { 'ru/README.md': 'ru/index.md' } } },
pageData: { title: 'T', ...pageData }
})
);

/**
* @param {import('vitepress').HeadConfig[]} head
* @param {Record<string, string>} attributes
*/
const find = (head, attributes) =>
head.find(([, attrs]) =>
Object.entries(attributes).every(([key, value]) => attrs[key] === value)
)?.[1];

test('the description is the first paragraph of the preferred section', () => {
const html = page(
const html =
'<h1 id="t">Title</h1><p>Lead.</p>' +
'<h2 id="problem">Problem</h2><p>The problem.</p>' +
'<h2 id="intent">Intent</h2><p><em>A note.</em></p><p>The intent.</p>'
);
'<h2 id="problem">Problem</h2><p>The problem.</p>' +
'<h2 id="intent">Intent</h2><p><em>A note.</em></p><p>The intent.</p>';
assert.equal(describe(html, ['intent', 'problem']), 'The intent.');
assert.equal(describe(html, ['propósito', 'problem']), 'The problem.');
});

test('without a listed section the description skips an all-italic note', () => {
const html = page('<h1 id="t">Tool</h1><p><em>Checked on 2026-11-01.</em></p><p>What it is.</p>');
const html = '<h1 id="t">Tool</h1><p><em>Checked on 2026-11-01.</em></p><p>What it is.</p>';
assert.equal(describe(html, ['intent']), 'What it is.');
});

Expand All @@ -28,42 +61,68 @@ test('a long description is cut on a word boundary', () => {
assert.match(result, /word…$/);
});

test('head tags carry canonical, hreflang and x-default links', () => {
const seo = createSeo({
baseUrl: 'https://example.org/book/',
siteName: 'Book',
siteDescription: 'About the book',
locales: ['ru', 'en', 'es'],
defaultLocale: 'en',
image: 'assets/og/{locale}.png',
imageWidth: 1200,
imageHeight: 630,
descriptionSections: ['назначение']
});
const siteConfig = /** @type {any} */ ({
pages: ['ru/grilling.md', 'en/grilling.md', 'ru/README.md'],
rewrites: { map: { 'ru/README.md': 'ru/index.md' } }
test('the markdown plugin puts the description into the frontmatter', () => {
const html = '<h1 id="г">Гриллинг</h1><h2 id="назначение">Назначение</h2><p>Суть.</p>';
const md = /** @type {any} */ ({ renderer: { render: () => html } });
newSeo().markdown(md);

/** @type {Record<string, any>} */
const env = {};
assert.equal(md.renderer.render([], {}, env), html);
assert.equal(env.frontmatter.description, 'Суть.');

const written = { frontmatter: { description: 'Written by hand.' } };
md.renderer.render([], {}, written);
assert.equal(written.frontmatter.description, 'Written by hand.');
});

test('head tags carry the description, canonical, hreflang and x-default links', () => {
const head = headFor('ru/grilling.md', ['ru/grilling.md', 'en/grilling.md', 'ru/README.md'], {
description: 'Суть.'
});
const head = seo.transformHead(
/** @type {any} */ ({
page: 'ru/grilling.md',
siteConfig,
pageData: { title: 'Гриллинг' },
content: page('<h1 id="г">Гриллинг</h1><h2 id="назначение">Назначение</h2><p>Суть.</p>')
})
);
const find = (/** @type {Record<string, string>} */ attributes) =>
head.find(([, attrs]) =>
Object.entries(attributes).every(([key, value]) => attrs[key] === value)
)?.[1];

assert.equal(find({ name: 'description' })?.content, 'Суть.');
assert.equal(find({ rel: 'canonical' })?.href, 'https://example.org/book/ru/grilling.html');
assert.equal(find({ hreflang: 'en' })?.href, 'https://example.org/book/en/grilling.html');
assert.equal(find({ hreflang: 'x-default' })?.href, 'https://example.org/book/en/grilling.html');
assert.equal(find({ hreflang: 'es' }), undefined);
assert.equal(find(head, { name: 'description' })?.content, 'Суть.');
assert.equal(find(head, { property: 'og:description' })?.content, 'Суть.');
assert.equal(find(head, { rel: 'canonical' })?.href, 'https://example.org/book/ru/grilling.html');
assert.equal(find(head, { hreflang: 'en' })?.href, 'https://example.org/book/en/grilling.html');
assert.equal(
find({ property: 'og:image' })?.content,
find(head, { hreflang: 'x-default' })?.href,
'https://example.org/book/en/grilling.html'
);
assert.equal(find(head, { hreflang: 'es' }), undefined);
assert.equal(
find(head, { property: 'og:image' })?.content,
'https://example.org/book/assets/og/ru.png'
);
});

test('a page with no description falls back to the site description', () => {
const head = headFor('ru/SUMMARY.md', ['ru/SUMMARY.md'], { description: '' });
assert.equal(find(head, { name: 'description' })?.content, 'About the book');
});

// VitePress's mergeHead keeps one meta per key: its id, else its first
// attribute other than content.
/** @param {import('vitepress').HeadConfig} tag */
const headKey = ([type, attrs]) => {
if (attrs.id) {
return `id=${attrs.id}`;
}
if (type === 'meta') {
const name = Object.keys(attrs).find((key) => key !== 'content');
return name && `${name}=${attrs[name]}`;
}
return undefined;
};

test('every locale alternate survives VitePress head deduplication', () => {
const head = headFor('ru/grilling.md', ['ru/grilling.md', 'en/grilling.md', 'es/grilling.md'], {
description: 'Суть.'
});
const keys = head.map(headKey).filter(Boolean);
assert.deepEqual(keys, [...new Set(keys)]);
const alternates = head
.filter(([, attrs]) => attrs.property === 'og:locale:alternate')
.map(([, attrs]) => attrs.content);
assert.deepEqual(alternates, ['en_US', 'es_ES']);
});