Skip to content

A visual, example-driven guide to Claude Code — from basic concepts to advanced agents, with copy-paste templates that bring immediate value.

refactor(scripts): replace Mermaid.js with Pele for diagrams (#197)

Luong NGUYEN0e0115935db9
diff --git a/.github/workflows/docs-check.yml b/.github/workflows/docs-check.yml
index 29738eb..39a4746 100644
--- a/.github/workflows/docs-check.yml
+++ b/.github/workflows/docs-check.yml
@@ -9,15 +9,22 @@ on:
- '.github/markdown-link-check-config.json'
- '.markdownlint.json'
- 'scripts/check_*.py'
+ - 'scripts/vendor_assets.py'
+ - 'scripts/pele_renderer.py'
+ - 'scripts/pele_render.mjs'
pull_request:
branches: [main]
paths:
- '**.md'
- 'CONTRIBUTING.md'
- 'LICENSE'
+ - '.github/workflows/docs-check.yml'
- '.github/markdown-link-check-config.json'
- '.markdownlint.json'
- 'scripts/check_*.py'
+ - 'scripts/vendor_assets.py'
+ - 'scripts/pele_renderer.py'
+ - 'scripts/pele_render.mjs'
# Cancel in-progress runs for the same branch
concurrency:
@@ -61,29 +68,36 @@ jobs:
LINK_CHECK_STRICT: "1"
mermaid:
- name: Mermaid Syntax
+ name: Mermaid Syntax (Pele)
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
+ # Pele needs Node.js >= 20; the pinned bundle is downloaded once and
+ # sha256-verified on every run (see scripts/vendor_assets.py).
- name: Setup Node.js
uses: actions/setup-node@v4
with:
- node-version: '18'
-
- - name: Install mermaid CLI
- run: npm install -g @mermaid-js/mermaid-cli
+ node-version: '22'
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
+ - name: Cache Pele bundle
+ uses: actions/cache@v4
+ with:
+ path: scripts/.vendor-cache/pele
+ key: pele-${{ hashFiles('scripts/vendor_assets.py') }}
+
+ # Strict: fails if Pele cannot run or no diagram is found, so a broken
+ # toolchain can never pass as a skipped check.
- name: Validate Mermaid diagrams
- run: python scripts/check_mermaid.py
+ run: python scripts/check_mermaid.py --strict
env:
- MERMAID_PUPPETEER_NO_SANDBOX: "true"
+ PELE_REQUIRED: "1"
cross-references:
name: Cross-reference Check
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 518e0f7..ecb3b61 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -22,13 +22,11 @@ jobs:
- name: Install uv
uses: astral-sh/setup-uv@v4
+ # Pele renders the diagrams and needs Node.js >= 20.
- name: Install Node.js
uses: actions/setup-node@v4
with:
- node-version: '20'
-
- - name: Install Mermaid CLI
- run: npm install -g @mermaid-js/mermaid-cli
+ node-version: '22'
- name: Install Python dependencies
run: |
@@ -36,11 +34,10 @@ jobs:
uv pip install -r scripts/requirements-dev.txt
- name: Build EPUB
- run: |
- echo '{"args":["--no-sandbox","--disable-setuid-sandbox"]}' > /tmp/puppeteer-ci.json
- uv run scripts/build_epub.py \
- --lang ${{ matrix.lang }} \
- --puppeteer-config /tmp/puppeteer-ci.json
+ run: uv run scripts/build_epub.py --lang ${{ matrix.lang }}
+
+ - name: Verify EPUB diagrams
+ run: python3 scripts/check_epub_diagrams.py claude-howto-guide*.epub
- name: Upload EPUB artifact
uses: actions/upload-artifact@v4
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 5c30d85..a54054f 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -40,6 +40,13 @@ jobs:
- name: Set up Python ${{ matrix.python-version }}
run: uv python install ${{ matrix.python-version }}
+ # The Pele helper tests run the real Node.js protocol; under CI they
+ # fail instead of skipping when Node.js is missing.
+ - name: Setup Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: '22'
+
- name: Create venv and install dependencies
run: |
uv venv
@@ -148,11 +155,12 @@ jobs:
needs: [pytest, lint, security, type-check]
if: ${{ !failure() && !cancelled() }}
- # This job is the only gate on the EPUB build — the equivalent pre-commit
- # hooks were removed because they need a local `mmdc` binary that has no
- # working arm64 build. The matrix covers every language build_epub.py
- # accepts, so a broken diagram in any tree fails here rather than at
- # release time.
+ # This job is the only gate on the full EPUB build, which stays out of
+ # pre-commit because it is slow (the pre-commit mermaid hooks already
+ # render every diagram with the same pinned Pele bundle). The matrix
+ # covers every language build_epub.py accepts, so a broken diagram in any
+ # tree fails here rather than at release time, and check_epub_diagrams.py
+ # proves the diagrams are embedded as real SVGs, not placeholders.
strategy:
fail-fast: false
matrix:
@@ -173,15 +181,14 @@ jobs:
uv venv
uv pip install -r scripts/requirements-dev.txt
- - name: Install mmdc (Mermaid CLI)
- run: npm install -g @mermaid-js/mermaid-cli
+ # Pele renders the diagrams and needs Node.js >= 20.
+ - name: Setup Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: '22'
- name: Build EPUB
- run: |
- echo '{"args":["--no-sandbox","--disable-setuid-sandbox"]}' > /tmp/puppeteer-ci.json
- uv run scripts/build_epub.py \
- --lang ${{ matrix.lang }} \
- --puppeteer-config /tmp/puppeteer-ci.json
+ run: uv run scripts/build_epub.py --lang ${{ matrix.lang }}
- name: Verify EPUB Created
run: |
@@ -195,6 +202,9 @@ jobs:
exit 1
fi
+ - name: Verify EPUB diagrams
+ run: python3 scripts/check_epub_diagrams.py claude-howto-guide*.epub
+
- name: Upload EPUB Artifact
uses: actions/upload-artifact@v4
with:
diff --git a/.gitignore b/.gitignore
index af660d6..fcaaee6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -93,7 +93,8 @@ update-plan*.md
site/
.gstack/
-# Cached vendor binaries/assets for the website build (Tailwind CLI, Mermaid, fonts).
+# Cached vendor binaries/assets (Tailwind CLI, Pele bundle, fonts) for the website,
+# EPUB and Mermaid checks.
scripts/.vendor-cache/
# Local agent/tooling state
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index cb77d32..7321be6 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -84,10 +84,17 @@ repos:
pass_filenames: false
types: [markdown]
+ # The three *mermaid hooks render every diagram with the pinned Pele
+ # bundle. `language: node` makes pre-commit provision Node.js 22 for the
+ # hook (nodeenv), so no system Node is needed, and `--strict` makes a
+ # failed bundle download fail the hook instead of skipping it. The first
+ # run needs network access; offline, skip them with
+ # SKIP=mermaid,vietnamese-mermaid,japanese-mermaid.
- id: mermaid
name: mermaid-syntax
- language: system
- entry: python scripts/check_mermaid.py
+ language: node
+ language_version: 22.12.0
+ entry: python scripts/check_mermaid.py --strict
pass_filenames: false
types: [markdown]
verbose: true
@@ -108,9 +115,9 @@ repos:
types: [markdown]
# The EPUB build is intentionally CI-only (see the `build-epub` job in
- # .github/workflows/test.yml). It needs a local `mmdc` binary, which has
- # no working arm64 build, so running it here made the gate impossible to
- # satisfy on arm64 machines while `check_mermaid.py` skipped silently.
+ # .github/workflows/test.yml): it is a slow full-book build. The mermaid
+ # hooks above already render every diagram with the same Pele bundle
+ # the EPUB uses, so a broken diagram still fails at commit time.
# Vietnamese documentation checks
- repo: local
@@ -132,8 +139,9 @@ repos:
- id: vietnamese-mermaid
name: vietnamese-mermaid-syntax
- language: system
- entry: python scripts/check_mermaid.py
+ language: node
+ language_version: 22.12.0
+ entry: python scripts/check_mermaid.py --strict
pass_filenames: false
files: ^vi/.*\.md$
verbose: true
@@ -166,8 +174,9 @@ repos:
- id: japanese-mermaid
name: japanese-mermaid-syntax
- language: system
- entry: python scripts/check_mermaid.py
+ language: node
+ language_version: 22.12.0
+ entry: python scripts/check_mermaid.py --strict
pass_filenames: false
files: ^ja/.*\.md$
verbose: true
diff --git a/CLAUDE.md b/CLAUDE.md
index 332fb33..9f714d4 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -13,7 +13,7 @@ pre-commit run --all-files
# Tests
pytest scripts/tests/ -v
-# EPUB build (renders Mermaid with the local mmdc CLI — no network, needs mmdc on PATH)
+# EPUB build (renders Mermaid with Pele — needs Node.js >= 20; the pinned bundle downloads once, then works offline)
uv run scripts/build_epub.py
# Python tooling
@@ -22,7 +22,7 @@ mypy scripts/ --ignore-missing-imports
bandit -c scripts/pyproject.toml -r scripts/ --exclude scripts/tests/
```
-Pre-commit runs 5 doc checks on `.md` changes: markdown-lint, cross-references, mermaid-syntax, link-check, markdown-rendering. All must pass. The EPUB build is **not** a pre-commit hook — it runs in CI only (`build-epub` job in `.github/workflows/test.yml`), because it needs a local `mmdc` binary that has no working arm64 build.
+Pre-commit runs 5 doc checks on `.md` changes: markdown-lint, cross-references, mermaid-syntax, link-check, markdown-rendering. All must pass. The EPUB build is **not** a pre-commit hook — it runs in CI only (`build-epub` job in `.github/workflows/test.yml`), because it is a slow full-book build; the mermaid-syntax hook already renders every diagram with the same Pele bundle.
## Architecture map
@@ -40,7 +40,7 @@ Pre-commit runs 5 doc checks on `.md` changes: markdown-lint, cross-references,
- Internal links use **relative paths** (e.g. `01-slash-commands/README.md`); anchors use `#heading-name`.
- Code fences **must** declare a language (`bash`, `python`, `json`, …) — the cross-reference check fails otherwise.
- External URLs must be reachable and stable. No ephemeral links.
-- Mermaid diagrams must parse (validated pre-commit, and only when `mmdc` is installed — the check skips with a warning otherwise). A broken EPUB build is usually invalid Mermaid or a missing/failing `mmdc`.
+- Mermaid diagrams must render with Pele. The pre-commit mermaid hooks get Node.js 22 from pre-commit and run strict, so they fail instead of skipping; the first run needs network to download Node.js and the pinned Pele bundle (offline: `SKIP=mermaid,vietnamese-mermaid,japanese-mermaid`). Run by hand, `scripts/check_mermaid.py` only warns without Node.js >= 20, and fails under `--strict` or in CI. A broken EPUB build is usually invalid Mermaid, a missing Node.js >= 20, or a failed bundle download.
- Commit format: `type(scope): subject` where `scope` matches the module folder (e.g. `feat(slash-commands):`, `docs(memory):`, `fix(README):`).
- Do not reorganize the `01-`–`10-` numbering. The order is the curriculum.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 125b572..d6b86f6 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -82,8 +82,9 @@ uv pip install -r scripts/requirements-dev.txt
# Markdown linter (Node.js)
npm install -g markdownlint-cli
-# Mermaid diagram validator (Node.js)
-npm install -g @mermaid-js/mermaid-cli
+# Mermaid diagrams render with Pele, which needs Node.js >= 20 (nothing to
+# install globally). Check your version:
+node --version
# Install pre-commit and activate hooks
uv pip install pre-commit
@@ -96,6 +97,8 @@ pre-commit install
pre-commit run --all-files
```
+The first run downloads Node.js 22 for the Mermaid hooks (pre-commit provisions it, so they work even without a system Node.js) and the pinned Pele bundle into `scripts/.vendor-cache/pele/`; later runs work offline. The Mermaid hooks run in strict mode and fail if Pele cannot run. To commit offline before that first download, skip them with `SKIP=mermaid,vietnamese-mermaid,japanese-mermaid`.
+
The hooks that run on every commit are:
| Hook | What it checks |
diff --git a/STYLE_GUIDE.md b/STYLE_GUIDE.md
index 53c9c18..cc011e9 100644
--- a/STYLE_GUIDE.md
+++ b/STYLE_GUIDE.md
@@ -391,6 +391,8 @@ Use Mermaid for all diagrams. Supported types:
- `sequenceDiagram` — interaction flows
- `timeline` — chronological sequences
+GitHub renders Mermaid natively. The website and the EPUB render the same source with [Pele](https://github.com/obsidianmd/pele), pinned in `scripts/vendor_assets.py`, and the `mermaid-syntax` pre-commit hook validates every block with that same bundle, so a block that passes the hook renders everywhere.
+
### Style Conventions
Apply consistent colors using style blocks:
@@ -419,6 +421,8 @@ graph TB
- Use `["Label text"]` for node labels (enables special characters)
- Use `<br/>` for line breaks within labels
+- Keep labels plain text and write numbered labels as-is (`["1. Load file"]`, no backslash before the period)
+- Don't rely on `%%{init}%%` directives or Mermaid themes: the website applies its own light and dark palette
- Keep diagrams simple (max 10-12 nodes)
- Add a brief text description below the diagram for accessibility
- Use top-to-bottom (`TB`) for hierarchies, left-to-right (`LR`) for workflows
diff --git a/ja/CLAUDE.md b/ja/CLAUDE.md
index 2f6998f..9496af0 100644
--- a/ja/CLAUDE.md
+++ b/ja/CLAUDE.md
@@ -33,7 +33,7 @@ pre-commit run --all-files
4. **link-check** — 外部 URL が到達可能か(Python スクリプト)
5. **markdown-rendering** — Markdown が壊れずにレンダリングされるか(Python スクリプト)
-EPUB ビルドは pre-commit フック **ではない** — CI のみで実行される(`.github/workflows/test.yml` の `build-epub` ジョブ)。ローカルの `mmdc` バイナリが必要であり、arm64 で動作するビルドが存在しないためである。
+EPUB ビルドは pre-commit フック **ではない** — CI のみで実行される(`.github/workflows/test.yml` の `build-epub` ジョブ)。本全体をビルドするため時間がかかるからである。mermaid-syntax フックが同じ Pele バンドルですべての図をすでにレンダリングしている。
### 開発環境のセットアップ
@@ -46,9 +46,11 @@ uv venv
source .venv/bin/activate
uv pip install -r scripts/requirements-dev.txt
-# Node.js ツール(Markdown リンタと Mermaid バリデータ)をインストール
+# Node.js ツール(Markdown リンタ)をインストール
npm install -g markdownlint-cli
-npm install -g @mermaid-js/mermaid-cli
+
+# Mermaid 図は Pele でレンダリングする(Node.js >= 20 が必要。グローバルインストールは不要)
+node --version
# pre-commit フックをインストール
uv pip install pre-commit
@@ -87,7 +89,7 @@ mypy scripts/ --ignore-missing-imports
### EPUB ビルド
```bash
-# 電子書籍を生成(Mermaid 図はローカルの mmdc CLI でレンダリング/ネットワーク不要)
+# 電子書籍を生成(Mermaid 図は Pele でレンダリング/Node.js >= 20 が必要。固定バンドルは初回のみダウンロード)
uv run scripts/build_epub.py
# オプション付き
@@ -108,7 +110,7 @@ uv run scripts/build_epub.py --verbose --output custom-name.epub --lang ja
├── 09-advanced-features/ # プランニング、シンキング、バックグラウンド
├── 10-cli/ # CLI リファレンス
├── scripts/
-│ ├── build_epub.py # EPUB ジェネレータ(Mermaid をローカル mmdc でレンダリング)
+│ ├── build_epub.py # EPUB ジェネレータ(Mermaid を Pele でレンダリング)
│ ├── check_cross_references.py # 内部リンクを検証
│ ├── check_links.py # 外部 URL を検証
│ ├── check_mermaid.py # Mermaid 構文を検証
@@ -127,7 +129,7 @@ uv run scripts/build_epub.py --verbose --output custom-name.epub --lang ja
### Mermaid 図
- すべての図は正常にパースできること(pre-commit フックで検査)
-- EPUB ビルドはローカルの `mmdc` CLI で図をレンダリングする(ネットワークは不要だが `mmdc` が必要)
+- EPUB ビルドは Pele で図をレンダリングする(Node.js >= 20 が必要。固定バンドルは初回のみダウンロードされ、以降はオフラインで動作する)
- フローチャート、シーケンス図、アーキテクチャ可視化に Mermaid を使用する
### 相互参照
@@ -148,7 +150,7 @@ uv run scripts/build_epub.py --verbose --output custom-name.epub --lang ja
3. **pre-commit がゲートキーパー** — PR が承認される前に 5 つの品質チェックがすべて通過しなければならない。CI パイプラインは同じチェックを 2 回目のパスとして実行する。
-4. **Mermaid のレンダリングにはローカルの `mmdc` が必要** — EPUB ビルドは図のレンダリングにローカルの `mmdc` CLI を呼び出す(ネットワークは不要)。ここでビルドが失敗する場合は、`mmdc` が未インストールか、Mermaid 構文エラーが典型的な原因である。EPUB ビルド自体は pre-commit では実行されず、CI のみで実行される。
+4. **Mermaid のレンダリングには Node.js >= 20 が必要** — EPUB ビルドは固定バージョンの Pele バンドルを Node.js で実行して図をレンダリングする(バンドルは初回のみダウンロードされ、sha256 で検証してキャッシュされる)。ここでビルドが失敗する場合は、Node.js >= 20 が未インストールか、バンドルのダウンロード失敗か、Mermaid 構文エラーが典型的な原因である。pre-commit の mermaid フックは pre-commit が用意する Node.js 22 で厳格モードで実行され、スキップせずに失敗する。EPUB ビルド自体は pre-commit では実行されず、CI のみで実行される。
5. **これはチュートリアルでありライブラリではない** — コンテンツを追加する際は、明快な解説、コピー&ペースト可能な例、視覚的な図を重視する。価値は概念を教えることにあり、再利用可能なコードを提供することではない。
diff --git a/ja/CONTRIBUTING.md b/ja/CONTRIBUTING.md
index 08e813c..005c84b 100644
--- a/ja/CONTRIBUTING.md
+++ b/ja/CONTRIBUTING.md
@@ -86,8 +86,9 @@ uv pip install -r scripts/requirements-dev.txt
# Markdown リンタ(Node.js)
npm install -g markdownlint-cli
-# Mermaid 図バリデータ(Node.js)
-npm install -g @mermaid-js/mermaid-cli
+# Mermaid 図は Pele でレンダリングする。Node.js >= 20 が必要(グローバルに
+# インストールするものはない)。バージョンを確認する:
+node --version
# pre-commit をインストールしてフックを有効化
uv pip install pre-commit
@@ -100,6 +101,8 @@ pre-commit install
pre-commit run --all-files
```
+初回の実行では、Mermaid フック用の Node.js 22(pre-commit が用意するため、システムに Node.js がなくても動作する)と、固定バージョンの Pele バンドルが `scripts/.vendor-cache/pele/` にダウンロードされる。以降の実行はオフラインで動作する。Mermaid フックは厳格モードで実行され、Pele を実行できない場合は失敗する。初回ダウンロード前にオフラインでコミットするには、`SKIP=mermaid,vietnamese-mermaid,japanese-mermaid` でスキップする。
+
各コミットで実行されるフックは以下のとおり:
| フック | 検査内容 |
diff --git a/ja/STYLE_GUIDE.md b/ja/STYLE_GUIDE.md
index e7ec9c8..f428f79 100644
--- a/ja/STYLE_GUIDE.md
+++ b/ja/STYLE_GUIDE.md
@@ -397,6 +397,8 @@ GitHub スタイルのアンカーで同一文書内のセクションへリン
- `sequenceDiagram` — インタラクションフロー
- `timeline` — 時系列
+GitHub は Mermaid をネイティブにレンダリングする。Web サイトと EPUB は同じソースを [Pele](https://github.com/obsidianmd/pele)(`scripts/vendor_assets.py` でバージョン固定)でレンダリングし、pre-commit の `mermaid-syntax` フックも同じバンドルですべてのブロックを検証する。そのため、フックを通過したブロックはどこでも表示される。
+
### スタイル規約
スタイルブロックで一貫した色を適用する:
@@ -425,6 +427,8 @@ graph TB
- ノードラベルには `["Label text"]` を使う(特殊文字を許可)
- ラベル内の改行には `<br/>` を使う
+- ラベルはプレーンテキストにし、番号付きラベルはそのまま書く(`["1. Load file"]`、ピリオドの前にバックスラッシュを付けない)
+- `%%{init}%%` ディレクティブや Mermaid のテーマに頼らない:Web サイトは独自のライト/ダーク配色を適用する
- 図はシンプルに保つ(最大 10〜12 ノード)
- アクセシビリティのため図の下に簡潔なテキスト説明を追加する
- 階層には上から下(`TB`)、ワークフローには左から右(`LR`)を使う
diff --git a/ja/scripts/README.md b/ja/scripts/README.md
index 3779ac9..14883a7 100644
--- a/ja/scripts/README.md
+++ b/ja/scripts/README.md
@@ -13,7 +13,7 @@ Claude How-To の Markdown ファイル群から EPUB 形式の電子書籍を
## 特徴
- フォルダ構成(01-slash-commands、02-memory など)に沿って章を整理する
-- Mermaid 図をローカルの `mmdc` CLI で PNG 画像としてレンダリングする(ネットワーク不要)
+- Mermaid 図を [Pele](https://github.com/obsidianmd/pele)(Node.js で実行する固定バージョンのバンドル)で SVG 画像としてレンダリングする。CSS 変数は白背景上の通常の色に置き換えるため、どの EPUB リーダーでも表示できる
- 同一の図をキャッシュし、ユニークな図は一度だけレンダリングする
- プロジェクトロゴから表紙画像を生成する
- 内部 Markdown リンクを EPUB の章参照へ変換する
@@ -23,7 +23,7 @@ Claude How-To の Markdown ファイル群から EPUB 形式の電子書籍を
- Python 3.10+
- [uv](https://github.com/astral-sh/uv)
-- Mermaid 図レンダリング用の [`mmdc`](https://github.com/mermaid-js/mermaid-cli)(`npm install -g @mermaid-js/mermaid-cli`)
+- Mermaid 図レンダリング用に `PATH` 上の Node.js >= 20。固定バージョンの Pele バンドルは初回実行時にダウンロードされ(ネットワークが必要なのは一度だけ)、sha256 で検証して `scripts/.vendor-cache/pele/` にキャッシュされる
## クイックスタート
@@ -53,17 +53,14 @@ python scripts/build_epub.py
```
usage: build_epub.py [-h] [--root ROOT] [--output OUTPUT] [--verbose]
- [--mmdc-path MMDC_PATH] [--lang {en,vi,zh,ja}]
- [--puppeteer-config PUPPETEER_CONFIG]
+ [--lang {en,vi,zh,ja}]
options:
-h, --help show this help message and exit
--root, -r ROOT Root directory (default: repo root)
--output, -o OUTPUT Output path (default: claude-howto-guide.epub)
--verbose, -v Enable verbose logging
- --mmdc-path PATH Path to mmdc binary (default: mmdc from PATH)
--lang {en,vi,zh,ja} Language to build (default: en)
- --puppeteer-config P Puppeteer config JSON passed to mmdc via -p
```
## 使用例
@@ -77,9 +74,6 @@ uv run scripts/build_epub.py --output ~/Desktop/claude-guide.epub
# 日本語版をビルド
uv run scripts/build_epub.py --lang ja
-
-# PATH にない mmdc を指定する
-uv run scripts/build_epub.py --mmdc-path ./node_modules/.bin/mmdc
```
## 出力
@@ -90,7 +84,7 @@ EPUB には次が含まれる:
- プロジェクトロゴ付きの表紙画像
- ネストされた目次
- すべての Markdown コンテンツを EPUB 互換 HTML に変換したもの
-- PNG 画像としてレンダリングされた Mermaid 図
+- SVG 画像としてレンダリングされた Mermaid 図
## テストの実行
@@ -119,8 +113,8 @@ PEP 723 のインラインスクリプトメタデータで管理する:
## トラブルシューティング
-**`mmdc not found` でビルドが失敗する**: Mermaid CLI をインストールする(`npm install -g @mermaid-js/mermaid-cli`)。`PATH` にない場合は `--mmdc-path` を渡す。arm64 では同梱 Chromium が動作しないため、EPUB は CI(`.github/workflows/test.yml` の `build-epub` ジョブ)でビルドすること。
+**`Pele is unavailable` でビルドが失敗する**: Node.js >= 20 をインストールし、`node` が `PATH` 上にあることを確認する(`node --version`)。
-**CI やコンテナで `mmdc` が失敗する**: Chromium にサンドボックスなしのプロファイルが必要。`{"args":["--no-sandbox","--disable-setuid-sandbox"]}` をファイルに書き出し、`--puppeteer-config` で渡す。
+**Pele バンドルのダウンロードまたはチェックサムの失敗**: 初回ビルドは固定バージョンの Pele バンドルを cdn.jsdelivr.net からダウンロードし、各ファイルの sha256 を検証する。オフラインやプロキシ環境では、ネットワークに接続した状態で一度ビルドすれば、以降は `scripts/.vendor-cache/pele/<version>/` のキャッシュを使う。チェックサムの不一致はダウンロードが改変または途中で切れたことを意味するので、そのフォルダを削除して再度ビルドする。
**ロゴが見つからない**: `claude-howto-logo.png` が見つからない場合、スクリプトはテキストのみの表紙を生成する。
diff --git a/scripts/README.md b/scripts/README.md
index 1492d6b..8eeaf2e 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -23,7 +23,7 @@ Build an EPUB ebook from the Claude How-To markdown files.
## Features
- Organizes chapters by folder structure (01-slash-commands, 02-memory, etc.)
-- Renders Mermaid diagrams as PNG images via the local `mmdc` CLI (no network required)
+- Renders Mermaid diagrams as SVG images with [Pele](https://github.com/obsidianmd/pele), a pinned bundle run by Node.js; CSS variables are flattened to plain colours on a white background so every EPUB reader shows them
- Caches identical diagrams so each unique diagram is rendered only once
- Generates a cover image from the project logo
- Converts internal markdown links to EPUB chapter references
@@ -33,7 +33,7 @@ Build an EPUB ebook from the Claude How-To markdown files.
- Python 3.10+
- [uv](https://github.com/astral-sh/uv)
-- [`mmdc`](https://github.com/mermaid-js/mermaid-cli) on `PATH` for Mermaid diagram rendering (`npm install -g @mermaid-js/mermaid-cli`)
+- Node.js >= 20 on `PATH` for Mermaid diagram rendering. The pinned Pele bundle is downloaded on first run (network needed once), sha256-verified, and cached in `scripts/.vendor-cache/pele/`
## Quick Start
@@ -63,17 +63,14 @@ python scripts/build_epub.py
```
usage: build_epub.py [-h] [--root ROOT] [--output OUTPUT] [--verbose]
- [--mmdc-path MMDC_PATH] [--lang {en,vi,zh,ja}]
- [--puppeteer-config PUPPETEER_CONFIG]
+ [--lang {en,vi,zh,ja}]
options:
-h, --help show this help message and exit
--root, -r ROOT Root directory (default: repo root)
--output, -o OUTPUT Output path (default: claude-howto-guide.epub)
--verbose, -v Enable verbose logging
- --mmdc-path PATH Path to mmdc binary (default: mmdc from PATH)
--lang {en,vi,zh,ja} Language to build (default: en)
- --puppeteer-config P Puppeteer config JSON passed to mmdc via -p
```
## Examples
@@ -87,9 +84,6 @@ uv run scripts/build_epub.py --output ~/Desktop/claude-guide.epub
# Build a translated edition
uv run scripts/build_epub.py --lang vi
-
-# Point at an mmdc that is not on PATH
-uv run scripts/build_epub.py --mmdc-path ./node_modules/.bin/mmdc
```
## Output
@@ -100,7 +94,7 @@ The EPUB includes:
- Cover image with project logo
- Table of contents with nested sections
- All markdown content converted to EPUB-compatible HTML
-- Mermaid diagrams rendered as PNG images
+- Mermaid diagrams rendered as SVG images
## Running Tests
@@ -129,9 +123,9 @@ Managed via PEP 723 inline script metadata:
## Troubleshooting
-**Build fails with `mmdc not found`**: Install the Mermaid CLI (`npm install -g @mermaid-js/mermaid-cli`), or pass `--mmdc-path` if the binary is not on `PATH`. There is no working arm64 build of the bundled Chromium, so on arm64 machines build the EPUB in CI instead — the `build-epub` job in `.github/workflows/test.yml` covers every language.
+**Build fails with `Pele is unavailable`**: Install Node.js >= 20 and make sure `node` is on `PATH` (`node --version`).
-**`mmdc` fails in CI or a container**: Chromium needs a sandbox-free profile. Write `{"args":["--no-sandbox","--disable-setuid-sandbox"]}` to a file and pass it via `--puppeteer-config`.
+**Pele bundle download or checksum failure**: The first build downloads the pinned Pele bundle from cdn.jsdelivr.net and checks every file's sha256. Offline or behind a proxy, run one build with network access; later builds use the cache in `scripts/.vendor-cache/pele/<version>/`. A checksum mismatch means the download was altered or truncated: delete that folder and build again.
**Missing logo**: The script generates a text-only cover if `claude-howto-logo.png` is not found.
@@ -149,8 +143,8 @@ files remain the single source of truth.
the corresponding pages on the site
- References to non-markdown repo files (templates, scripts, JSON) become
GitHub blob URLs that open the source on github.com
-- Mermaid diagrams render client-side via `mermaid.min.js`, served from the
- built site (no CDN at runtime)
+- Mermaid diagrams render client-side with Pele (`pele.global.js`), served
+ from the built site (no CDN at runtime); they follow the dark mode toggle
- Tailwind CSS compiled with the standalone CLI (Go binary, no Node.js) and
served from the built site — responsive layout with sidebar nav, in-page
TOC, dark mode toggle, and prev/next page navigation
@@ -204,7 +198,7 @@ ships HTML templates under `scripts/website_templates/`:
`site/assets/tailwind.css` with just the utilities actually used
- `site.css` — small layer of site-specific styles plus Pygments theme
-The Tailwind CLI binary, Mermaid bundle, and font files are downloaded on
+The Tailwind CLI binary, Pele bundle, and font files are downloaded on
first build into `scripts/.vendor-cache/` (gitignored) — see
`scripts/vendor_assets.py`.
diff --git a/scripts/build_epub.py b/scripts/build_epub.py
index d5d39c7..13193a2 100755
--- a/scripts/build_epub.py
+++ b/scripts/build_epub.py
@@ -17,7 +17,7 @@ Usage:
--root, -r Root directory containing markdown files (default: repo root)
--output, -o Output EPUB file path (default: <root>/claude-howto-guide.epub)
--verbose, -v Enable verbose logging
- --mmdc-path Path to mmdc binary (default: mmdc from PATH)
+ --lang Language tree to build: en, vi, zh or ja (default: en)
The script uses inline script dependencies (PEP 723), so uv will
automatically install required packages in an isolated environment.
@@ -27,15 +27,19 @@ Output:
Features:
- Organizes chapters by folder structure (01-slash-commands, etc.)
- - Renders Mermaid diagrams as PNG images via local mmdc CLI (no network required)
+ - Renders Mermaid diagrams as SVG images with the pinned Pele bundle; CSS
+ variables are flattened to literal colours on an opaque white canvas so
+ every EPUB reader shows them
- Generates a cover image from the project logo
- Converts internal markdown links to EPUB chapter references
- - Handles SVG images by replacing with styled placeholders
+ - Embeds SVG images referenced by the Markdown as EPUB image resources
- Strict error mode: fails if any diagram cannot be rendered
Requirements:
- uv (recommended) or Python 3.10+ with dependencies installed
- - @mermaid-js/mermaid-cli installed globally: npm install -g @mermaid-js/mermaid-cli
+ - Node.js >= 20 on PATH. The pinned Pele bundle is downloaded on first run
+ (network needed once), checksum-verified, and cached in
+ scripts/.vendor-cache/pele/; later builds work offline
- Repository structure with markdown files and claude-howto-logo.png
"""
@@ -46,10 +50,11 @@ import html
import logging
import os
import re
-import shutil
-import subprocess # nosec B404
import sys
-import tempfile
+
+# Parses SVG produced moments ago by the pinned, checksum-verified Pele
+# bundle from this repo's own Markdown, not untrusted input.
+import xml.etree.ElementTree as ET # nosec B405
from dataclasses import dataclass, field
from io import BytesIO
from pathlib import Path
@@ -59,6 +64,12 @@ from bs4 import BeautifulSoup
from ebooklib import epub
from PIL import Image, ImageDraw, ImageFont
+# Make sibling script modules importable regardless of cwd.
+sys.path.insert(0, str(Path(__file__).parent))
+
+from pele_renderer import PeleHelperError, PeleUnavailableError, render_diagrams
+from vendor_assets import PELE_VERSION
+
# =============================================================================
# Custom Exceptions
# =============================================================================
@@ -125,10 +136,6 @@ class EPUBConfig:
cover_title_color: tuple[int, int, int] = (78, 205, 196)
cover_subtitle_color: tuple[int, int, int] = (168, 178, 209)
- # Local rendering settings
- mmdc_path: str = "mmdc"
- puppeteer_config: str | None = None
-
# Font paths (platform-specific)
title_font_paths: list[str] = field(
default_factory=lambda: [
@@ -240,115 +247,212 @@ def validate_inputs(config: EPUBConfig, logger: logging.Logger) -> None:
# =============================================================================
-# Mermaid Rendering (Local mmdc)
+# Mermaid Rendering (Pele)
# =============================================================================
+SVG_NS = "http://www.w3.org/2000/svg"
+ET.register_namespace("", SVG_NS)
+
+# Pele measures label widths with Arial metrics, so keep a metric-compatible
+# stack: EPUB readers cannot see the website's web fonts.
+EPUB_DIAGRAM_FONT = "Arial, Helvetica, 'Liberation Sans', sans-serif"
+
+_ALIAS_DECL_RE = re.compile(
+ r"^(--_[a-z0-9]+)\s*:\s*var\(\s*(--pele-[a-z0-9-]+)\s*,\s*(.+?)\s*\)$"
+)
+# Digits matter: series colours are `--pele-series-1`, `--pele-series-2`, ...
+_PELE_VAR_RE = re.compile(r"var\(\s*(--pele-[a-z0-9-]+)\s*,\s*([^()]+?)\s*\)")
+_ALIAS_REF_RE = re.compile(r"var\(\s*(--_[a-z0-9]+)\s*\)")
+_COLOR_MIX_RE = re.compile(
+ r"color-mix\(\s*in srgb\s*,\s*(#[0-9a-fA-F]{3,6})\s+(\d+(?:\.\d+)?)%"
+ r"\s*,\s*(#[0-9a-fA-F]{3,6})\s*\)"
+)
+
+
+def _hex_to_rgb(color: str) -> list[int]:
+ value = color.lstrip("#")
+ if len(value) == 3:
+ value = "".join(ch * 2 for ch in value)
+ return [int(value[i : i + 2], 16) for i in (0, 2, 4)]
+
+
+def _mix_colors(match: re.Match[str]) -> str:
+ first = _hex_to_rgb(match.group(1))
+ weight = float(match.group(2)) / 100
+ second = _hex_to_rgb(match.group(3))
+ return "#" + "".join(
+ f"{round(a * weight + b * (1 - weight)):02x}"
+ for a, b in zip(first, second, strict=True)
+ )
-def sanitize_mermaid(mermaid_code: str) -> str:
- """Sanitize mermaid code to avoid markdown parsing issues.
- Mermaid's markdown-in-nodes feature incorrectly interprets numbered
- lists (e.g., "1. Item") inside node labels. This escapes the period
- to prevent that.
+def flatten_svg_vars(svg: str, theme: dict[str, str] | None = None) -> str:
+ """Resolve Pele's CSS custom properties to literal values for EPUB readers.
+
+ EPUB readers do not reliably support CSS variables, which Pele uses for
+ every colour. This parses the SVG and, in ATTRIBUTE VALUES ONLY (text
+ nodes are never touched, so a label such as ``claude --model: opus``
+ survives), resolves ``var(--pele-x, fallback)`` to the ``theme`` override
+ or the fallback, ``var(--_x)`` aliases to their resolved value, and
+ ``color-mix(in srgb, ...)`` to a hex colour. The custom-property
+ declarations are dropped from the root ``style``, ``style="rx:..."`` becomes
+ an ``rx`` attribute, the font becomes ``EPUB_DIAGRAM_FONT``, and an opaque
+ background ``<rect>`` covering the viewBox is inserted as the first child so
+ dark-mode readers keep edges and text visible. The default theme is Pele's
+ own fallbacks (white background).
"""
- # Escape numbered list patterns inside brackets: [1. Text] -> [1\. Text]
- sanitized = re.sub(r'\[(["\']?)(\d+)\.(\s)', r"[\1\2\\.\3", mermaid_code)
- return sanitized
+ theme = theme or {}
+ try:
+ root = ET.fromstring(svg) # nosec B314
+ except ET.ParseError as exc:
+ raise MermaidRenderError(f"Pele produced invalid SVG: {exc}") from exc
+ aliases = _strip_root_custom_properties(root, theme)
-class MermaidRenderer:
- """Renders Mermaid diagrams locally via the mmdc CLI (no network required)."""
-
- def __init__(
- self, config: EPUBConfig, state: BuildState, logger: logging.Logger
- ) -> None:
- self.config = config
- self.state = state
- self.logger = logger
+ def resolve_pele_var(match: re.Match[str]) -> str:
+ if match.group(1) == "--pele-font":
+ return EPUB_DIAGRAM_FONT
+ return theme.get(match.group(1), match.group(2))
- def _resolve_mmdc(self) -> str:
- """Resolve the mmdc binary path, raising if not found."""
- mmdc = shutil.which(self.config.mmdc_path) or self.config.mmdc_path
- if not shutil.which(mmdc):
+ def resolve_alias(match: re.Match[str]) -> str:
+ if match.group(1) not in aliases:
raise MermaidRenderError(
- f"mmdc not found at '{self.config.mmdc_path}'. "
- "Install it with: npm install -g @mermaid-js/mermaid-cli"
+ f"Pele SVG references undefined CSS variable {match.group(1)}"
)
- return mmdc
-
- def _render_one(
- self, mmdc: str, mermaid_code: str, index: int
- ) -> tuple[bytes, str]:
- """Render a single Mermaid diagram to PNG bytes using mmdc."""
- cache_key = mermaid_code.strip()
- if cache_key in self.state.mermaid_cache:
- self.logger.debug(f"Cache hit for diagram {index}")
- return self.state.mermaid_cache[cache_key]
-
- with tempfile.TemporaryDirectory() as tmpdir:
- input_file = Path(tmpdir) / "diagram.mmd"
- output_file = Path(tmpdir) / "diagram.png"
- input_file.write_text(mermaid_code, encoding="utf-8")
+ return aliases[match.group(1)]
- try:
- cmd = [
- mmdc,
- "-i",
- str(input_file),
- "-o",
- str(output_file),
- "-b",
- "white",
- ]
- if self.config.puppeteer_config:
- cmd += ["-p", self.config.puppeteer_config]
- result = subprocess.run( # nosec B603
- cmd,
- capture_output=True,
- text=True,
- check=False,
- timeout=60,
- )
- except subprocess.TimeoutExpired as exc:
- raise MermaidRenderError(
- f"mmdc timed out rendering diagram {index} (60s limit)"
- ) from exc
-
- if result.returncode != 0:
+ for element in root.iter():
+ for name, value in list(element.attrib.items()):
+ if "var(" not in value and "color-mix" not in value:
+ continue
+ flat = _PELE_VAR_RE.sub(resolve_pele_var, value)
+ flat = _ALIAS_REF_RE.sub(resolve_alias, flat)
+ flat = _COLOR_MIX_RE.sub(_mix_colors, flat)
+ if "var(" in flat or "color-mix" in flat:
raise MermaidRenderError(
- f"mmdc failed for diagram {index}: {result.stderr.strip()}"
+ f"Could not flatten CSS in Pele SVG attribute {name}={flat!r}"
)
+ element.set(name, flat)
+ _move_radius_to_attribute(element)
+
+ _insert_background(root, theme.get("--pele-bg", aliases.get("--_bg", "#fff")))
+ return ET.tostring(root, encoding="unicode")
+
+
+def _strip_root_custom_properties(
+ root: ET.Element, theme: dict[str, str]
+) -> dict[str, str]:
+ """Drop `--*` declarations from the root style; return resolved aliases."""
+ aliases: dict[str, str] = {}
+ kept: list[str] = []
+ for decl in (d.strip() for d in root.get("style", "").split(";")):
+ if not decl:
+ continue
+ match = _ALIAS_DECL_RE.match(decl)
+ if match:
+ aliases[match.group(1)] = theme.get(match.group(2), match.group(3))
+ elif not decl.startswith("--"):
+ kept.append(decl)
+ root.set("style", ";".join(kept))
+ return aliases
+
+
+def _move_radius_to_attribute(element: ET.Element) -> None:
+ """Turn `style="rx:4px;..."` into `rx="4"`, keeping other declarations."""
+ style = element.get("style")
+ if not style or not style.startswith("rx:"):
+ return
+ radius, _, rest = style.partition(";")
+ element.set("rx", radius[3:].strip().removesuffix("px"))
+ if rest.strip():
+ element.set("style", rest)
+ else:
+ del element.attrib["style"]
+
- if not output_file.exists():
- raise MermaidRenderError(f"mmdc produced no output for diagram {index}")
+def _insert_background(root: ET.Element, color: str) -> None:
+ """Insert an opaque `<rect>` covering the viewBox as the first child."""
+ view_box = (root.get("viewBox") or "").split()
+ if len(view_box) != 4:
+ raise MermaidRenderError(
+ f"Pele SVG has a missing or malformed viewBox: {root.get('viewBox')!r}"
+ )
+ x, y, width, height = view_box
+ root.insert(
+ 0,
+ ET.Element(
+ f"{{{SVG_NS}}}rect",
+ {"x": x, "y": y, "width": width, "height": height, "fill": color},
+ ),
+ )
- png_bytes = output_file.read_bytes()
- self.state.mermaid_counter += 1
- img_name = f"mermaid_{self.state.mermaid_counter}.png"
- entry = (png_bytes, img_name)
- self.state.mermaid_cache[cache_key] = entry
- self.logger.info(f"Rendered diagram {index} -> {img_name}")
- return entry
+class MermaidRenderer:
+ """Renders Mermaid diagrams to flattened SVG with the pinned Pele bundle."""
+
+ def __init__(
+ self, config: EPUBConfig, state: BuildState, logger: logging.Logger
+ ) -> None:
+ self.config = config
+ self.state = state
+ self.logger = logger
def render_all(
self, diagrams: list[tuple[int, str]]
) -> dict[str, tuple[bytes, str]]:
- """Render all Mermaid diagrams using local mmdc."""
- mmdc = self._resolve_mmdc()
- results: dict[str, tuple[bytes, str]] = {}
+ """Render every diagram with ONE Pele call; cache SVG bytes by source.
- self.logger.info(f"Rendering {len(diagrams)} Mermaid diagrams locally...")
+ Returns ``{code.strip(): (svg_bytes, "mermaid_N.svg")}``. Any diagram
+ Pele rejects, or Pele being unavailable, raises MermaidRenderError.
+ """
+ pending: dict[str, int] = {}
for idx, code in diagrams:
- sanitized = sanitize_mermaid(code)
- cache_key = sanitized.strip()
- data = self._render_one(mmdc, sanitized, idx)
- results[cache_key] = data
+ key = code.strip()
+ if key not in self.state.mermaid_cache and key not in pending:
+ pending[key] = idx
+
+ if pending:
+ sources = list(pending)
+ self.logger.info(
+ f"Rendering {len(sources)} Mermaid diagrams with Pele {PELE_VERSION}..."
+ )
+ try:
+ results = render_diagrams(sources, self.logger)
+ except PeleUnavailableError as exc:
+ raise MermaidRenderError(
+ f"Pele is unavailable: {exc}. The EPUB build needs Node.js >= 20 "
+ "and network access the first time, to download the bundle."
+ ) from exc
+ except PeleHelperError as exc:
+ raise MermaidRenderError(f"Pele helper failed: {exc}") from exc
+
+ failures = [
+ f"Pele failed for diagram {pending[source]}: {result.error.describe()}"
+ for source, result in zip(sources, results, strict=True)
+ if result.error is not None
+ ]
+ if failures:
+ raise MermaidRenderError("\n".join(failures))
+ for source, result in zip(sources, results, strict=True):
+ if result.svg is None:
+ raise MermaidRenderError(
+ f"Pele returned no SVG for diagram {pending[source]}"
+ )
+ svg_bytes = flatten_svg_vars(result.svg).encode("utf-8")
+ self.state.mermaid_counter += 1
+ img_name = f"mermaid_{self.state.mermaid_counter}.svg"
+ self.state.mermaid_cache[source] = (svg_bytes, img_name)
+ self.logger.debug(f"Rendered diagram {pending[source]} -> {img_name}")
+
+ rendered = {
+ code.strip(): self.state.mermaid_cache[code.strip()] for _, code in diagrams
+ }
self.logger.info(
- f"Successfully rendered {len(results)} unique diagrams ({len(diagrams)} total blocks)"
+ f"Rendered {len(rendered)} unique Mermaid diagrams with Pele "
+ f"{PELE_VERSION} ({len(diagrams)} blocks)"
)
- return results
+ return rendered
def extract_all_mermaid_blocks(
@@ -725,8 +829,7 @@ def process_mermaid_blocks(
pattern = r"```mermaid\n(.*?)```"
def replace_mermaid(match: re.Match[str]) -> str:
- mermaid_code = sanitize_mermaid(match.group(1))
- cache_key = mermaid_code.strip()
+ cache_key = match.group(1).strip()
if cache_key in state.mermaid_cache:
img_data, img_name = state.mermaid_cache[cache_key]
@@ -735,7 +838,7 @@ def process_mermaid_blocks(
img_item = epub.EpubItem(
uid=img_name.replace(".", "_"),
file_name=f"images/{img_name}",
- media_type="image/png",
+ media_type="image/svg+xml",
content=img_data,
)
book.add_item(img_item)
@@ -806,7 +909,7 @@ def md_to_html(
"""Convert markdown to HTML with proper styling.
Handles:
- - Mermaid diagrams (rendered as PNG images)
+ - Mermaid diagrams (rendered by Pele as SVG images)
- SVG images (embedded as EPUB image resources)
- Internal links (converted to EPUB chapter references)
- Standard markdown features
@@ -844,6 +947,10 @@ def md_to_html(
# Skip external URLs (badges, shields, etc.)
if src.startswith(("http://", "https://")):
continue
+ # Rendered diagrams are already EPUB items, not files on disk; sending
+ # them to handle_svg_image would swap them for a "not found" note.
+ if Path(src).name in state.mermaid_added_to_book:
+ continue
alt = img.get("alt", "Image")
converted = handle_svg_image(
src, alt, book, state, chapter_dir, root_path, logger
@@ -894,7 +1001,7 @@ def build_epub_async(
logger: logging.Logger,
state: BuildState | None = None,
) -> Path:
- """Build EPUB with local Mermaid diagram rendering."""
+ """Build the EPUB, rendering every Mermaid diagram to SVG with Pele."""
state = state or BuildState()
state.reset() # Ensure clean state
@@ -922,7 +1029,7 @@ def build_epub_async(
collector = ChapterCollector(config.root_path, state)
chapter_infos = collector.collect_all_chapters(get_chapter_order())
- # Extract and render all Mermaid diagrams locally
+ # Extract all Mermaid diagrams and render them in one Pele batch
logger.info("Extracting Mermaid diagrams...")
md_files = [(ch.file_path, ch.file_title) for ch in chapter_infos]
all_diagrams = extract_all_mermaid_blocks(md_files, logger)
@@ -1051,12 +1158,6 @@ def main() -> int:
parser.add_argument(
"--verbose", "-v", action="store_true", help="Enable verbose logging"
)
- parser.add_argument(
- "--mmdc-path",
- type=str,
- default="mmdc",
- help="Path to mmdc binary (default: mmdc from PATH)",
- )
parser.add_argument(
"--lang",
type=str,
@@ -1067,12 +1168,6 @@ def main() -> int:
"'zh' for Chinese, 'ja' for Japanese (default: en)"
),
)
- parser.add_argument(
- "--puppeteer-config",
- type=str,
- default=None,
- help="Path to Puppeteer config JSON file passed to mmdc via -p (e.g. for --no-sandbox in CI)",
- )
args = parser.parse_args()
@@ -1101,8 +1196,6 @@ def main() -> int:
output_path=output,
language=language,
title=title,
- mmdc_path=args.mmdc_path,
- puppeteer_config=args.puppeteer_config,
)
try:
diff --git a/scripts/build_website.py b/scripts/build_website.py
index f9c6499..266c7ef 100644
--- a/scripts/build_website.py
+++ b/scripts/build_website.py
@@ -28,11 +28,12 @@ Features:
- Rewrites repo-file/folder references (`.json`, `.sh`, `.py`, etc.) to
GitHub source URLs so users can jump to the source on github.com.
- Self-hosted Tailwind CSS (compiled via standalone CLI), Inter font, and
- `mermaid.min.js` — no third-party CDN scripts at runtime.
+ the pinned Pele bundle (`pele.global.js`) that renders Mermaid diagrams
+ in the browser — no third-party CDN scripts at runtime.
- Light/dark theme toggle, mobile-friendly responsive layout, sidebar.
- Hostable as plain static files (e.g. GitHub Pages).
-Vendor assets (Tailwind CLI binary, Mermaid bundle, font files) are downloaded
+Vendor assets (Tailwind CLI binary, Pele bundle, font files) are downloaded
on first build and cached under `scripts/.vendor-cache/`. See
`scripts/vendor_assets.py` for details.
"""
@@ -59,7 +60,7 @@ sys.path.insert(0, str(Path(__file__).parent))
from vendor_assets import (
build_tailwind_css,
fetch_fonts,
- fetch_mermaid,
+ fetch_pele,
write_vendor_manifest,
)
@@ -548,7 +549,12 @@ MERMAID_BLOCK_RE = re.compile(r"```mermaid\n(.*?)```", re.DOTALL)
def replace_mermaid_blocks(md_content: str) -> str:
- """Replace ```mermaid``` fences with `<pre class="mermaid">` for client-side render."""
+ """Replace ```mermaid``` fences with `<pre class="mermaid">` for client-side render.
+
+ The page script swaps each block for a Pele-rendered diagram; without
+ JavaScript, or when Pele cannot render a diagram, the source stays as a
+ readable code block.
+ """
def _replace(match: re.Match[str]) -> str:
code = match.group(1)
@@ -997,7 +1003,7 @@ def build_website(
) -> Path:
"""Generate the full static site at `config.output_path`.
- ``skip_vendor=True`` skips the Tailwind CLI compile and the Mermaid/font
+ ``skip_vendor=True`` skips the Tailwind CLI compile and the Pele/font
downloads — used by tests that don't need network access.
"""
if not config.root_path.is_dir():
@@ -1037,7 +1043,7 @@ def build_website(
logger.info("Skipping vendor asset fetch (skip_vendor=True)")
else:
vendor_dir = assets_dir / "vendor"
- fetch_mermaid(vendor_dir / "mermaid", logger)
+ fetch_pele(vendor_dir / "pele", logger)
fonts_css = fetch_fonts(vendor_dir / "fonts", logger)
# Run Tailwind LAST so it can scan the rendered HTML for class usage.
build_tailwind_css(
diff --git a/scripts/check_epub_diagrams.py b/scripts/check_epub_diagrams.py
new file mode 100644
index 0000000..5b84fda
--- /dev/null
+++ b/scripts/check_epub_diagrams.py
@@ -0,0 +1,161 @@
+#!/usr/bin/env python3
+"""Check that built EPUBs carry real Pele-rendered diagrams (stdlib only).
+
+For each EPUB given on the command line:
+
+- at least one ``images/mermaid_N.svg`` item must exist;
+- every such SVG must parse as XML, have no ``var(``, ``--_`` or ``color-mix``
+ left in any attribute value (EPUB readers lack CSS custom properties), and
+ start with an opaque background ``<rect>`` covering its viewBox;
+- every diagram SVG must be referenced by an ``<img>`` in some chapter, and
+ every such reference must resolve to an item in the EPUB;
+- no chapter may contain the ``SVG not found`` placeholder.
+
+Exit 0 when every EPUB passes, 1 when any check fails, 2 on usage errors.
+Used by the build-epub CI job and the release workflow.
+"""
+
+from __future__ import annotations
+
+import argparse
+import posixpath
+import re
+import sys
+
+# Parses SVG items of an EPUB this repo has just built from its own Markdown
+# with the pinned, checksum-verified Pele bundle, not untrusted input.
+import xml.etree.ElementTree as ET # nosec B405
+import zipfile
+from dataclasses import dataclass, field
+from pathlib import Path
+
+DIAGRAM_ITEM_RE = re.compile(r"(?:^|/)images/mermaid_\d+\.svg$")
+DIAGRAM_NAME_RE = re.compile(r"^mermaid_\d+\.svg$")
+IMG_SRC_RE = re.compile(
+ r"<img\b[^>]*?\bsrc\s*=\s*([\"'])(.*?)\1", re.IGNORECASE | re.DOTALL
+)
+PLACEHOLDER = "SVG not found"
+FORBIDDEN_IN_ATTRIBUTES = ("var(", "--_", "color-mix")
+TRANSPARENT_FILLS = {"", "none", "transparent"}
+
+
+@dataclass
+class EpubReport:
+ """What one EPUB contains and everything wrong with it."""
+
+ diagrams: int = 0
+ references: int = 0
+ placeholders: int = 0
+ errors: list[str] = field(default_factory=list)
+
+
+def _local_name(tag: str) -> str:
+ return tag.rsplit("}", 1)[-1]
+
+
+def check_svg(name: str, data: bytes) -> list[str]:
+ """Return the problems with one diagram SVG item."""
+ try:
+ root = ET.fromstring(data) # nosec B314
+ except ET.ParseError as exc:
+ return [f"{name} is not valid XML: {exc}"]
+ if _local_name(root.tag) != "svg":
+ return [f"{name} root element is <{_local_name(root.tag)}>, not <svg>"]
+
+ problems = [
+ f"{name} has unflattened CSS {token!r} in <{_local_name(element.tag)} {attr}>"
+ for element in root.iter()
+ for attr, value in element.attrib.items()
+ for token in FORBIDDEN_IN_ATTRIBUTES
+ if token in value
+ ]
+
+ first = root[0] if len(root) else None
+ if first is None or _local_name(first.tag) != "rect":
+ problems.append(f"{name} has no background <rect> as its first child")
+ elif first.get("fill", "").strip().lower() in TRANSPARENT_FILLS:
+ problems.append(f"{name} background <rect> is not opaque")
+ else:
+ view_box = (root.get("viewBox") or "").split()
+ box = [first.get(k) for k in ("x", "y", "width", "height")]
+ if len(view_box) == 4 and box != view_box:
+ problems.append(
+ f"{name} background <rect> {box} does not cover viewBox {view_box}"
+ )
+ return problems
+
+
+def inspect_epub(path: Path) -> EpubReport:
+ """Collect diagram counts and problems for one EPUB."""
+ report = EpubReport()
+ try:
+ with zipfile.ZipFile(path) as zf:
+ names = zf.namelist()
+ diagrams = {n for n in names if DIAGRAM_ITEM_RE.search(n)}
+ report.diagrams = len(diagrams)
+ if not diagrams:
+ report.errors.append(
+ "no Pele-rendered diagrams (images/mermaid_N.svg) found"
+ )
+ for name in sorted(diagrams):
+ report.errors.extend(check_svg(name, zf.read(name)))
+
+ referenced: set[str] = set()
+ for doc in names:
+ if not doc.endswith((".xhtml", ".html")):
+ continue
+ text = zf.read(doc).decode("utf-8", errors="replace")
+ if PLACEHOLDER in text:
+ report.placeholders += text.count(PLACEHOLDER)
+ report.errors.append(
+ f"{doc} contains an {PLACEHOLDER!r} placeholder"
+ )
+ for _quote, src in IMG_SRC_RE.findall(text):
+ if not DIAGRAM_NAME_RE.match(posixpath.basename(src)):
+ continue
+ report.references += 1
+ target = posixpath.normpath(
+ posixpath.join(posixpath.dirname(doc), src)
+ )
+ if target not in diagrams:
+ report.errors.append(f"{doc} references missing diagram {src}")
+ referenced.add(target)
+ report.errors.extend(
+ f"{name} is never referenced by a chapter"
+ for name in sorted(diagrams - referenced)
+ )
+ except (OSError, zipfile.BadZipFile) as exc:
+ report.errors.append(f"cannot read EPUB: {exc}")
+ return report
+
+
+def check_epub(path: Path) -> list[str]:
+ """Return every problem found in `path` (empty when it passes)."""
+ return inspect_epub(path).errors
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(
+ description="Check that EPUBs embed flattened Pele diagram SVGs."
+ )
+ parser.add_argument("epubs", nargs="+", type=Path, help="EPUB file(s) to check")
+ args = parser.parse_args(argv)
+
+ failed = False
+ for path in args.epubs:
+ report = inspect_epub(path)
+ if report.errors:
+ failed = True
+ for error in report.errors:
+ print(f"❌ {path.name}: {error}")
+ else:
+ print(
+ f"✅ {path.name}: {report.diagrams} Pele-rendered diagram(s), "
+ f"{report.references} reference(s), "
+ f"{report.placeholders} placeholder(s)"
+ )
+ return 1 if failed else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/check_mermaid.py b/scripts/check_mermaid.py
index 7ea7802..bad1abe 100644
--- a/scripts/check_mermaid.py
+++ b/scripts/check_mermaid.py
@@ -1,84 +1,154 @@
#!/usr/bin/env python3
-"""Validate Mermaid diagram syntax in Markdown files using mmdc."""
+"""Validate Mermaid diagram syntax in Markdown files by rendering them with Pele.
-import json
+Every ```mermaid block under the current directory is rendered with the same
+pinned, sha256-verified Pele bundle that the website and the EPUB use, so a
+block that passes here renders there too. Identical blocks are rendered once.
+
+Strict mode (``--strict``, or ``PELE_REQUIRED`` / ``CI`` set to 1/true/yes)
+fails when Pele cannot run (Node.js >= 20 missing, bundle download or checksum
+failure) and when no Mermaid block is found at all. Without strict mode a
+missing Pele only prints a warning, so a contributor without Node.js can still
+commit; CI and the pre-commit hooks run strict.
+"""
+
+from __future__ import annotations
+
+import argparse
+import logging
import os
import re
-import shutil
-import subprocess # nosec B404
import sys
-import tempfile
+from collections import Counter
+from dataclasses import dataclass
from pathlib import Path
+# Make sibling script modules importable regardless of cwd.
+sys.path.insert(0, str(Path(__file__).parent))
+
+from pele_renderer import (
+ MIN_NODE_MAJOR,
+ PeleHelperError,
+ PeleUnavailableError,
+ render_diagrams,
+)
+from vendor_assets import PELE_VERSION
+
IGNORE_DIRS = {".venv", "node_modules", ".git", "blog-posts", ".agents"}
+MERMAID_BLOCK_RE = re.compile(r"```mermaid\n(.*?)```", re.DOTALL)
+TRUTHY = {"1", "true", "yes"}
-def main() -> int:
- if not shutil.which("mmdc"):
- print(
- "⚠ mmdc not found — skipping Mermaid validation (install @mermaid-js/mermaid-cli)"
- )
- return 0
+@dataclass(frozen=True)
+class MermaidBlock:
+ """One ```mermaid block: where it is and what it contains."""
- errors = []
- checked = 0
-
- # On GitHub Actions Linux runners, Chrome/Puppeteer requires --no-sandbox.
- # Write a temporary puppeteer config when MERMAID_PUPPETEER_NO_SANDBOX is set.
- puppeteer_config_path = None
- extra_args: list[str] = []
- if os.environ.get("MERMAID_PUPPETEER_NO_SANDBOX") == "true":
- with tempfile.NamedTemporaryFile(
- suffix=".json", mode="w", delete=False
- ) as pcfg:
- json.dump({"args": ["--no-sandbox", "--disable-setuid-sandbox"]}, pcfg)
- puppeteer_config_path = pcfg.name
- extra_args = ["-p", puppeteer_config_path]
-
- md_files = [
+ path: Path
+ line: int
+ index: int
+ source: str
+
+
+def _env_truthy(name: str) -> bool:
+ return os.environ.get(name, "").strip().lower() in TRUTHY
+
+
+def is_strict(flag: bool) -> bool:
+ """Strict when asked on the command line or when running in CI."""
+ return flag or _env_truthy("PELE_REQUIRED") or _env_truthy("CI")
+
+
+def find_markdown_files(root: Path) -> list[Path]:
+ """All Markdown files under `root`, minus IGNORE_DIRS, in a stable order."""
+ return sorted(
f
- for f in Path().rglob("*.md")
+ for f in root.rglob("*.md")
if not any(part in IGNORE_DIRS for part in f.parts)
+ )
+
+
+def extract_blocks(path: Path) -> list[MermaidBlock]:
+ """Return every ```mermaid block in `path` with its fence line number."""
+ content = path.read_text(encoding="utf-8")
+ return [
+ MermaidBlock(
+ path=path,
+ line=content.count("\n", 0, match.start()) + 1,
+ index=index,
+ source=match.group(1),
+ )
+ for index, match in enumerate(MERMAID_BLOCK_RE.finditer(content), start=1)
]
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(
+ description="Validate Mermaid diagrams in Markdown files with Pele."
+ )
+ parser.add_argument(
+ "--strict",
+ action="store_true",
+ help="fail when Pele cannot run or no Mermaid block is found "
+ "(also enabled by PELE_REQUIRED or CI)",
+ )
+ args = parser.parse_args(argv)
+ strict = is_strict(args.strict)
+
+ md_files = find_markdown_files(Path())
+ blocks = [block for path in md_files for block in extract_blocks(path)]
+ if not blocks:
+ if strict:
+ print(
+ f"❌ No Mermaid blocks found in {len(md_files)} Markdown file(s) "
+ "— refusing a vacuous pass in strict mode"
+ )
+ return 1
+ print("✅ No Mermaid blocks found")
+ return 0
+ return validate_blocks(blocks, strict=strict)
+
+
+def validate_blocks(blocks: list[MermaidBlock], *, strict: bool) -> int:
+ """Render the unique sources once and report failures per block."""
+ unique_sources = list(dict.fromkeys(block.source for block in blocks))
+ logger = logging.getLogger("check_mermaid")
try:
- for file_path in md_files:
- content = file_path.read_text()
- blocks = re.findall(r"```mermaid\n(.*?)```", content, re.DOTALL)
- for i, block in enumerate(blocks):
- with tempfile.NamedTemporaryFile(
- suffix=".mmd", mode="w", delete=False
- ) as tmp:
- tmp.write(block)
- tmp_path = tmp.name
- out_path = str(Path(tmp_path).with_suffix(".svg"))
- try:
- result = subprocess.run( # nosec B603 B607
- ["mmdc", "-i", tmp_path, "-o", out_path, *extra_args],
- capture_output=True,
- text=True,
- check=False,
- )
- if result.returncode != 0:
- errors.append(
- f"{file_path} (block {i + 1}): {result.stderr.strip()}"
- )
- else:
- checked += 1
- finally:
- Path(tmp_path).unlink(missing_ok=True)
- Path(out_path).unlink(missing_ok=True)
- finally:
- if puppeteer_config_path:
- Path(puppeteer_config_path).unlink(missing_ok=True)
-
- print(f"✅ Checked {checked} Mermaid diagram(s)")
+ results = render_diagrams(unique_sources, logger)
+ except PeleUnavailableError as exc:
+ if strict:
+ print(f"❌ Pele is unavailable: {exc}")
+ return 1
+ print(
+ f"⚠ Pele is unavailable ({exc}) — skipping Mermaid validation "
+ f"(install Node.js >= {MIN_NODE_MAJOR})"
+ )
+ return 0
+ except PeleHelperError as exc:
+ print(f"❌ Pele helper failed: {exc}")
+ return 1
+
+ by_source = dict(zip(unique_sources, results, strict=True))
+ errors = []
+ for block in blocks:
+ error = by_source[block.source].error
+ if error is not None:
+ errors.append(
+ f"{block.path}:{block.line} (block {block.index}): {error.describe()}"
+ )
+
if errors:
- print("\n❌ Mermaid errors:")
- for e in errors:
- print(f" - {e}")
+ print(f"❌ Pele {PELE_VERSION} rejected {len(errors)} Mermaid block(s):")
+ for message in errors:
+ print(f" - {message}")
return 1
+ types = Counter(r.diagram_type or "unknown" for r in results)
+ summary = ", ".join(f"{name} {count}" for name, count in sorted(types.items()))
+ files = len({block.path for block in blocks})
+ print(
+ f"✅ Pele {PELE_VERSION} rendered {len(blocks)} Mermaid block(s) "
+ f"({len(unique_sources)} unique) from {files} file(s): {summary}"
+ )
return 0
diff --git a/scripts/pele_render.mjs b/scripts/pele_render.mjs
new file mode 100644
index 0000000..ed797f1
--- /dev/null
+++ b/scripts/pele_render.mjs
@@ -0,0 +1,73 @@
+// Render a batch of Mermaid sources to SVG with a pinned Pele bundle.
+//
+// Usage: node scripts/pele_render.mjs <absolute path to pele.mjs>
+// (Pele's dist/pele.js, cached under a .mjs name so every Node.js >= 20
+// loads it as an ES module.)
+// stdin: {"diagrams": ["<mermaid source>", ...], "options": {...}}
+// stdout: {"results": [{"svg", "type", "width", "height"} | {"error": {...}}]}
+//
+// Results keep the input order. A diagram that fails to render is reported as
+// data ({"error": {"code", "message", "line", "column"}}) and the process still
+// exits 0. Exit 2 means a usage error or a Node.js version below 20; any other
+// non-zero exit is a crash. Called by scripts/pele_renderer.py.
+import { pathToFileURL } from 'node:url';
+
+const MIN_NODE_MAJOR = 20;
+const PELE_CODES = new Set(['unsupported-diagram', 'syntax', 'semantic', 'limit']);
+
+function usage(message) {
+ process.stderr.write(`pele_render: ${message}\n`);
+ process.exit(2);
+}
+
+const nodeMajor = Number(process.versions.node.split('.')[0]);
+if (!(nodeMajor >= MIN_NODE_MAJOR)) {
+ usage(`Node.js >= ${MIN_NODE_MAJOR} is required (found ${process.versions.node})`);
+}
+if (process.argv.length !== 3) {
+ usage('expected exactly one argument: the path to pele.mjs');
+}
+
+const { render } = await import(pathToFileURL(process.argv[2]).href);
+if (typeof render !== 'function') {
+ usage(`${process.argv[2]} does not export render()`);
+}
+
+let input = '';
+process.stdin.setEncoding('utf8');
+for await (const chunk of process.stdin) {
+ input += chunk;
+}
+
+let request;
+try {
+ request = JSON.parse(input);
+} catch (err) {
+ usage(`stdin is not valid JSON: ${err.message}`);
+}
+if (!request || !Array.isArray(request.diagrams)) {
+ usage('stdin must be an object with a "diagrams" array');
+}
+const options = request.options && typeof request.options === 'object' ? request.options : {};
+
+function toError(err) {
+ const known = err !== null && typeof err === 'object' && PELE_CODES.has(err.code);
+ const message = err !== null && typeof err === 'object' && 'message' in err ? err.message : err;
+ return {
+ code: known ? err.code : 'internal',
+ message: String(message),
+ line: known && Number.isInteger(err.line) ? err.line : null,
+ column: known && Number.isInteger(err.column) ? err.column : null,
+ };
+}
+
+const results = request.diagrams.map((source) => {
+ try {
+ const out = render(String(source), options);
+ return { svg: out.svg, type: out.type, width: out.width, height: out.height };
+ } catch (err) {
+ return { error: toError(err) };
+ }
+});
+
+process.stdout.write(JSON.stringify({ results }));
diff --git a/scripts/pele_renderer.py b/scripts/pele_renderer.py
new file mode 100644
index 0000000..9d0876d
--- /dev/null
+++ b/scripts/pele_renderer.py
@@ -0,0 +1,202 @@
+"""Render Mermaid sources to SVG with the pinned Pele bundle (stdlib only).
+
+Shared by ``check_mermaid.py`` (validation) and ``build_epub.py`` (EPUB
+images). All diagrams of a run go to ONE Node.js process running
+``pele_render.mjs``, which imports the sha256-verified bundle from
+``vendor_assets.ensure_pele_bundle``.
+
+Two failure classes keep environment problems apart from broken diagrams:
+
+- ``PeleUnavailableError``: Node.js is missing or too old, or the bundle could
+ not be downloaded or verified. Callers decide whether that is fatal.
+- ``PeleHelperError``: the helper crashed, timed out or returned malformed
+ output. Always a real failure.
+
+A diagram Pele rejects is not an exception: its ``PeleResult.error`` is set.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+import shutil
+import subprocess # nosec B404
+import sys
+from collections.abc import Sequence
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+# Make the sibling vendor_assets module importable regardless of cwd.
+sys.path.insert(0, str(Path(__file__).parent))
+
+from vendor_assets import PELE_ESM_BUNDLE, PELE_VERSION, ensure_pele_bundle
+
+MIN_NODE_MAJOR = 20
+HELPER = Path(__file__).with_name("pele_render.mjs")
+NODE_INSTALL_HINT = f"Install Node.js >= {MIN_NODE_MAJOR} (https://nodejs.org/)"
+
+_NODE_VERSION_RE = re.compile(r"^v?(\d+)\.")
+
+
+class PeleUnavailableError(RuntimeError):
+ """Pele cannot run here: no suitable Node.js, or no verified bundle."""
+
+
+class PeleHelperError(RuntimeError):
+ """The Node.js helper crashed, timed out or returned malformed output."""
+
+
+@dataclass(frozen=True)
+class PeleDiagramError:
+ """Why Pele rejected one diagram (codes from PeleError, or ``internal``)."""
+
+ code: str
+ message: str
+ line: int | None = None
+ column: int | None = None
+
+ def describe(self) -> str:
+ """Return ``[code] message (diagram line L, column C)``."""
+ text = f"[{self.code}] {self.message}"
+ if self.line is not None:
+ text += f" (diagram line {self.line}"
+ if self.column is not None:
+ text += f", column {self.column}"
+ text += ")"
+ return text
+
+
+@dataclass(frozen=True)
+class PeleResult:
+ """Outcome for one source: an SVG and its diagram type, or an error."""
+
+ svg: str | None
+ diagram_type: str | None
+ error: PeleDiagramError | None = None
+
+
+def find_node() -> str:
+ """Return the path of a ``node`` binary that is at least MIN_NODE_MAJOR."""
+ node = shutil.which("node")
+ if node is None:
+ raise PeleUnavailableError(f"node not found on PATH. {NODE_INSTALL_HINT}")
+ try:
+ # Fixed argv (resolved node binary + flag), no shell.
+ proc = subprocess.run( # nosec B603
+ [node, "--version"],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ raise PeleUnavailableError(
+ f"could not run {node} --version: {exc}. {NODE_INSTALL_HINT}"
+ ) from exc
+ version = proc.stdout.strip()
+ match = _NODE_VERSION_RE.match(version)
+ if proc.returncode != 0 or match is None:
+ raise PeleUnavailableError(
+ f"could not read the Node.js version from {node} "
+ f"(got {version!r}). {NODE_INSTALL_HINT}"
+ )
+ if int(match.group(1)) < MIN_NODE_MAJOR:
+ raise PeleUnavailableError(
+ f"Node.js {version} is too old for Pele {PELE_VERSION}. {NODE_INSTALL_HINT}"
+ )
+ return node
+
+
+def _optional_int(value: Any) -> int | None:
+ return value if isinstance(value, int) and not isinstance(value, bool) else None
+
+
+def _parse_result(item: Any, index: int) -> PeleResult:
+ if not isinstance(item, dict):
+ raise PeleHelperError(f"result {index} is not an object: {item!r}")
+ error = item.get("error")
+ if error is not None:
+ if not isinstance(error, dict):
+ raise PeleHelperError(f"result {index} has a malformed error: {error!r}")
+ return PeleResult(
+ svg=None,
+ diagram_type=None,
+ error=PeleDiagramError(
+ code=str(error.get("code", "internal")),
+ message=str(error.get("message", "")),
+ line=_optional_int(error.get("line")),
+ column=_optional_int(error.get("column")),
+ ),
+ )
+ svg = item.get("svg")
+ if not isinstance(svg, str) or not svg.lstrip().startswith("<svg"):
+ raise PeleHelperError(f"result {index} has no SVG output")
+ diagram_type = item.get("type")
+ return PeleResult(
+ svg=svg,
+ diagram_type=diagram_type if isinstance(diagram_type, str) else None,
+ )
+
+
+def render_diagrams(
+ sources: Sequence[str],
+ logger: logging.Logger,
+ *,
+ options: dict[str, Any] | None = None,
+ timeout: float = 120,
+) -> list[PeleResult]:
+ """Render every source with Pele, returning one result per source in order.
+
+ Raises PeleUnavailableError when Node.js or the bundle is missing, and
+ PeleHelperError when the helper fails as a whole.
+ """
+ node = find_node()
+ try:
+ bundle_dir = ensure_pele_bundle(logger)
+ except (OSError, RuntimeError, ValueError) as exc:
+ raise PeleUnavailableError(
+ f"could not fetch or verify the Pele {PELE_VERSION} bundle: {exc}. "
+ "The first run needs network access; later runs use the cache in "
+ "scripts/.vendor-cache/pele/."
+ ) from exc
+
+ payload = json.dumps({"diagrams": list(sources), "options": options or {}})
+ cmd = [node, str(HELPER), str(bundle_dir / PELE_ESM_BUNDLE)]
+ logger.debug(f"Rendering {len(sources)} diagram(s) with Pele {PELE_VERSION}")
+ try:
+ # Fixed argv: resolved node binary, the repo's helper script and the
+ # checksum-verified bundle path. No shell; sources travel on stdin.
+ proc = subprocess.run( # nosec B603
+ cmd,
+ input=payload,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ timeout=timeout,
+ check=False,
+ )
+ except subprocess.TimeoutExpired as exc:
+ raise PeleHelperError(f"Pele helper timed out after {timeout}s") from exc
+ except OSError as exc:
+ raise PeleHelperError(f"could not start the Pele helper: {exc}") from exc
+
+ if proc.returncode != 0:
+ raise PeleHelperError(
+ f"Pele helper exited with status {proc.returncode}: "
+ f"{proc.stderr.strip() or '(no stderr)'}"
+ )
+ try:
+ data = json.loads(proc.stdout)
+ except json.JSONDecodeError as exc:
+ raise PeleHelperError(f"Pele helper returned invalid JSON: {exc}") from exc
+ results = data.get("results") if isinstance(data, dict) else None
+ if not isinstance(results, list):
+ raise PeleHelperError("Pele helper output has no results list")
+ if len(results) != len(sources):
+ raise PeleHelperError(
+ f"Pele helper returned {len(results)} result(s) for "
+ f"{len(sources)} diagram(s)"
+ )
+ return [_parse_result(item, index) for index, item in enumerate(results)]
diff --git a/scripts/tests/test_build_epub.py b/scripts/tests/test_build_epub.py
index 9d0cf4c..5debf2a 100644
--- a/scripts/tests/test_build_epub.py
+++ b/scripts/tests/test_build_epub.py
@@ -3,14 +3,18 @@
from __future__ import annotations
import logging
+import xml.etree.ElementTree as ET
+import zipfile
from pathlib import Path
-from unittest.mock import MagicMock, patch
+from typing import Any
+from unittest.mock import patch
import pytest
# Fixtures are imported from conftest.py automatically by pytest
# Import from parent directory (handled by conftest.py sys.path)
from build_epub import (
+ EPUB_DIAGRAM_FONT,
BuildState,
ChapterCollector,
EPUBConfig,
@@ -19,11 +23,126 @@ from build_epub import (
ValidationError,
create_chapter_html,
extract_all_mermaid_blocks,
+ flatten_svg_vars,
get_chapter_order,
- sanitize_mermaid,
setup_logging,
validate_inputs,
)
+from pele_renderer import (
+ PeleDiagramError,
+ PeleHelperError,
+ PeleResult,
+ PeleUnavailableError,
+)
+
+SVG_NS = "{http://www.w3.org/2000/svg}"
+
+# Real Pele 1.6.0 output for `graph TD; A[ユーザー] --> B[エージェント]`.
+PELE_SVG = (
+ '<svg xmlns="http://www.w3.org/2000/svg" class="pele pele-flowchart" '
+ 'viewBox="0 0 148 160" width="148" height="160" style="max-width:100%;'
+ "height:auto;--_bg:var(--pele-bg,#fff);--_fg:var(--pele-fg,#1f1f1f);"
+ "--_m:var(--pele-muted,#6e6e6e);--_l:var(--pele-line,#1f1f1f);"
+ "--_s:var(--pele-surface,#f3f3f3);--_a:var(--pele-surface-alt,#e6e6e6);"
+ "--_b:var(--pele-border,#8a8a8a);--_c:var(--pele-accent,#5b7bd5);"
+ "color:var(--_fg);--_r:var(--pele-radius,4px);"
+ "--_fm:var(--pele-font-mono,monospace);font:16px sans-serif;"
+ "letter-spacing:normal;word-spacing:normal;text-transform:none;"
+ 'direction:ltr;font-family:var(--pele-font,sans-serif)" fill="var(--_fg)" '
+ 'role="graphics-document document" aria-roledescription="flowchart">'
+ '<g class="pele-edges" fill="none" stroke="var(--_l)" stroke-linecap="round">'
+ '<g class="pele-edge" data-id="L_A_B_0"><path d="M74,56L74,97"/>'
+ '<path class="pele-marker" d="M74,104L70.64,96L77.36,96Z" fill="var(--_l)" '
+ 'stroke="none"/></g></g><g class="pele-nodes">'
+ '<g class="pele-node pele-shape-rect" data-id="A" transform="translate(74,32)">'
+ '<rect x="-50" y="-24" width="100" height="48" fill="var(--_s)" '
+ 'stroke="var(--_b)" style="rx:var(--_r)"/><text class="pele-label" x="0" '
+ 'y="5.6" text-anchor="middle">ユーザー</text></g>'
+ '<g class="pele-node pele-shape-rect" data-id="B" transform="translate(74,128)">'
+ '<rect x="-66" y="-24" width="132" height="48" fill="var(--_s)" '
+ 'stroke="var(--_b)" style="rx:var(--_r)"/><text class="pele-label" x="0" '
+ 'y="5.6" text-anchor="middle">エージェント</text></g></g></svg>'
+)
+
+# Pele-shaped SVG with labels that look like CSS (`--model: opus`, `;`), XML
+# entities, a Mermaid `style` statement after the radius, and a cluster title
+# halo drawn with color-mix().
+ADVERSARIAL_LABELS = [
+ "claude --model: opus",
+ "a; b & c",
+ "x > y",
+ '"quoted"',
+ "--resume: x",
+ "Session",
+]
+ADVERSARIAL_SVG = (
+ '<svg xmlns="http://www.w3.org/2000/svg" class="pele pele-flowchart" '
+ 'viewBox="0 0 745 124" width="745" height="124" style="max-width:100%;'
+ "height:auto;--_bg:var(--pele-bg,#fff);--_fg:var(--pele-fg,#1f1f1f);"
+ "--_m:var(--pele-muted,#6e6e6e);--_l:var(--pele-line,#1f1f1f);"
+ "--_s:var(--pele-surface,#f3f3f3);--_a:var(--pele-surface-alt,#e6e6e6);"
+ "--_b:var(--pele-border,#8a8a8a);--_c:var(--pele-accent,#5b7bd5);"
+ "color:var(--_fg);--_r:var(--pele-radius,4px);"
+ "--_fm:var(--pele-font-mono,monospace);font:16px sans-serif;"
+ 'font-family:var(--pele-font,sans-serif)" fill="var(--_fg)">'
+ '<g class="pele-clusters"><g class="pele-cluster" data-id="S">'
+ '<rect x="8" y="8" width="466.43" height="108" fill="var(--_a)" '
+ 'fill-opacity="0.5" stroke="var(--_b)" style="rx:var(--_r)"/>'
+ '<text fill="none" stroke="color-mix(in srgb,var(--_a) 50%,var(--_bg))" '
+ 'stroke-width="5" x="50.46" y="33.6">Session</text></g></g>'
+ '<g class="pele-edge-labels" font-size="14"><g class="pele-edge-label">'
+ '<rect x="235.89" y="61.5" width="78.78" height="21" rx="3" '
+ 'fill="var(--_bg)"/><text x="275.28" y="76.9">--resume: x</text></g></g>'
+ '<g class="pele-nodes"><g class="pele-node" data-id="A">'
+ '<rect x="-92.7" y="-24" width="185.39" height="48" fill="var(--_s)" '
+ 'stroke="var(--_b)" style="rx:var(--_r);fill:#e1f5fe;stroke:#333;"/>'
+ '<text class="pele-label">claude --model: opus</text></g>'
+ '<g class="pele-node" data-id="B"><rect fill="var(--_s)" '
+ 'style="rx:var(--_r)"/><text class="pele-label">a; b &amp; c</text></g>'
+ '<g class="pele-node" data-id="C"><text class="pele-label">x &gt; y</text></g>'
+ '<g class="pele-node" data-id="D"><text class="pele-label">&quot;quoted&quot;'
+ "</text></g></g></svg>"
+)
+
+# Real Pele 1.6.0 pie output (trimmed to two slices). Series colours use
+# numbered custom properties (`--pele-series-1`), as do timeline, mindmap and
+# journey diagrams.
+PIE_SVG = (
+ '<svg xmlns="http://www.w3.org/2000/svg" class="pele pele-pie" '
+ 'viewBox="0 0 397 352" width="397" height="352" style="max-width:100%;'
+ "height:auto;--_bg:var(--pele-bg,#fff);--_fg:var(--pele-fg,#1f1f1f);"
+ "--_m:var(--pele-muted,#6e6e6e);--_l:var(--pele-line,#1f1f1f);"
+ "--_s:var(--pele-surface,#f3f3f3);--_a:var(--pele-surface-alt,#e6e6e6);"
+ "--_b:var(--pele-border,#8a8a8a);--_c:var(--pele-accent,#5b7bd5);"
+ "color:var(--_fg);--_tw:var(--pele-title-weight,bold);"
+ "--_fm:var(--pele-font-mono,monospace);font:16px sans-serif;"
+ "letter-spacing:normal;word-spacing:normal;text-transform:none;"
+ 'direction:ltr;font-family:var(--pele-font,sans-serif)" fill="var(--_fg)" '
+ 'role="graphics-document document" aria-roledescription="pie">'
+ '<text class="pele-title" font-weight="var(--_tw)" text-anchor="middle" '
+ 'xml:space="preserve"><tspan x="198.5" y="25.6">Pets</tspan></text>'
+ '<g class="pele-slices" transform="translate(156,196)" stroke="var(--_bg)" '
+ 'stroke-width="1" stroke-linejoin="round">'
+ '<path class="pele-slice" data-id="Dogs" '
+ 'd="M0,0L0,-120A120,120 0 1 1 -115.39,-32.93Z" '
+ 'fill="var(--pele-series-1,#4c78a8)"/>'
+ '<path class="pele-slice" data-id="Cats" '
+ 'd="M0,0L-115.39,-32.93A120,120 0 0 1 0,-120Z" '
+ 'fill="var(--pele-series-2,#f58518)"/></g>'
+ '<g class="pele-legend" font-size="14">'
+ '<g class="pele-legend-item" data-id="Dogs"><rect x="336" y="164" '
+ 'width="12" height="12" rx="2" fill="var(--pele-series-1,#4c78a8)"/>'
+ '<text x="372.34" y="174.9" text-anchor="middle">Dogs</text></g></g></svg>'
+)
+
+
+def _attribute_values(svg: str) -> list[str]:
+ return [v for el in ET.fromstring(svg).iter() for v in el.attrib.values()]
+
+
+def _texts(svg: str) -> list[str]:
+ return [el.text or "" for el in ET.fromstring(svg).iter(f"{SVG_NS}text")]
+
# =============================================================================
# BuildState Tests
@@ -94,7 +213,6 @@ class TestEPUBConfig:
assert config.title == "Claude Code How-To Guide"
assert config.language == "en"
assert config.author == "Claude Code Community"
- assert config.mmdc_path == "mmdc"
def test_custom_values(self, tmp_path: Path) -> None:
"""Test that custom values override defaults."""
@@ -102,10 +220,8 @@ class TestEPUBConfig:
root_path=tmp_path,
output_path=tmp_path / "out.epub",
title="Custom Title",
- mmdc_path="/usr/local/bin/mmdc",
)
assert config.title == "Custom Title"
- assert config.mmdc_path == "/usr/local/bin/mmdc"
# =============================================================================
@@ -172,16 +288,35 @@ class TestValidation:
class TestMermaidProcessing:
"""Tests for Mermaid diagram processing."""
- def test_sanitize_mermaid_numbered_list(self) -> None:
- """Test that numbered lists in brackets are escaped."""
- input_code = 'A["1. First item"] --> B["2. Second item"]'
- expected = 'A["1\\. First item"] --> B["2\\. Second item"]'
- assert sanitize_mermaid(input_code) == expected
+ def test_numbered_label_passes_through_unchanged(
+ self, tmp_path: Path, logger: logging.Logger
+ ) -> None:
+ """`[1. Load file]` reaches Pele as written (no backslash escaping).
- def test_sanitize_mermaid_no_change(self) -> None:
- """Test that code without numbered lists is unchanged."""
- input_code = "A --> B --> C"
- assert sanitize_mermaid(input_code) == input_code
+ Pele renders `1. Load file` correctly but would draw an escape
+ backslash literally, so the source must not be rewritten.
+ """
+ md_file = tmp_path / "steps.md"
+ md_file.write_text(
+ '```mermaid\ngraph TD\n A["1. Load file"] --> B[2. Parse]\n```\n',
+ encoding="utf-8",
+ )
+
+ source = 'graph TD\n A["1. Load file"] --> B[2. Parse]'
+
+ diagrams = extract_all_mermaid_blocks([(md_file, "Steps")], logger)
+ assert diagrams == [(1, source)]
+
+ state = BuildState()
+ config = EPUBConfig(root_path=tmp_path, output_path=tmp_path / "o.epub")
+ with patch(
+ "build_epub.render_diagrams",
+ return_value=[PeleResult(svg=PELE_SVG, diagram_type="flowchart")],
+ ) as mock_render:
+ MermaidRenderer(config, state, logger).render_all(diagrams)
+
+ assert mock_render.call_args.args[0] == [source]
+ assert list(state.mermaid_cache) == [source]
def test_extract_mermaid_blocks(
self, tmp_path: Path, logger: logging.Logger
@@ -379,102 +514,212 @@ class TestLogging:
class TestMermaidRenderer:
- """Tests for local MermaidRenderer."""
+ """Tests for the Pele-backed MermaidRenderer (render_diagrams mocked)."""
def _make_renderer(
self, tmp_path: Path, state: BuildState, logger: logging.Logger
) -> MermaidRenderer:
- config = EPUBConfig(
- root_path=tmp_path,
- output_path=tmp_path / "out.epub",
- mmdc_path="mmdc",
- )
+ config = EPUBConfig(root_path=tmp_path, output_path=tmp_path / "out.epub")
return MermaidRenderer(config, state, logger)
def test_render_all_success(
self, tmp_path: Path, state: BuildState, logger: logging.Logger
) -> None:
- """Test that render_all uses mmdc and caches results."""
- fake_png = b"\x89PNG\r\n\x1a\n" + b"\x00" * 100
+ """Pele SVG is flattened, encoded and cached as mermaid_N.svg."""
renderer = self._make_renderer(tmp_path, state, logger)
- with (
- patch("shutil.which", return_value="/usr/bin/mmdc"),
- patch("subprocess.run") as mock_run,
- patch("pathlib.Path.exists", return_value=True),
- patch("pathlib.Path.read_bytes", return_value=fake_png),
+ with patch(
+ "build_epub.render_diagrams",
+ return_value=[PeleResult(svg=PELE_SVG, diagram_type="flowchart")],
):
- mock_run.return_value = MagicMock(returncode=0, stderr="")
- results = renderer.render_all([(1, "graph TD\n A --> B")])
+ results = renderer.render_all([(1, "graph TD\n A --> B\n")])
- assert len(results) == 1
- png_bytes, img_name = next(iter(results.values()))
- assert png_bytes == fake_png
- assert img_name.startswith("mermaid_")
- assert img_name.endswith(".png")
+ assert list(results) == ["graph TD\n A --> B"]
+ svg_bytes, img_name = results["graph TD\n A --> B"]
+ assert img_name == "mermaid_1.svg"
+ svg = svg_bytes.decode("utf-8")
+ assert "var(" not in svg
+ assert "ユーザー" in svg
+ assert state.mermaid_cache["graph TD\n A --> B"] == (svg_bytes, img_name)
+
+ def test_render_all_diagram_error(
+ self, tmp_path: Path, state: BuildState, logger: logging.Logger
+ ) -> None:
+ """A diagram Pele rejects fails the build with its code and line."""
+ renderer = self._make_renderer(tmp_path, state, logger)
+ error = PeleDiagramError("syntax", "Expecting 'NODE_STRING'", 3, 1)
+
+ with (
+ patch(
+ "build_epub.render_diagrams",
+ return_value=[
+ PeleResult(svg=PELE_SVG, diagram_type="flowchart"),
+ PeleResult(svg=None, diagram_type=None, error=error),
+ ],
+ ),
+ pytest.raises(
+ MermaidRenderError,
+ match=r"Pele failed for diagram 7: \[syntax\] .*diagram line 3",
+ ),
+ ):
+ renderer.render_all([(1, "graph TD\n A --> B"), (7, "graph TD\n A -->")])
- def test_render_all_mmdc_not_found(
+ def test_render_all_pele_unavailable(
self, tmp_path: Path, state: BuildState, logger: logging.Logger
) -> None:
- """Test that missing mmdc raises MermaidRenderError."""
+ """Missing Node.js surfaces as MermaidRenderError with the hint."""
renderer = self._make_renderer(tmp_path, state, logger)
with (
- patch("shutil.which", return_value=None),
- pytest.raises(MermaidRenderError, match="mmdc not found"),
+ patch(
+ "build_epub.render_diagrams",
+ side_effect=PeleUnavailableError("node not found on PATH"),
+ ),
+ pytest.raises(MermaidRenderError, match=r"Node\.js >= 20"),
):
renderer.render_all([(1, "graph TD\n A --> B")])
- def test_render_all_mmdc_failure(
+ def test_render_all_helper_failure(
self, tmp_path: Path, state: BuildState, logger: logging.Logger
) -> None:
- """Test that mmdc non-zero exit raises MermaidRenderError."""
+ """A crashed or timed-out helper raises MermaidRenderError."""
renderer = self._make_renderer(tmp_path, state, logger)
with (
- patch("shutil.which", return_value="/usr/bin/mmdc"),
- patch("subprocess.run") as mock_run,
+ patch(
+ "build_epub.render_diagrams",
+ side_effect=PeleHelperError("Pele helper timed out after 120s"),
+ ),
+ pytest.raises(MermaidRenderError, match="timed out"),
):
- mock_run.return_value = MagicMock(returncode=1, stderr="parse error")
- with pytest.raises(MermaidRenderError, match="mmdc failed"):
- renderer.render_all([(1, "graph TD\n A --> B")])
+ renderer.render_all([(1, "graph TD\n A --> B")])
def test_render_all_deduplication(
self, tmp_path: Path, state: BuildState, logger: logging.Logger
) -> None:
- """Test that identical diagrams are only rendered once."""
- fake_png = b"\x89PNG\r\n\x1a\n" + b"\x00" * 100
+ """Identical diagrams are rendered once, in a single Pele call."""
renderer = self._make_renderer(tmp_path, state, logger)
same_code = "graph TD\n A --> B"
- with (
- patch("shutil.which", return_value="/usr/bin/mmdc"),
- patch("subprocess.run") as mock_run,
- patch("pathlib.Path.exists", return_value=True),
- patch("pathlib.Path.read_bytes", return_value=fake_png),
- ):
- mock_run.return_value = MagicMock(returncode=0, stderr="")
- results = renderer.render_all([(1, same_code), (2, same_code)])
+ with patch(
+ "build_epub.render_diagrams",
+ return_value=[PeleResult(svg=PELE_SVG, diagram_type="flowchart")],
+ ) as mock_render:
+ results = renderer.render_all([(1, same_code), (2, same_code + "\n")])
- # mmdc should only be called once for duplicate diagrams
- assert mock_run.call_count == 1
- # Both entries map to the same cached result
+ assert mock_render.call_count == 1
+ assert mock_render.call_args.args[0] == [same_code]
assert len(results) == 1
- def test_render_all_timeout(
- self, tmp_path: Path, state: BuildState, logger: logging.Logger
- ) -> None:
- """Test that a hung mmdc process raises MermaidRenderError."""
- import subprocess as _subprocess
- renderer = self._make_renderer(tmp_path, state, logger)
+# =============================================================================
+# SVG flattening (EPUB readers lack CSS custom properties)
+# =============================================================================
- with (
- patch("shutil.which", return_value="/usr/bin/mmdc"),
- patch("subprocess.run", side_effect=_subprocess.TimeoutExpired("mmdc", 60)),
- pytest.raises(MermaidRenderError, match="timed out"),
- ):
- renderer.render_all([(1, "graph TD\n A --> B")])
+
+class TestFlattenSvgVars:
+ @pytest.mark.parametrize(
+ "svg", [PELE_SVG, ADVERSARIAL_SVG, PIE_SVG], ids=["real", "adv", "series"]
+ )
+ def test_no_css_variables_left_and_valid_xml(self, svg: str) -> None:
+ out = flatten_svg_vars(svg)
+
+ ET.fromstring(out) # still well-formed XML
+ for value in _attribute_values(out):
+ assert "var(" not in value
+ assert "--_" not in value
+ assert "color-mix" not in value
+
+ def test_text_nodes_are_untouched(self) -> None:
+ out = flatten_svg_vars(ADVERSARIAL_SVG)
+
+ assert _texts(out) == _texts(ADVERSARIAL_SVG)
+ assert sorted(_texts(out)) == sorted(ADVERSARIAL_LABELS)
+
+ def test_aliases_resolve_to_pele_fallbacks(self) -> None:
+ root = ET.fromstring(flatten_svg_vars(ADVERSARIAL_SVG))
+
+ assert root.get("fill") == "#1f1f1f"
+ style = root.get("style", "")
+ assert "color:#1f1f1f" in style
+ assert "max-width:100%" in style
+ halo = next(t for t in root.iter(f"{SVG_NS}text") if t.get("stroke"))
+ # color-mix(in srgb, #e6e6e6 50%, #fff)
+ assert halo.get("stroke") == "#f2f2f2"
+
+ def test_numbered_series_variables_resolve(self) -> None:
+ root = ET.fromstring(flatten_svg_vars(PIE_SVG))
+ slices = [p for p in root.iter(f"{SVG_NS}path") if p.get("data-id")]
+
+ assert [p.get("fill") for p in slices] == ["#4c78a8", "#f58518"]
+ title = next(root.iter(f"{SVG_NS}text"))
+ assert title.get("font-weight") == "bold"
+ themed = ET.fromstring(
+ flatten_svg_vars(PIE_SVG, {"--pele-series-1": "#123456"})
+ )
+ assert {
+ r.get("fill") for r in themed.iter(f"{SVG_NS}rect") if r.get("rx") == "2"
+ } == {"#123456"}
+
+ def test_theme_override_applied(self) -> None:
+ root = ET.fromstring(
+ flatten_svg_vars(
+ PELE_SVG, {"--pele-surface": "#abcdef", "--pele-bg": "#000"}
+ )
+ )
+
+ node_rects = list(root.iter(f"{SVG_NS}rect"))[1:]
+ assert {r.get("fill") for r in node_rects} == {"#abcdef"}
+ assert root[0].get("fill") == "#000"
+
+ def test_radius_moves_to_attribute_keeping_other_declarations(self) -> None:
+ root = ET.fromstring(flatten_svg_vars(ADVERSARIAL_SVG))
+ node_a = next(g for g in root.iter(f"{SVG_NS}g") if g.get("data-id") == "A")
+ rect = node_a.find(f"{SVG_NS}rect")
+
+ assert rect is not None
+ assert rect.get("rx") == "4"
+ assert rect.get("style") == "fill:#e1f5fe;stroke:#333;"
+ node_b = next(g for g in root.iter(f"{SVG_NS}g") if g.get("data-id") == "B")
+ rect_b = node_b.find(f"{SVG_NS}rect")
+ assert rect_b is not None
+ assert rect_b.get("rx") == "4"
+ assert "style" not in rect_b.attrib
+
+ def test_font_stack_replaces_pele_font(self) -> None:
+ root = ET.fromstring(flatten_svg_vars(PELE_SVG))
+
+ assert f"font-family:{EPUB_DIAGRAM_FONT}" in root.get("style", "")
+
+ def test_opaque_background_rect_is_first_child(self) -> None:
+ root = ET.fromstring(flatten_svg_vars(PELE_SVG))
+
+ first = root[0]
+ assert first.tag == f"{SVG_NS}rect"
+ assert (first.get("x"), first.get("y")) == ("0", "0")
+ assert (first.get("width"), first.get("height")) == ("148", "160")
+ assert first.get("fill") == "#fff"
+
+ def test_serialises_with_default_namespace(self) -> None:
+ out = flatten_svg_vars(PELE_SVG)
+
+ assert out.startswith('<svg xmlns="http://www.w3.org/2000/svg"')
+ assert "ns0:" not in out
+
+ @pytest.mark.parametrize(
+ "svg",
+ [
+ "<svg xmlns='http://www.w3.org/2000/svg'><g></svg>",
+ '<svg xmlns="http://www.w3.org/2000/svg" width="1"/>',
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10"/>',
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1" '
+ 'fill="var(--_zz)"/>',
+ ],
+ ids=["malformed-xml", "no-viewbox", "short-viewbox", "unknown-alias"],
+ )
+ def test_unflattenable_svg_raises(self, svg: str) -> None:
+ with pytest.raises(MermaidRenderError):
+ flatten_svg_vars(svg)
# =============================================================================
@@ -505,6 +750,48 @@ class TestIntegration:
assert result.exists()
assert result.suffix == ".epub"
+ def test_build_embeds_mermaid_as_svg(
+ self, tmp_project: Path, logger: logging.Logger
+ ) -> None:
+ """Diagrams land in the EPUB as image/svg+xml items, never placeholders."""
+ from build_epub import build_epub_async
+ from check_epub_diagrams import check_epub
+
+ (tmp_project / "README.md").write_text(
+ "# Test Project\n\n```mermaid\ngraph TD\n A --> B\n```\n\n"
+ "Same diagram again:\n\n```mermaid\ngraph TD\n A --> B\n```\n",
+ encoding="utf-8",
+ )
+ config = EPUBConfig(root_path=tmp_project, output_path=tmp_project / "t.epub")
+
+ def fake_render(sources: list[str], *_a: Any, **_k: Any) -> list[PeleResult]:
+ return [PeleResult(svg=PELE_SVG, diagram_type="flowchart") for _ in sources]
+
+ with (
+ patch("build_epub.get_chapter_order") as mock_order,
+ patch("build_epub.render_diagrams", side_effect=fake_render),
+ ):
+ mock_order.return_value = [("README.md", "Introduction")]
+ build_epub_async(config, logger)
+
+ with zipfile.ZipFile(config.output_path) as zf:
+ names = zf.namelist()
+ opf_name = next(n for n in names if n.endswith(".opf"))
+ opf = zf.read(opf_name).decode("utf-8")
+ chapter = zf.read("EPUB/chap_01.xhtml").decode("utf-8")
+ svg = zf.read("EPUB/images/mermaid_1.svg").decode("utf-8")
+
+ assert "EPUB/images/mermaid_1.svg" in names
+ assert not any(n.endswith(".png") and "mermaid" in n for n in names)
+ item = next(
+ line for line in opf.split("<item ") if "images/mermaid_1.svg" in line
+ )
+ assert 'media-type="image/svg+xml"' in item
+ assert chapter.count('src="images/mermaid_1.svg"') == 2
+ assert "SVG not found" not in chapter
+ assert "var(" not in svg
+ assert check_epub(config.output_path) == []
+
# =============================================================================
# Run tests
diff --git a/scripts/tests/test_build_website.py b/scripts/tests/test_build_website.py
index 3e01c1f..3523f61 100644
--- a/scripts/tests/test_build_website.py
+++ b/scripts/tests/test_build_website.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import hashlib
import json
import logging
+import re
import shutil
import subprocess
import sys
@@ -467,6 +468,22 @@ class TestBuildWebsite:
# Back-link to README rewrites to index.html
assert "index.html" in example_html
+ # Diagrams render with the self-hosted Pele bundle, not Mermaid.js.
+ assert "vendor/pele/pele.global.js" in sc_html
+ assert "pele.mount(" in sc_html
+ assert "vendor/mermaid/" not in sc_html
+ # A diagram Pele rejects (reported on m.error, not thrown) gets its
+ # source back instead of a bare error message.
+ assert "m.error !== undefined" in sc_html
+ assert "container.replaceWith(pre)" in sc_html
+ # Zoom stays on, and zoom makes a shrunk diagram a tab stop: every
+ # <svg> Pele draws (it draws a new one on resize and font load) is
+ # named in onRender after the nearest heading.
+ assert "zoom: 'auto'" in sc_html
+ assert "onRender: nameDiagram" in sc_html
+ assert "svg.setAttribute('aria-label'" in sc_html
+ assert "svg.hasAttribute('aria-labelledby')" in sc_html
+
# Stylesheet copied into assets
assert (out_dir / "assets" / "site.css").exists()
# Logo copied into assets
@@ -494,14 +511,33 @@ class TestVendorAssets:
for attr in (
"build_tailwind_css",
- "fetch_mermaid",
+ "fetch_pele",
+ "ensure_pele_bundle",
"fetch_fonts",
"write_vendor_manifest",
"ensure_tailwind_binary",
"TAILWIND_VERSION",
- "MERMAID_VERSION",
+ "PELE_VERSION",
):
assert hasattr(vendor_assets, attr), f"missing {attr}"
+ for gone in ("fetch_mermaid", "MERMAID_VERSION", "MERMAID_URL"):
+ assert not hasattr(vendor_assets, gone), f"{gone} should be removed"
+
+ def test_pele_version_is_pinned_exactly(self) -> None:
+ """The Pele bundle is pinned to an exact X.Y.Z with a digest per file."""
+ import re
+
+ import vendor_assets
+
+ assert re.fullmatch(r"\d+\.\d+\.\d+", vendor_assets.PELE_VERSION)
+ assert f"pele@{vendor_assets.PELE_VERSION}" in vendor_assets.PELE_BASE_URL
+ assert set(vendor_assets.PELE_FILES) == {
+ "dist/pele.js",
+ "dist/pele.global.js",
+ "LICENSE",
+ }
+ for digest in vendor_assets.PELE_FILES.values():
+ assert re.fullmatch(r"[0-9a-f]{64}", digest)
def test_detect_tailwind_asset_name(self) -> None:
"""Platform detection returns one of the known asset names."""
@@ -561,6 +597,220 @@ class TestVendorAssets:
assert downloads == urls
+# =============================================================================
+# Pele bundle: pinned, sha256-verified on every use
+# =============================================================================
+
+
+_FAKE_PELE = {
+ "dist/pele.js": b"export function render() {}\n",
+ "dist/pele.global.js": b"var pele = (() => ({}))();\n",
+ "LICENSE": b"MIT License\n",
+}
+
+
+class TestPeleBundle:
+ @pytest.fixture
+ def fake_pele(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> tuple[Path, list[str], dict[str, bytes]]:
+ """Point the vendor cache at tmp_path and serve fake bundle bytes."""
+ import vendor_assets
+
+ cache_root = tmp_path / "vendor-cache"
+ monkeypatch.setattr(vendor_assets, "_vendor_cache_dir", lambda: cache_root)
+ monkeypatch.setattr(
+ vendor_assets,
+ "PELE_FILES",
+ {rel: hashlib.sha256(data).hexdigest() for rel, data in _FAKE_PELE.items()},
+ )
+ served = dict(_FAKE_PELE)
+ downloads: list[str] = []
+
+ def fake_download(
+ url: str, dest: Path, headers: dict[str, str] | None = None
+ ) -> None:
+ del headers
+ rel = url.removeprefix(vendor_assets.PELE_BASE_URL + "/")
+ downloads.append(rel)
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_bytes(served[rel])
+
+ monkeypatch.setattr(vendor_assets, "_download", fake_download)
+ cache = cache_root / "pele" / vendor_assets.PELE_VERSION
+ return cache, downloads, served
+
+ def test_good_bytes_cached_and_not_redownloaded(
+ self,
+ fake_pele: tuple[Path, list[str], dict[str, bytes]],
+ logger: logging.Logger,
+ ) -> None:
+ import vendor_assets
+
+ cache, downloads, _ = fake_pele
+ assert vendor_assets.ensure_pele_bundle(logger) == cache
+ assert sorted(downloads) == sorted(_FAKE_PELE)
+ assert (cache / "pele.mjs").read_bytes() == _FAKE_PELE["dist/pele.js"]
+ assert (cache / "LICENSE").read_bytes() == _FAKE_PELE["LICENSE"]
+
+ downloads.clear()
+ vendor_assets.ensure_pele_bundle(logger)
+ assert downloads == [], "verified cache must not be downloaded again"
+
+ def test_corrupted_cache_is_redownloaded(
+ self,
+ fake_pele: tuple[Path, list[str], dict[str, bytes]],
+ logger: logging.Logger,
+ ) -> None:
+ import vendor_assets
+
+ cache, downloads, _ = fake_pele
+ vendor_assets.ensure_pele_bundle(logger)
+ (cache / "pele.mjs").write_bytes(b"tampered")
+ downloads.clear()
+
+ vendor_assets.ensure_pele_bundle(logger)
+
+ assert downloads == ["dist/pele.js"]
+ assert (cache / "pele.mjs").read_bytes() == _FAKE_PELE["dist/pele.js"]
+
+ def test_esm_bundle_is_cached_under_an_mjs_name(
+ self,
+ fake_pele: tuple[Path, list[str], dict[str, bytes]],
+ logger: logging.Logger,
+ ) -> None:
+ # Node.js 20.0-20.18 and 22.0-22.6 load a bare .js file with no
+ # "type": "module" beside it as CommonJS and fail on `export`.
+ import vendor_assets
+
+ cache, downloads, _ = fake_pele
+ cache.mkdir(parents=True)
+ # A cache written before the rename holds only pele.js.
+ (cache / "pele.js").write_bytes(_FAKE_PELE["dist/pele.js"])
+
+ vendor_assets.ensure_pele_bundle(logger)
+
+ assert vendor_assets.PELE_ESM_BUNDLE == "pele.mjs"
+ assert "dist/pele.js" in downloads
+ assert (cache / "pele.mjs").read_bytes() == _FAKE_PELE["dist/pele.js"]
+
+ def test_mismatching_download_raises_and_leaves_no_file(
+ self,
+ fake_pele: tuple[Path, list[str], dict[str, bytes]],
+ logger: logging.Logger,
+ ) -> None:
+ import vendor_assets
+
+ cache, _, served = fake_pele
+ served["dist/pele.global.js"] = b"not the pinned bundle"
+
+ with pytest.raises(RuntimeError, match="Checksum mismatch"):
+ vendor_assets.ensure_pele_bundle(logger)
+
+ assert not (cache / "pele.global.js").exists()
+ assert not (cache / "pele.global.js.part").exists()
+
+ def test_fetch_pele_copies_bundle_and_license(
+ self,
+ fake_pele: tuple[Path, list[str], dict[str, bytes]],
+ tmp_path: Path,
+ logger: logging.Logger,
+ ) -> None:
+ import vendor_assets
+
+ target = tmp_path / "site" / "assets" / "vendor" / "pele"
+ script = vendor_assets.fetch_pele(target, logger)
+
+ assert script == target / "pele.global.js"
+ assert script.read_bytes() == _FAKE_PELE["dist/pele.global.js"]
+ assert (target / "LICENSE").read_bytes() == _FAKE_PELE["LICENSE"]
+
+ def test_manifest_records_pele_not_mermaid(self, tmp_path: Path) -> None:
+ import vendor_assets
+
+ vendor_assets.write_vendor_manifest(tmp_path, fonts_count=3)
+ manifest = json.loads((tmp_path / "manifest.json").read_text("utf-8"))
+ assert manifest["pele"] == vendor_assets.PELE_VERSION
+ assert "mermaid" not in manifest
+
+
+# =============================================================================
+# Diagram styles (site.css)
+# =============================================================================
+
+SITE_CSS = Path(__file__).parent.parent / "website_templates" / "site.css"
+# Light fills that site lessons set on nodes without a text colour.
+SOURCE_NODE_FILLS = ("#e1f5ff", "#e1f5fe", "#fff9c4")
+
+
+def _css_rule(css: str, selector: str) -> str:
+ match = re.search(rf"^{re.escape(selector)}\s*\{{(.*?)\}}", css, re.M | re.S)
+ assert match, f"no rule for {selector!r} in site.css"
+ return match.group(1)
+
+
+def _css_color(rule: str, prop: str) -> str:
+ match = re.search(rf"(?<![\w-]){re.escape(prop)}:\s*(#[0-9a-fA-F]{{6}})", rule)
+ assert match, f"no {prop} colour in rule"
+ return match.group(1)
+
+
+def _contrast(first: str, second: str) -> float:
+ def luminance(color: str) -> float:
+ channels = [int(color[i : i + 2], 16) / 255 for i in (1, 3, 5)]
+ r, g, b = (
+ c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
+ for c in channels
+ )
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b
+
+ high, low = sorted((luminance(first), luminance(second)), reverse=True)
+ return (high + 0.05) / (low + 0.05)
+
+
+class TestDiagramStyles:
+ @pytest.mark.parametrize("selector", [".mermaid", ".dark .mermaid"])
+ def test_border_has_3_to_1_contrast(self, selector: str) -> None:
+ # --pele-bg mirrors the page background (bg-slate-50 / bg-slate-950).
+ rule = _css_rule(SITE_CSS.read_text("utf-8"), selector)
+ border = _css_color(rule, "--pele-border")
+ for surface in ("--pele-bg", "--pele-surface", "--pele-surface-alt"):
+ assert _contrast(border, _css_color(rule, surface)) >= 3, surface
+
+ def test_layout_rules_leave_the_source_fallback_alone(self) -> None:
+ css = SITE_CSS.read_text("utf-8")
+ assert "background" not in _css_rule(css, ".mermaid")
+ assert "background: transparent" in _css_rule(css, "div.mermaid")
+
+ def test_diagram_starts_below_the_zoom_buttons(self) -> None:
+ # Pele 1.6.0 draws its zoom box 8px below the top of a diagram it
+ # shrank to fit (two 24px buttons, 2px gap, 2px padding, 1px border:
+ # 56px tall) and sets [hidden] on it when the diagram fits.
+ rule = _css_rule(
+ SITE_CSS.read_text("utf-8"),
+ "div.mermaid:has(> .pele-zoom:not([hidden]))",
+ )
+ match = re.search(r"padding-top:\s*([^;]+);", rule)
+ assert match, "no padding-top in the zoom-box rule"
+ value = match.group(1)
+ room = sum(float(n) for n in re.findall(r"([\d.]+)px", value))
+ room += 16 * sum(float(n) for n in re.findall(r"([\d.]+)rem", value))
+ assert room > 8 + 56
+ # Side padding would narrow the width Pele lays the diagram out to.
+ assert "padding-right" not in rule
+ assert "padding-left" not in rule
+
+ def test_dark_labels_on_source_fills_are_readable(self) -> None:
+ rule = _css_rule(
+ SITE_CSS.read_text("utf-8"),
+ '.dark .mermaid .pele-node:has(> [style*="fill:"]) '
+ '> .pele-label:not([style*="fill:"])',
+ )
+ label = _css_color(rule, "fill")
+ for fill in SOURCE_NODE_FILLS:
+ assert _contrast(label, fill) >= 4.5, fill
+
+
# =============================================================================
# Landing page
# =============================================================================
diff --git a/scripts/tests/test_check_epub_diagrams.py b/scripts/tests/test_check_epub_diagrams.py
new file mode 100644
index 0000000..ed6c6fb
--- /dev/null
+++ b/scripts/tests/test_check_epub_diagrams.py
@@ -0,0 +1,213 @@
+"""Tests for check_epub_diagrams.py (the CI proof that EPUB diagrams are real)."""
+
+from __future__ import annotations
+
+import sys
+import zipfile
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).parent.parent))
+
+from check_epub_diagrams import check_epub, main
+
+GOOD_SVG = (
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 148 160" '
+ 'style="max-width:100%;font-family:Arial, sans-serif" fill="#1f1f1f">'
+ '<rect x="0" y="0" width="148" height="160" fill="#fff"/>'
+ '<rect x="-50" y="-24" width="100" height="48" fill="#f3f3f3" rx="4"/>'
+ '<text x="0" y="5.6">claude --model: opus uses var(--x) in a label</text>'
+ "</svg>"
+)
+
+
+def _chapter(*srcs: str, extra: str = "") -> str:
+ imgs = "".join(f'<img alt="Diagram" src="{src}"/>' for src in srcs)
+ return (
+ '<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE html>\n'
+ '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>T</title></head>'
+ f"<body><p>&nbsp;Intro</p>{imgs}{extra}</body></html>"
+ )
+
+
+def _epub(
+ path: Path,
+ svgs: dict[str, str] | None = None,
+ chapters: dict[str, str] | None = None,
+) -> Path:
+ """Write a minimal EPUB-shaped zip with ebooklib's EPUB/ layout."""
+ svgs = {"mermaid_1.svg": GOOD_SVG} if svgs is None else svgs
+ chapters = (
+ {"chap_01.xhtml": _chapter("images/mermaid_1.svg")}
+ if chapters is None
+ else chapters
+ )
+ with zipfile.ZipFile(path, "w") as zf:
+ zf.writestr("mimetype", "application/epub+zip")
+ zf.writestr("EPUB/content.opf", "<package/>")
+ for name, svg in svgs.items():
+ zf.writestr(f"EPUB/images/{name}", svg)
+ for name, html in chapters.items():
+ zf.writestr(f"EPUB/{name}", html)
+ return path
+
+
+class TestCheckEpub:
+ def test_good_epub_passes(
+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ epub = _epub(
+ tmp_path / "guide.epub",
+ svgs={"mermaid_1.svg": GOOD_SVG, "mermaid_2.svg": GOOD_SVG},
+ chapters={
+ "chap_01.xhtml": _chapter(
+ "images/mermaid_1.svg", "images/mermaid_2.svg"
+ ),
+ "chap_02.xhtml": _chapter("images/mermaid_1.svg"),
+ },
+ )
+
+ assert check_epub(epub) == []
+ assert main([str(epub)]) == 0
+ assert (
+ "✅ guide.epub: 2 Pele-rendered diagram(s), 3 reference(s), "
+ "0 placeholder(s)"
+ ) in capsys.readouterr().out
+
+ def test_single_quoted_src_is_recognised(self, tmp_path: Path) -> None:
+ chapter = _chapter().replace(
+ "</body>", "<img alt='D' src='images/mermaid_1.svg'/></body>"
+ )
+ epub = _epub(tmp_path / "g.epub", chapters={"chap_01.xhtml": chapter})
+
+ assert check_epub(epub) == []
+
+ def test_placeholder_fails(
+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ epub = _epub(
+ tmp_path / "guide.epub",
+ chapters={
+ "chap_01.xhtml": _chapter(
+ "images/mermaid_1.svg",
+ extra="<p><em>[SVG not found: images/mermaid_2.svg]</em></p>",
+ )
+ },
+ )
+
+ assert any("SVG not found" in e for e in check_epub(epub))
+ assert main([str(epub)]) == 1
+ assert "❌ guide.epub:" in capsys.readouterr().out
+
+ def test_unreferenced_svg_fails(self, tmp_path: Path) -> None:
+ epub = _epub(
+ tmp_path / "g.epub",
+ svgs={"mermaid_1.svg": GOOD_SVG, "mermaid_2.svg": GOOD_SVG},
+ )
+
+ errors = check_epub(epub)
+ assert errors == ["EPUB/images/mermaid_2.svg is never referenced by a chapter"]
+
+ def test_dangling_reference_fails(self, tmp_path: Path) -> None:
+ epub = _epub(
+ tmp_path / "g.epub",
+ chapters={
+ "chap_01.xhtml": _chapter(
+ "images/mermaid_1.svg", "images/mermaid_9.svg"
+ )
+ },
+ )
+
+ errors = check_epub(epub)
+ assert errors == [
+ "EPUB/chap_01.xhtml references missing diagram images/mermaid_9.svg"
+ ]
+
+ @pytest.mark.parametrize(
+ "leftover",
+ [
+ 'fill="var(--_s)"',
+ 'stroke="var(--pele-border,#8a8a8a)"',
+ 'stroke="color-mix(in srgb,#e6e6e6 50%,#fff)"',
+ ],
+ ids=["alias", "pele-var", "color-mix"],
+ )
+ def test_leftover_css_variable_in_attribute_fails(
+ self, tmp_path: Path, leftover: str
+ ) -> None:
+ svg = GOOD_SVG.replace('fill="#f3f3f3"', leftover)
+ epub = _epub(tmp_path / "g.epub", svgs={"mermaid_1.svg": svg})
+
+ errors = check_epub(epub)
+ assert errors
+ assert all("unflattened CSS" in e for e in errors)
+
+ def test_css_like_label_text_is_not_flagged(self, tmp_path: Path) -> None:
+ """Only attribute values are checked; label text may contain var(."""
+ assert "var(" in GOOD_SVG
+ epub = _epub(tmp_path / "g.epub")
+
+ assert check_epub(epub) == []
+
+ def test_no_diagrams_fails(self, tmp_path: Path) -> None:
+ epub = _epub(tmp_path / "g.epub", svgs={}, chapters={"c.xhtml": _chapter()})
+
+ errors = check_epub(epub)
+ assert errors == ["no Pele-rendered diagrams (images/mermaid_N.svg) found"]
+
+ @pytest.mark.parametrize(
+ ("svg", "reason"),
+ [
+ (
+ GOOD_SVG.replace(
+ '<rect x="0" y="0" width="148" height="160" fill="#fff"/>', ""
+ ),
+ "does not cover viewBox",
+ ),
+ (
+ GOOD_SVG.replace(
+ '<rect x="0" y="0" width="148" height="160" fill="#fff"/>',
+ '<g><rect x="0" y="0" width="148" height="160" fill="#fff"/></g>',
+ ),
+ "no background <rect>",
+ ),
+ (
+ GOOD_SVG.replace(
+ 'height="160" fill="#fff"', 'height="160" fill="none"'
+ ),
+ "not opaque",
+ ),
+ ],
+ ids=["missing", "not-first-child", "transparent"],
+ )
+ def test_missing_background_rect_fails(
+ self, tmp_path: Path, svg: str, reason: str
+ ) -> None:
+ epub = _epub(tmp_path / "g.epub", svgs={"mermaid_1.svg": svg})
+
+ errors = check_epub(epub)
+ assert len(errors) == 1
+ assert reason in errors[0]
+
+ def test_invalid_svg_xml_fails(self, tmp_path: Path) -> None:
+ epub = _epub(tmp_path / "g.epub", svgs={"mermaid_1.svg": "<svg><g></svg>"})
+
+ assert any("not valid XML" in e for e in check_epub(epub))
+
+ def test_missing_file_fails(
+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ assert main([str(tmp_path / "absent.epub")]) == 1
+ assert "cannot read EPUB" in capsys.readouterr().out
+
+ def test_one_bad_epub_fails_the_run(self, tmp_path: Path) -> None:
+ good = _epub(tmp_path / "good.epub")
+ bad = _epub(tmp_path / "bad.epub", svgs={}, chapters={})
+
+ assert main([str(good), str(bad)]) == 1
+
+ def test_no_arguments_is_usage_error(self) -> None:
+ with pytest.raises(SystemExit) as exc:
+ main([])
+ assert exc.value.code == 2
diff --git a/scripts/tests/test_check_mermaid.py b/scripts/tests/test_check_mermaid.py
new file mode 100644
index 0000000..e1818bd
--- /dev/null
+++ b/scripts/tests/test_check_mermaid.py
@@ -0,0 +1,258 @@
+"""Tests for the Pele-based Mermaid validator (check_mermaid.py)."""
+
+from __future__ import annotations
+
+import logging
+import sys
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).parent.parent))
+
+import check_mermaid
+from pele_renderer import (
+ PeleDiagramError,
+ PeleHelperError,
+ PeleResult,
+ PeleUnavailableError,
+)
+
+FLOW = "graph TD\n A --> B\n"
+SEQ = "sequenceDiagram\n A->>B: hi\n"
+BROKEN = "graph TD\n A -->\n"
+
+
+def _md(*blocks: str) -> str:
+ body = ["# Title", ""]
+ for block in blocks:
+ body += ["Some prose.", "", f"```mermaid\n{block}```", ""]
+ return "\n".join(body)
+
+
[email protected](autouse=True)
+def _no_ambient_strictness(monkeypatch: pytest.MonkeyPatch) -> None:
+ """CI=true on runners would make every 'non-strict' case strict."""
+ monkeypatch.delenv("CI", raising=False)
+ monkeypatch.delenv("PELE_REQUIRED", raising=False)
+
+
+def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Run the validator from an empty tmp project (discovery is cwd-based)."""
+ monkeypatch.chdir(tmp_path)
+ return tmp_path
+
+
+class FakeRenderer:
+ """Stands in for pele_renderer.render_diagrams and records its calls."""
+
+ def __init__(self) -> None:
+ self.calls: list[list[str]] = []
+
+ def __call__(
+ self, sources: Sequence[str], logger: logging.Logger, **_: Any
+ ) -> list[PeleResult]:
+ self.calls.append(list(sources))
+ results = []
+ for source in sources:
+ if source == BROKEN:
+ results.append(
+ PeleResult(
+ svg=None,
+ diagram_type=None,
+ error=PeleDiagramError("syntax", "Expecting node", 2, 9),
+ )
+ )
+ else:
+ kind = "sequence" if source.startswith("sequence") else "flowchart"
+ results.append(PeleResult(svg="<svg/>", diagram_type=kind))
+ return results
+
+
+def fake_render(monkeypatch: pytest.MonkeyPatch) -> FakeRenderer:
+ fake = FakeRenderer()
+ monkeypatch.setattr(check_mermaid, "render_diagrams", fake)
+ return fake
+
+
+def _unavailable(*_a: Any, **_k: Any) -> list[PeleResult]:
+ raise PeleUnavailableError("node not found on PATH")
+
+
+class TestValidBlocks:
+ def test_valid_blocks_pass_with_count_line(
+ self,
+ project: Path,
+ fake_render: FakeRenderer,
+ capsys: pytest.CaptureFixture[str],
+ ) -> None:
+ (project / "a.md").write_text(_md(FLOW, SEQ), encoding="utf-8")
+ (project / "b.md").write_text(_md(FLOW), encoding="utf-8")
+
+ assert check_mermaid.main([]) == 0
+
+ out = capsys.readouterr().out
+ assert (
+ "✅ Pele 1.6.0 rendered 3 Mermaid block(s) (2 unique) from 2 file(s): "
+ "flowchart 1, sequence 1"
+ ) in out
+
+ def test_duplicates_rendered_once(
+ self, project: Path, fake_render: FakeRenderer
+ ) -> None:
+ (project / "a.md").write_text(_md(FLOW, FLOW), encoding="utf-8")
+ (project / "b.md").write_text(_md(FLOW, SEQ), encoding="utf-8")
+
+ assert check_mermaid.main([]) == 0
+
+ assert fake_render.calls == [[FLOW, SEQ]]
+
+ def test_ignore_dirs_are_skipped(
+ self, project: Path, fake_render: FakeRenderer
+ ) -> None:
+ (project / "a.md").write_text(_md(FLOW), encoding="utf-8")
+ for ignored in ("node_modules", ".venv", "blog-posts"):
+ (project / ignored).mkdir()
+ (project / ignored / "x.md").write_text(_md(BROKEN), encoding="utf-8")
+
+ assert check_mermaid.main([]) == 0
+ assert fake_render.calls == [[FLOW]]
+
+
+class TestBrokenBlocks:
+ def test_failure_reports_path_and_line(
+ self,
+ project: Path,
+ fake_render: FakeRenderer,
+ capsys: pytest.CaptureFixture[str],
+ ) -> None:
+ (project / "doc.md").write_text(_md(FLOW, BROKEN), encoding="utf-8")
+ # The second ```mermaid fence sits on line 12 of the generated file.
+ lines = (project / "doc.md").read_text(encoding="utf-8").splitlines()
+ assert lines[11] == "```mermaid"
+
+ assert check_mermaid.main([]) == 1
+
+ out = capsys.readouterr().out
+ assert (
+ "doc.md:12 (block 2): [syntax] Expecting node (diagram line 2, column 9)"
+ ) in out
+
+ def test_shared_broken_source_reported_for_every_block(
+ self,
+ project: Path,
+ fake_render: FakeRenderer,
+ capsys: pytest.CaptureFixture[str],
+ ) -> None:
+ (project / "a.md").write_text(_md(BROKEN), encoding="utf-8")
+ (project / "b.md").write_text(_md(BROKEN), encoding="utf-8")
+
+ assert check_mermaid.main([]) == 1
+
+ out = capsys.readouterr().out
+ assert "a.md:5 (block 1)" in out
+ assert "b.md:5 (block 1)" in out
+ assert fake_render.calls == [[BROKEN]]
+
+ def test_helper_error_always_fails(
+ self,
+ project: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ ) -> None:
+ (project / "a.md").write_text(_md(FLOW), encoding="utf-8")
+
+ def crash(*_a: Any, **_k: Any) -> list[PeleResult]:
+ raise PeleHelperError("helper exited with status 1")
+
+ monkeypatch.setattr(check_mermaid, "render_diagrams", crash)
+
+ assert check_mermaid.main([]) == 1
+ assert "❌ Pele helper failed" in capsys.readouterr().out
+
+
+class TestStrictness:
+ def test_unavailable_non_strict_warns_and_passes(
+ self,
+ project: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ ) -> None:
+ (project / "a.md").write_text(_md(FLOW), encoding="utf-8")
+ monkeypatch.setattr(check_mermaid, "render_diagrams", _unavailable)
+
+ assert check_mermaid.main([]) == 0
+
+ out = capsys.readouterr().out
+ assert "⚠" in out
+ assert "skipping Mermaid validation" in out
+ assert "Node.js >= 20" in out
+
+ @pytest.mark.parametrize(
+ ("argv", "env"),
+ [
+ (["--strict"], {}),
+ ([], {"PELE_REQUIRED": "1"}),
+ ([], {"CI": "true"}),
+ ([], {"CI": "YES"}),
+ ],
+ ids=["flag", "PELE_REQUIRED", "CI", "CI-uppercase"],
+ )
+ def test_unavailable_strict_fails(
+ self,
+ project: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ argv: list[str],
+ env: dict[str, str],
+ ) -> None:
+ (project / "a.md").write_text(_md(FLOW), encoding="utf-8")
+ monkeypatch.setattr(check_mermaid, "render_diagrams", _unavailable)
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+
+ assert check_mermaid.main(argv) == 1
+ assert "❌ Pele is unavailable" in capsys.readouterr().out
+
+ def test_falsy_env_is_not_strict(
+ self, project: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ (project / "a.md").write_text(_md(FLOW), encoding="utf-8")
+ monkeypatch.setattr(check_mermaid, "render_diagrams", _unavailable)
+ monkeypatch.setenv("CI", "false")
+ monkeypatch.setenv("PELE_REQUIRED", "0")
+
+ assert check_mermaid.main([]) == 0
+
+ @pytest.mark.parametrize(
+ ("argv", "env"),
+ [(["--strict"], {}), ([], {"PELE_REQUIRED": "1"}), ([], {"CI": "1"})],
+ ids=["flag", "PELE_REQUIRED", "CI"],
+ )
+ def test_zero_blocks_strict_fails(
+ self,
+ project: Path,
+ fake_render: FakeRenderer,
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ argv: list[str],
+ env: dict[str, str],
+ ) -> None:
+ (project / "a.md").write_text("# No diagrams here\n", encoding="utf-8")
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+
+ assert check_mermaid.main(argv) == 1
+ assert "No Mermaid blocks found" in capsys.readouterr().out
+ assert fake_render.calls == []
+
+ def test_zero_blocks_non_strict_passes(
+ self, project: Path, fake_render: FakeRenderer
+ ) -> None:
+ (project / "a.md").write_text("# No diagrams here\n", encoding="utf-8")
+
+ assert check_mermaid.main([]) == 0
diff --git a/scripts/tests/test_pele_renderer.py b/scripts/tests/test_pele_renderer.py
new file mode 100644
index 0000000..8e131ee
--- /dev/null
+++ b/scripts/tests/test_pele_renderer.py
@@ -0,0 +1,331 @@
+"""Tests for the Pele rendering glue (pele_renderer.py + pele_render.mjs)."""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).parent.parent))
+
+import pele_renderer
+from pele_renderer import (
+ HELPER,
+ PeleHelperError,
+ PeleUnavailableError,
+ find_node,
+ render_diagrams,
+)
+
+# Read once at import time on purpose: fixtures that clear CI for other tests
+# must not turn the "fail instead of skip in CI" rule below into a skip.
+_IN_CI = os.environ.get("CI", "").strip().lower() in {"1", "true", "yes"}
+
+# A stand-in for dist/pele.js that speaks the same protocol as the real
+# bundle: render() returns {svg, type, width, height} or throws an object
+# carrying a PeleError-style code/line/column.
+STUB_BUNDLE = """\
+export function render(source, options) {
+ if (source.includes('SYNTAX_ERROR')) {
+ throw { code: 'syntax', message: 'Unexpected token', line: 2, column: 3 };
+ }
+ if (source.includes('CRASH')) {
+ throw new TypeError('boom');
+ }
+ const kind = source.startsWith('sequenceDiagram') ? 'sequence' : 'flowchart';
+ return { svg: '<svg xmlns="http://www.w3.org/2000/svg"/>', type: kind,
+ width: 1, height: 1, links: [] };
+}
+"""
+
+
+def logger() -> logging.Logger:
+ return logging.getLogger("test_pele_renderer")
+
+
+def real_node() -> str:
+ """A real Node.js binary; skip locally without one, but fail in CI."""
+ node = shutil.which("node")
+ if node is None:
+ if _IN_CI:
+ pytest.fail("node is required in CI to test the Pele helper")
+ pytest.skip("node is not installed")
+ return node
+
+
+def _completed(
+ stdout: str = "", returncode: int = 0, stderr: str = ""
+) -> subprocess.CompletedProcess[str]:
+ return subprocess.CompletedProcess(
+ args=["node"], returncode=returncode, stdout=stdout, stderr=stderr
+ )
+
+
+# =============================================================================
+# find_node
+# =============================================================================
+
+
+class TestFindNode:
+ def test_missing_node(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(pele_renderer.shutil, "which", lambda _name: None)
+ with pytest.raises(PeleUnavailableError, match=r"Node\.js >= 20"):
+ find_node()
+
+ def test_node_too_old(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(pele_renderer.shutil, "which", lambda _name: "/x/node")
+ monkeypatch.setattr(
+ pele_renderer.subprocess,
+ "run",
+ lambda *_a, **_k: _completed("v18.19.1\n"),
+ )
+ with pytest.raises(PeleUnavailableError, match="too old"):
+ find_node()
+
+ def test_node_20_is_accepted(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(pele_renderer.shutil, "which", lambda _name: "/x/node")
+ monkeypatch.setattr(
+ pele_renderer.subprocess,
+ "run",
+ lambda *_a, **_k: _completed("v20.1.0\n"),
+ )
+ assert find_node() == "/x/node"
+
+ def test_unreadable_version(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(pele_renderer.shutil, "which", lambda _name: "/x/node")
+ monkeypatch.setattr(
+ pele_renderer.subprocess,
+ "run",
+ lambda *_a, **_k: _completed("", returncode=1),
+ )
+ with pytest.raises(PeleUnavailableError, match="version"):
+ find_node()
+
+
+# =============================================================================
+# render_diagrams (helper process mocked)
+# =============================================================================
+
+
+class TestRenderDiagramsMocked:
+ @pytest.fixture
+ def env(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
+ """Stub node discovery and the bundle so only the protocol is tested."""
+ monkeypatch.setattr(pele_renderer, "find_node", lambda: "/x/node")
+ monkeypatch.setattr(
+ pele_renderer, "ensure_pele_bundle", lambda _logger: tmp_path
+ )
+ calls: dict[str, Any] = {}
+ return calls
+
+ def _fake_run(
+ self, monkeypatch: pytest.MonkeyPatch, calls: dict[str, Any], **result: Any
+ ) -> None:
+ def fake_run(cmd: list[str], **kwargs: Any) -> Any:
+ calls["cmd"] = cmd
+ calls["input"] = kwargs.get("input")
+ if isinstance(result.get("raise"), BaseException):
+ raise result["raise"]
+ return _completed(
+ result.get("stdout", ""),
+ result.get("returncode", 0),
+ result.get("stderr", ""),
+ )
+
+ monkeypatch.setattr(pele_renderer.subprocess, "run", fake_run)
+
+ def test_parses_results_in_order(
+ self,
+ env: dict[str, Any],
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ logger: logging.Logger,
+ ) -> None:
+ payload = {
+ "results": [
+ {"svg": "<svg/>", "type": "flowchart", "width": 1, "height": 1},
+ {
+ "error": {
+ "code": "syntax",
+ "message": "Unexpected token",
+ "line": 2,
+ "column": 3,
+ }
+ },
+ ]
+ }
+ self._fake_run(monkeypatch, env, stdout=json.dumps(payload))
+
+ results = render_diagrams(["graph TD\n A-->B", "graph TD\n A-->"], logger)
+
+ assert env["cmd"] == ["/x/node", str(HELPER), str(tmp_path / "pele.mjs")]
+ assert json.loads(env["input"])["diagrams"] == [
+ "graph TD\n A-->B",
+ "graph TD\n A-->",
+ ]
+ assert results[0].svg == "<svg/>"
+ assert results[0].diagram_type == "flowchart"
+ assert results[0].error is None
+ assert results[1].svg is None
+ assert results[1].error is not None
+ assert results[1].error.code == "syntax"
+ assert results[1].error.line == 2
+ assert results[1].error.describe() == (
+ "[syntax] Unexpected token (diagram line 2, column 3)"
+ )
+
+ def test_wrong_result_count(
+ self, env: dict[str, Any], monkeypatch: pytest.MonkeyPatch, logger: Any
+ ) -> None:
+ self._fake_run(monkeypatch, env, stdout=json.dumps({"results": []}))
+ with pytest.raises(PeleHelperError, match="0 result"):
+ render_diagrams(["graph TD\n A-->B"], logger)
+
+ def test_invalid_json(
+ self, env: dict[str, Any], monkeypatch: pytest.MonkeyPatch, logger: Any
+ ) -> None:
+ self._fake_run(monkeypatch, env, stdout="not json")
+ with pytest.raises(PeleHelperError, match="invalid JSON"):
+ render_diagrams(["graph TD\n A-->B"], logger)
+
+ def test_missing_svg_is_malformed(
+ self, env: dict[str, Any], monkeypatch: pytest.MonkeyPatch, logger: Any
+ ) -> None:
+ self._fake_run(
+ monkeypatch, env, stdout=json.dumps({"results": [{"type": "flowchart"}]})
+ )
+ with pytest.raises(PeleHelperError, match="no SVG"):
+ render_diagrams(["graph TD\n A-->B"], logger)
+
+ def test_nonzero_exit(
+ self, env: dict[str, Any], monkeypatch: pytest.MonkeyPatch, logger: Any
+ ) -> None:
+ self._fake_run(monkeypatch, env, returncode=1, stderr="SyntaxError: x")
+ with pytest.raises(PeleHelperError, match="status 1: SyntaxError"):
+ render_diagrams(["graph TD\n A-->B"], logger)
+
+ def test_timeout(
+ self, env: dict[str, Any], monkeypatch: pytest.MonkeyPatch, logger: Any
+ ) -> None:
+ self._fake_run(
+ monkeypatch, env, **{"raise": subprocess.TimeoutExpired("node", 5)}
+ )
+ with pytest.raises(PeleHelperError, match="timed out"):
+ render_diagrams(["graph TD\n A-->B"], logger, timeout=5)
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ RuntimeError("Checksum mismatch for Pele"),
+ OSError("network is unreachable"),
+ ],
+ )
+ def test_bundle_failure_is_unavailable(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ logger: logging.Logger,
+ error: Exception,
+ ) -> None:
+ monkeypatch.setattr(pele_renderer, "find_node", lambda: "/x/node")
+
+ def broken_bundle(_logger: logging.Logger) -> Path:
+ raise error
+
+ monkeypatch.setattr(pele_renderer, "ensure_pele_bundle", broken_bundle)
+ with pytest.raises(PeleUnavailableError, match="bundle"):
+ render_diagrams(["graph TD\n A-->B"], logger)
+
+
+# =============================================================================
+# Real helper protocol (Node required, stub bundle, no network)
+# =============================================================================
+
+
+class TestHelperWithNode:
+ def test_round_trip_with_stub_bundle(
+ self,
+ real_node: str,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ logger: logging.Logger,
+ ) -> None:
+ (tmp_path / "pele.mjs").write_text(STUB_BUNDLE, encoding="utf-8")
+ monkeypatch.setattr(
+ pele_renderer, "ensure_pele_bundle", lambda _logger: tmp_path
+ )
+
+ results = render_diagrams(
+ [
+ "graph TD\n A --> B",
+ "graph TD\n SYNTAX_ERROR",
+ "sequenceDiagram\n A->>B: hi",
+ "graph TD\n CRASH",
+ ],
+ logger,
+ )
+
+ assert [r.diagram_type for r in results] == [
+ "flowchart",
+ None,
+ "sequence",
+ None,
+ ]
+ assert results[0].svg is not None
+ assert results[0].svg.startswith("<svg")
+ syntax = results[1].error
+ assert syntax is not None
+ assert (syntax.code, syntax.line, syntax.column) == ("syntax", 2, 3)
+ crash = results[3].error
+ assert crash is not None
+ assert crash.code == "internal"
+ assert "boom" in crash.message
+
+ def test_helper_rejects_missing_argument(self, real_node: str) -> None:
+ proc = subprocess.run(
+ [real_node, str(HELPER)],
+ input="{}",
+ capture_output=True,
+ text=True,
+ timeout=60,
+ check=False,
+ )
+ assert proc.returncode == 2
+ assert "pele.mjs" in proc.stderr
+
+ def test_bundle_loads_as_esm_without_syntax_detection(
+ self,
+ real_node: str,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ logger: logging.Logger,
+ ) -> None:
+ # Node.js 20.0-20.18 and 22.0-22.6 have no ES module syntax
+ # detection: a bare .js bundle loads as CommonJS and fails on
+ # `export`. Turn detection off to get that behaviour on newer Node.
+ flag = "--no-experimental-detect-module"
+ probe = subprocess.run(
+ [real_node, flag, "-e", ""], capture_output=True, timeout=60, check=False
+ )
+ if probe.returncode != 0:
+ pytest.skip(f"this Node.js does not accept {flag}")
+ monkeypatch.setenv("NODE_OPTIONS", flag)
+ bundle = tmp_path / pele_renderer.PELE_ESM_BUNDLE
+ bundle.write_text(STUB_BUNDLE, encoding="utf-8")
+ monkeypatch.setattr(
+ pele_renderer, "ensure_pele_bundle", lambda _logger: tmp_path
+ )
+
+ results = render_diagrams(["graph TD\n A --> B"], logger)
+
+ assert bundle.suffix == ".mjs"
+ assert results[0].error is None
+ assert results[0].diagram_type == "flowchart"
diff --git a/scripts/vendor_assets.py b/scripts/vendor_assets.py
index e36bba5..aca2a5f 100644
--- a/scripts/vendor_assets.py
+++ b/scripts/vendor_assets.py
@@ -1,9 +1,15 @@
-"""Download and self-host third-party assets (Tailwind, Mermaid, Inter font).
+"""Download and self-host third-party assets (Tailwind, Pele, Inter font).
Replaces the previous CDN-based approach so the rendered site has no external
runtime dependencies. Assets are cached under `scripts/.vendor-cache/` and
copied into the built site's `assets/vendor/` directory.
+Pele (https://github.com/obsidianmd/pele) renders the Mermaid diagrams. Its
+bundle is pinned to an exact version and every file is sha256-verified each
+time it is used, so a stale or corrupted cache is re-downloaded rather than
+trusted. The website, the Mermaid validator and the EPUB builder all share the
+same cached copy.
+
The Tailwind standalone CLI (a Go binary, no Node.js required) is downloaded
on first use and reused thereafter. We pin to Tailwind v3 because the templates
use v3-style runtime configuration; Tailwind v4 deprecated that config format.
@@ -24,10 +30,22 @@ import urllib.request
from pathlib import Path
TAILWIND_VERSION = "v3.4.19"
-MERMAID_VERSION = "10"
-MERMAID_URL = (
- f"https://cdn.jsdelivr.net/npm/mermaid@{MERMAID_VERSION}/dist/mermaid.min.js"
-)
+PELE_VERSION = "1.6.0"
+PELE_BASE_URL = f"https://cdn.jsdelivr.net/npm/pele@{PELE_VERSION}"
+# Relative path inside the npm package -> expected sha256 of that file.
+PELE_FILES: dict[str, str] = {
+ "dist/pele.js": "d1ebc1889f3069d7759fe5db34c4ad4b4823285edbee2b537d0ef3d505a76d8d",
+ "dist/pele.global.js": (
+ "b82d1bcd435302779a945e1e0f4a54ea56fb26e010ce3f2122f4216fcfc095d7"
+ ),
+ "LICENSE": "311bccc30de6f7b9cbfb64232bb0c911ccb2191abe316550813ae25b2c7925b9",
+}
+# The cache keeps each file under its base name, except the ES module build:
+# with no package.json "type": "module" beside it, Node.js 20.0-20.18 and
+# 22.0-22.6 load a bare .js file as CommonJS and fail on `export`. A .mjs
+# name loads as an ES module on every Node.js >= 20.
+PELE_ESM_BUNDLE = "pele.mjs"
+_PELE_CACHE_NAMES = {"dist/pele.js": PELE_ESM_BUNDLE}
GOOGLE_FONTS_CSS_URL = (
"https://fonts.googleapis.com/css2?"
"family=Fraunces:ital,opsz,wght@0,9..144,300..700;1,9..144,300..600"
@@ -141,19 +159,57 @@ def build_tailwind_css(
logger.debug(f"Tailwind CLI: {result.stderr.strip()}")
-def fetch_mermaid(target_dir: Path, logger: logging.Logger) -> Path:
- """Download Mermaid's UMD bundle into `target_dir` and return its path."""
- cache = _vendor_cache_dir() / "mermaid"
- cache.mkdir(parents=True, exist_ok=True)
- cached = cache / f"mermaid-{MERMAID_VERSION}.min.js"
- if not cached.exists():
- logger.info(f"Downloading Mermaid {MERMAID_VERSION}")
- _download(MERMAID_URL, cached)
+def _sha256_file(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as fh:
+ for chunk in iter(lambda: fh.read(65536), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+def ensure_pele_bundle(logger: logging.Logger) -> Path:
+ """Return the cache dir holding the pinned, sha256-verified Pele bundle.
+
+ Every file is verified on every call, not only after a download: CI
+ restores caches by prefix, so a cached copy can be stale or truncated. A
+ file whose digest does not match is downloaded again into a temporary file
+ next to it, verified, and only then moved into place. A download that
+ does not match raises ``RuntimeError`` and leaves no file behind.
+ """
+ cache = _vendor_cache_dir() / "pele" / PELE_VERSION
+ cache.mkdir(parents=True, exist_ok=True)
+ for rel_path, expected in PELE_FILES.items():
+ dest = cache / _PELE_CACHE_NAMES.get(rel_path, Path(rel_path).name)
+ if dest.is_file() and _sha256_file(dest) == expected:
+ continue
+ logger.info(f"Downloading Pele {PELE_VERSION}: {rel_path}")
+ part = dest.with_name(dest.name + ".part")
+ try:
+ _download(f"{PELE_BASE_URL}/{rel_path}", part)
+ actual = _sha256_file(part)
+ if actual != expected:
+ raise RuntimeError(
+ f"Checksum mismatch for Pele {PELE_VERSION} {rel_path}: "
+ f"expected sha256 {expected}, got {actual}"
+ )
+ part.replace(dest)
+ finally:
+ part.unlink(missing_ok=True)
+ return cache
+
+
+def fetch_pele(target_dir: Path, logger: logging.Logger) -> Path:
+ """Copy Pele's browser bundle and its LICENSE into `target_dir`.
+
+ Returns the path of the copied ``pele.global.js``. The LICENSE (MIT, plus
+ the ISC notice for the Lucide icon used by the zoom controls) ships next
+ to the bundle.
+ """
+ cache = ensure_pele_bundle(logger)
target_dir.mkdir(parents=True, exist_ok=True)
- target = target_dir / "mermaid.min.js"
- shutil.copy2(cached, target)
- return target
+ for name in ("pele.global.js", "LICENSE"):
+ shutil.copy2(cache / name, target_dir / name)
+ return target_dir / "pele.global.js"
_FONT_URL_RE = re.compile(r"url\((https://fonts\.gstatic\.com/[^)]+)\)")
@@ -206,7 +262,7 @@ def write_vendor_manifest(target_dir: Path, fonts_count: int) -> None:
"""Record what was vendored — useful for debugging."""
manifest = {
"tailwind": TAILWIND_VERSION,
- "mermaid": MERMAID_VERSION,
+ "pele": PELE_VERSION,
"fonts": {
"family": ["Fraunces", "Inter", "JetBrains Mono", "Manrope"],
"files": fonts_count,
diff --git a/scripts/website_templates/page.html.j2 b/scripts/website_templates/page.html.j2
index 3175bb2..9394c18 100644
--- a/scripts/website_templates/page.html.j2
+++ b/scripts/website_templates/page.html.j2
@@ -200,16 +200,58 @@
{% endif %}
</div>
- <script src="{{ assets_prefix }}vendor/mermaid/mermaid.min.js"></script>
+ <script src="{{ assets_prefix }}vendor/pele/pele.global.js"></script>
<script>
(function () {
- if (typeof mermaid === 'undefined') return;
- var prefersDark = document.documentElement.classList.contains('dark');
- mermaid.initialize({
- startOnLoad: true,
- theme: prefersDark ? 'dark' : 'default',
- securityLevel: 'strict',
- fontFamily: 'Inter, ui-sans-serif, system-ui, sans-serif',
+ if (typeof pele === 'undefined') return;
+ // Mount each diagram into a fresh <div>, never into the <pre>: the <pre>
+ // would pass on the monospace font and the dark code-block background.
+ // Colours come from the --pele-* variables in site.css, so the theme
+ // toggle restyles diagrams without re-rendering them.
+ var headings = document.querySelectorAll(
+ 'article h1, article h2, article h3, article h4'
+ );
+ // Text of the last heading before `node` in document order.
+ function headingBefore(node) {
+ var text = '';
+ for (var i = 0; i < headings.length; i++) {
+ if (!(headings[i].compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING)) break;
+ text = headings[i].textContent.trim();
+ }
+ return text;
+ }
+ document.querySelectorAll('pre.mermaid').forEach(function (pre) {
+ var source = pre.textContent;
+ var name = headingBefore(pre) || 'Diagram';
+ var container = document.createElement('div');
+ container.className = 'mermaid';
+ pre.replaceWith(container);
+ // Zoom makes a shrunk diagram a tab stop, so it needs a name beyond
+ // its role ("flowchart"). Pele draws a new <svg> on every render
+ // (resize, font load), so name it in onRender, not once after mount.
+ function nameDiagram() {
+ var svg = container.firstElementChild;
+ if (!svg || svg.localName !== 'svg') return;
+ if (svg.hasAttribute('aria-label') || svg.hasAttribute('aria-labelledby')) return;
+ var kind = svg.getAttribute('aria-roledescription');
+ svg.setAttribute('aria-label', kind ? name + ' — ' + kind : name);
+ }
+ try {
+ var m = pele.mount(container, source, {
+ zoom: 'auto',
+ autoDirection: true,
+ onRender: nameDiagram
+ });
+ // mount() reports a diagram it cannot parse or render on m.error
+ // (showing only a short message) instead of throwing: put the
+ // readable source back.
+ if (m.error !== undefined) {
+ m.destroy();
+ container.replaceWith(pre);
+ }
+ } catch (e) {
+ container.replaceWith(pre);
+ }
});
})();
</script>
diff --git a/scripts/website_templates/site.css b/scripts/website_templates/site.css
index b2d2296..3a8e93b 100644
--- a/scripts/website_templates/site.css
+++ b/scripts/website_templates/site.css
@@ -11,8 +11,39 @@ samp {
font-family: 'JetBrains Mono', ui-monospace, monospace;
}
-/* Mermaid diagrams: centre and constrain width so they read on mobile. */
+/* Mermaid diagrams (rendered by Pele). Pele draws with the --pele-* custom
+ properties below, so the light/dark toggle on <html> restyles diagrams
+ without re-rendering them. Borders keep >= 3:1 against the page and the
+ node surface in both themes (WCAG 1.4.11). */
.mermaid {
+ --pele-font: 'Inter', ui-sans-serif, system-ui, sans-serif;
+ --pele-font-mono: 'JetBrains Mono', ui-monospace, monospace;
+ --pele-bg: #f8fafc;
+ --pele-fg: #0f172a;
+ --pele-muted: #475569;
+ --pele-line: #475569;
+ --pele-surface: #ffffff;
+ --pele-surface-alt: #f1f5f9;
+ --pele-border: #64748b;
+ --pele-accent: #0284c7;
+}
+
+.dark .mermaid {
+ --pele-bg: #020617;
+ --pele-fg: #e2e8f0;
+ --pele-muted: #94a3b8;
+ --pele-line: #94a3b8;
+ --pele-surface: #0f172a;
+ --pele-surface-alt: #1e293b;
+ --pele-border: #64748b;
+ --pele-accent: #38bdf8;
+}
+
+/* Layout applies to the mounted diagram only: a <pre class="mermaid"> left
+ in place (no JavaScript, or a diagram Pele cannot render) stays a normal,
+ readable dark code block. Centre and constrain width so diagrams read on
+ mobile. */
+div.mermaid {
background: transparent !important;
padding: 1rem 0;
margin: 1.5rem 0;
@@ -25,6 +56,22 @@ samp {
height: auto;
}
+/* Pele puts its zoom buttons (a box 56px tall, 8px below the top edge) over
+ a diagram it shrank to fit, and sets [hidden] on the box when the diagram
+ fits. Start the diagram below the box so the buttons never cover a label.
+ Room on top, not on the side: Pele lays the diagram out to the content
+ width, so side padding would shrink it further and re-lay it out. */
+div.mermaid:has(> .pele-zoom:not([hidden])) {
+ padding-top: calc(8px + 56px + 0.5rem);
+}
+
+/* Dark mode: a node whose Mermaid source sets a fill but no text colour
+ (`style A fill:#e1f5ff`) gets a light fill, so its label would inherit the
+ light --pele-fg. Give such labels dark text, as in light mode. */
+.dark .mermaid .pele-node:has(> [style*="fill:"]) > .pele-label:not([style*="fill:"]) {
+ fill: #0f172a;
+}
+
/* Prevent prose pre/code from inheriting the Tailwind dark prose background
which can clash with our slate-900 preference. */
.prose pre {
diff --git a/uk/CLAUDE.md b/uk/CLAUDE.md
index b3ccf54..87fa637 100644
--- a/uk/CLAUDE.md
+++ b/uk/CLAUDE.md
@@ -33,7 +33,7 @@ pre-commit run --all-files
4. **link-check** — Доступність зовнішніх URL (Python-скрипт)
5. **markdown-rendering** — Markdown рендериться без помилок (Python-скрипт)
-Збірка EPUB **не є** pre-commit хуком — вона виконується лише в CI (джоб `build-epub` у `.github/workflows/test.yml`), бо потребує локального бінарника `mmdc`, для якого немає робочої збірки під arm64.
+Збірка EPUB **не є** pre-commit хуком — вона виконується лише в CI (джоб `build-epub` у `.github/workflows/test.yml`), бо це повільна збірка всієї книги; хук mermaid-syntax уже рендерить кожну діаграму тим самим бандлом Pele.
### Налаштування середовища розробки
@@ -46,9 +46,11 @@ uv venv
source .venv/bin/activate
uv pip install -r scripts/requirements-dev.txt
-# Install Node.js tools (markdown linter and Mermaid validator)
+# Install Node.js tools (markdown linter)
npm install -g markdownlint-cli
-npm install -g @mermaid-js/mermaid-cli
+
+# Mermaid diagrams render with Pele: needs Node.js >= 20, no global package
+node --version
# Install pre-commit hooks
uv pip install pre-commit
@@ -87,11 +89,11 @@ mypy scripts/ --ignore-missing-imports
### Збірка EPUB
```bash
-# Generate ebook (renders Mermaid diagrams with the local mmdc CLI — no network)
+# Generate ebook (renders Mermaid diagrams with Pele — needs Node.js >= 20; the pinned bundle downloads once)
uv run scripts/build_epub.py
# With options
-uv run scripts/build_epub.py --verbose --output custom-name.epub --mmdc-path ./node_modules/.bin/mmdc
+uv run scripts/build_epub.py --verbose --output custom-name.epub
```
## Структура каталогів
@@ -108,7 +110,7 @@ uv run scripts/build_epub.py --verbose --output custom-name.epub --mmdc-path ./n
├── 09-advanced-features/ # Планування, мислення, фони
├── 10-cli/ # Довідник CLI
├── scripts/
-│ ├── build_epub.py # Генератор EPUB (рендерить Mermaid через локальний mmdc)
+│ ├── build_epub.py # Генератор EPUB (рендерить Mermaid через Pele)
│ ├── check_cross_references.py # Валідація внутрішніх посилань
│ ├── check_links.py # Перевірка зовнішніх URL
│ ├── check_mermaid.py # Валідація синтаксису Mermaid
@@ -127,7 +129,7 @@ uv run scripts/build_epub.py --verbose --output custom-name.epub --mmdc-path ./n
### Mermaid-діаграми
- Усі діаграми повинні успішно парситися (перевіряється pre-commit хуком)
-- Збірка EPUB рендерить діаграми через локальний `mmdc` CLI (інтернет не потрібен, але потрібен `mmdc`)
+- Збірка EPUB рендерить діаграми через Pele (потрібен Node.js >= 20; закріплений бандл завантажується лише під час першого запуску, далі все працює офлайн)
- Використовуйте Mermaid для блок-схем, діаграм послідовностей та архітектурних візуалізацій
### Перехресні посилання
@@ -148,7 +150,7 @@ uv run scripts/build_epub.py --verbose --output custom-name.epub --mmdc-path ./n
3. **Pre-commit — привратник** — Усі перевірки якості повинні пройти перед прийняттям PR. CI-конвеєр запускає ці ж перевірки як другий прохід.
-4. **Рендеринг Mermaid потребує локального `mmdc`** — Збірка EPUB викликає локальний `mmdc` CLI для рендерингу діаграм (мережа не потрібна). Помилки збірки тут зазвичай пов'язані з відсутнім `mmdc` або невалідним синтаксисом Mermaid. Сама збірка EPUB не виконується у pre-commit — лише в CI.
+4. **Рендеринг Mermaid потребує Node.js >= 20** — Збірка EPUB запускає закріплений бандл Pele через Node.js для рендерингу діаграм (бандл завантажується лише під час першого запуску, перевіряється за sha256 і кешується). Помилки збірки тут зазвичай пов'язані з відсутнім Node.js >= 20, невдалим завантаженням бандла або невалідним синтаксисом Mermaid. Хуки mermaid у pre-commit працюють у суворому режимі з Node.js 22, який надає сам pre-commit, тож вони падають, а не пропускають перевірку. Сама збірка EPUB не виконується у pre-commit — лише в CI.
5. **Це туторіал, а не бібліотека** — При додаванні контенту зосереджуйтесь на чітких поясненнях, готових прикладах та візуальних діаграмах. Цінність — у навчанні концепцій, а не у наданні повторно використовуваного коду.
diff --git a/uk/CONTRIBUTING.md b/uk/CONTRIBUTING.md
index a4c4f10..9ae0253 100644
--- a/uk/CONTRIBUTING.md
+++ b/uk/CONTRIBUTING.md
@@ -86,8 +86,9 @@ uv pip install -r scripts/requirements-dev.txt
# Markdown linter (Node.js)
npm install -g markdownlint-cli
-# Mermaid diagram validator (Node.js)
-npm install -g @mermaid-js/mermaid-cli
+# Mermaid diagrams render with Pele, which needs Node.js >= 20 (nothing to
+# install globally). Check your version:
+node --version
# Install pre-commit and activate hooks
uv pip install pre-commit
@@ -100,6 +101,8 @@ pre-commit install
pre-commit run --all-files
```
+Перший запуск завантажує Node.js 22 для хуків Mermaid (його надає сам pre-commit, тож вони працюють навіть без системного Node.js) і закріплений бандл Pele у `scripts/.vendor-cache/pele/`; наступні запуски працюють офлайн. Хуки Mermaid працюють у суворому режимі й падають, якщо Pele не вдається запустити. Щоб зробити коміт офлайн до першого завантаження, пропустіть їх через `SKIP=mermaid,vietnamese-mermaid,japanese-mermaid`.
+
Хуки, що запускаються при кожному коміті:
| Хук | Що перевіряє |
diff --git a/uk/STYLE_GUIDE.md b/uk/STYLE_GUIDE.md
index c87928b..095f396 100644
--- a/uk/STYLE_GUIDE.md
+++ b/uk/STYLE_GUIDE.md
@@ -395,6 +395,8 @@ ls .claude/commands/
- `sequenceDiagram` — потоки взаємодії
- `timeline` — хронологічні послідовності
+GitHub рендерить Mermaid нативно. Вебсайт і EPUB рендерять те саме джерело через [Pele](https://github.com/obsidianmd/pele) (версія закріплена в `scripts/vendor_assets.py`), а pre-commit хук `mermaid-syntax` перевіряє кожен блок тим самим бандлом, тож блок, який пройшов хук, відображається всюди.
+
### Стильові конвенції
Застосовуйте консистентні кольори за допомогою блоків стилів:
@@ -423,6 +425,8 @@ graph TB
- Використовуйте `["Label text"]` для міток вузлів (дозволяє спеціальні символи)
- Використовуйте `<br/>` для переносу рядків у мітках
+- Пишіть мітки простим текстом, а нумеровані мітки — як є (`["1. Load file"]`, без зворотної скісної риски перед крапкою)
+- Не покладайтеся на директиви `%%{init}%%` чи теми Mermaid: вебсайт застосовує власну світлу й темну палітру
- Тримайте діаграми простими (максимум 10-12 вузлів)
- Додавайте короткий текстовий опис під діаграмою для доступності
- Використовуйте зверху вниз (`TB`) для ієрархій, зліва направо (`LR`) для робочих процесів
diff --git a/uk/scripts/README.md b/uk/scripts/README.md
index 9693848..5d912c1 100644
--- a/uk/scripts/README.md
+++ b/uk/scripts/README.md
@@ -10,7 +10,7 @@
## Функції
- Організує розділи за структурою каталогів (01-slash-commands, 02-memory тощо)
-- Рендерить Mermaid-діаграми як PNG-зображення через локальний `mmdc` CLI (без мережі)
+- Рендерить Mermaid-діаграми як SVG-зображення через [Pele](https://github.com/obsidianmd/pele) — закріплений бандл, який запускає Node.js; CSS-змінні замінюються звичайними кольорами на білому тлі, тож діаграми видно в будь-якій EPUB-читалці
- Кешує однакові діаграми — кожна унікальна діаграма рендериться лише раз
- Генерує обкладинку з логотипу проєкту
- Конвертує внутрішні markdown-посилання у посилання на розділи EPUB
@@ -20,7 +20,7 @@
- Python 3.10+
- [uv](https://github.com/astral-sh/uv)
-- [`mmdc`](https://github.com/mermaid-js/mermaid-cli) у `PATH` для рендерингу Mermaid-діаграм (`npm install -g @mermaid-js/mermaid-cli`)
+- Node.js >= 20 у `PATH` для рендерингу Mermaid-діаграм. Закріплений бандл Pele завантажується під час першого запуску (мережа потрібна лише раз), перевіряється за sha256 і кешується в `scripts/.vendor-cache/pele/`
## Швидкий старт
@@ -50,17 +50,14 @@ python scripts/build_epub.py
```
usage: build_epub.py [-h] [--root ROOT] [--output OUTPUT] [--verbose]
- [--mmdc-path MMDC_PATH] [--lang {en,vi,zh,ja}]
- [--puppeteer-config PUPPETEER_CONFIG]
+ [--lang {en,vi,zh,ja}]
options:
-h, --help show this help message and exit
--root, -r ROOT Root directory (default: repo root)
--output, -o OUTPUT Output path (default: claude-howto-guide.epub)
--verbose, -v Enable verbose logging
- --mmdc-path PATH Path to mmdc binary (default: mmdc from PATH)
--lang {en,vi,zh,ja} Language to build (default: en)
- --puppeteer-config P Puppeteer config JSON passed to mmdc via -p
```
## Приклади
@@ -74,9 +71,6 @@ uv run scripts/build_epub.py --output ~/Desktop/claude-guide.epub
# Build a translated edition
uv run scripts/build_epub.py --lang vi
-
-# Point at an mmdc that is not on PATH
-uv run scripts/build_epub.py --mmdc-path ./node_modules/.bin/mmdc
```
## Вивід
@@ -87,7 +81,7 @@ EPUB включає:
- Обкладинку з логотипом проєкту
- Зміст з вкладеними секціями
- Весь markdown-контент, конвертований у EPUB-сумісний HTML
-- Mermaid-діаграми, відрендерені як PNG-зображення
+- Mermaid-діаграми, відрендерені як SVG-зображення
## Запуск тестів
@@ -116,8 +110,8 @@ uv run --with pytest --with pytest-asyncio \
## Усунення проблем
-**Збірка падає з `mmdc not found`**: Встановіть Mermaid CLI (`npm install -g @mermaid-js/mermaid-cli`) або вкажіть шлях через `--mmdc-path`. На arm64 вбудований Chromium не працює — збирайте EPUB у CI (джоб `build-epub` у `.github/workflows/test.yml`).
+**Збірка падає з `Pele is unavailable`**: Встановіть Node.js >= 20 і переконайтеся, що `node` є у `PATH` (`node --version`).
-**`mmdc` падає в CI або контейнері**: Chromium потребує профілю без пісочниці. Запишіть `{"args":["--no-sandbox","--disable-setuid-sandbox"]}` у файл і передайте його через `--puppeteer-config`.
+**Помилка завантаження або контрольної суми бандла Pele**: Перша збірка завантажує закріплений бандл Pele з cdn.jsdelivr.net і перевіряє sha256 кожного файлу. Офлайн або за проксі виконайте одну збірку з доступом до мережі; наступні збірки використовують кеш у `scripts/.vendor-cache/pele/<version>/`. Невідповідність контрольної суми означає, що завантаження змінене або обірване: видаліть цю папку й зберіть знову.
**Відсутній логотип**: Скрипт генерує текстову обкладинку, якщо `claude-howto-logo.png` не знайдено.
diff --git a/vi/CLAUDE.md b/vi/CLAUDE.md
index 0118bbf..3ede955 100644
--- a/vi/CLAUDE.md
+++ b/vi/CLAUDE.md
@@ -29,7 +29,7 @@ Năm kiểm tra là:
4. **link-check** — Các URL bên ngoài có thể truy cập được (Python script)
5. **markdown-rendering** — Markdown render không lỗi (Python script)
-Việc build EPUB **không phải** là một pre-commit hook — nó chỉ chạy trong CI (job `build-epub` trong `.github/workflows/test.yml`), vì nó cần binary `mmdc` cục bộ, vốn không có bản build hoạt động trên arm64.
+Việc build EPUB **không phải** là một pre-commit hook — nó chỉ chạy trong CI (job `build-epub` trong `.github/workflows/test.yml`), vì đây là bản build toàn bộ sách, chạy chậm; hook mermaid-syntax đã render mọi sơ đồ bằng cùng bundle Pele.
### Thiết Lập Môi Trường Phát Triển
@@ -42,9 +42,11 @@ uv venv
source .venv/bin/activate
uv pip install -r scripts/requirements-dev.txt
-# Cài đặt Node.js tools (markdown linter và Mermaid validator)
+# Cài đặt Node.js tools (markdown linter)
npm install -g markdownlint-cli
-npm install -g @mermaid-js/mermaid-cli
+
+# Sơ đồ Mermaid được render bằng Pele: cần Node.js >= 20, không cần cài package toàn cục
+node --version
# Cài đặt pre-commit hooks
uv pip install pre-commit
@@ -83,7 +85,7 @@ mypy scripts/ --ignore-missing-imports
### Build EPUB
```bash
-# Tạo ebook (render Mermaid diagrams bằng mmdc CLI cục bộ — không cần mạng)
+# Tạo ebook (render Mermaid diagrams bằng Pele — cần Node.js >= 20; bundle cố định chỉ tải về một lần)
uv run scripts/build_epub.py
# Với các tùy chọn
@@ -104,7 +106,7 @@ uv run scripts/build_epub.py --verbose --output custom-name.epub --lang vi
├── 09-advanced-features/ # Lập kế hoạch, suy nghĩ, background tasks
├── 10-cli/ # Tham chiếu CLI
├── scripts/
-│ ├── build_epub.py # EPUB generator (render Mermaid bằng mmdc cục bộ)
+│ ├── build_epub.py # EPUB generator (render Mermaid bằng Pele)
│ ├── check_cross_references.py # Xác thực liên kết nội bộ
│ ├── check_links.py # Kiểm tra các URL bên ngoài
│ ├── check_mermaid.py # Xác thực cú pháp Mermaid
@@ -124,7 +126,7 @@ Mỗi thư mục đánh số tuân theo pattern:
### Sơ Đồ Mermaid
- Tất cả sơ đồ phải parse thành công (được kiểm tra bởi pre-commit hook)
-- EPUB build render sơ đồ bằng `mmdc` CLI cục bộ (không cần internet, nhưng cần cài `mmdc`)
+- EPUB build render sơ đồ bằng Pele (cần Node.js >= 20; bundle cố định chỉ tải về trong lần chạy đầu tiên, sau đó chạy offline)
- Sử dụng Mermaid cho flowcharts, sequence diagrams, và architecture visuals
### Cross-References
@@ -145,7 +147,7 @@ Mỗi thư mục đánh số tuân theo pattern:
3. **Pre-commit là người gác cổng** — Tất cả năm kiểm tra chất lượng phải pass trước khi PR được chấp nhận. CI pipeline chạy các kiểm tra tương tự như lần thứ hai.
-4. **Mermaid rendering cần `mmdc` cục bộ** — EPUB build gọi `mmdc` CLI cục bộ để render diagrams (không cần network). Các lỗi build ở đây thường là do chưa cài `mmdc` hoặc cú pháp Mermaid không hợp lệ. Bản thân EPUB build không chạy trong pre-commit — nó chỉ chạy trong CI.
+4. **Mermaid rendering cần Node.js >= 20** — EPUB build chạy bundle Pele cố định bằng Node.js để render diagrams (bundle chỉ tải về trong lần chạy đầu tiên, được kiểm tra sha256 và lưu cache). Các lỗi build ở đây thường là do chưa cài Node.js >= 20, tải bundle thất bại, hoặc cú pháp Mermaid không hợp lệ. Các hook mermaid của pre-commit chạy ở chế độ strict với Node.js 22 do pre-commit cung cấp, nên chúng sẽ báo lỗi thay vì bỏ qua. Bản thân EPUB build không chạy trong pre-commit — nó chỉ chạy trong CI.
5. **Đây là tutorial, không phải thư viện** — Khi thêm nội dung, tập trung vào giải thích rõ ràng, ví dụ copy-paste, và sơ đồ trực quan. Giá trị nằm ở việc dạy các khái niệm, không cung cấp code có thể tái sử dụng.
diff --git a/vi/CONTRIBUTING.md b/vi/CONTRIBUTING.md
index d9d9c50..a0331ab 100644
--- a/vi/CONTRIBUTING.md
+++ b/vi/CONTRIBUTING.md
@@ -82,8 +82,9 @@ uv pip install -r scripts/requirements-dev.txt
# Markdown linter (Node.js)
npm install -g markdownlint-cli
-# Mermaid diagram validator (Node.js)
-npm install -g @mermaid-js/mermaid-cli
+# Sơ đồ Mermaid được render bằng Pele, cần Node.js >= 20 (không cần cài
+# package toàn cục). Kiểm tra phiên bản:
+node --version
# Install pre-commit và activate hooks
uv pip install pre-commit
@@ -96,6 +97,8 @@ pre-commit install
pre-commit run --all-files
```
+Lần chạy đầu tiên sẽ tải Node.js 22 cho các hook Mermaid (do pre-commit cung cấp, nên chúng vẫn chạy được khi máy không có Node.js) và bundle Pele cố định vào `scripts/.vendor-cache/pele/`; các lần sau chạy offline. Các hook Mermaid chạy ở chế độ strict và báo lỗi nếu không chạy được Pele. Để commit offline trước lần tải đầu tiên, hãy bỏ qua chúng bằng `SKIP=mermaid,vietnamese-mermaid,japanese-mermaid`.
+
Các hooks chạy trên mỗi commit là:
- Kiểm tra markdown-lint
- Kiểm tra cross-references
diff --git a/vi/STYLE_GUIDE.md b/vi/STYLE_GUIDE.md
index dfe18c7..f8d4baf 100644
--- a/vi/STYLE_GUIDE.md
+++ b/vi/STYLE_GUIDE.md
@@ -205,6 +205,9 @@ graph TD
### Quy Tắc / Rules
- Sử dụng Mermaid cho tất cả các sơ đồ
+- GitHub render Mermaid trực tiếp; website và EPUB render cùng mã nguồn bằng [Pele](https://github.com/obsidianmd/pele) (phiên bản cố định trong `scripts/vendor_assets.py`), và hook `mermaid-syntax` của pre-commit kiểm tra mọi block bằng cùng bundle đó
+- Viết nhãn bằng văn bản thuần, nhãn có đánh số giữ nguyên (`["1. Load file"]`, không thêm dấu gạch chéo ngược trước dấu chấm)
+- Không dựa vào chỉ thị `%%{init}%%` hay theme của Mermaid: website dùng bảng màu sáng/tối riêng
- Giữ sơ đồ đơn giản và dễ hiểu
- Thêm mô tả text khi cần thiết
- Test tất cả các sơ đồ trước khi commit
diff --git a/zh/CONTRIBUTING.md b/zh/CONTRIBUTING.md
index 59ee92f..1bc9771 100644
--- a/zh/CONTRIBUTING.md
+++ b/zh/CONTRIBUTING.md
@@ -82,8 +82,9 @@ uv pip install -r scripts/requirements-dev.txt
# Markdown lint 工具(Node.js)
npm install -g markdownlint-cli
-# Mermaid 图表校验器(Node.js)
-npm install -g @mermaid-js/mermaid-cli
+# Mermaid 图表由 Pele 渲染,需要 Node.js >= 20(无需全局安装任何包)。
+# 检查版本:
+node --version
# 安装 pre-commit 并启用 hooks
uv pip install pre-commit
@@ -96,6 +97,8 @@ pre-commit install
pre-commit run --all-files
```
+首次运行时会为 Mermaid hooks 下载 Node.js 22(由 pre-commit 提供,因此即使系统没有 Node.js 也能运行),并把固定版本的 Pele 包下载到 `scripts/.vendor-cache/pele/`;之后的运行可以离线完成。Mermaid hooks 以严格模式运行,如果 Pele 无法运行就会失败。如需在首次下载之前离线提交,可以用 `SKIP=mermaid,vietnamese-mermaid,japanese-mermaid` 跳过它们。
+
每次提交都会运行这些 hooks:
| Hook | 检查内容 |
diff --git a/zh/STYLE_GUIDE.md b/zh/STYLE_GUIDE.md
index 4dc8cc8..7dcff36 100644
--- a/zh/STYLE_GUIDE.md
+++ b/zh/STYLE_GUIDE.md
@@ -391,6 +391,8 @@ ls .claude/commands/
- `sequenceDiagram` - 交互流程
- `timeline` - 时间顺序
+GitHub 会原生渲染 Mermaid。网站和 EPUB 使用 [Pele](https://github.com/obsidianmd/pele)(版本固定在 `scripts/vendor_assets.py` 中)渲染同一份源码,pre-commit 的 `mermaid-syntax` hook 也用同一个包校验每个代码块,所以通过 hook 的代码块在各处都能正常显示。
+
### 样式约定
使用 style block 保持颜色一致:
@@ -419,6 +421,8 @@ graph TB
- 节点标签使用 `["Label text"]`,这样可以包含特殊字符
- 在标签中换行使用 `<br/>`
+- 标签使用纯文本,编号标签按原样书写(`["1. Load file"]`,句点前不要加反斜杠)
+- 不要依赖 `%%{init}%%` 指令或 Mermaid 主题:网站会应用自己的浅色和深色配色
- 图表保持简洁,最多 10-12 个节点
- 图表下方添加简短文字说明,方便无障碍阅读
- 层级结构使用自上而下(`TB`),流程使用左右(`LR`)
diff --git a/zh/scripts/README.md b/zh/scripts/README.md
index 7623e1c..da35989 100644
--- a/zh/scripts/README.md
+++ b/zh/scripts/README.md
@@ -9,6 +9,7 @@
- Python 环境
- `uv`
- 相关依赖
+- Node.js >= 20(Mermaid 图表由固定版本的 Pele 渲染,首次运行时下载并缓存到 `scripts/.vendor-cache/pele/`)
## 快速开始
@@ -67,3 +68,4 @@ uv run scripts/build_epub.py
- 检查 `uv` 是否可用
- 检查 Python 版本
- 检查依赖是否安装完整
+- 检查 `node --version` 是否 >= 20;首次构建需要联网下载 Pele 包