diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index ddcf85f..5becde7 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -26,8 +26,6 @@ jobs: version: 2026.11.8 install_args: --locked - run: pnpm install --frozen-lockfile - # Mermaid diagrams are rendered at build time in headless Chromium. - - run: pnpm exec playwright install --with-deps chromium - run: mise run build - if: github.event_name != 'pull_request' uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0 diff --git a/.gitignore b/.gitignore index 424073a..95ddd81 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ npm-cache/ node_modules/ dist/ +book/.vitepress/cache/ *.pdf *.epub .DS_Store diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 563016f..2832e22 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -6,6 +6,7 @@ ".agents/skills/**", ".claude/skills/**", "dist/**", + "book/.vitepress/cache/**", "pnpm-lock.yaml", "skills-lock.json" ] diff --git a/.syncpackrc.json b/.syncpackrc.json index 273f1bd..2659c08 100644 --- a/.syncpackrc.json +++ b/.syncpackrc.json @@ -1,6 +1,6 @@ { "$schema": "https://syncpack.dev/schema.json", - "source": ["package.json", "plugins/*/package.json"], + "source": ["package.json"], "semverGroups": [ { "dependencies": ["**"], diff --git a/AGENTS.md b/AGENTS.md index 0c6b3a7..36437bc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,21 +11,20 @@ Operating guide for agents (and humans) working in this repository. ## Diagrams - Diagrams are written as ```` ```mermaid ```` fences directly in the chapter, so the labels are translated together with the prose and GitHub renders them in the repo. -- `plugins/honkit-plugin-mermaid` renders the fences into inline SVG at build time (Mermaid in headless Playwright), so diagrams also survive `honkit pdf`, which never runs JS. +- [vitepress-mermaid](https://github.com/mokevnin/vitepress-mermaid) turns the fences into a `` component that draws the diagram in the reader's browser and redraws it when dark mode is toggled. Rendering happens in the browser, so `mise run build` does not catch a Mermaid syntax error: open the page after editing a diagram and look for red source text (a `data-mermaid-error` element). - Shared palette and theme live in `mermaid.config.json`. Use the `accent`, `warn` and `muted` classes (`node:::accent`) instead of per-diagram `classDef`. -- The website also gets every diagram in a dark palette for the Honkit night theme: `mermaid.config.dark.json` holds only the keys that differ and is merged over `mermaid.config.json`. A new color or class in the light config needs its dark counterpart there, including the `accent`/`warn`/`muted` rules in `themeCSS`. The PDF gets the light palette only. -- Rendered SVGs are cached in `node_modules/.cache/honkit-mermaid`, keyed by diagram source plus theme config. The theme is read once at startup, so restart `mise run serve` after editing `mermaid.config.json` or `mermaid.config.dark.json`. +- Dark mode uses a dark palette: `mermaid.config.dark.json` holds only the keys that differ and is merged over `mermaid.config.json` in `book/.vitepress/theme/mermaid-palette.mjs`. A new color or class in the light config needs its dark counterpart there, including the `accent`/`warn`/`muted` rules in `themeCSS`. `fontFamily` is ignored: diagrams use the page font. - Beyond `flowchart`, the types that survive this pipeline and the palette are `sequenceDiagram`, `stateDiagram-v2`, `gitGraph`, `quadrantChart`, `pie` and `sankey-beta`. - `sankey-beta` accepts **ASCII only in node names** (Mermaid 12.0.0) — quoting does not help, and Cyrillic or even Spanish accents raise a parse error. Its `title:` and `%%` comments do take non-ASCII. Where it is used, node labels stay English with a `%% TODO` to localize them once upstream is fixed. - Types that silently drop the frontmatter `title:` the book uses as a caption: `sankey-beta`, `mindmap`, `timeline`, `kanban`, `block-beta`, `architecture-beta`. Put the thesis in the paragraph under the diagram instead. `treemap-beta` scales label size with box area, so the smallest — usually most important — share is the least readable. -- A diagram is read inside a ~770px column. Keep it under ~1200px wide — prefer `flowchart TB` over a long left-to-right chain, and remember that a note hung off a node with `-.-` widens the diagram. +- A diagram is read inside a ~690px column. Keep it under ~1200px wide — prefer `flowchart TB` over a long left-to-right chain, and remember that a note hung off a node with `-.-` widens the diagram. ## SEO and link previews -- `plugins/honkit-plugin-seo` post-processes the website build: it fills `meta description` from the chapter text, adds canonical, `hreflang` and Open Graph/Twitter tags, and writes `sitemap.xml`. PDFs are untouched. -- The public URL and preview image live in `pluginsConfig.seo` in `book/book.json`; change `baseUrl` there when the site moves to its own domain. +- `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. +- 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/.png`, rendered from `plugins/honkit-plugin-seo/og-card.html`; the command to rerender one is at the top of that file. +- Preview cards are `book/assets/og/.png`, rendered from `book/.vitepress/og-card.html`; the command to rerender one is at the top of that file. ## Markdown formatting @@ -57,11 +56,10 @@ Operating guide for agents (and humans) working in this repository. - Use mise 2026.11.3 or newer; CI pins 2026.11.8. Commit `mise.lock` alongside tool updates; it covers Linux x64 and macOS arm64. - `mise run setup` — install locked deps, pinned linters and git hooks -- `mise run serve` — local preview (Honkit serve) -- `mise run build` — static build into `./dist` -- `pnpm exec playwright install chromium` — one-off, needed to render diagrams -- `mise run pdf` — PDFs for all locales -- `mise run update` — bump project tools and dependencies in every workspace package; when hk changes, also update both versioned Pkl imports in `hk.pkl` +- `mise run serve` — local preview with hot reload (VitePress dev server) +- `mise run build` — static build into `./dist`; VitePress fails it on a dead link between pages +- `mise run preview` — serve the `./dist` build locally +- `mise run update` — bump project tools and dependencies; when hk changes, also update both versioned Pkl imports in `hk.pkl` ## Structure conventions diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d4135a9..92f339e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing -The book is built from markdown with [Honkit](https://github.com/honkit/honkit). Navigation and grouping come from `book//SUMMARY.md` — a separate file per language. +The book is built from Markdown with [VitePress](https://vitepress.dev/). Navigation and grouping come from `book//SUMMARY.md` — a separate file per language; the site config turns it into the sidebar. ## Add a new pattern @@ -8,9 +8,9 @@ The book is built from markdown with [Honkit](https://github.com/honkit/honkit). 1. Pick a kebab-case `slug` (e.g. `chain-of-thought`). It becomes the file name in every locale and the key under `book/assets/`. 2. Create the chapter in the canonical locale: copy [`templates/ru/pattern.md`](templates/ru/pattern.md) to `book/ru/.md` and fill it in. Do not change the section headings — they are the same across all chapters of that language. 3. Add a link in `book/ru/SUMMARY.md` under the right group heading (line order = order in the book). -4. Draw diagrams as ```` ```mermaid ```` fences right in the chapter — they are rendered to SVG at build time and translated together with the surrounding text. Use the shared `accent` / `warn` / `muted` classes (`node:::accent`) so every diagram in the book shares one palette; the theme lives in `mermaid.config.json`, and its night-theme counterpart in `mermaid.config.dark.json`. +4. Draw diagrams as ```` ```mermaid ```` fences right in the chapter — they are drawn in the reader's browser by [vitepress-mermaid](https://github.com/mokevnin/vitepress-mermaid) and translated together with the surrounding text. The build does not catch a syntax error, so check the page in `mise run serve`. Use the shared `accent` / `warn` / `muted` classes (`node:::accent`) so every diagram in the book shares one palette; the theme lives in `mermaid.config.json`, and its dark-mode counterpart in `mermaid.config.dark.json`. 5. Anything that is genuinely a file — images, sample code — goes in `book/assets//` and is referenced with a relative path `../assets//...`. -6. Preview with `pnpm start`. +6. Preview with `mise run serve`. ## Extend an existing pattern @@ -29,7 +29,7 @@ Recheck a tool profile against the tool's primary documentation before each book ## Chapter front matter (optional but useful) -Honkit takes the title from the first `#` and navigation from `SUMMARY.md`. A small front matter is handy as metadata and reads well on GitHub: +VitePress takes the title from the first `#` and navigation from `SUMMARY.md`. A small front matter is handy as metadata and reads well on GitHub. Avoid keys VitePress reserves (`title`, `description`, `layout`, `outline`, `sidebar` and the like) unless you mean to override the page: ```yaml --- @@ -42,7 +42,7 @@ source_rev: # for NON-canonical locales only (see below) ## Translation -- The canonical locale is `ru` (`language` in `book/book.json`). A pattern is written in Russian first. +- The canonical locale is `ru`. A pattern is written in Russian first. - To translate, copy `book/ru/.md` to `book//.md`, translate the text, and add a link to `book//SUMMARY.md` in the same group. Use the matching template under `templates//` for the localized headings. - In the translation's front matter set `source_rev` — the git SHA of the ru chapter at the time of translating, so staleness can be tracked: diff --git a/README.md b/README.md index 615fd77..432bcf7 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,6 @@ # Agentic Coding Design Patterns -A catalog of patterns in the spirit of the "Gang of Four" (GoF) about **how a -developer works with an AI agent when writing code**. It is a book built from -markdown with [Honkit](https://github.com/honkit/honkit) (a GitBook fork), with -print (PDF/EPUB) in mind. +A catalog of patterns in the spirit of the "Gang of Four" (GoF) about **how a developer works with an AI agent when writing code**. It is a book written in Markdown and published as a website with [VitePress](https://vitepress.dev/). 📖 **Online:** @@ -12,11 +9,11 @@ print (PDF/EPUB) in mind. ## Repository layout ```text -book/ — the book root (Honkit) - book.json — Honkit config - LANGS.md — list of languages (Honkit multilingual) +book/ — the book root (VitePress source directory) + .vitepress/ — site config: locales, sidebar, SEO, theme and Mermaid palette + README.md — language picker at the site root / - SUMMARY.md — table of contents: groups = headings, patterns = links + SUMMARY.md — table of contents: groups = headings, patterns = links; builds the sidebar README.md — locale landing page .md — a chapter (flat list, no group folders) assets// — diagrams and code samples shared across languages @@ -36,17 +33,17 @@ same across all locales. ## Development ```sh -mise run setup # locked toolchain, workspace dependencies and git hooks -mise run serve # local preview (honkit serve) +mise run setup # locked toolchain, dependencies and git hooks +mise run serve # local preview with hot reload (VitePress dev server) mise run check # the same quality gates as CI mise run build # static build into ./dist -mise run pdf # PDFs for all locales (requires Calibre/ebook-convert) -mise run update # update project tools and all workspace dependencies +mise run preview # serve the ./dist build locally +mise run update # update project tools and dependencies ``` Use [mise](https://mise.jdx.dev/) 2026.11.3 or newer; CI pins 2026.11.4. Node is pinned in `mise.toml`; mise reads pnpm from `package.json`. `mise.lock` records tool downloads and checksums for Linux x64 and macOS arm64. Both setup and CI install from the committed lockfiles. After updating hk, update the two versioned Pkl imports in `hk.pkl` as well. -The [Dev Quality Gates](https://github.com/mokevnin/dev-quality-gates) checks run through `hk.pkl`: code lint and formatting, workspace dependency consistency, Markdown, spelling, agent configuration, workflow security, secrets, local documentation links, conflict markers, filename case collisions and broken symlinks. Local links are checked offline so commits do not depend on external websites. Known dependency vulnerabilities are checked by the scheduled audit workflow. +The [Dev Quality Gates](https://github.com/mokevnin/dev-quality-gates) checks run through `hk.pkl`: code lint and formatting, unit tests for the site config, dependency range consistency, Markdown, spelling, agent configuration, workflow security, secrets, local documentation links, conflict markers, filename case collisions and broken symlinks. Local links are checked offline so commits do not depend on external websites. Known dependency vulnerabilities are checked by the scheduled audit workflow. - How to add a pattern and how translations work — see [CONTRIBUTING.md](CONTRIBUTING.md). - The canonical locale is `ru`: a pattern is first written in Russian, then diff --git a/book/.vitepress/config.mjs b/book/.vitepress/config.mjs new file mode 100644 index 0000000..2843e69 --- /dev/null +++ b/book/.vitepress/config.mjs @@ -0,0 +1,221 @@ +// @ts-check + +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import slugid from 'github-slugid'; +import { mermaidMarkdown } from '@mokevnin/vitepress-mermaid/markdown'; +import { defineConfig } from 'vitepress'; + +import { createSeo } from './seo.mjs'; +import { readSummary } from './summary.mjs'; + +const repoRoot = fileURLToPath(new URL('../..', import.meta.url)); +const bookRoot = path.join(repoRoot, 'book'); + +const SITE_NAME = 'Agentic Design Patterns'; +const SITE_DESCRIPTION = + 'Design patterns for coding with AI agents, in the spirit of the Gang of Four'; +const REPO_URL = 'https://github.com/mokevnin/agentic-coding-design-patterns'; +// The public URL. Change it (and `base`) when the site moves to its own domain. +const BASE_URL = 'https://mokevnin.github.io/agentic-coding-design-patterns/'; + +const seo = createSeo({ + baseUrl: BASE_URL, + siteName: SITE_NAME, + siteDescription: SITE_DESCRIPTION, + locales: ['ru', 'en', 'es'], + defaultLocale: 'en', + image: 'assets/og/{locale}.png', + imageWidth: 1200, + imageHeight: 630, + // Heading ids of the section whose first paragraph becomes the description: + // a pattern's intent, then an anti-pattern's problem, in every locale. + descriptionSections: ['назначение', 'intent', 'propósito', 'проблема', 'problem', 'problema'] +}); + +/** + * Settings shared by every locale, plus the strings each one translates. + * + * @param {string} locale + * @param {Partial} strings + * @returns {import('vitepress').DefaultTheme.Config} + */ +function themeFor(locale, strings) { + return { + sidebar: readSummary(path.join(bookRoot, locale, 'SUMMARY.md'), locale), + ...strings + }; +} + +export default defineConfig({ + title: SITE_NAME, + description: SITE_DESCRIPTION, + lang: 'en', + base: '/agentic-coding-design-patterns/', + outDir: '../dist', + // Keep the .html URLs the book has always had. + cleanUrls: false, + // README.md is the home page of the book and of each locale, as on GitHub. + rewrites: { + 'README.md': 'index.md', + ':locale/README.md': ':locale/index.md' + }, + // SUMMARY.md also builds the sidebar; as a page it is the table of contents + // the locale home pages link to. + srcExclude: ['dist/**'], + + // No root locale: the site root is the language picker, outside all three. + locales: { + ru: { + label: 'Русский', + lang: 'ru', + themeConfig: themeFor('ru', { + outline: { level: [2, 3], label: 'На этой странице' }, + docFooter: { prev: 'Назад', next: 'Далее' }, + darkModeSwitchLabel: 'Оформление', + lightModeSwitchTitle: 'Светлая тема', + darkModeSwitchTitle: 'Тёмная тема', + sidebarMenuLabel: 'Меню', + returnToTopLabel: 'Наверх', + langMenuLabel: 'Язык', + skipToContentLabel: 'Перейти к содержимому', + notFound: { + title: 'Страница не найдена', + quote: 'Такой страницы в книге нет.', + linkLabel: 'на главную', + linkText: 'На главную' + } + }) + }, + en: { + label: 'English', + lang: 'en', + themeConfig: themeFor('en', { outline: { level: [2, 3] } }) + }, + es: { + label: 'Español', + lang: 'es', + themeConfig: themeFor('es', { + outline: { level: [2, 3], label: 'En esta página' }, + docFooter: { prev: 'Anterior', next: 'Siguiente' }, + darkModeSwitchLabel: 'Apariencia', + lightModeSwitchTitle: 'Team claro', + darkModeSwitchTitle: 'Team oscuro', + sidebarMenuLabel: 'Menú', + returnToTopLabel: 'Volver arriba', + langMenuLabel: 'Idioma', + skipToContentLabel: 'Saltar al contenido', + notFound: { + title: 'Página no encontrada', + quote: 'Esta página no existe en el libro.', + linkLabel: 'ir al inicio', + linkText: 'Ir al inicio' + } + }) + } + }, + + themeConfig: { + nav: [ + { + text: 'Telegram', + items: [ + { text: 'Hexlet AI Club', link: 'https://t.me/hexletclub' }, + { text: 'Organized Programming', link: 'https://t.me/orgprog' } + ] + } + ], + socialLinks: [ + { icon: 'github', link: REPO_URL, ariaLabel: 'GitHub' }, + { + icon: 'youtube', + link: 'https://www.youtube.com/@mokevnin', + ariaLabel: 'Organized Programming (YouTube)' + } + ], + search: { + provider: 'local', + options: { + locales: { + ru: { + translations: { + button: { buttonText: 'Поиск', buttonAriaLabel: 'Поиск' }, + modal: { + displayDetails: 'Подробный список', + resetButtonTitle: 'Сбросить поиск', + backButtonTitle: 'Закрыть поиск', + noResultsText: 'Ничего не найдено', + footer: { + selectText: 'выбрать', + navigateText: 'перейти', + closeText: 'закрыть' + } + } + } + }, + es: { + translations: { + button: { buttonText: 'Buscar', buttonAriaLabel: 'Buscar' }, + modal: { + displayDetails: 'Lista detallada', + resetButtonTitle: 'Restablecer búsqueda', + backButtonTitle: 'Cerrar búsqueda', + noResultsText: 'Sin resultados', + footer: { + selectText: 'seleccionar', + navigateText: 'navegar', + closeText: 'cerrar' + } + } + } + } + } + } + } + }, + + markdown: { + // Honkit's heading ids, so links into a section keep working. The default + // slugify strips accents and й/ё, which breaks ru and es anchors. + anchor: { slugify: (text) => slugid(text.trim()) }, + config: (md) => { + md.use(mermaidMarkdown); + const linkOpen = md.renderer.rules.link_open; + md.renderer.rules.link_open = (tokens, index, options, env, self) => { + const token = tokens[index]; + const href = token.attrGet('href'); + if (href && !/^[a-z]+:/i.test(href)) { + // Rewrites move README.md to index.md but leave links alone, so + // point links at README.md to the folder before VitePress resolves them. + token.attrSet('href', href.replace(/(^|\/)README\.md(?=#|$)/, '$1./')); + // A shared file under book/assets/ (copied in buildEnd) is not a page: + // a target keeps VitePress from adding .html and the router from + // taking the click. lychee in `mise run check` verifies the file. + if (/(^|\/)assets\//.test(href) && !token.attrGet('target')) { + token.attrSet('target', '_self'); + } + } + return linkOpen + ? linkOpen(tokens, index, options, env, self) + : self.renderToken(tokens, index, options); + }; + } + }, + + sitemap: { + hostname: BASE_URL, + transformItems: seo.sitemapItems + }, + + transformHead: seo.transformHead, + + // Shared files (preview cards, chapter samples) keep their plain URLs under + // assets/, next to the hashed bundles VitePress writes there. + buildEnd(siteConfig) { + fs.cpSync(path.join(bookRoot, 'assets'), path.join(siteConfig.outDir, 'assets'), { + recursive: true + }); + } +}); diff --git a/plugins/honkit-plugin-seo/og-card.html b/book/.vitepress/og-card.html similarity index 91% rename from plugins/honkit-plugin-seo/og-card.html rename to book/.vitepress/og-card.html index 85d27e6..2b203d4 100644 --- a/plugins/honkit-plugin-seo/og-card.html +++ b/book/.vitepress/og-card.html @@ -5,7 +5,7 @@ so localized copy stays in the locale folders. Rerender a card from the repo root, URL-encoding the sentence (it may hold quotes): lead=$(node -e 'console.log(encodeURIComponent(process.argv[1]))' "") - pnpm exec playwright screenshot --viewport-size=1200,630 "file://$PWD/plugins/honkit-plugin-seo/og-card.html?lead=$lead" book/assets/og/.png + pnpm dlx playwright@1.65.1 screenshot --viewport-size=1200,630 "file://$PWD/book/.vitepress/og-card.html?lead=$lead" book/assets/og/.png --> diff --git a/book/.vitepress/seo.mjs b/book/.vitepress/seo.mjs new file mode 100644 index 0000000..a34edce --- /dev/null +++ b/book/.vitepress/seo.mjs @@ -0,0 +1,217 @@ +// @ts-check + +// Search and link-preview metadata for every page: a description taken from +// 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. + +import * as cheerio from 'cheerio'; + +const DESCRIPTION_LENGTH = 160; + +// og:locale wants language_TERRITORY; hreflang takes the bare language. +/** @type {Record} */ +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[]} locales + * @property {string} defaultLocale the x-default and the picker's language + * @property {string} image preview card path under baseUrl; "{locale}" is replaced + * @property {number} imageWidth + * @property {number} imageHeight + * @property {string[]} descriptionSections heading ids, most preferred first + */ + +/** + * Cut text to the description length on a word boundary. + * + * @param {string} text + * @returns {string} + */ +export function truncate(text) { + const clean = text.replace(/\s+/g, ' ').trim(); + if (clean.length <= DESCRIPTION_LENGTH) { + return clean; + } + const cut = clean.slice(0, DESCRIPTION_LENGTH - 1); + const boundary = cut.lastIndexOf(' '); + return `${(boundary > 0 ? cut.slice(0, boundary) : cut).replace(/[\s,;:.—–-]+$/, '')}…`; +} + +/** + * The description of a rendered page: the first paragraph of the first section + * listed in `sections` that the page has (a pattern's intent, an anti-pattern's + * 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[]} sections heading ids, most preferred first + * @returns {string} + */ +export function describe(html, sections) { + const $ = cheerio.load(html); + const content = $('.vp-doc > div').first(); + + /** @param {import('cheerio').Cheerio} paragraphs */ + const firstProse = (paragraphs) => + paragraphs + .toArray() + .filter((element) => { + const node = $(element); + const onlyItalic = + node.children('em').length === 1 && node.children('em').text() === node.text(); + return node.text().trim() !== '' && !onlyItalic; + }) + .map((element) => $(element).text())[0]; + + const heading = sections + .map((id) => content.children(`h2[id="${id}"]`)) + .find((match) => match.length > 0); + const paragraph = heading + ? firstProse(heading.first().nextUntil('h2', 'p')) + : firstProse(content.children('p')); + return truncate(paragraph || ''); +} + +/** + * Public path of a page source, relative to the site root. + * + * @param {string} page e.g. "ru/grilling.md" or "ru/index.md" + * @returns {string} + */ +function pathFor(page) { + return page.replace(/(^|\/)index\.md$/, '$1').replace(/\.md$/, '.html'); +} + +/** + * @param {SeoOptions} options + */ +export function createSeo(options) { + const { baseUrl, locales, defaultLocale } = options; + + /** @type {Map | null} */ + let alternatesBySlug = null; + + /** + * Slug (path inside a locale) -> locales that have it. + * + * @param {import('vitepress').SiteConfig} siteConfig + */ + const alternatesFor = (siteConfig) => { + if (alternatesBySlug === null) { + alternatesBySlug = new Map(); + for (const source of siteConfig.pages) { + const page = siteConfig.rewrites.map[source] || source; + const [locale, ...rest] = page.split('/'); + if (locales.includes(locale)) { + const slug = rest.join('/'); + alternatesBySlug.set(slug, [...(alternatesBySlug.get(slug) || []), locale]); + } + } + } + return alternatesBySlug; + }; + + /** + * @param {Record} tags + * @param {'name' | 'property'} key + * @returns {import('vitepress').HeadConfig[]} + */ + const meta = (tags, key) => + Object.entries(tags).map(([name, content]) => ['meta', { [key]: name, content }]); + + return { + /** @type {(context: import('vitepress').TransformContext) => import('vitepress').HeadConfig[]} */ + transformHead({ page, siteConfig, pageData, content }) { + if (page === '404.md') { + return []; + } + const [first, ...rest] = page.split('/'); + const isPicker = !locales.includes(first); + const locale = isPicker ? defaultLocale : first; + const slug = isPicker ? 'index.md' : rest.join('/'); + const isHome = slug === 'index.md'; + 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 image = baseUrl + options.image.replace('{locale}', locale); + + /** @type {import('vitepress').HeadConfig[]} */ + const links = [['link', { rel: 'canonical', href: url }]]; + for (const alternate of alternates) { + links.push([ + 'link', + { rel: 'alternate', hreflang: alternate, href: baseUrl + pathFor(`${alternate}/${slug}`) } + ]); + } + if (alternates.includes(defaultLocale)) { + const href = isHome ? baseUrl : baseUrl + pathFor(`${defaultLocale}/${slug}`); + links.push(['link', { rel: 'alternate', hreflang: 'x-default', href }]); + } + + /** @type {Record} */ + const og = { + 'og:type': isHome ? 'website' : 'article', + 'og:site_name': options.siteName, + 'og:title': title, + 'og:url': url, + 'og:locale': OG_LOCALES[locale] || locale + }; + 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. + ['meta', { name: 'description', content: description }], + ...links, + ...meta(og, 'property'), + ...alternates + .filter((alternate) => alternate !== locale) + .map( + (alternate) => + /** @type {import('vitepress').HeadConfig} */ ([ + 'meta', + { property: 'og:locale:alternate', content: OG_LOCALES[alternate] || alternate } + ]) + ), + ...meta({ 'twitter:card': 'summary_large_image' }, 'name') + ]; + }, + + /** + * VitePress groups pages by their path inside a locale, which lumps the + * language picker (index.md) in with the locale home pages. Give the picker + * no alternates, and point every group's x-default at the default locale, + * or at the picker for the home pages. + * + * @param {import('vitepress').SitemapItem[]} items + * @returns {import('vitepress').SitemapItem[]} + */ + sitemapItems(items) { + return items.map((item) => { + if (item.url === '' || !item.links) { + return { ...item, links: undefined }; + } + const links = item.links.filter((link) => link.url !== ''); + const fallback = links.find((link) => link.lang === defaultLocale); + if (fallback) { + const isHome = fallback.url === `${defaultLocale}/`; + links.push({ lang: 'x-default', url: isHome ? '' : fallback.url }); + } + return { ...item, links }; + }); + } + }; +} diff --git a/book/.vitepress/summary.mjs b/book/.vitepress/summary.mjs new file mode 100644 index 0000000..734ac8a --- /dev/null +++ b/book/.vitepress/summary.mjs @@ -0,0 +1,82 @@ +// @ts-check + +// Builds a locale's sidebar from its SUMMARY.md, so the book's grouping keeps +// living in one Markdown file per language: +// +// * [Title](file.md) a chapter; README.md is the locale's home page +// ## Heading a sidebar group +// ### Heading a group nested in the current `##` group +// +// The `#` title and anything else in the file are ignored. + +import fs from 'node:fs'; + +const LINK = /^\s*[*-]\s+\[([^\]]+)\]\(([^)]+)\)\s*$/; +const HEADING = /^(#{2,3})\s+(.+?)\s*$/; + +/** + * @typedef {{ text: string, link?: string, items?: SidebarItem[] }} SidebarItem + */ + +/** + * @param {string} locale + * @param {string} file chapter path from SUMMARY.md + * @returns {string} + */ +function linkFor(locale, file) { + const page = file.replace(/(^|\/)README\.md$/, '$1').replace(/\.md$/, ''); + return `/${locale}/${page}`; +} + +/** + * @param {string} source SUMMARY.md contents + * @param {string} locale + * @returns {SidebarItem[]} + */ +export function parseSummary(source, locale) { + /** @type {SidebarItem[]} */ + const sidebar = []; + /** @type {SidebarItem | null} */ + let group = null; + /** @type {SidebarItem | null} */ + let subgroup = null; + + for (const line of source.split('\n')) { + const heading = HEADING.exec(line); + if (heading) { + const item = { text: heading[2], items: [] }; + if (heading[1] === '##') { + group = item; + subgroup = null; + sidebar.push(group); + } else { + if (group === null) { + throw new Error(`SUMMARY.md (${locale}): "### ${heading[2]}" comes before any "##"`); + } + subgroup = item; + group.items?.push(subgroup); + } + continue; + } + const link = LINK.exec(line); + if (link) { + const item = { text: link[1], link: linkFor(locale, link[2]) }; + const parent = subgroup ?? group; + if (parent) { + parent.items?.push(item); + } else { + sidebar.push(item); + } + } + } + return sidebar; +} + +/** + * @param {string} file path to a SUMMARY.md + * @param {string} locale + * @returns {SidebarItem[]} + */ +export function readSummary(file, locale) { + return parseSummary(fs.readFileSync(file, 'utf8'), locale); +} diff --git a/book/.vitepress/theme/index.mjs b/book/.vitepress/theme/index.mjs new file mode 100644 index 0000000..bf52d8d --- /dev/null +++ b/book/.vitepress/theme/index.mjs @@ -0,0 +1,17 @@ +// @ts-check + +import { enhanceAppWithMermaid } from '@mokevnin/vitepress-mermaid/client'; +import '@mokevnin/vitepress-mermaid/style.css'; +import DefaultTheme from 'vitepress/theme'; + +import './style.css'; + +import { bookPalette } from './mermaid-palette.mjs'; + +/** @type {import('vitepress').Theme} */ +export default { + extends: DefaultTheme, + enhanceApp({ app }) { + enhanceAppWithMermaid(app, bookPalette()); + } +}; diff --git a/book/.vitepress/theme/mermaid-palette.mjs b/book/.vitepress/theme/mermaid-palette.mjs new file mode 100644 index 0000000..5c6b1b1 --- /dev/null +++ b/book/.vitepress/theme/mermaid-palette.mjs @@ -0,0 +1,56 @@ +// @ts-check + +// The book's Mermaid palette for vitepress-mermaid, which draws diagrams in the +// browser and redraws them when the reader toggles dark mode. +// +// The package takes one config for both modes, and spreads it on every render. +// So the keys that differ between the palettes are getters: each render reads +// the light or the dark value for the mode the page is in at that moment. + +import light from '../../../mermaid.config.json'; +import overrides from '../../../mermaid.config.dark.json'; + +// Sections the dark file overrides only in part; they merge key by key. +const NESTED = ['themeVariables', 'flowchart', 'sequence', 'sankey']; + +/** @typedef {import('mermaid').MermaidConfig} MermaidConfig */ + +/** + * The dark palette: the light config with the dark file merged over it. + * + * @returns {Record} + */ +function darkConfig() { + /** @type {Record} */ + const base = light; + /** @type {Record} */ + const dark = { ...base, ...overrides }; + for (const section of NESTED) { + dark[section] = { + ...base[section], + .../** @type {Record} */ (overrides)[section] + }; + } + return dark; +} + +/** @returns {MermaidConfig} */ +export function bookPalette() { + const dark = darkConfig(); + /** @type {Record} */ + const config = {}; + for (const key of new Set([...Object.keys(light), ...Object.keys(dark)])) { + // The page font, which the package measures labels with, replaces ours. + if (key === 'fontFamily') { + continue; + } + Object.defineProperty(config, key, { + enumerable: true, + get: () => + document.documentElement.classList.contains('dark') + ? dark[key] + : /** @type {Record} */ (light)[key] + }); + } + return config; +} diff --git a/book/.vitepress/theme/style.css b/book/.vitepress/theme/style.css new file mode 100644 index 0000000..77b9d52 --- /dev/null +++ b/book/.vitepress/theme/style.css @@ -0,0 +1,4 @@ +/* Diagrams follow the paragraphs they illustrate with the same rhythm as figures. */ +.vp-doc .mermaid-diagram { + margin: 1.5em 0; +} diff --git a/book/LANGS.md b/book/LANGS.md deleted file mode 100644 index c9df1f7..0000000 --- a/book/LANGS.md +++ /dev/null @@ -1,5 +0,0 @@ -# Languages - -* [English](en/) -* [Русский](ru/) -* [Español](es/) diff --git a/book/book.json b/book/book.json deleted file mode 100644 index 84c06a4..0000000 --- a/book/book.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "title": "Agentic Design Patterns", - "description": "Design patterns for coding with AI agents, in the spirit of the Gang of Four", - "author": "Hexlet", - "language": "en", - "plugins": ["toolbar", "mermaid", "seo"], - "pluginsConfig": { - "seo": { - "baseUrl": "https://mokevnin.github.io/agentic-coding-design-patterns/", - "image": "assets/og/{locale}.png", - "imageWidth": 1200, - "imageHeight": 630, - "descriptionSections": [ - "назначение", - "intent", - "propósito", - "проблема", - "problem", - "problema" - ] - }, - "toolbar": { - "buttons": [ - { - "label": "GitHub", - "icon": "fa fa-github", - "url": "https://github.com/mokevnin/agentic-coding-design-patterns", - "position": "left" - }, - { - "label": "Hexlet AI Club", - "icon": "fa fa-users", - "url": "https://t.me/hexletclub", - "position": "left" - }, - { - "label": "Organized Programming (Telegram)", - "icon": "fa fa-paper-plane", - "url": "https://t.me/orgprog", - "position": "left" - }, - { - "label": "Organized Programming (YouTube)", - "icon": "fa fa-youtube-play", - "url": "https://www.youtube.com/@mokevnin", - "position": "left" - } - ] - } - }, - "structure": { - "readme": "README.md", - "summary": "SUMMARY.md", - "langs": "LANGS.md" - }, - "pdf": { - "pageNumbers": true, - "fontSize": 12, - "paperSize": "a4" - }, - "styles": { - "website": "styles/website.css" - } -} diff --git a/book/en/styles/website.css b/book/en/styles/website.css deleted file mode 100644 index e7d4052..0000000 --- a/book/en/styles/website.css +++ /dev/null @@ -1,11 +0,0 @@ -/* Wide tables run off a phone screen: the theme keeps them at display:table, - where overflow has no effect. Screen only, so print keeps every column. - Drop this once honkit/honkit#532 is released. */ -@media screen { - .markdown-section table { - display: block; - width: max-content; - max-width: 100%; - overflow-x: auto; - } -} diff --git a/book/es/styles/website.css b/book/es/styles/website.css deleted file mode 100644 index e7d4052..0000000 --- a/book/es/styles/website.css +++ /dev/null @@ -1,11 +0,0 @@ -/* Wide tables run off a phone screen: the theme keeps them at display:table, - where overflow has no effect. Screen only, so print keeps every column. - Drop this once honkit/honkit#532 is released. */ -@media screen { - .markdown-section table { - display: block; - width: max-content; - max-width: 100%; - overflow-x: auto; - } -} diff --git a/book/ru/styles/website.css b/book/ru/styles/website.css deleted file mode 100644 index e7d4052..0000000 --- a/book/ru/styles/website.css +++ /dev/null @@ -1,11 +0,0 @@ -/* Wide tables run off a phone screen: the theme keeps them at display:table, - where overflow has no effect. Screen only, so print keeps every column. - Drop this once honkit/honkit#532 is released. */ -@media screen { - .markdown-section table { - display: block; - width: max-content; - max-width: 100%; - overflow-x: auto; - } -} diff --git a/hk.pkl b/hk.pkl index 70c4d80..45dfb85 100644 --- a/hk.pkl +++ b/hk.pkl @@ -12,7 +12,7 @@ local checks = new Mapping { ["oxlint"] = Builtins.ox_lint // Markdown stays with rumdl: book prose uses one physical line per paragraph. ["oxfmt"] = (Builtins.oxfmt) { - glob = List("*.js", "*.json", "*.css", "*.yml", "*.yaml", "*.toml") + glob = List("*.js", "*.mjs", "*.json", "*.css", "*.yml", "*.yaml", "*.toml") exclude = List("pnpm-lock.yaml", "skills-lock.json") } ["syncpack"] { @@ -20,9 +20,10 @@ local checks = new Mapping { check = "syncpack lint" fix = "syncpack fix" } - ["search"] { - glob = List("*.js", "package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", "patches/**") - check = "node --test tests/*.test.js" + // Sidebar and SEO logic of the VitePress config, plus SUMMARY.md links. + ["tests"] { + glob = List("*.mjs", "**/SUMMARY.md", "package.json", "pnpm-lock.yaml") + check = "node --test tests/" } // Check references across the whole book, beyond the files selected by the hook. ["links"] = (Builtins.lychee) { diff --git a/mise.toml b/mise.toml index 9e83938..e51beca 100644 --- a/mise.toml +++ b/mise.toml @@ -33,16 +33,16 @@ run = [ ] [tasks.serve] -description = "Local preview (Honkit serve)" +description = "Local preview with hot reload (VitePress dev server)" run = "pnpm start" [tasks.build] description = "Static build into ./dist" run = "pnpm build" -[tasks.pdf] -description = "PDFs for all locales" -run = ["pnpm pdf:ru", "pnpm pdf:en", "pnpm pdf:es"] +[tasks.preview] +description = "Serve the ./dist build locally" +run = "pnpm preview" [tasks.check] description = "Run every check (hk.pkl); CI runs the same task" diff --git a/package.json b/package.json index 9725719..1c87b74 100644 --- a/package.json +++ b/package.json @@ -5,25 +5,24 @@ "description": "Design patterns for coding with AI agents (ru/en/es), in the spirit of the Gang of Four", "license": "CC-BY-SA-4.0", "scripts": { - "start": "honkit serve ./book", - "build": "honkit build ./book ../dist", - "deps:update": "ncu --deep -u && pnpm update --recursive --latest", - "pdf:ru": "honkit pdf ./book/ru ../../dist/agentic-coding-design-patterns-ru.pdf", - "pdf:en": "honkit pdf ./book/en ../../dist/agentic-coding-design-patterns-en.pdf", - "pdf:es": "honkit pdf ./book/es ../../dist/agentic-coding-design-patterns-es.pdf" + "start": "vitepress dev book", + "build": "vitepress build book", + "preview": "vitepress preview book", + "test": "node --test tests/", + "deps:update": "ncu -u && pnpm update --latest" }, "devDependencies": { "@commitlint/cli": "^21.2.4", "@commitlint/config-conventional": "^21.2.4", - "gitbook-plugin-toolbar": "^0.6.0", - "honkit": "^6.2.6", - "honkit-plugin-mermaid": "workspace:*", - "honkit-plugin-seo": "workspace:*", + "@mokevnin/vitepress-mermaid": "github:mokevnin/vitepress-mermaid#semver:^v0.1.0", + "cheerio": "^1.2.0", + "github-slugid": "^1.0.1", + "mermaid": "^12.3.0", "npm-check-updates": "^23.1.1", "oxfmt": "^0.78.0", "oxlint": "^1.93.0", - "playwright": "^1.65.1", - "syncpack": "^15.3.3" + "syncpack": "^15.3.3", + "vitepress": "^2.0.0-alpha.21" }, "packageManager": "pnpm@12.18.0" } diff --git a/patches/@honkit__honkit-plugin-lunr.patch b/patches/@honkit__honkit-plugin-lunr.patch deleted file mode 100644 index aefdebf..0000000 --- a/patches/@honkit__honkit-plugin-lunr.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/index.js b/index.js -index 26a818f08aa3138bbccec7dd756fa496c8a85ae6..2a24f7a17e3620b2d2cb8675aa1e3ac96efc18c3 100644 ---- a/index.js -+++ b/index.js -@@ -55,6 +55,8 @@ function getState(context) { - - // Return the text of a page without HTML entities and tags - function toPlainText(content) { -+ // Inline \n` - ); - fs.writeFileSync( - path.join(root, locale, 'SUMMARY.md'), - `# Summary\n\n* [${title}](README.md)\n` - ); - } - - execFileSync( - process.execPath, - [require.resolve('honkit/bin/honkit.js'), 'build', root, output], - { - timeout: 30_000, - stdio: 'pipe' - } - ); - - for (const [locale, { title, token }] of Object.entries(editions)) { - const { store, index } = JSON.parse( - fs.readFileSync(path.join(output, locale, 'search_index.json'), 'utf8') - ); - const documents = Object.values(store); - assert.equal(documents.length, 1, `${locale}: unexpected search documents`); - assert.equal(documents[0].title, title, `${locale}: wrong search result title`); - assert.match(documents[0].body, new RegExp(token), `${locale}: wrong search excerpt`); - assert.doesNotMatch( - documents[0].body, - /invisiblestyle/, - `${locale}: styles are not searchable prose` - ); - // Check the actual search index too: correcting the display store alone - // would still let words from another edition match the current page. - const search = lunr.Index.load(index); - assert.equal(search.search(token).length, 1, `${locale}: local word must match`); - assert.equal(search.search('invisiblestyle').length, 0, `${locale}: CSS must not match`); - for (const other of Object.values(editions).filter((edition) => edition.token !== token)) { - assert.equal( - search.search(other.token).length, - 0, - `${locale}: foreign word must not match` - ); - } - } - } finally { - fs.rmSync(root, { recursive: true, force: true }); - } -}); diff --git a/tests/seo.test.mjs b/tests/seo.test.mjs new file mode 100644 index 0000000..4c434c8 --- /dev/null +++ b/tests/seo.test.mjs @@ -0,0 +1,69 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { createSeo, describe, truncate } from '../book/.vitepress/seo.mjs'; + +/** @param {string} body */ +const page = (body) => `
${body}
`; + +test('the description is the first paragraph of the preferred section', () => { + const html = page( + '

Title

Lead.

' + + '

Problem

The problem.

' + + '

Intent

A note.

The intent.

' + ); + 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('

Tool

Checked on 2026-11-01.

What it is.

'); + assert.equal(describe(html, ['intent']), 'What it is.'); +}); + +test('a long description is cut on a word boundary', () => { + const text = `${'word '.repeat(40)}end`; + const result = truncate(text); + assert.ok(result.length <= 160, String(result.length)); + 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' } } + }); + const head = seo.transformHead( + /** @type {any} */ ({ + page: 'ru/grilling.md', + siteConfig, + pageData: { title: 'Гриллинг' }, + content: page('

Гриллинг

Назначение

Суть.

') + }) + ); + const find = (/** @type {Record} */ 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({ property: 'og:image' })?.content, + 'https://example.org/book/assets/og/ru.png' + ); +}); diff --git a/tests/summary.test.mjs b/tests/summary.test.mjs new file mode 100644 index 0000000..b453bdc --- /dev/null +++ b/tests/summary.test.mjs @@ -0,0 +1,61 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { test } from 'node:test'; + +import { parseSummary, readSummary } from '../book/.vitepress/summary.mjs'; + +test('SUMMARY.md becomes top-level links, groups and nested groups', () => { + const source = [ + '# Contents', + '', + '* [Introduction](README.md)', + '* [Preface](preface.md)', + '', + '## Spec-driven development', + '', + '* [Overview](spec-driven-development.md)', + '', + '### Tool reviews', + '', + '* [OpenSpec](openspec.md)', + '', + '## Anti-patterns', + '', + '* [Vibe coding](vibe-coding.md)', + '' + ].join('\n'); + + assert.deepEqual(parseSummary(source, 'en'), [ + { text: 'Introduction', link: '/en/' }, + { text: 'Preface', link: '/en/preface' }, + { + text: 'Spec-driven development', + items: [ + { text: 'Overview', link: '/en/spec-driven-development' }, + { text: 'Tool reviews', items: [{ text: 'OpenSpec', link: '/en/openspec' }] } + ] + }, + { text: 'Anti-patterns', items: [{ text: 'Vibe coding', link: '/en/vibe-coding' }] } + ]); +}); + +test('a nested group before any group is an error', () => { + assert.throws(() => parseSummary('### Orphan\n', 'en'), /before any "##"/); +}); + +test('every chapter in each SUMMARY.md exists in its locale', () => { + for (const locale of ['ru', 'en', 'es']) { + const links = readSummary(`book/${locale}/SUMMARY.md`, locale) + .flatMap(function flatten(item) { + return [item, ...(item.items ?? []).flatMap(flatten)]; + }) + .map((item) => item.link) + .filter((link) => link !== undefined); + + assert.ok(links.length > 0, locale); + for (const link of links) { + const page = link.slice(`/${locale}/`.length) || 'README'; + assert.ok(fs.existsSync(`book/${locale}/${page}.md`), `${locale}: ${link}`); + } + } +});