Compare commits

..

1 Commits

Author SHA1 Message Date
github-actions[bot] a3c0b413f3 Version Packages 2026-11-25 12:43:47 +00:00
97 changed files with 340 additions and 2789 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep links in generated Markdown usable outside the source page.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Handle optional emoji and icon values when rendering tags.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Point agents to the site MCP server from Markdown pages, the page HTML, llms.txt and llms-full.txt.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Serve the site AI Catalog as specification version 0.9, with identifiers in its `urn:air:{publisher}:{name}:{kind}` format.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fade the bottom of collapsed code blocks so readers can tell there is more code, matching the editor.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Answer Assistant questions with medium reasoning instead of low, matching AI search.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Bump Next.js to 16.4.6 and OpenNext (Cloudflare 1.20.17, AWS 4.1.16), keeping the dev-mode OOM patch.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Bump `@opennextjs/aws` to 4.2.0 and `@opennextjs/cloudflare` to 1.20.18.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix horizontal page scroll caused by card carousels bleeding past the viewport.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Name a site's MCP server as docs, such as "Acme Docs MCP Server", in AI clients and in the install commands and links, so it is not confused with a product's own MCP server.
-6
View File
@@ -1,6 +0,0 @@
---
"@gitbook/embed": minor
"gitbook": patch
---
Emit an `escape` event from the Docs Embed when Escape is pressed inside it and nothing in the embed used it, so the host can close its own panel.
@@ -1,6 +0,0 @@
---
"@gitbook/embed": minor
"gitbook": patch
---
Use the site's suggested questions when the embedded Assistant receives an empty or omitted list, including from older SDKs.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Reduce the wait after typing in site search to 100 ms.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Prevent self-redirect loops and skip redirects targeting hidden adaptive content.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix the table of contents keeping published pages busy in older Chrome versions such as Chrome 130.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix `'use cache'` entries never being stored in or read from R2 and the regional cache on Cloudflare.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Remove duplicated declarations from the global stylesheet.
@@ -1,5 +0,0 @@
---
"@gitbook/icons": minor
---
Add a `@gitbook/icons/validateIconName` entry that validates icon names without loading the icon labels and search terms.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep inline code and highlighted text readable when a paragraph crosses the bottom edge of a background page cover.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep published pages available when an integration block needs its connection or settings checked.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep published site search results visible while visitors refine a query.
@@ -1,6 +0,0 @@
---
"gitbook": patch
"@gitbook/icons": patch
---
Add a skip link, keyboard navigation between content tabs, focusable table of contents toggles, and hide decorative icons from assistive technologies.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Apply the default language-aware search scope to legacy search links.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Reduce memory and CPU use of the OpenNext workers: minify the middleware, resolve the site context once per request, cache parsed OpenAPI descriptions across a spec, drop the redis client and the unused force-revalidate route from the server bundle.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Load the OpenAPI stylesheet only on pages with OpenAPI blocks.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Render the llms.txt directive as the first element in the page body so agents find it before the navigation.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Count only MCP tool calls in the MCP request insights event.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Answer GET requests to the MCP endpoint with an `Allow: POST` header.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Challenge MCP clients to authorize again when a visitor-auth site rejects their bearer token.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Support MCP protocol version 2025-11-25 on published site MCP servers.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Limit the MCP `searchDocumentation` tool to one language: the one the client passes in the new optional `language` argument, or else the language of the site variant the MCP endpoint is served from.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Flush insights events when the page is hidden, preload the search index at low priority and prioritize the dark page cover on dark-default sites.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep published revision URLs out of search results.
@@ -1,5 +0,0 @@
---
"@gitbook/react-openapi": patch
---
Copy the current spec's server in OpenAPI endpoint URLs instead of a server kept from a previously visited page.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Resolve GitBook links in OpenAPI schema descriptions to the site's published URLs instead of the editor.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Publish an OpenSearch description on every site so browsers can offer its search from the address bar.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show H3 headings in the page outline.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Render a page's search keywords in its metadata.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": minor
---
Open a link in the same or a new tab when its author chose one, instead of the site-wide external links setting.
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': patch
---
Respect disabled change request previews on published sites.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix the search button accessible name, hoverable link previews, IME-safe Enter on Safari, cookie banner semantics, active outline item announcement and textarea shrinking.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Send change request and revision links to the site preview, where GitBook members can sign in, when a site turns off public change request previews.
@@ -1,6 +0,0 @@
---
"gitbook": patch
"@gitbook/embed": patch
---
Respect reduced motion for enter and exit animations, keep the header separator and input focus visible in forced colors mode, and size mobile surfaces with dynamic viewport units.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Send only the site origin as referrer to third parties, and only let the embedding page open the embed messaging channel.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Remove the ChatGPT-specific plain text response for Markdown and llms.txt routes; these now always serve `text/markdown`.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Drop description HTML supplied by OpenAPI specs and sanitize example descriptions that could render HTML.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Track the displayed position and search request ID when a visitor opens a search result.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Send site searches straight to the search API when the site hands out a search pass, and use the site's search route when it does not or when the API refuses a search.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Include navigation-hidden published spaces in direct browser search lookup and avoid latching on unknown spaces.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Send each search once on sites without a top header, and make search work between 768 and 1023 px wide.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show loading rows shaped like search results while search waits for the server.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show search results with one-line breadcrumbs and no icons or shortcut hints, and select the result under the mouse.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Stop caching site search results in the framework cache, so every search reaches the API.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show one server-ordered search list and open its top result on Enter.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Load the data of the page actions menu from the menu itself, so it can be cached apart from the page body.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Load Shiki languages and themes from static assets instead of bundling them.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Follow the API's cache lifetime for site data, so a site preview shows layout changes soon after they are saved.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show site revision previews as their site revision pins them, including OpenAPI specs.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Render small cards in a responsive four-column grid and carousel.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Ignore tag category references when displaying assigned tags and update filters.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Update the GitBook API SDK for site revision responses.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix wide content in Updates blocks overflowing into the page outline.
+32 -32
View File
@@ -49,7 +49,7 @@
},
"packages/embed": {
"name": "@gitbook/embed",
"version": "0.7.0",
"version": "0.8.0",
"dependencies": {
"@gitbook/api": "catalog:",
"bidc": "catalog:",
@@ -109,7 +109,7 @@
},
"packages/gitbook": {
"name": "gitbook",
"version": "0.28.2",
"version": "0.29.0",
"dependencies": {
"@base-ui/react": "catalog:",
"@cloudflare/workers-types": "^4.20251011.0",
@@ -228,7 +228,7 @@
},
"packages/icons": {
"name": "@gitbook/icons",
"version": "0.5.0",
"version": "0.6.0",
"bin": {
"gitbook-icons": "./bin/gitbook-icons.js",
},
@@ -266,7 +266,7 @@
},
"packages/react-contentkit": {
"name": "@gitbook/react-contentkit",
"version": "0.7.18",
"version": "0.7.19",
"dependencies": {
"@gitbook/api": "catalog:",
"@gitbook/icons": "workspace:*",
@@ -309,7 +309,7 @@
},
"packages/react-openapi": {
"name": "@gitbook/react-openapi",
"version": "2.0.1",
"version": "2.0.2",
"dependencies": {
"@base-ui/react": "catalog:",
"@gitbook/expr": "workspace:*",
@@ -1023,43 +1023,43 @@
"@oxfmt/binding-win32-x64-msvc": ["@oxfmt/binding-win32-x64-msvc@0.62.0", "", { "os": "win32", "cpu": "x64" }, "sha512-dlI5SY7XYQCiCBafntWagCR6HcAJB/NpsLtdlPx8x08+Osz8Ok1HHz1GZuusegCe/VoJ6pAnF5a4pd5OZAq7qQ=="],
"@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.93.0", "", { "os": "android", "cpu": "arm" }, "sha512-KKw70pbD5Pvq3G2lJ+WQ71XPMjCmg37rkSe2+mDqCRP3PoTSdDMuEi4UOnE8JBtyNM7bek61EC2s0Jt7S7u+Sg=="],
"@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.95.0", "", { "os": "android", "cpu": "arm" }, "sha512-hJna6w3COWJjfMPxomjZL82klTdrITm56PEpCsfO/xMkzQw/fNtJWauQ/YEwQqVttj0L5vDIa8rCcuhfAE3L4w=="],
"@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.93.0", "", { "os": "android", "cpu": "arm64" }, "sha512-fvr1fTUZGelwRxKDt64pf28aL1WaWgviwz3X+E/FcRYvrlEahH0NECRz/c1SY+K+KWmZk5uAf6h1kQnyBkp/2A=="],
"@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.95.0", "", { "os": "android", "cpu": "arm64" }, "sha512-uAIGZQ9uJVUeogeWOSboI3F7twOuM4mNuZcHXD9+LdYLcWp7J6kbtRUXJ6GVqcs5E0Cjb4emmSBK9FNrkGuhqQ=="],
"@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.93.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-VdvSN9JRf4Es6ZzoAdvEeh8tgKdw8L4H82WmA8MMPVfPdZGCwE/nI27Z1HrRHYQhPxOh4kmnxQEioSUFrOvDaw=="],
"@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.95.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Ogh1vfHO5vshKRop/He46r+WqC5BTqonYwhB4fp9e2gvOFvg1Xi6XsHTuM/lBSH85ZcaG+DS99EMAy9GcwDong=="],
"@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.93.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-QR1V890Ml0YGRG0F/iV0K9igG+pOhe+VWd+aZnxY849rRHZf3F2gEoQks5+GVHf105X9Mh/6HdShTP5juekG2g=="],
"@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.95.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-kTrE1xfpQUBMMS50Ws6KY92N8OsJ8LE6JqxKqkHEY3KdsmguQ6kKVGSjzyt1HLwsSi0fQCvNRog8YRBBovD1AA=="],
"@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.93.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-jDfIbi30zZaKi+rTvig3sge+Xhi8pFFSgHxb0jzovc4qh8ETm/irKV9c7N/JsuwnYc5sbvf4IC8w1vQQ0IL+BA=="],
"@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.95.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-ho7E1VCInK0VnpneRaI1BEpe1ceJE8VjxP2O9THWdReV6bth1Q4+80kYVGGK47mHRyZ2NGztQZ2dWRo6j1lavA=="],
"@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.93.0", "", { "os": "linux", "cpu": "arm" }, "sha512-qtxZ714ND/koFgVH00QgxlzZiIbRPmguaPhnHRU5DFFtrtEdOrSnZD4U/H2AzXrXkZ59eQbMBnJwbum5XohrIQ=="],
"@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.95.0", "", { "os": "linux", "cpu": "arm" }, "sha512-94afnouMHcnHr/OtRh07gG5LehC9M0GjiSoik3xxTtrmq6cWxXOTAhYlBtxa67u/GlycbnHlDoGJfYlTshcr/w=="],
"@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.93.0", "", { "os": "linux", "cpu": "arm" }, "sha512-5pJ9NjMvH7WMUqXB6bTTOSemBm39w2cod27Hu3+Yom/GhbTeNXlYcpDx1o4CgBP6fhp0YHG66TNdVaUm6sHjsA=="],
"@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.95.0", "", { "os": "linux", "cpu": "arm" }, "sha512-LEeclqV1/fafxPgJWN21Bri6HBBBZpEFluq/ZH7Avvu9HjJh/XOn6WwogJqX9X7pG2aITZ2nRH39+sUKEQt2WA=="],
"@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.93.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-pRf+7jtbt2fHE23SX7qBxRgnBZicUgsoCK1PVIjnOk+t3a6UBkpt/GrKI99WlxsKUxftz/5nv/kfKvScmYywkw=="],
"@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.95.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-EpXpEQKmgtkvc6RyU84LM1e3CrVDWQkgghVzf1hMGgwjBzgKAJ/QntHgnzmu5cNeLBfa7GPCY+gGXxEll8Adcg=="],
"@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.93.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-zM8Fd/K8sqGvsBcJBZ3oVZ3ctGWbszA08IaGt5gFFF5RcunppAI/ZnAXbouABvnWeJ//S44KKlfPZnDDbeiphg=="],
"@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.95.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-+96Md8c2BAgFp8nWHrUrpqba87DoU+HVJYIun6qA+QKFoeNd3xAWq1JYE6da4nVli9GgwRpfncfRePcgmQQaIQ=="],
"@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.93.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-7qKCnvhZKDXJG2pdbLazd2hw4FxjJHbZOFrrbzyy5PdHfPLH9vnNUa1le01A8uItZuYKPBPncH+HCoEiFT4SgA=="],
"@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.95.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-6yG99vsXct3Uv536w6Z1s03w2makRKnE0q3eJSmf+W/IwPmO56QLk8XUA6ebu/R5peCbJ67HmcWqACH+kg/6Bg=="],
"@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.93.0", "", { "os": "linux", "cpu": "none" }, "sha512-2pgulxC6G8V5wE750NJE/fRkf9aO6i6yoj10wyaR2EdiNtan4OemsOtsQ0ZTXGdY8Q3IoTmlND3GYvjJsvikYg=="],
"@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.95.0", "", { "os": "linux", "cpu": "none" }, "sha512-Eir0Z4ldh55AsQUqVDlLF4Pw3lSFXIdAl8ZNgU8tp/gTwT9JVCzWY0o3+ys9pCcpTN0vCqBwwuQfAUxzbIgvcQ=="],
"@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.93.0", "", { "os": "linux", "cpu": "none" }, "sha512-yWsn6Gg2PnGG5jlyDz5+pHGiMTMiy4adaa4WRMzDgzB8efaShk1JMmTHIBSVLQMh0tYXRs4CN5uJCO79r4Mi4g=="],
"@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.95.0", "", { "os": "linux", "cpu": "none" }, "sha512-ceRx+K2WJ7C3tIv+XjZS28oAoZ7DY29ZcWChPdXG5M100phI72FRDYwGRlWZEeDfmkROnarLTMKnnrQAtsC42Q=="],
"@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.93.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-WCn5plwp/ezS2RDPQKp0/EXEVRr9/dDexUdRKmsMFqzNM5xBSZ1wbsi3PuMk1VfkMRnI5BuazCsziCWMXRDOlw=="],
"@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.95.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-WbD3sM08ZDk2QE6060wK/omihQKbRm+LVzKIg4W5zNTbEhYJChciqX49UZuqW59RGF+wBUxzAup7egUIESTjUA=="],
"@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.93.0", "", { "os": "linux", "cpu": "x64" }, "sha512-F2CGjb9LAkzH+IYTZSzd1klQ1vk5z6Utjax64WeLByCkYXbVDbsun+Oy2hLfW2MDSKCvW+jwy/9ld0EPgdeu+A=="],
"@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.95.0", "", { "os": "linux", "cpu": "x64" }, "sha512-F4ST2ZkFIiLL9OKyRCyC0KQQpwM5WIv0GTcMiZuYVa6xSRJHR05iVRqst+arOVudEPkhP47EnbuoC9UfVCYDyg=="],
"@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.93.0", "", { "os": "linux", "cpu": "x64" }, "sha512-plf5DE2objcG8Tf7mXRuRa8tT8rzDkpjqXQtKoGsKHWkpgsialbON1+cCtoSEUTVbQUjXvuAm8vV9+3rR0yCBw=="],
"@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.95.0", "", { "os": "linux", "cpu": "x64" }, "sha512-hEpYDZatpuxLrWlTlkwhHZ1e8QkL02aFS55BPQX1XA9iOd+yUEADGFF1iY6z+xkw6RkpzXFrtnDFe4/JNOLSRA=="],
"@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.93.0", "", { "os": "none", "cpu": "arm64" }, "sha512-Kp2yJrKvoTe9FfKdO/xwLNUbs2bYTMKx0+aoQD1s0h/Tx0kSgtHSdGmrk8tTKdluosjFbo88qYRIaNIX43AfFw=="],
"@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.95.0", "", { "os": "none", "cpu": "arm64" }, "sha512-+JwIH9/uLgQXfxBvOAKzvp616m5i0fBR5ELEBHm5D+++fStBZ+74T7YW4xBpX13zNU2blr52Swoe3GTF1JyqRg=="],
"@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.93.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-vigjcHCFsR6KjnWTEVfaCxcMYapEuaK9FZa1MpewwQ1S+Xud3v0okfkj1RySsD6RF1NRHIjSlQSalTnKIaj3nA=="],
"@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.95.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-pzJgcp3WkOSchukg5y5pn5mVIQ6P83RDI79YJ9gQZKed1pOgjhrmlc5AMizjuq6/P8VifhxzBsMqYI6LLjO2TA=="],
"@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.93.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-0Ot3BEe/AAr2/uQhe55r8CmPlperYk2mQmxdutOru7oU0kir6IiEVHb1TG3GORRlfra97lPHVDLhgmihiKzLrg=="],
"@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.95.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-54MeQvLRXkJqF1nEFs7wb73SrnurZJQy9fVK4NdEwumNKVwyUUxpGHhvfDMIY2NqJZS7kz0pY9uVty5664Gt1Q=="],
"@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.93.0", "", { "os": "win32", "cpu": "x64" }, "sha512-ZzzIIVs/Qkm8trUWYKF0OYub5ALlv50/3gsEZbKAvWgz+yNJX6uRmQ8ySPXU2Q0/Y9m4JCOjhpmC8XUYbPHX5Q=="],
"@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.95.0", "", { "os": "win32", "cpu": "x64" }, "sha512-I/Fn+Fed1qzb1k2uRjMe2VRtRN1+ZObyU+E76B6v/Ul3Z6JdeAW5zBHSe0n5d8a0ZyU4iorzVy0Rw9LYgo3MSQ=="],
"@panzoom/panzoom": ["@panzoom/panzoom@4.6.1", "", {}, "sha512-ogf/KhHHjj+DYAvHfaf3TXMQ8OE36pJtKpabLlx1OmpjcgtpCvkUoCiNONA8kuVRPGJdLiqMf0n8LRFXj1OyuA=="],
@@ -1365,17 +1365,17 @@
"@tsconfig/strictest": ["@tsconfig/strictest@2.0.6", "", {}, "sha512-tPOhmDhIUcDjvpDDYyiUdssP84Eqm7n5KxJe5J3/g+s6xoDIPAf+SIn06dhw7VkhxIvLOnhDDrX7tsqMHNEhDg=="],
"@turbo/darwin-64": ["@turbo/darwin-64@2.11.11", "", { "os": "darwin", "cpu": "x64" }, "sha512-HMMeUIEAsmyIbSYn1ySvF/4gGMa0joiTMq4dQDuloIAnOpbtFT3JEiVsYnASdTWDXvplbRbZlqjU1EBeSR9G1A=="],
"@turbo/darwin-64": ["@turbo/darwin-64@2.11.13", "", { "os": "darwin", "cpu": "x64" }, "sha512-5IT29i4j55E5O66+la7L8Y46ut7dFaNZqrgUIYYNtcpMt9Ql7aYnSQb/6tZ+prE2AfX1RBCAtRJE41txS2rG3w=="],
"@turbo/darwin-arm64": ["@turbo/darwin-arm64@2.11.11", "", { "os": "darwin", "cpu": "arm64" }, "sha512-+8iySNgqYWY6PZYUQzYu6zn0C04z2OEq1vQ6oMGsJ9sxN6wOpg1gzi1AJ5VKDHviWvMUjhqng51hTEQZOuiqYQ=="],
"@turbo/darwin-arm64": ["@turbo/darwin-arm64@2.11.13", "", { "os": "darwin", "cpu": "arm64" }, "sha512-YFJPayVNlhSPRIZSeERiZYGKKqPs6N6qGhim8J3GtBdv5ZjUNF1ixfnAAyCVTqFEnMSkn1W7F0Y07kca8EjWsg=="],
"@turbo/linux-64": ["@turbo/linux-64@2.11.11", "", { "os": [ "linux", "android", ], "cpu": "x64" }, "sha512-uImTKFYCFKsoFxjaXeJXlMPv4uU3OIIDjyzoIwYVqOtu9LnCZ/5/fzu/WP6+G9YfwGAPRplTHkKFfcI5t97RGw=="],
"@turbo/linux-64": ["@turbo/linux-64@2.11.13", "", { "os": [ "linux", "android", ], "cpu": "x64" }, "sha512-R5RIQflV4ffBDNuUwjmtmzIr6Y2UeyeeHTtultYF7cnFn3tG1RZ4GRBlpjUhHB6JxuR7l1B450hlbzdtlD3ghg=="],
"@turbo/linux-arm64": ["@turbo/linux-arm64@2.11.11", "", { "os": [ "linux", "android", ], "cpu": "arm64" }, "sha512-Y7xffSVfyyYRGzNy6PLdrFL4xXN6iTuR3W0SyJvH/yd3d4defA6dansZwJpPDVnIpD8a2Qn256DwY/Qin4Ip4g=="],
"@turbo/linux-arm64": ["@turbo/linux-arm64@2.11.13", "", { "os": [ "linux", "android", ], "cpu": "arm64" }, "sha512-AwV8pVO/cH/lwx1B7SGfzUA/3e6vmPaygFp9NOSRESs6t3Wr63zrBuXlluDogAOIxIMlHDB2ZbBueDsBnQxh2Q=="],
"@turbo/windows-64": ["@turbo/windows-64@2.11.11", "", { "os": "win32", "cpu": "x64" }, "sha512-e2WqNtkPGo3QDwNNwwBo89Dx3PtSJ9Wp9QuRNzn80rrRnSHB+1mfBMZTpdHjA8/G/sG9rl76TdWdpgVsimjRdg=="],
"@turbo/windows-64": ["@turbo/windows-64@2.11.13", "", { "os": "win32", "cpu": "x64" }, "sha512-PGXYTaFaN3FZloe4RffNGJmfB+TIWlqQgKK1PVyKwPN+PUzxGa+byxHBWFHredMaVbnUc6L/F6/QR4iHyM/wug=="],
"@turbo/windows-arm64": ["@turbo/windows-arm64@2.11.11", "", { "os": "win32", "cpu": "arm64" }, "sha512-LURivfmgv34Osm8NR1gZGx4vdlux9KAgRM+FoooXNG0838ff0+akWZ76iPSke0NS2rsf7Z4Gw+YSaygzNTZuRA=="],
"@turbo/windows-arm64": ["@turbo/windows-arm64@2.11.13", "", { "os": "win32", "cpu": "arm64" }, "sha512-YdRHWstBUHWt/eChOEM4f9LT0dPiWK5SNgtV77bLCr3JNke9M5E7metqelNYj+tXe36dH0BZrk2CMnFlWqHKng=="],
"@tusbar/cache-control": ["@tusbar/cache-control@1.0.2", "", {}, "sha512-PXfjYTYBVvMPYCLDWj+xIOA9ITFbbhWCHzLcqUCJ5TPGm4JO4cxpGb7x3K8Q1K1ADgNgfBxLsDcTMVRydtZB9A=="],
@@ -2689,7 +2689,7 @@
"oxfmt": ["oxfmt@0.62.0", "", { "dependencies": { "tinypool": "2.1.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.62.0", "@oxfmt/binding-android-arm64": "0.62.0", "@oxfmt/binding-darwin-arm64": "0.62.0", "@oxfmt/binding-darwin-x64": "0.62.0", "@oxfmt/binding-freebsd-x64": "0.62.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.62.0", "@oxfmt/binding-linux-arm-musleabihf": "0.62.0", "@oxfmt/binding-linux-arm64-gnu": "0.62.0", "@oxfmt/binding-linux-arm64-musl": "0.62.0", "@oxfmt/binding-linux-ppc64-gnu": "0.62.0", "@oxfmt/binding-linux-riscv64-gnu": "0.62.0", "@oxfmt/binding-linux-riscv64-musl": "0.62.0", "@oxfmt/binding-linux-s390x-gnu": "0.62.0", "@oxfmt/binding-linux-x64-gnu": "0.62.0", "@oxfmt/binding-linux-x64-musl": "0.62.0", "@oxfmt/binding-openharmony-arm64": "0.62.0", "@oxfmt/binding-win32-arm64-msvc": "0.62.0", "@oxfmt/binding-win32-ia32-msvc": "0.62.0", "@oxfmt/binding-win32-x64-msvc": "0.62.0" }, "peerDependencies": { "svelte": "^5.0.0", "vite-plus": "*" }, "optionalPeers": ["svelte", "vite-plus"], "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-vxgGHTmnDU9j4CX7dDBLzxgmHxfda/yPcgJkGCMUSCwRmz+euo/V08xXLNgXTeqAB9Fhf3Pe2nO1RNKLCVgphQ=="],
"oxlint": ["oxlint@1.93.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.93.0", "@oxlint/binding-android-arm64": "1.93.0", "@oxlint/binding-darwin-arm64": "1.93.0", "@oxlint/binding-darwin-x64": "1.93.0", "@oxlint/binding-freebsd-x64": "1.93.0", "@oxlint/binding-linux-arm-gnueabihf": "1.93.0", "@oxlint/binding-linux-arm-musleabihf": "1.93.0", "@oxlint/binding-linux-arm64-gnu": "1.93.0", "@oxlint/binding-linux-arm64-musl": "1.93.0", "@oxlint/binding-linux-ppc64-gnu": "1.93.0", "@oxlint/binding-linux-riscv64-gnu": "1.93.0", "@oxlint/binding-linux-riscv64-musl": "1.93.0", "@oxlint/binding-linux-s390x-gnu": "1.93.0", "@oxlint/binding-linux-x64-gnu": "1.93.0", "@oxlint/binding-linux-x64-musl": "1.93.0", "@oxlint/binding-openharmony-arm64": "1.93.0", "@oxlint/binding-win32-arm64-msvc": "1.93.0", "@oxlint/binding-win32-ia32-msvc": "1.93.0", "@oxlint/binding-win32-x64-msvc": "1.93.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2005", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-19JMsQFX+YvEbcUTFQxjTwhvs0Ibg0D6CFneSLgpwnACWcY/6LjhpGpkPodh0T5aIT1pjMTLlYaeBFzaVgugTA=="],
"oxlint": ["oxlint@1.95.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.95.0", "@oxlint/binding-android-arm64": "1.95.0", "@oxlint/binding-darwin-arm64": "1.95.0", "@oxlint/binding-darwin-x64": "1.95.0", "@oxlint/binding-freebsd-x64": "1.95.0", "@oxlint/binding-linux-arm-gnueabihf": "1.95.0", "@oxlint/binding-linux-arm-musleabihf": "1.95.0", "@oxlint/binding-linux-arm64-gnu": "1.95.0", "@oxlint/binding-linux-arm64-musl": "1.95.0", "@oxlint/binding-linux-ppc64-gnu": "1.95.0", "@oxlint/binding-linux-riscv64-gnu": "1.95.0", "@oxlint/binding-linux-riscv64-musl": "1.95.0", "@oxlint/binding-linux-s390x-gnu": "1.95.0", "@oxlint/binding-linux-x64-gnu": "1.95.0", "@oxlint/binding-linux-x64-musl": "1.95.0", "@oxlint/binding-openharmony-arm64": "1.95.0", "@oxlint/binding-win32-arm64-msvc": "1.95.0", "@oxlint/binding-win32-ia32-msvc": "1.95.0", "@oxlint/binding-win32-x64-msvc": "1.95.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2008", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-eNzjFjm1TU02/+ohAJjOB7aekRQgTXhOWxMGscEm8VJMokNnnix+PCZn7kqIuGIqxAoBnHxatqlN3Chz3N6PKA=="],
"p-filter": ["p-filter@2.1.0", "", { "dependencies": { "p-map": "^2.0.0" } }, "sha512-ZBxxZ5sL2HghephhpGAQdoskxplTwr7ICaehZwLIlfL6acuVgZPm8yBNuRAFBGEqtD/hmUeq9eqLg2ys9Xr/yw=="],
@@ -3121,7 +3121,7 @@
"tsx": ["tsx@4.21.0", "", { "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw=="],
"turbo": ["turbo@2.11.11", "", { "optionalDependencies": { "@turbo/darwin-64": "2.11.11", "@turbo/darwin-arm64": "2.11.11", "@turbo/linux-64": "2.11.11", "@turbo/linux-arm64": "2.11.11", "@turbo/windows-64": "2.11.11", "@turbo/windows-arm64": "2.11.11" }, "bin": { "turbo": "bin/turbo" } }, "sha512-AI4UJbUE/2cVZdoXJ4PODc8qvrjhQQX9Fa93eKGOI6Ims/w7+kUIb9T1jhlgSnZcf+gtUruci/ohSwqtNNC5Yw=="],
"turbo": ["turbo@2.11.13", "", { "optionalDependencies": { "@turbo/darwin-64": "2.11.13", "@turbo/darwin-arm64": "2.11.13", "@turbo/linux-64": "2.11.13", "@turbo/linux-arm64": "2.11.13", "@turbo/windows-64": "2.11.13", "@turbo/windows-arm64": "2.11.13" }, "bin": { "turbo": "bin/turbo" } }, "sha512-2EZ8StW6tqaj71HGF60oUOmJrPQHidmZ5dcwv2VORofya9JthVrfZhxbzRMx/QxjPwYi754i2h5RFsZSDzpnaQ=="],
"type": ["type@2.7.3", "", {}, "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ=="],
@@ -1,104 +0,0 @@
# Shiki assets — measurements
Commands (from `packages/gitbook`):
- Next: `bun run build:local && bun scripts/measure-shiki-bundles.ts next`
- Cold highlight: `bun scripts/bench-highlight-cold.ts 7` (fresh process per run, first highlight of javascript + python + vue; medians)
- Cloudflare: `bun run build:cloudflare && bun scripts/measure-shiki-bundles.ts cloudflare`
- Worker memory: wipe `openNext/customWorkers/.wrangler`, then
`PROFILE_URL=http://127.0.0.1:8771/url/gitbook.com/docs/developers/gitbook-api/quickstart PROFILE_REQUESTS=3 PROFILE_FORCE_GC=true bun scripts/profile-opennext-memory.ts`
(page with highlighted code; heap of the server worker after the first render and after 3 more)
| Metric | Baseline | Task 2 (server + client) | Task 3 | Task 4 |
|---|---|---|---|---|
| **Vercel / Node** | | | | |
| Page function trace, total | 20.01 MB (760 files) | 19.01 MB (756 files) | | |
| ↳ Shiki langs/themes in trace | 9.29 MB | 8.27 MB (JSON, 307 files) | | |
| Cold import of `highlight` (median) | 183 ms | 179 ms | | |
| Cold first highlight, 3 langs (median) | 195 ms | 188 ms | | |
| RSS after first highlight (median) | 207 MB | 207 MB | | |
| **Cloudflare server worker** | | | | |
| `handler.mjs` | 23.61 MB (gzip 5.21 MB) | — | 14.85 MB (gzip 3.82 MB) | |
| ↳ Shiki in handler | 8.69 MB | — | 0 | |
| Upload (wrangler dry-run) | 23 542 KiB (gzip 5 529 KiB) | — | 15 032 KiB (gzip 4 184 KiB) | |
| Server heap after first render | 53.3 MB | — | 52.9 MB | |
| Server heap after load | 71.6 MB | — | 52.9 MB (not comparable, see notes) | |
| **Client** | | | | |
| JS chunks | 12.60 MB (437 files) | 3.59 MB (142 files) | | |
| ↳ grammar chunks | 8.19 MB (236 files) | 0 (2 remaining `scopeName` chunks are the Shiki engine and an unrelated lib) | | |
Notes:
- First-request page timings on `next start` (~10 s) are dominated by API fetching, so cold
highlighting cost is measured with the micro-benchmark instead.
- Next keeps `shiki` external on the server: grammars reach the Vercel function through the
file trace, not `.next/server`.
- Task 2 also moved the client to assets (Task 4's switch), because the client could no longer
import the server entry once it read from `node:fs`.
- Vercel: the grammars still ship in the function, as on-demand JSON instead of module files; the
trace only shrinks by ~1 MB. A dynamic `join(process.cwd(), 'public/~gitbook/static', path)` made
file tracing pull all of `static` (65 MB trace); keeping `shiki` in the literal fixed it.
- Cloudflare heap: the 3 follow-up requests re-rendered in the baseline run (~11 s each) but were
served in <1 s after Task 3, so "after load" is not comparable. Heap after the first render is
the like-for-like number: unchanged, since lazily imported grammar modules were never evaluated
unless used. The Cloudflare gain is script size (−37 % raw, −24 % gzip upload), not heap.
- Cloudflare render verified on the split workers: quickstart page 200, 154 highlighted tokens
(same as baseline), grammars read through the server worker's `ASSETS` binding.
- Task 4 (browser check, headless Chromium on `next start`): the quickstart page fetches
`shiki/3.21.0/grammars/javascript.json` and `python.json` (200, `public, max-age=31536000,
immutable`) and highlights client-rendered blocks; no theme requests, since the default themes
are the custom ones kept in code. Cross-origin `GITBOOK_ASSETS_URL` not testable locally; static
assets already send `Access-Control-Allow-Origin: *`. Bundle numbers unchanged from Task 2.
## Summary (baseline → final)
| Target | Baseline | Final | Change |
|---|---|---|---|
| Cloudflare server `handler.mjs` | 23.61 MB | 14.85 MB | −8.76 MB (−37 %) |
| Cloudflare upload, gzip | 5 529 KiB | 4 184 KiB | −1 345 KiB (−24 %) |
| Cloudflare server heap after first render | 53.3 MB | 52.9 MB | ≈ 0 (grammar modules were already lazy) |
| Client JS chunks | 12.60 MB / 437 files | 3.59 MB / 142 files | −9.02 MB (−72 %), −295 files |
| Client grammar chunks | 8.19 MB / 236 files | 0 | −100 % (grammars are fetched as JSON on demand, cached immutable) |
| Vercel page function trace | 20.01 MB | 19.02 MB | −1.0 MB (−5 %): grammars still ship, as JSON |
| Cold first highlight (3 langs) | 195 ms | 188 ms | ≈ 0 (no regression) |
Grammar assets: 247 deduplicated grammar files (7.3 MB) + 60 themes (1.4 MB), versus 9.7 MB of
language modules before; a flattened file per language would have been 39 MB.
## Dynamic route check
Earlier render checks hit `/sites/static/...` (ISR). Re-checked on the dynamic route with the
`gitbook-dynamic-route` cookie, on builds made with `GITBOOK_ALLOW_CUSTOMIZATION_OVERRIDE=true`, page
`/url/gitbook.com/docs/developers/gitbook-api/quickstart`, two requests per case (each re-rendered, ~8 s):
| Runtime | Route | Default themes | `github-light` / `github-dark` (via `?customization=`) |
|---|---|---|---|
| `next start` | `x-gitbook-route-type: dynamic` | 200, 154 tokens | 200, 124 tokens, GitHub colours (`#D73A49`) |
| Split Cloudflare workers | `/sites/dynamic/...` `SERVER-MISS` | 200, 154 tokens | 200, 124 tokens, GitHub colours |
No load errors in either server log. Bundled themes are read from JSON on the server (disk on Node,
`ASSETS` on Cloudflare). Token-for-token parity with Shiki's own bundled highlighter was checked for
javascript, python, vue, markdown (fenced js), bash and yaml with the GitHub themes.
## Cloudflare server worker memory, dynamic route (supersedes the heap rows above)
Split workers (`dev:cf:server` + `dev:cf:middleware`, fresh `.wrangler`), every request with the
`gitbook-dynamic-route` cookie so each page renders on the server worker. First page
`developers/gitbook-api/quickstart`, then 8 more distinct developer pages (all 200). `main` = 7af524a83.
Two runs per build; the runs agreed within ~2 MB.
- Heap: V8 `Runtime.getHeapUsage` of the server isolate after a forced GC (heap snapshot).
- RSS: `VmRSS` of the server `workerd` process, from separate runs with no heap snapshots (snapshots
inflate RSS by hundreds of MB and that memory isn't returned).
| Point | Heap used, main | Heap used, branch | Δ heap | RSS, main | RSS, branch | Δ RSS |
|---|---|---|---|---|---|---|
| Idle (before any request) | 47.1 MB | 29.6 MB | −17.5 MB (−37 %) | 59.1 MB | 58.9 MB | ≈ 0 |
| After first render | 71.0 MB | 52.3 MB | −18.7 MB (−26 %) | 88.7 MB | 97.1 MB | +8.4 MB |
| After 9 pages | 86.3 MB | 66.6 MB | −19.7 MB (−23 %) | 140.5 MB | 151.5 MB | +11.0 MB |
Reading:
- The heap saving is the Shiki source code no longer in the worker script; it is there from idle and
stays constant, so grammars loaded from JSON cost about what the lazily imported modules cost.
- The RSS increase appears only once requests start fetching from `ASSETS`. Locally, wrangler/miniflare
serves the assets binding from a service in the same `workerd` process, so that memory is likely the
local assets service rather than the worker isolate (not verified; it would not be part of the
isolate in production, where the 128 MB limit applies per isolate).
@@ -1,291 +0,0 @@
# Shiki Assets Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Serve Shiki grammars and bundled themes as static JSON loaded on demand instead of bundling them into the Cloudflare worker, the Vercel function and the client.
**Architecture:** A generate script writes every Shiki language and theme as JSON under `public/~gitbook/static/shiki/<version>/`, plus a committed name catalog. The highlighting logic moves into a factory that takes an asset loader; the server entry binds a loader that reads via the Cloudflare `ASSETS` binding or `fs`, the client entry binds a `fetch` loader. Every step is measured against a recorded baseline.
**Tech Stack:** Next.js (webpack), OpenNext Cloudflare / wrangler, Shiki 3.21 (`shiki/core`, JS regex engine), Bun test.
**Spec:** `docs/superpowers/specs/2026-11-25-shiki-assets-design.md`
## Global Constraints
- All paths below are relative to `packages/gitbook` unless they start with `docs/` or `.changeset/`.
- Highlighted output must be identical: `highlight.test.ts` passes without edits.
- No module under `shiki/langs`, `shiki/themes`, `@shikijs/langs` or `@shikijs/themes` may be imported by app code after Task 4 (the generate script may).
- Engine stays `createJavaScriptRegexEngine({ forgiving: true, target: 'ES2018' })`.
- Asset URL path: `shiki/<shiki version>/langs/<id>.json` and `shiki/<shiki version>/themes/<id>.json`, relative to `~gitbook/static` (served immutable by the existing `/~gitbook/static/:path*` header rule).
- Server rendering must never do a network hop to read these assets.
- Comments explain why, one line where possible (AGENTS.md). Run `bun run format` before every commit.
- Bun tests run as `bun test <file> --preload ./tests/preload-bun.ts`.
- Every task that changes bundling ends by appending a column to `docs/superpowers/plans/2026-11-25-shiki-assets-measurements.md`.
## Review Focus
1. Many concurrent renders of the same language on a cold instance → the asset is read and registered once, no error. Test in Task 2.
2. An asset that fails to load (missing file, ASSETS 404) → that block renders plain, the error is logged, a later render retries. Test in Task 2.
3. Aliases and casing (`js`, `JSON`, `objectivec`, `parser`) → same language as before the change. Test in Task 1.
4. Languages that embed others (`vue`, `markdown` with fences, `html` with `<script>`) → embedded parts highlighted. Test in Task 2.
5. Client-side highlighting (blocks with expressions, large blocks) with `GITBOOK_ASSETS_URL` on another origin → loads via CORS (`Access-Control-Allow-Origin: *` already set). Manual check in Task 4.
---
### Task 0: Worktree setup, measurement script and baseline
**Files:**
- Create: `scripts/measure-shiki-bundles.ts`
- Create: `docs/superpowers/plans/2026-11-25-shiki-assets-measurements.md`
**Interfaces:**
- Produces: `bun scripts/measure-shiki-bundles.ts next|cloudflare` printing one JSON object (fields below) used by every later task.
- [ ] **Step 1: Prepare the worktree** (fresh worktree, deps are missing)
Run from repo root: `bun install && bunx turbo run build --filter='gitbook^...'`, then in `packages/gitbook`: `bun run generate`.
Expected: `public/~gitbook/static/{icons,math,mermaid,scalar,fonts}` exist and `worker-configuration.d.ts` exists.
- [ ] **Step 2: Write `scripts/measure-shiki-bundles.ts`**
Mode `next` (after `bun run build:local`) prints:
- `clientChunksBytes`, `clientChunksCount`: all files in `.next/static/chunks/**/*.js`.
- `clientGrammarChunksBytes`, `clientGrammarChunksCount`: those chunks whose content contains `"scopeName"` (present in every grammar).
- `serverBytes`: total size of `.next/server`; `serverGrammarBytes`: `.next/server/**/*.js` files containing `"scopeName"`.
Mode `cloudflare` (after `bun run build:cloudflare`) prints:
- `handlerBytes`, `handlerGzipBytes` for `.open-next/server-functions/default/packages/gitbook/handler.mjs` (gzip with `Bun.gzipSync`).
- `shikiBytes`: sum of `bytesInOutput` in `handler.mjs.meta.json` for inputs whose path contains `@shikijs/langs` or `@shikijs/themes` (reuse the logic in `scripts/profile-opennext-memory.ts` `getBundleMetrics`).
- `uploadKiB`, `uploadGzipKiB`: parsed from `bunx wrangler deploy --dry-run --config openNext/customWorkers/defaultWrangler.jsonc --env dev` ("Total Upload: X KiB / gzip: Y KiB").
- [ ] **Step 3: Record the baseline**
Run, on the unmodified code:
1. `bun run build:local && bun scripts/measure-shiki-bundles.ts next`
2. Cold render cost on Node: `bun run start`, then the first request to a code-heavy page with several languages (pick one under `http://localhost:3000/url/gitbook.com/docs` with ≥3 languages; note its URL in the measurements file). Measure `curl -o /dev/null -w '%{time_total}'` for the first request after a fresh `start`, 3 fresh starts, report the median. Kill the server by port afterwards.
3. `bun run build:cloudflare && bun scripts/measure-shiki-bundles.ts cloudflare`
4. Server worker memory: follow the OpenNext profiling caveats (delete `openNext/customWorkers/.wrangler` first, `PROFILE_FORCE_GC=true`, request distinct pages including the code-heavy page) with `bun run profile:cf:memory`; record cold and after-load heap of the server worker and its `shikiLanguageBytes`.
Write these into the measurements file as a table: one row per metric, a `Baseline` column, empty columns `Task 2`, `Task 3`, `Task 4`.
- [ ] **Step 4: Commit**
```bash
git add scripts/measure-shiki-bundles.ts docs/superpowers
git commit -m "Add Shiki assets design, plan, measurement script and baseline"
```
---
### Task 1: Generate Shiki assets and the name catalog
**Files:**
- Create: `scripts/generate-shiki-assets.ts`
- Create: `src/components/DocumentView/CodeBlock/shiki-catalog.ts` (generated, committed)
- Create: `src/components/DocumentView/CodeBlock/shiki-catalog.test.ts`
- Modify: `package.json` (`generate:assets`, `clean`)
- Modify: `src/components/DocumentView/CodeBlock/plain-highlight.ts` (drop `shiki/themes`)
- Modify: `src/components/DocumentView/CodeBlock/highlight.ts` (language resolution uses the catalog)
**Interfaces:**
- Produces (in `shiki-catalog.ts`):
- `SHIKI_ASSETS_PATH: string` = `` `shiki/${version}` ``
- `SHIKI_LANGUAGES: Record<string, string>`: every id and alias (lowercase) → canonical id.
- `SHIKI_THEMES: Record<string, { type: 'light' | 'dark' }>`: bundled theme id → type.
- `getShikiLanguageAssetPath(id: string): string` → `` `${SHIKI_ASSETS_PATH}/langs/${id}.json` ``
- `getShikiThemeAssetPath(id: string): string` → `` `${SHIKI_ASSETS_PATH}/themes/${id}.json` ``
- Produces (in `highlight.ts`): `getLanguageForSyntax(syntax: string): string | null` now returns a canonical id (exported for tests).
- [ ] **Step 1: Write the failing tests** in `shiki-catalog.test.ts`
```ts
it('maps ids and aliases to canonical ids', () => {
expect(SHIKI_LANGUAGES.javascript).toBe('javascript');
expect(SHIKI_LANGUAGES.js).toBe('javascript');
expect(SHIKI_LANGUAGES['objective-c']).toBe('objective-c');
});
it('writes one self-contained JSON file per language', async () => {
const vue = await Bun.file(`public/~gitbook/static/${getShikiLanguageAssetPath('vue')}`).json();
expect(vue.map((l: { name: string }) => l.name)).toEqual(expect.arrayContaining(['vue', 'html', 'css', 'javascript']));
});
it('writes every bundled theme', async () => {
expect(SHIKI_THEMES['github-dark'].type).toBe('dark');
expect(await Bun.file(`public/~gitbook/static/${getShikiThemeAssetPath('github-dark')}`).exists()).toBe(true);
});
it('resolves GitBook syntaxes', () => {
expect(getLanguageForSyntax('JSON')).toBe('json');
expect(getLanguageForSyntax('js')).toBe('javascript');
expect(getLanguageForSyntax('objectivec')).toBe('objective-c');
expect(getLanguageForSyntax('parser')).toBe('blade');
expect(getLanguageForSyntax('not-a-language')).toBeNull();
});
```
- [ ] **Step 2: Run to verify it fails**
Run: `bun test src/components/DocumentView/CodeBlock/shiki-catalog.test.ts --preload ./tests/preload-bun.ts`
Expected: FAIL, `shiki-catalog` not found.
- [ ] **Step 3: Implement `scripts/generate-shiki-assets.ts`**
Iterate `bundledLanguagesInfo` / `bundledThemesInfo` from `shiki/langs` / `shiki/themes`; for each, `(await info.import()).default` and write `JSON.stringify` of it to `public/~gitbook/static/<path>` (language default exports are already flat arrays including embedded languages). Remove `public/~gitbook/static/shiki` first. Version from `require('shiki/package.json')`. Write `shiki-catalog.ts` (header comment: generated by the script, do not edit). Add `bun ./scripts/generate-shiki-assets.ts` to `generate:assets` and `rm -rf ./public/~gitbook/static/shiki` to `clean`.
- [ ] **Step 4: Switch `plain-highlight.ts` to `SHIKI_THEMES` and `highlight.ts`'s `getLanguageForSyntax` to `SHIKI_LANGUAGES`** (keep `syntaxAliases`; `highlight.ts` still uses the bundled highlighter in this task, keyed by the canonical id).
- [ ] **Step 5: Run the new and existing tests**
Run: `bun run generate:assets && bun test src/components/DocumentView/CodeBlock --preload ./tests/preload-bun.ts`
Expected: all PASS.
- [ ] **Step 6: Commit**
```bash
bun run format
git add scripts/generate-shiki-assets.ts src/components/DocumentView/CodeBlock package.json
git commit -m "Generate Shiki languages and themes as static JSON assets"
```
---
### Task 2: Highlighter factory and the Node (fs) loader
**Files:**
- Create: `src/components/DocumentView/CodeBlock/highlighter.ts` (factory: all logic now in `highlight.ts`)
- Create: `src/components/DocumentView/CodeBlock/shiki-assets.server.ts` (server loader)
- Create: `src/components/DocumentView/CodeBlock/highlighter.test.ts`
- Modify: `src/components/DocumentView/CodeBlock/highlight.ts` (server entry: binds the server loader)
- Modify: `next.config.mjs` (`outputFileTracingIncludes`)
**Interfaces:**
- Consumes: Task 1 catalog.
- Produces:
- `type ShikiAssetLoader = (path: string) => Promise<unknown>` (path relative to `~gitbook/static`).
- `createHighlight(loadAsset: ShikiAssetLoader): { highlight: typeof highlight; preloadHighlight: typeof preloadHighlight }` in `highlighter.ts`; signatures of `highlight` / `preloadHighlight` unchanged.
- `loadShikiAssetOnServer: ShikiAssetLoader` in `shiki-assets.server.ts`.
- `highlight.ts` keeps exporting `highlight`, `preloadHighlight`, `getLanguageForSyntax` and `export * from './highlight-tokens'`.
- [ ] **Step 1: Write the failing tests** in `highlighter.test.ts`, using a fake loader that reads from `public/~gitbook/static` and counts calls per path
```ts
it('loads each asset once under concurrency', async () => {
const { highlight } = createHighlight(countingLoader);
await Promise.all(Array.from({ length: 10 }, () => highlight(jsBlock, [])));
expect(calls.get(getShikiLanguageAssetPath('javascript'))).toBe(1);
});
it('falls back to plain highlighting and retries after a failure', async () => {
const { highlight } = createHighlight(failOnceLoader);
const first = await highlight(jsBlock, []);
expect(first.lines[0].tokens.every((t) => t.type !== 'shiki')).toBe(true); // plain
const second = await highlight(jsBlock, []);
expect(second.lines[0].tokens.some((t) => t.type === 'shiki')).toBe(true);
});
it('highlights embedded languages', async () => {
const { highlight } = createHighlight(countingLoader);
const result = await highlight(vueBlockWithScript, []);
// the `const` inside <script> gets a keyword colour distinct from plain text
expect(colorOf(result, 'const')).not.toBe(result.fg);
});
it('loads custom themes from code, not from assets', async () => {
const { highlight } = createHighlight(countingLoader);
await highlight(jsBlock, [], { themes: { light: 'default-light', dark: 'github-dark' } });
expect([...calls.keys()].some((p) => p.includes('default-light'))).toBe(false);
});
```
Adjust the token-shape assertions to the real `HighlightToken` type in `highlight-tokens.ts`; the intent of each test is fixed.
- [ ] **Step 2: Run to verify they fail**
Run: `bun test src/components/DocumentView/CodeBlock/highlighter.test.ts --preload ./tests/preload-bun.ts`
Expected: FAIL, `createHighlight` not found.
- [ ] **Step 3: Implement `createHighlight` in `highlighter.ts`**
Move the body of `highlight.ts` here. One `createHighlighterCore({ themes: [], langs: [], engine })` promise per factory call. A `Map<string, Promise<void>>` of load-and-register promises keyed by asset path (custom themes keyed by name, registered with `loadTheme(customThemes[name])`); delete the entry on rejection so later renders retry. `highlight` awaits the language and both themes; on any load error, `console.error` and return `plainHighlight(...)`.
- [ ] **Step 4: Implement `loadShikiAssetOnServer`** (Node branch only in this task)
`JSON.parse(await readFile(join(process.cwd(), 'public/~gitbook/static', path), 'utf8'))`. `highlight.ts` becomes `export const { highlight, preloadHighlight } = createHighlight(loadShikiAssetOnServer)` plus its re-exports. `ClientCodeBlock` still imports `./highlight` in this task.
- [ ] **Step 5: Add tracing** in `next.config.mjs`: `outputFileTracingIncludes: { '/**': ['./public/~gitbook/static/shiki/**/*'] }` with a one-line why comment.
- [ ] **Step 6: Run all CodeBlock tests**
Run: `bun test src/components/DocumentView/CodeBlock --preload ./tests/preload-bun.ts`
Expected: all PASS, including the unmodified `highlight.test.ts`.
- [ ] **Step 7: Verify the Node build and measure**
Run: `bun run build:local && bun scripts/measure-shiki-bundles.ts next`. Expected: `serverGrammarBytes` near 0. Check `.next/server/**/*.nft.json` of the page route lists `public/~gitbook/static/shiki` files. Repeat the cold render measurement (Task 0 Step 3.2) and confirm the code-heavy page renders with colours. Fill the `Task 2` column.
- [ ] **Step 8: Commit**
```bash
bun run format
git add src/components/DocumentView/CodeBlock next.config.mjs docs/superpowers/plans/2026-11-25-shiki-assets-measurements.md
git commit -m "Load Shiki grammars and themes from assets on the server"
```
---
### Task 3: Cloudflare loader through the ASSETS binding
**Files:**
- Modify: `src/components/DocumentView/CodeBlock/shiki-assets.server.ts`
- Modify: `openNext/customWorkers/defaultWrangler.jsonc` (add `"assets": { "directory": "../../.open-next/assets", "binding": "ASSETS" }`, as in `middlewareWrangler.jsonc`)
**Interfaces:**
- Consumes: `getCloudflareContext()` from `src/lib/data/cloudflare.ts` (returns null off Cloudflare).
- [ ] **Step 1: Add the Cloudflare branch**: when `getCloudflareContext()` is non-null, `env.ASSETS.fetch(new URL(`/~gitbook/static/${path}`, 'https://assets.local'))`, throw on non-OK, return `response.json()`. Regenerate types with `wrangler types` if `ASSETS` is missing from the env type.
- [ ] **Step 2: Check whether the deployed server worker config is generated elsewhere** (`grep -rn "defaultWrangler\|gitbook-open-v2-server" ../../.github ../../scripts packages/gitbook/openNext`) and add the binding there too if so. Note the finding in the commit message.
- [ ] **Step 3: Verify on the split workers and measure**
Run: `bun run build:cloudflare && bun scripts/measure-shiki-bundles.ts cloudflare`. Expected: `shikiBytes` near 0, `uploadKiB` down by roughly the grammar size. Delete `openNext/customWorkers/.wrangler`, run `bun run dev:cf:server` and `bun run dev:cf:middleware`, load the code-heavy page at `http://127.0.0.1:8771/url/gitbook.com/docs/...`: colours present, server log has no `Failed to` / asset errors. Re-run the memory profile (Task 0 Step 3.4). Fill the `Task 3` column.
- [ ] **Step 4: Commit**
```bash
bun run format
git add src/components/DocumentView/CodeBlock openNext/customWorkers/defaultWrangler.jsonc docs/superpowers/plans/2026-11-25-shiki-assets-measurements.md
git commit -m "Read Shiki assets through the ASSETS binding on Cloudflare"
```
---
### Task 4: Client loader
**Files:**
- Create: `src/components/DocumentView/CodeBlock/highlight-client.ts`
- Modify: `src/components/DocumentView/CodeBlock/ClientCodeBlock.tsx:53,102` (`import('./highlight-client')`)
**Interfaces:**
- Produces: `highlight-client.ts` exports `{ highlight, preloadHighlight } = createHighlight((path) => fetch(getAssetURL(path)).then(...))`, throwing on non-OK. It must not import `shiki-assets.server.ts`, `node:*` or `@opennextjs/cloudflare`.
- [ ] **Step 1: Implement `highlight-client.ts` and switch both dynamic imports in `ClientCodeBlock.tsx`.**
- [ ] **Step 2: Verify no grammar or server code reaches the client, and measure**
Run: `bun run build:local && bun scripts/measure-shiki-bundles.ts next`. Expected: `clientGrammarChunksCount` 0; `grep -l "node:fs\|ASSETS" .next/static/chunks -r` finds nothing from this change. Fill the `Task 4` column (client metrics; re-run the Cloudflare measurement too since client changes don't affect it but the final column should be complete).
- [ ] **Step 3: Manual browser check**: on `bun run start`, open a page with a code block containing an expression or a large block (rendered by `ClientCodeBlock`); confirm it gets highlighted and the Network tab shows `~gitbook/static/shiki/.../langs/<id>.json` requests with `immutable` caching. If a staging-like `GITBOOK_ASSETS_URL` is available, confirm the cross-origin load works.
- [ ] **Step 4: Commit**
```bash
bun run format
git add src/components/DocumentView/CodeBlock docs/superpowers/plans/2026-11-25-shiki-assets-measurements.md
git commit -m "Load Shiki assets over the CDN in the browser"
```
---
### Task 5: Final checks, review and changeset
- [ ] **Step 1:** `bun run lint`, `bun run typecheck`, `bun run unit` (via `test-runner`). Expected: clean.
- [ ] **Step 2:** `grep -rn "shiki/langs\|shiki/themes\|@shikijs/langs\|@shikijs/themes" src` returns only the generate script's consumers (none in `src`).
- [ ] **Step 3:** Run `code-reviewer` on the branch diff against `main`; fix findings or say why they are wrong.
- [ ] **Step 4:** Add a summary row of deltas (baseline → final, absolute and %) to the measurements file and commit it.
- [ ] **Step 5:** Changeset `.changeset/shiki-static-assets.md` (`"gitbook": patch`, "Load Shiki languages and themes from static assets instead of bundling them."), committed separately with message `changeset`.
@@ -1,61 +0,0 @@
# Load Shiki languages and themes from static assets
## Why
`highlight.ts` imports `bundledLanguages` / `bundledThemes`, so ~670 language modules (9.7 MB) and the
themes (1.7 MB) are emitted as lazy chunks in every build: the Cloudflare server worker (counts against
the upload size limit and startup), the Vercel function and the client bundle (`ClientCodeBlock` imports
`./highlight`). Goal: improve all three by moving grammars and themes out of the JS bundles into static
JSON loaded on demand.
## Goals / non-goals
- Goal: no Shiki grammar or bundled theme in any JS bundle; identical highlighting output.
- Goal: measurable before/after on worker upload size, Vercel function size, client chunks, and
server memory on a cold render.
- Non-goal: changing highlighting behaviour, themes, or the custom themes (`customThemes.ts` stays in code).
- Anti-goal: rendering depending on an external network hop on the server.
## Approaches
- **A. Per-runtime reader (picked).** Cloudflare reads via an `ASSETS` binding on the server worker,
Vercel reads files traced into the function with `fs`, the browser fetches the CDN URL.
No server network hop; one small helper with three branches.
- B. HTTP fetch everywhere via `getAssetURL()`. Single code path, but every cold isolate does a network
round trip per language and rendering depends on the assets host (preview/local builds included).
- C. A, but keep bundled imports on Vercel. Less change, leaves Vercel untouched — rejected since all
three targets should improve.
## Design
1. **Generate step** — `scripts/generate-shiki-assets.ts`, added to `generate:assets` (and the `clean`
script). For every entry of `bundledLanguages` / `bundledThemes`, import the module and write its
default export as JSON to `public/~gitbook/static/shiki/<shiki version>/{langs,themes}/<name>.json`.
Language modules already export a flat array including their embedded languages, so each file is
self-contained: one fetch per language. The versioned path keeps URLs immutable, like the Mermaid
runtime. Also emit a small generated TS module with the language names, aliases and theme names so
`getLanguageForSyntax` and theme validation keep working without importing grammars.
2. **Loader** — `loadShikiAsset(kind, name)`:
- `GITBOOK_RUNTIME === 'cloudflare'`: `getCloudflareContext().env.ASSETS.fetch(...)`; add the
`assets` binding to `openNext/customWorkers/defaultWrangler.jsonc` (and `wrangler.jsonc` if the
single-worker setup still deploys).
- Node (Vercel, `next start`, dev): `fs.readFile` from the traced `public/~gitbook/static/shiki`
directory; add it to `outputFileTracingIncludes` in `next.config.mjs`.
- Browser: `fetch(getAssetURL(...))`.
Each asset is loaded at most once per isolate (memoised promise, cleared on failure).
3. **Highlighter** — replace `createdBundledHighlighter` with a core highlighter
(`createHighlighterCore` + JS regex engine) that `loadLanguage` / `loadTheme`s what a block needs
before tokenising; custom themes are loaded from code. `highlight` and `preloadHighlight` keep their
signatures. If loading fails, log it and fall back to `plainHighlight`.
4. **Verification** — existing `highlight.test.ts` passes unchanged; check that no `@shikijs/langs`
chunk remains in `.next` / `.open-next` output; compare sizes and cold-render memory before/after
(see the OpenNext memory profiling notes); render a page with code blocks on `next start` and on the
split Cloudflare workers.
Not customer-visible: highlighted output is unchanged, so no comms decision is needed.
## Left to the builder
- Exact location of the traced files on Vercel (`process.cwd()` vs a path relative to the module).
- Whether the deployed Cloudflare config is generated elsewhere and also needs the binding.
- The unit-test path for the loader (`fs` branch is what `bun test` exercises).
+2 -2
View File
@@ -7,8 +7,8 @@
"devDependencies": {
"@changesets/cli": "^2.31.1",
"oxfmt": "^0.62.0",
"oxlint": "^1.93.0",
"turbo": "^2.11.11",
"oxlint": "^1.95.0",
"turbo": "^2.11.13",
"vercel": "50.37.3"
},
"packageManager": "bun@1.3.7",
+11
View File
@@ -1,5 +1,16 @@
# @gitbook/embed
## 0.8.0
### Minor Changes
- a9535cd: Emit an `escape` event from the Docs Embed when Escape is pressed inside it and nothing in the embed used it, so the host can close its own panel.
- 6b2e806: Use the site's suggested questions when the embedded Assistant receives an empty or omitted list, including from older SDKs.
### Patch Changes
- 65210b7: Respect reduced motion for enter and exit animations, keep the header separator and input focus visible in forced colors mode, and size mobile surfaces with dynamic viewport units.
## 0.7.0
### Minor Changes
+1 -1
View File
@@ -13,7 +13,7 @@
}
},
"sideEffects": false,
"version": "0.7.0",
"version": "0.8.0",
"license": "Apache-2.0",
"dependencies": {
"@gitbook/api": "catalog:",
+77
View File
@@ -1,5 +1,82 @@
# gitbook
## 0.29.0
### Minor Changes
- 7ad3fff: Open a link in the same or a new tab when its author chose one, instead of the site-wide external links setting.
### Patch Changes
- 4eb32b1: Keep links in generated Markdown usable outside the source page.
- 13c0ff0: Handle optional emoji and icon values when rendering tags.
- 5755e6d: Point agents to the site MCP server from Markdown pages, the page HTML, llms.txt and llms-full.txt.
- bd38317: Serve the site AI Catalog as specification version 0.9, with identifiers in its `urn:air:{publisher}:{name}:{kind}` format.
- 960d7ec: Fade the bottom of collapsed code blocks so readers can tell there is more code, matching the editor.
- 818cbbe: Answer Assistant questions with medium reasoning instead of low, matching AI search.
- ddccd3d: Bump Next.js to 16.4.6 and OpenNext (Cloudflare 1.20.17, AWS 4.1.16), keeping the dev-mode OOM patch.
- b0f3822: Bump `@opennextjs/aws` to 4.2.0 and `@opennextjs/cloudflare` to 1.20.18.
- 0c3a51e: Fix horizontal page scroll caused by card carousels bleeding past the viewport.
- 22df281: Name a site's MCP server as docs, such as "Acme Docs MCP Server", in AI clients and in the install commands and links, so it is not confused with a product's own MCP server.
- a9535cd: Emit an `escape` event from the Docs Embed when Escape is pressed inside it and nothing in the embed used it, so the host can close its own panel.
- 6b2e806: Use the site's suggested questions when the embedded Assistant receives an empty or omitted list, including from older SDKs.
- 7e2658a: Reduce the wait after typing in site search to 100 ms.
- 7af524a: Prevent self-redirect loops and skip redirects targeting hidden adaptive content.
- ae1e370: Fix the table of contents keeping published pages busy in older Chrome versions such as Chrome 130.
- c85d84f: Fix `'use cache'` entries never being stored in or read from R2 and the regional cache on Cloudflare.
- 5997a66: Remove duplicated declarations from the global stylesheet.
- c3df458: Keep inline code and highlighted text readable when a paragraph crosses the bottom edge of a background page cover.
- 1ecd2ca: Keep published pages available when an integration block needs its connection or settings checked.
- 7cee30e: Keep published site search results visible while visitors refine a query.
- 265ca4b: Add a skip link, keyboard navigation between content tabs, focusable table of contents toggles, and hide decorative icons from assistive technologies.
- 76e1abd: Apply the default language-aware search scope to legacy search links.
- 9fcde5f: Reduce memory and CPU use of the OpenNext workers: minify the middleware, resolve the site context once per request, cache parsed OpenAPI descriptions across a spec, drop the redis client and the unused force-revalidate route from the server bundle.
- 9b5b8c8: Load the OpenAPI stylesheet only on pages with OpenAPI blocks.
- a3b5ce5: Render the llms.txt directive as the first element in the page body so agents find it before the navigation.
- 21b96e1: Count only MCP tool calls in the MCP request insights event.
- adbc358: Answer GET requests to the MCP endpoint with an `Allow: POST` header.
- fa7d4a9: Challenge MCP clients to authorize again when a visitor-auth site rejects their bearer token.
- 596b8c5: Support MCP protocol version 2025-11-25 on published site MCP servers.
- adfd921: Limit the MCP `searchDocumentation` tool to one language: the one the client passes in the new optional `language` argument, or else the language of the site variant the MCP endpoint is served from.
- 19660ed: Flush insights events when the page is hidden, preload the search index at low priority and prioritize the dark page cover on dark-default sites.
- a035d19: Keep published revision URLs out of search results.
- 867da7b: Resolve GitBook links in OpenAPI schema descriptions to the site's published URLs instead of the editor.
- 506aa78: Publish an OpenSearch description on every site so browsers can offer its search from the address bar.
- c09da2e: Show H3 headings in the page outline.
- d2be885: Render a page's search keywords in its metadata.
- 6cdbafc: Respect disabled change request previews on published sites.
- 19660ed: Fix the search button accessible name, hoverable link previews, IME-safe Enter on Safari, cookie banner semantics, active outline item announcement and textarea shrinking.
- d2c56e5: Send change request and revision links to the site preview, where GitBook members can sign in, when a site turns off public change request previews.
- 65210b7: Respect reduced motion for enter and exit animations, keep the header separator and input focus visible in forced colors mode, and size mobile surfaces with dynamic viewport units.
- 3e86382: Send only the site origin as referrer to third parties, and only let the embedding page open the embed messaging channel.
- 7d1cd9f: Remove the ChatGPT-specific plain text response for Markdown and llms.txt routes; these now always serve `text/markdown`.
- 3ec61a7: Drop description HTML supplied by OpenAPI specs and sanitize example descriptions that could render HTML.
- 63a4a98: Track the displayed position and search request ID when a visitor opens a search result.
- cf8c3d5: Send site searches straight to the search API when the site hands out a search pass, and use the site's search route when it does not or when the API refuses a search.
- 48fe81b: Include navigation-hidden published spaces in direct browser search lookup and avoid latching on unknown spaces.
- adbec4c: Send each search once on sites without a top header, and make search work between 768 and 1023 px wide.
- 8f5175e: Show loading rows shaped like search results while search waits for the server.
- 386a5c1: Show search results with one-line breadcrumbs and no icons or shortcut hints, and select the result under the mouse.
- b145bfc: Stop caching site search results in the framework cache, so every search reaches the API.
- 7856e08: Show one server-ordered search list and open its top result on Enter.
- a10eff9: Load the data of the page actions menu from the menu itself, so it can be cached apart from the page body.
- 1c71849: Follow the API's cache lifetime for site data, so a site preview shows layout changes soon after they are saved.
- 7f08fb1: Show site revision previews as their site revision pins them, including OpenAPI specs.
- b5f7e55: Render small cards in a responsive four-column grid and carousel.
- 8dd308b: Ignore tag category references when displaying assigned tags and update filters.
- 4cbbda7: Update the GitBook API SDK for site revision responses.
- 060f1f6: Fix wide content in Updates blocks overflowing into the page outline.
- Updated dependencies [a9535cd]
- Updated dependencies [6b2e806]
- Updated dependencies [9fcde5f]
- Updated dependencies [265ca4b]
- Updated dependencies [262749a]
- Updated dependencies [65210b7]
- @gitbook/embed@0.8.0
- @gitbook/icons@0.6.0
- @gitbook/react-openapi@2.0.2
- @gitbook/react-contentkit@0.7.19
## 0.28.2
### Patch Changes
-5
View File
@@ -120,11 +120,6 @@ const nextConfig = {
],
},
// Shiki grammars and themes are read from disk at runtime, see shiki-assets.server.ts.
outputFileTracingIncludes: {
'/**': ['./public/~gitbook/static/shiki/**/*'],
},
webpack(config, { isServer }) {
if (isServer) {
// mcp-handler only needs redis for SSE, which we disable: keep the client out of the server bundle.
@@ -12,13 +12,6 @@
"observability": {
"enabled": false,
},
// Lets the server read Shiki grammars and themes without a network hop.
// run_worker_first keeps every request going to the worker, as before.
"assets": {
"directory": "../../.open-next/assets",
"binding": "ASSETS",
"run_worker_first": true,
},
"vars": {
"NEXT_CACHE_DO_QUEUE_DISABLE_SQLITE": "true",
},
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "gitbook",
"version": "0.28.2",
"version": "0.29.0",
"private": true,
"dependencies": {
"@base-ui/react": "catalog:",
@@ -119,9 +119,9 @@
},
"scripts": {
"generate": "./scripts/generate.sh",
"generate:assets": "bun ./scripts/generate-shiki-assets.ts && bun ./scripts/generate-mermaid-runtime.ts && bun ./scripts/generate-scalar-runtime.ts && bun ./scripts/download-fonts.ts",
"generate:assets": "bun ./scripts/generate-mermaid-runtime.ts && bun ./scripts/generate-scalar-runtime.ts && bun ./scripts/download-fonts.ts",
"generate:fonts": "bun ./scripts/generate-font-faces.ts",
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static/icons && rm -rf ./public/~gitbook/static/math && rm -rf ./public/~gitbook/static/mermaid && rm -rf ./public/~gitbook/static/scalar && rm -rf ./public/~gitbook/static/fonts && rm -rf ./public/~gitbook/static/shiki",
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static/icons && rm -rf ./public/~gitbook/static/math && rm -rf ./public/~gitbook/static/mermaid && rm -rf ./public/~gitbook/static/scalar && rm -rf ./public/~gitbook/static/fonts",
"dev": "bun run generate:assets && env-cmd --silent -f ../../.env.local next --webpack",
"build": "bun run generate:assets && next build --webpack",
"build:local": "bun run generate:assets && GITBOOK_URL=http://localhost:3000 next build --webpack",
@@ -1,60 +0,0 @@
import { spawn } from 'bun';
import type { DocumentBlockCode } from '@gitbook/api';
/**
* Time the first highlights in fresh processes, where grammars and themes are loaded.
* Usage: bun scripts/bench-highlight-cold.ts [runs]
*/
const SAMPLES: Record<string, string> = {
javascript: 'const answer = await fetch("/api").then((r) => r.json());',
python: 'def greet(name: str) -> str:\n return f"Hello {name}"',
vue: '<template><p>{{ msg }}</p></template>\n<script setup>\nconst msg = "hi";\n</script>',
};
function codeBlock(syntax: string, code: string): DocumentBlockCode {
return {
object: 'block',
type: 'code',
data: { syntax },
nodes: code.split('\n').map((text) => ({
object: 'block',
type: 'code-line',
data: {},
nodes: [{ object: 'text', leaves: [{ object: 'leaf', marks: [], text }] }],
})),
} as DocumentBlockCode;
}
if (process.env.BENCH_CHILD) {
const importStart = performance.now();
const { highlight } = await import('../src/components/DocumentView/CodeBlock/highlight');
const importMs = performance.now() - importStart;
const start = performance.now();
await Promise.all(
Object.entries(SAMPLES).map(([syntax, code]) => highlight(codeBlock(syntax, code), []))
);
const firstMs = performance.now() - start;
console.log(JSON.stringify({ importMs, firstMs, rssMB: process.memoryUsage().rss / 1e6 }));
} else {
const runs = Number(process.argv[2] ?? 5);
const results: { importMs: number; firstMs: number; rssMB: number }[] = [];
for (let i = 0; i < runs; i++) {
const child = spawn(['bun', import.meta.path], {
env: { ...process.env, BENCH_CHILD: '1' },
stdout: 'pipe',
});
results.push(JSON.parse(await new Response(child.stdout).text()));
}
const median = (values: number[]) =>
values.sort((a, b) => a - b)[Math.floor(values.length / 2)]!;
console.log(
JSON.stringify({
runs,
importMsMedian: Math.round(median(results.map((r) => r.importMs))),
firstHighlightMsMedian: Math.round(median(results.map((r) => r.firstMs))),
rssMBMedian: Math.round(median(results.map((r) => r.rssMB))),
})
);
}
@@ -1,110 +0,0 @@
import { $ } from 'bun';
import { createHash } from 'node:crypto';
import { mkdir, rm, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { bundledLanguagesInfo } from 'shiki/langs';
import { bundledThemesInfo } from 'shiki/themes';
/**
* Write every Shiki language and theme as static JSON, so the app loads them on demand
* instead of bundling them, and generate the catalog of their names.
*/
const scriptDir = dirname(fileURLToPath(import.meta.url));
const staticDir = join(scriptDir, '../public/~gitbook/static');
const codeBlockDir = join(scriptDir, '../src/components/DocumentView/CodeBlock');
const require = createRequire(import.meta.url);
const { version } = require('shiki/package.json') as { version: string };
const languages: Record<string, string> = {};
const languageGrammars: Record<string, string[]> = {};
const grammars = new Map<string, string>();
for (const info of bundledLanguagesInfo) {
// A language module exports its embedded grammars followed by its own, in registration order.
const registrations = (await info.import()).default;
for (const registration of registrations) {
const json = JSON.stringify(registration);
const existing = grammars.get(registration.name);
if (existing !== undefined && existing !== json) {
throw new Error(`Grammar "${registration.name}" differs between languages`);
}
grammars.set(registration.name, json);
}
languageGrammars[info.id] = registrations.map((registration) => registration.name);
languages[info.id] = info.id;
for (const alias of info.aliases ?? []) {
languages[alias] ??= info.id;
}
}
const themes: Record<string, { type: 'light' | 'dark' }> = {};
const themeFiles = new Map<string, string>();
for (const info of bundledThemesInfo) {
themeFiles.set(info.id, JSON.stringify((await info.import()).default));
themes[info.id] = { type: info.type };
}
// Hash the content into the path: assets are served immutable, so any change needs a new URL.
const hash = createHash('sha256');
for (const [name, json] of [...grammars, ...themeFiles].sort(compareEntries)) {
hash.update(name).update('\0').update(json).update('\0');
}
const assetsPath = `shiki/${version}-${hash.digest('hex').slice(0, 8)}`;
await rm(join(staticDir, 'shiki'), { force: true, recursive: true });
await mkdir(join(staticDir, assetsPath, 'grammars'), { recursive: true });
await mkdir(join(staticDir, assetsPath, 'themes'), { recursive: true });
// One file per grammar so embedded grammars are stored and downloaded once.
for (const [name, json] of grammars) {
await writeFile(join(staticDir, assetsPath, 'grammars', `${name}.json`), json);
}
for (const [id, json] of themeFiles) {
await writeFile(join(staticDir, assetsPath, 'themes', `${id}.json`), json);
}
await writeFile(
join(codeBlockDir, 'shiki-catalog.ts'),
`// Generated by scripts/generate-shiki-assets.ts, do not edit.
export const SHIKI_ASSETS_PATH = ${JSON.stringify(assetsPath)};
/** Every Shiki language id and alias, mapped to the id of its asset. */
export const SHIKI_LANGUAGES: Record<string, string> = ${JSON.stringify(sorted(languages), null, 4)};
/** Grammars to register for each language, embedded ones first. */
export const SHIKI_LANGUAGE_GRAMMARS: Record<string, string[]> = ${JSON.stringify(sorted(languageGrammars), null, 4)};
export function getShikiGrammarAssetPath(name: string): string {
return \`\${SHIKI_ASSETS_PATH}/grammars/\${name}.json\`;
}
export function getShikiThemeAssetPath(id: string): string {
return \`\${SHIKI_ASSETS_PATH}/themes/\${id}.json\`;
}
`
);
// Separate from the catalog: plain highlighting only needs theme types and ships in the eager chunk.
await writeFile(
join(codeBlockDir, 'shiki-themes.ts'),
`// Generated by scripts/generate-shiki-assets.ts, do not edit.
/** Every bundled Shiki theme id, with its type. */
export const SHIKI_THEMES: Record<string, { type: 'light' | 'dark' }> = ${JSON.stringify(sorted(themes), null, 4)};
`
);
// Format like the rest of the repo so regenerating doesn't leave the committed files modified.
await $`bunx oxfmt ${join(codeBlockDir, 'shiki-catalog.ts')} ${join(codeBlockDir, 'shiki-themes.ts')}`.quiet();
function compareEntries([a]: [string, unknown], [b]: [string, unknown]) {
// Code-point order keeps the output identical whatever the machine's locale.
return a < b ? -1 : a > b ? 1 : 0;
}
function sorted<T>(record: Record<string, T>) {
return Object.fromEntries(Object.entries(record).sort(compareEntries));
}
@@ -1,115 +0,0 @@
import { $, Glob, file, gzipSync } from 'bun';
import { stat } from 'node:fs/promises';
import { dirname, join } from 'node:path';
/**
* Measure how much of the build output is made of Shiki grammars and themes.
* Usage: bun scripts/measure-shiki-bundles.ts next|cloudflare
*/
const appPath = join(import.meta.dir, '..');
const mode = process.argv[2];
// Every Shiki grammar carries a scopeName, so it is a cheap marker for grammar chunks.
const GRAMMAR_MARKER = 'scopeName';
async function measureFiles(root: string, pattern: string) {
let bytes = 0;
let count = 0;
let grammarBytes = 0;
let grammarCount = 0;
for await (const path of new Glob(pattern).scan({ cwd: root, onlyFiles: true })) {
const content = await file(join(root, path)).text();
const size = Buffer.byteLength(content);
bytes += size;
count += 1;
if (content.includes(GRAMMAR_MARKER)) {
grammarBytes += size;
grammarCount += 1;
}
}
return { bytes, count, grammarBytes, grammarCount };
}
// Next keeps shiki external on the server, so its files reach the function through the trace.
async function measurePageTrace() {
const nftPath = join(
appPath,
'.next/server/app/sites/dynamic/[mode]/[siteURL]/[siteData]/(content)/[pagePath]/page.js.nft.json'
);
const { files } = (await file(nftPath).json()) as { files: string[] };
let bytes = 0;
let shikiBytes = 0;
for (const relative of files) {
const size = (await stat(join(dirname(nftPath), relative))).size;
bytes += size;
if (/@shikijs\/(langs|themes)|shiki\/dist\/(langs|themes)/.test(relative)) {
shikiBytes += size;
}
}
return { bytes, shikiBytes, count: files.length };
}
async function measureNext() {
const client = await measureFiles(join(appPath, '.next/static/chunks'), '**/*.js');
const server = await measureFiles(join(appPath, '.next/server'), '**/*.js');
const serverAll = await measureFiles(join(appPath, '.next/server'), '**/*');
const trace = await measurePageTrace();
return {
pageTraceBytes: trace.bytes,
pageTraceFiles: trace.count,
pageTraceShikiAssetBytes: trace.shikiBytes,
clientChunksBytes: client.bytes,
clientChunksCount: client.count,
clientGrammarChunksBytes: client.grammarBytes,
clientGrammarChunksCount: client.grammarCount,
serverBytes: serverAll.bytes,
serverGrammarBytes: server.grammarBytes,
serverGrammarFiles: server.grammarCount,
};
}
async function measureCloudflare() {
const handlerPath = join(
appPath,
'.open-next/server-functions/default/packages/gitbook/handler.mjs'
);
const metafile = (await file(`${handlerPath}.meta.json`).json()) as {
outputs: Record<string, { inputs: Record<string, { bytesInOutput: number }> }>;
};
const output = Object.values(metafile.outputs)[0];
if (!output) {
throw new Error('No output in handler metafile');
}
const shikiBytes = Object.entries(output.inputs).reduce(
(total, [path, input]) =>
path.includes('@shikijs/langs') || path.includes('@shikijs/themes')
? total + input.bytesInOutput
: total,
0
);
const dryRun =
await $`bunx wrangler deploy --dry-run --config openNext/customWorkers/defaultWrangler.jsonc --env dev`
.cwd(appPath)
.quiet()
.nothrow()
.text();
const upload = dryRun.match(/Total Upload: ([\d.]+) KiB \/ gzip: ([\d.]+) KiB/);
return {
handlerBytes: (await stat(handlerPath)).size,
handlerGzipBytes: gzipSync(await file(handlerPath).arrayBuffer()).byteLength,
shikiBytes,
uploadKiB: upload ? Number(upload[1]) : null,
uploadGzipKiB: upload ? Number(upload[2]) : null,
};
}
if (mode === 'next') {
console.log(JSON.stringify(await measureNext(), null, 2));
} else if (mode === 'cloudflare') {
console.log(JSON.stringify(await measureCloudflare(), null, 2));
} else {
throw new Error('Usage: bun scripts/measure-shiki-bundles.ts next|cloudflare');
}
@@ -23,8 +23,6 @@ export type ClientBlockProps = Pick<BlockProps<DocumentBlockCode>, 'block' | 'st
evaluateInlineExpression?: (expression: string) => string;
mode: BlockProps<DocumentBlockCode>['context']['mode'];
themes?: CustomizationThemedCodeTheme;
/** Base URL of `~gitbook/static`, where the Shiki assets are loaded from. */
staticAssetsURL: string;
embedded?: boolean;
/** Node key for comments, set only where commenting is possible. */
commentKey?: string;
@@ -37,17 +35,8 @@ export const CODE_BLOCK_DEFAULT_COLLAPSED_LINE_COUNT = 10;
* It allows us to defer some load to avoid blocking the rendering of the whole page with block highlighting.
*/
export function ClientCodeBlock(props: ClientBlockProps) {
const {
block,
mode,
style,
inlines,
evaluateInlineExpression,
themes,
staticAssetsURL,
embedded,
commentKey,
} = props;
const { block, mode, style, inlines, evaluateInlineExpression, themes, embedded, commentKey } =
props;
const blockRef = useRef<HTMLDivElement>(null);
const isInViewportRef = useRef(false);
const [isInViewport, setIsInViewport] = useState(false);
@@ -61,10 +50,8 @@ export function ClientCodeBlock(props: ClientBlockProps) {
// Preload the highlighter when the block is mounted.
useEffect(() => {
import('./highlight-client').then(({ getClientHighlight }) =>
getClientHighlight(staticAssetsURL).preloadHighlight(block, themes)
);
}, [block, themes, staticAssetsURL]);
import('./highlight').then(({ preloadHighlight }) => preloadHighlight(block, themes));
}, [block, themes]);
// When user scrolls, we need to wait for the scroll to finish before running the highlight
const isScrollingRef = useRef(false);
@@ -112,8 +99,7 @@ export function ClientCodeBlock(props: ClientBlockProps) {
if (typeof window !== 'undefined') {
setHighlighting(true);
import('./highlight-client').then(({ getClientHighlight }) => {
const { highlight } = getClientHighlight(staticAssetsURL);
import('./highlight').then(({ highlight }) => {
highlight(block, inlines, { evaluateInlineExpression, themes }).then(
(theme) => {
if (cancelled) {
@@ -134,7 +120,7 @@ export function ClientCodeBlock(props: ClientBlockProps) {
// Otherwise if the block is not in viewport, we reset to the plain lines
setTheme(null);
}, [isInViewport, block, inlines, evaluateInlineExpression, themes, staticAssetsURL]);
}, [isInViewport, block, inlines, evaluateInlineExpression, themes]);
const expandable = block.data.expandable;
@@ -15,9 +15,8 @@ export function ClientPlainCodeBlock(props: {
syntax: string;
mode?: DocumentContext['mode'];
themes?: CustomizationThemedCodeTheme;
staticAssetsURL: string;
}) {
const { code, syntax, mode = 'default', themes, staticAssetsURL } = props;
const { code, syntax, mode = 'default', themes } = props;
const id = useId();
const block = convertCodeStringToBlock({ key: id, code, syntax });
@@ -29,7 +28,6 @@ export function ClientPlainCodeBlock(props: {
inlineExprVariables={{}}
mode={mode}
themes={themes}
staticAssetsURL={staticAssetsURL}
/>
);
}
@@ -122,7 +122,6 @@ export async function CodeBlock(
inlineExprVariables: variables,
mode: context.mode,
themes,
staticAssetsURL: getAssetURL(''),
embedded,
...getCommentKeyProp(context, block.key),
};
@@ -1,61 +0,0 @@
import { afterAll, describe, expect, it } from 'bun:test';
import { join } from 'node:path';
import { getClientHighlight } from './highlight-client';
import { getShikiGrammarAssetPath } from './shiki-catalog';
const staticDir = join(import.meta.dir, '../../../../public/~gitbook/static');
const requested: string[] = [];
// Stands in for the CDN serving `~gitbook/static`.
const server = Bun.serve({
port: 0,
fetch(request) {
const { pathname } = new URL(request.url);
requested.push(pathname);
const prefix = '/~gitbook/static/';
if (!pathname.startsWith(prefix)) {
return new Response('not found', { status: 404 });
}
const file = Bun.file(join(staticDir, pathname.slice(prefix.length)));
return new Response(file);
},
});
afterAll(() => server.stop(true));
const jsBlock = {
object: 'block',
type: 'code',
data: { syntax: 'javascript' },
nodes: [
{
object: 'block',
type: 'code-line',
data: {},
nodes: [
{ object: 'text', leaves: [{ object: 'leaf', marks: [], text: 'const a = 1;' }] },
],
},
],
} as never;
describe('getClientHighlight', () => {
it('fetches assets relative to the given static assets URL', async () => {
const { highlight } = getClientHighlight(`${server.url}~gitbook/static/`);
const result = await highlight(jsBlock, []);
expect(result.lines[0]?.tokens.some((token) => token.type === 'shiki')).toBe(true);
expect(requested).toContain(`/~gitbook/static/${getShikiGrammarAssetPath('javascript')}`);
});
it('reuses one highlighter per assets URL', () => {
const url = `${server.url}~gitbook/static/`;
expect(getClientHighlight(url)).toBe(getClientHighlight(url));
});
it('falls back to plain when the assets host answers an error', async () => {
const { highlight } = getClientHighlight(`${server.url}missing/`);
const result = await highlight(jsBlock, []);
expect(result.lines[0]?.tokens.map((token) => token.type)).toEqual(['plain']);
});
});
@@ -1,23 +0,0 @@
import { createHighlight } from './highlighter';
import { joinPathWithBaseURL } from '@/lib/paths';
const highlighters = new Map<string, ReturnType<typeof createHighlight>>();
/**
* Highlighting functions for the browser, loading Shiki assets from the static assets URL.
* The URL comes from the server because the client build doesn't know the runtime assets host.
*/
export function getClientHighlight(staticAssetsURL: string) {
let highlighter = highlighters.get(staticAssetsURL);
if (!highlighter) {
highlighter = createHighlight(async (path) => {
const response = await fetch(joinPathWithBaseURL(staticAssetsURL, path));
if (!response.ok) {
throw new Error(`Failed to fetch ${path}: ${response.status}`);
}
return response.json();
});
highlighters.set(staticAssetsURL, highlighter);
}
return highlighter;
}
@@ -1,7 +1,178 @@
import { createHighlight } from './highlighter';
import { loadShikiAssetOnServer } from './shiki-assets.server';
import { createSingletonShorthands, createdBundledHighlighter } from 'shiki/core';
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
import { type BundledLanguage, bundledLanguages } from 'shiki/langs';
import { bundledThemes } from 'shiki/themes';
import type { CustomizationThemedCodeTheme, DocumentBlockCode } from '@gitbook/api';
import { customThemes } from './customThemes';
import {
DEFAULT_THEMES,
type HighlightTheme,
type HighlightToken,
type PositionedToken,
type RenderedInline,
getPlainCodeBlock,
matchTokenAndInlines,
parseDiffNotation,
truncateHighlightTokens,
} from './highlight-tokens';
import { plainHighlight } from './plain-highlight';
export * from './highlight-tokens';
export { getLanguageForSyntax } from './highlighter';
export const { highlight, preloadHighlight } = createHighlight(loadShikiAssetOnServer);
// Merge bundled Shiki themes with our custom themes so both are available to the highlighter
const { getSingletonHighlighter } = createSingletonShorthands(
createdBundledHighlighter<any, any>({
langs: bundledLanguages,
themes: { ...bundledThemes, ...customThemes },
engine: () => createJavaScriptRegexEngine({ forgiving: true, target: 'ES2018' }),
})
);
/**
* Preload the highlighter for a code block.
*/
export async function preloadHighlight(
block: DocumentBlockCode,
themes: CustomizationThemedCodeTheme = DEFAULT_THEMES
) {
const langName = getBlockLang(block);
if (langName) {
await getSingletonHighlighter({
langs: [langName],
themes: [themes.light, themes.dark],
});
}
}
/**
* Highlight a code block while preserving inline elements.
*/
export async function highlight(
block: DocumentBlockCode,
inlines: RenderedInline[],
options?: {
evaluateInlineExpression?: (expr: string) => string;
themes?: CustomizationThemedCodeTheme;
}
): Promise<HighlightTheme> {
const langName = getBlockLang(block);
if (!langName) {
// Fallback to plain highlighting if language is not found
return plainHighlight(block, inlines, options);
}
const themes = options?.themes ?? DEFAULT_THEMES;
const code = getPlainCodeBlock(block, undefined, options);
const highlighter = await getSingletonHighlighter({
langs: [langName],
themes: [themes.light, themes.dark],
});
const resolvedThemes = {
light: highlighter.getTheme(themes.light),
dark: highlighter.getTheme(themes.dark),
};
let tokenizeMaxLineLength = 400;
// In some cases, people will use unindented code blocks with a single line.
// In this case, we can safely increase the max line length to avoid not highlighting the code.
if (block.nodes.length === 1) {
tokenizeMaxLineLength = 5000;
}
const result = highlighter.codeToTokens(code, {
lang: langName,
themes: resolvedThemes,
// Shiki's light-dark() CSS function provides different colors for light/dark modes based on the resolved themes
defaultColor: 'light-dark()',
tokenizeMaxLineLength,
});
const lines = result.tokens;
let currentIndex = 0;
return {
bg: result.bg,
fg: result.fg,
themes: resolvedThemes,
lines: lines.map((tokens, index) => {
const lineBlock = block.nodes[index];
const result: HighlightToken[] = [];
const lineText = tokens.map((token) => token.content).join('');
const notation = parseDiffNotation(lineText);
const eatToken = (): PositionedToken | null => {
const token = tokens.shift();
if (token) {
currentIndex += token.content.length;
}
return token
? { ...token, start: currentIndex - token.content.length, end: currentIndex }
: null;
};
while (tokens.length > 0) {
result.push(...matchTokenAndInlines(eatToken, inlines));
}
currentIndex += 1; // for the \n
const finalTokens = notation
? truncateHighlightTokens(result, notation.markerStart)
: result;
return {
highlighted: Boolean(lineBlock?.data.highlighted),
diff: notation?.diff ?? null,
tokens: finalTokens,
};
}),
};
}
/**
* Get the language of a code block.
*/
function getBlockLang(block: DocumentBlockCode): string | null {
return block.data.syntax ? getLanguageForSyntax(block.data.syntax) : null;
}
const syntaxAliases: Record<string, BundledLanguage> = {
// "Parser" language does not exist in Shiki, but it's used in GitBook
// The closest language is "Blade"
parser: 'blade',
// From GitBook App we receive "objectivec" instead of "objective-c"
objectivec: 'objective-c',
};
function checkIsBundledLanguage(lang: string): lang is BundledLanguage {
return lang in bundledLanguages;
}
/**
* Validate a language name.
*/
function getLanguageForSyntax(syntax: string): BundledLanguage | null {
// Normalize the syntax to lowercase.
syntax = syntax.toLowerCase();
// Check if the syntax is a bundled language.
if (checkIsBundledLanguage(syntax)) {
return syntax;
}
// Check if there is a valid alias for the syntax.
const alias = syntaxAliases[syntax];
if (alias && checkIsBundledLanguage(alias)) {
return alias;
}
return null;
}
@@ -1,109 +0,0 @@
import { beforeEach, describe, expect, it } from 'bun:test';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import type { DocumentBlockCode } from '@gitbook/api';
import type { HighlightTheme } from './highlight-tokens';
import { type ShikiAssetLoader, createHighlight } from './highlighter';
import { getShikiGrammarAssetPath } from './shiki-catalog';
const staticDir = join(import.meta.dir, '../../../../public/~gitbook/static');
let calls: Map<string, number>;
const readAsset: ShikiAssetLoader = async (path) =>
JSON.parse(await readFile(join(staticDir, path), 'utf8'));
const countingLoader: ShikiAssetLoader = async (path) => {
calls.set(path, (calls.get(path) ?? 0) + 1);
return readAsset(path);
};
beforeEach(() => {
calls = new Map();
});
function codeBlock(syntax: string, code: string): DocumentBlockCode {
return {
object: 'block',
type: 'code',
data: { syntax },
nodes: code.split('\n').map((text) => ({
object: 'block',
type: 'code-line',
data: {},
nodes: [{ object: 'text', leaves: [{ object: 'leaf', marks: [], text }] }],
})),
} as DocumentBlockCode;
}
const jsBlock = codeBlock('javascript', 'const answer = 42;');
function isHighlighted(result: HighlightTheme) {
return result.lines.some((line) => line.tokens.some((token) => token.type === 'shiki'));
}
function colorOf(result: HighlightTheme, content: string) {
for (const line of result.lines) {
for (const token of line.tokens) {
if (token.type === 'shiki' && token.token.content.trim() === content) {
// light-dark() output puts the colour in htmlStyle rather than color.
const style = token.token.htmlStyle;
return typeof style === 'object' ? style.color : undefined;
}
}
}
return undefined;
}
describe('createHighlight', () => {
it('loads each grammar once under concurrency', async () => {
const { highlight } = createHighlight(countingLoader);
const results = await Promise.all(Array.from({ length: 10 }, () => highlight(jsBlock, [])));
expect(results.every(isHighlighted)).toBe(true);
expect(calls.get(getShikiGrammarAssetPath('javascript'))).toBe(1);
});
it('falls back to plain highlighting and retries after a failure', async () => {
let failed = false;
const failOnceLoader: ShikiAssetLoader = async (path) => {
if (!failed && path === getShikiGrammarAssetPath('javascript')) {
failed = true;
throw new Error('asset unavailable');
}
return readAsset(path);
};
const { highlight } = createHighlight(failOnceLoader);
const first = await highlight(jsBlock, []);
expect(isHighlighted(first)).toBe(false);
expect(first.lines[0]?.tokens.map((token) => token.type)).toEqual(['plain']);
const second = await highlight(jsBlock, []);
expect(isHighlighted(second)).toBe(true);
});
it('highlights embedded languages', async () => {
const { highlight } = createHighlight(countingLoader);
const result = await highlight(
codeBlock('vue', '<template><p>hi</p></template>\n<script>\nconst msg = 1;\n</script>'),
[]
);
const keywordColor = colorOf(result, 'const');
expect(keywordColor).toBeDefined();
expect(keywordColor).not.toBe(colorOf(result, 'msg'));
});
it('loads custom themes from code, not from assets', async () => {
const { highlight } = createHighlight(countingLoader);
const result = await highlight(jsBlock, [], {
themes: { light: 'default-light', dark: 'github-dark' } as never,
});
expect(isHighlighted(result)).toBe(true);
expect([...calls.keys()].some((path) => path.includes('default-light'))).toBe(false);
expect([...calls.keys()].some((path) => path.endsWith('themes/github-dark.json'))).toBe(
true
);
});
});
@@ -1,247 +0,0 @@
import {
type HighlighterCore,
type LanguageRegistration,
type ThemeRegistrationAny,
createHighlighterCore,
} from 'shiki/core';
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
import type { CustomizationThemedCodeTheme, DocumentBlockCode } from '@gitbook/api';
import { customThemes } from './customThemes';
import {
DEFAULT_THEMES,
type HighlightTheme,
type HighlightToken,
type PositionedToken,
type RenderedInline,
getPlainCodeBlock,
matchTokenAndInlines,
parseDiffNotation,
truncateHighlightTokens,
} from './highlight-tokens';
import { plainHighlight } from './plain-highlight';
import {
SHIKI_LANGUAGES,
SHIKI_LANGUAGE_GRAMMARS,
getShikiGrammarAssetPath,
getShikiThemeAssetPath,
} from './shiki-catalog';
import { SHIKI_THEMES } from './shiki-themes';
/**
* Read a Shiki asset (grammar or theme JSON) from its path relative to `~gitbook/static`.
*/
export type ShikiAssetLoader = (path: string) => Promise<unknown>;
// Syntaxes sent by GitBook that are not Shiki ids or aliases.
const syntaxAliases: Record<string, string> = {
// "Parser" language does not exist in Shiki, but it's used in GitBook
// The closest language is "Blade"
parser: 'blade',
// From GitBook App we receive "objectivec" instead of "objective-c"
objectivec: 'objective-c',
};
/**
* Resolve a code block syntax to a canonical Shiki language id.
*/
export function getLanguageForSyntax(syntax: string): string | null {
const normalized = syntax.toLowerCase();
return SHIKI_LANGUAGES[normalized] ?? SHIKI_LANGUAGES[syntaxAliases[normalized] ?? ''] ?? null;
}
function getBlockLang(block: DocumentBlockCode): string | null {
return block.data.syntax ? getLanguageForSyntax(block.data.syntax) : null;
}
/**
* Create the highlighting functions, loading grammars and themes on demand through `loadAsset`.
*/
export function createHighlight(loadAsset: ShikiAssetLoader) {
let highlighterPromise: Promise<HighlighterCore> | null = null;
const pending = new Map<string, Promise<unknown>>();
// Share in-flight and finished loads; forget failures so a later render retries.
function once<T>(key: string, load: () => Promise<T>): Promise<T> {
let promise = pending.get(key) as Promise<T> | undefined;
if (!promise) {
promise = load();
pending.set(key, promise);
promise.catch(() => pending.delete(key));
}
return promise;
}
function getHighlighter() {
highlighterPromise ??= createHighlighterCore({
engine: createJavaScriptRegexEngine({ forgiving: true, target: 'ES2018' }),
});
return highlighterPromise;
}
function loadLanguage(highlighter: HighlighterCore, lang: string) {
return once(`lang:${lang}`, async () => {
const names = SHIKI_LANGUAGE_GRAMMARS[lang];
if (!names) {
throw new Error(`Unknown language "${lang}"`);
}
const grammars = await Promise.all(
names.map(
(name) =>
once(`grammar:${name}`, () =>
loadAsset(getShikiGrammarAssetPath(name))
) as Promise<LanguageRegistration>
)
);
const loaded = new Set(highlighter.getLoadedLanguages());
await highlighter.loadLanguage(
...grammars.filter((grammar) => !loaded.has(grammar.name))
);
});
}
function loadTheme(highlighter: HighlighterCore, theme: string) {
return once(`theme:${theme}`, async () => {
const custom = customThemes[theme];
if (custom) {
await highlighter.loadTheme(custom);
return;
}
if (!SHIKI_THEMES[theme]) {
throw new Error(`Unknown theme "${theme}"`);
}
await highlighter.loadTheme(
(await loadAsset(getShikiThemeAssetPath(theme))) as ThemeRegistrationAny
);
});
}
async function loadHighlighter(lang: string, themes: CustomizationThemedCodeTheme) {
const highlighter = await getHighlighter();
await Promise.all([
loadLanguage(highlighter, lang),
loadTheme(highlighter, themes.light),
loadTheme(highlighter, themes.dark),
]);
return highlighter;
}
/**
* Preload the highlighter for a code block.
*/
async function preloadHighlight(
block: DocumentBlockCode,
themes: CustomizationThemedCodeTheme = DEFAULT_THEMES
) {
const langName = getBlockLang(block);
if (langName) {
await loadHighlighter(langName, themes).catch(() => {
// Rendering retries and reports the failure.
});
}
}
/**
* Highlight a code block while preserving inline elements.
*/
async function highlight(
block: DocumentBlockCode,
inlines: RenderedInline[],
options?: {
evaluateInlineExpression?: (expr: string) => string;
themes?: CustomizationThemedCodeTheme;
}
): Promise<HighlightTheme> {
const langName = getBlockLang(block);
if (!langName) {
// Fallback to plain highlighting if language is not found
return plainHighlight(block, inlines, options);
}
const themes = options?.themes ?? DEFAULT_THEMES;
const code = getPlainCodeBlock(block, undefined, options);
let highlighter: HighlighterCore;
try {
highlighter = await loadHighlighter(langName, themes);
} catch (error) {
console.error(
`Failed to load the "${langName}" highlighter, falling back to plain`,
error
);
return plainHighlight(block, inlines, options);
}
const resolvedThemes = {
light: highlighter.getTheme(themes.light),
dark: highlighter.getTheme(themes.dark),
};
let tokenizeMaxLineLength = 400;
// In some cases, people will use unindented code blocks with a single line.
// In this case, we can safely increase the max line length to avoid not highlighting the code.
if (block.nodes.length === 1) {
tokenizeMaxLineLength = 5000;
}
const result = highlighter.codeToTokens(code, {
lang: langName,
themes: resolvedThemes,
// Shiki's light-dark() CSS function provides different colors for light/dark modes based on the resolved themes
defaultColor: 'light-dark()',
tokenizeMaxLineLength,
});
const lines = result.tokens;
let currentIndex = 0;
return {
bg: result.bg,
fg: result.fg,
themes: resolvedThemes,
lines: lines.map((tokens, index) => {
const lineBlock = block.nodes[index];
const result: HighlightToken[] = [];
const lineText = tokens.map((token) => token.content).join('');
const notation = parseDiffNotation(lineText);
const eatToken = (): PositionedToken | null => {
const token = tokens.shift();
if (token) {
currentIndex += token.content.length;
}
return token
? {
...token,
start: currentIndex - token.content.length,
end: currentIndex,
}
: null;
};
while (tokens.length > 0) {
result.push(...matchTokenAndInlines(eatToken, inlines));
}
currentIndex += 1; // for the \n
const finalTokens = notation
? truncateHighlightTokens(result, notation.markerStart)
: result;
return {
highlighted: Boolean(lineBlock?.data.highlighted),
diff: notation?.diff ?? null,
tokens: finalTokens,
};
}),
};
}
return { highlight, preloadHighlight };
}
@@ -1,3 +1,5 @@
import { bundledThemesInfo } from 'shiki/themes';
import type { CustomizationThemedCodeTheme, DocumentBlockCode } from '@gitbook/api';
import { customThemes } from './customThemes';
@@ -9,7 +11,6 @@ import {
parseDiffNotation,
truncateHighlightTokens,
} from './highlight-tokens';
import { SHIKI_THEMES } from './shiki-themes';
import { getNodeText } from '@/lib/document';
/**
@@ -28,11 +29,11 @@ export function plainHighlight(
// Resolve theme objects: first check bundled Shiki themes, then custom themes, finally fallback to type-only
// The type-only fallback ensures HighlightTheme always has valid theme objects even when theme names don't match
const themes = {
light: getBundledThemeInfo(options?.themes?.light) ??
light: bundledThemesInfo.find((theme) => theme.id === options?.themes?.light) ??
Object.values(customThemes).find((theme) => theme.name === options?.themes?.light) ?? {
type: 'light',
},
dark: getBundledThemeInfo(options?.themes?.dark) ??
dark: bundledThemesInfo.find((theme) => theme.id === options?.themes?.dark) ??
Object.values(customThemes).find((theme) => theme.name === options?.themes?.dark) ?? {
type: 'dark',
},
@@ -81,8 +82,3 @@ export function plainHighlight(
}),
};
}
function getBundledThemeInfo(name: string | undefined) {
const info = name ? SHIKI_THEMES[name] : undefined;
return info ? { name, type: info.type } : undefined;
}
@@ -1,40 +0,0 @@
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import type { ShikiAssetLoader } from './highlighter';
import { getCloudflareContext } from '@/lib/data/cloudflare';
const SHIKI_PREFIX = 'shiki/';
/**
* Read a Shiki asset on the server without a network hop.
*/
export const loadShikiAssetOnServer: ShikiAssetLoader = async (path) => {
if (!path.startsWith(SHIKI_PREFIX)) {
throw new Error(`Not a Shiki asset: ${path}`);
}
const cloudflare = getCloudflareContext();
if (cloudflare) {
const assets = cloudflare.env.ASSETS;
if (!assets) {
throw new Error('The ASSETS binding is missing on this worker');
}
// The host is ignored by the assets binding, only the path matters.
const response = await assets.fetch(
new URL(`/~gitbook/static/${path}`, 'https://assets.local')
);
if (!response.ok) {
throw new Error(`Failed to read ${path} from assets: ${response.status}`);
}
return response.json();
}
// Keep `shiki` in the literal so file tracing only pulls this folder, not all of `static`.
const file = join(
process.cwd(),
'public/~gitbook/static/shiki',
path.slice(SHIKI_PREFIX.length)
);
return JSON.parse(await readFile(file, 'utf8'));
};
@@ -1,69 +0,0 @@
import { describe, expect, it } from 'bun:test';
import { join } from 'node:path';
import { getLanguageForSyntax } from './highlight';
import {
SHIKI_ASSETS_PATH,
SHIKI_LANGUAGES,
SHIKI_LANGUAGE_GRAMMARS,
getShikiGrammarAssetPath,
getShikiThemeAssetPath,
} from './shiki-catalog';
import { SHIKI_THEMES } from './shiki-themes';
const staticDir = join(import.meta.dir, '../../../../public/~gitbook/static');
describe('shiki catalog', () => {
it('maps ids and aliases to canonical ids', () => {
expect(SHIKI_LANGUAGES.javascript).toBe('javascript');
expect(SHIKI_LANGUAGES.js).toBe('javascript');
expect(SHIKI_LANGUAGES['objective-c']).toBe('objective-c');
});
it('lists embedded grammars before the language grammar', () => {
const vue = SHIKI_LANGUAGE_GRAMMARS.vue ?? [];
expect(vue.at(-1)).toBe('vue');
expect(vue).toEqual(expect.arrayContaining(['html', 'css', 'javascript']));
});
it('writes one JSON file per grammar, including internal ones', async () => {
const grammar = await Bun.file(
join(staticDir, getShikiGrammarAssetPath('cpp-macro'))
).json();
expect(grammar.name).toBe('cpp-macro');
expect(grammar.scopeName).toBeString();
});
it('writes every bundled theme', async () => {
expect(SHIKI_THEMES['github-dark']?.type).toBe('dark');
expect(
await Bun.file(join(staticDir, getShikiThemeAssetPath('github-dark'))).exists()
).toBe(true);
});
});
describe('shiki assets path', () => {
it('changes with the generated content, not only the shiki version', () => {
// Assets are served immutable, so a format change must move them to a new URL.
expect(SHIKI_ASSETS_PATH).toMatch(/^shiki\/\d+\.\d+\.\d+-[0-9a-f]{8}$/);
});
});
describe('client bundle', () => {
it('keeps the language catalog out of plain highlighting', async () => {
// plain-highlight is in the eager ClientCodeBlock chunk; only theme types are needed there.
const source = await Bun.file(join(import.meta.dir, 'plain-highlight.ts')).text();
expect(source).not.toContain("'./shiki-catalog'");
expect(source).toContain("'./shiki-themes'");
});
});
describe('getLanguageForSyntax', () => {
it('resolves GitBook syntaxes to canonical ids', () => {
expect(getLanguageForSyntax('JSON')).toBe('json');
expect(getLanguageForSyntax('js')).toBe('javascript');
expect(getLanguageForSyntax('objectivec')).toBe('objective-c');
expect(getLanguageForSyntax('parser')).toBe('blade');
expect(getLanguageForSyntax('not-a-language')).toBeNull();
});
});
@@ -1,902 +0,0 @@
// Generated by scripts/generate-shiki-assets.ts, do not edit.
export const SHIKI_ASSETS_PATH = 'shiki/3.21.0-f9eb29ba';
/** Every Shiki language id and alias, mapped to the id of its asset. */
export const SHIKI_LANGUAGES: Record<string, string> = {
'1c': 'bsl',
'1c-query': 'sdbl',
abap: 'abap',
'actionscript-3': 'actionscript-3',
ada: 'ada',
adoc: 'asciidoc',
'angular-html': 'angular-html',
'angular-ts': 'angular-ts',
apache: 'apache',
apex: 'apex',
apl: 'apl',
applescript: 'applescript',
ara: 'ara',
asciidoc: 'asciidoc',
asm: 'asm',
astro: 'astro',
awk: 'awk',
ballerina: 'ballerina',
bash: 'shellscript',
bat: 'bat',
batch: 'bat',
be: 'berry',
beancount: 'beancount',
berry: 'berry',
bibtex: 'bibtex',
bicep: 'bicep',
blade: 'blade',
bsl: 'bsl',
c: 'c',
'c#': 'csharp',
'c++': 'cpp',
c3: 'c3',
cadence: 'cadence',
cairo: 'cairo',
cdc: 'cadence',
cjs: 'javascript',
clarity: 'clarity',
clj: 'clojure',
clojure: 'clojure',
'closure-templates': 'soy',
cmake: 'cmake',
cmd: 'vb',
cobol: 'cobol',
codeowners: 'codeowners',
codeql: 'codeql',
coffee: 'coffee',
coffeescript: 'coffee',
'common-lisp': 'common-lisp',
console: 'shellsession',
coq: 'coq',
cpp: 'cpp',
cql: 'cypher',
crystal: 'crystal',
cs: 'csharp',
csharp: 'csharp',
css: 'css',
csv: 'csv',
cts: 'typescript',
cue: 'cue',
cypher: 'cypher',
d: 'd',
dart: 'dart',
dax: 'dax',
desktop: 'desktop',
diff: 'diff',
docker: 'docker',
dockerfile: 'docker',
dotenv: 'dotenv',
'dream-maker': 'dream-maker',
edge: 'edge',
elisp: 'emacs-lisp',
elixir: 'elixir',
elm: 'elm',
'emacs-lisp': 'emacs-lisp',
erb: 'erb',
erl: 'erlang',
erlang: 'erlang',
f: 'fortran-fixed-form',
'f#': 'fsharp',
f03: 'fortran-free-form',
f08: 'fortran-free-form',
f18: 'fortran-free-form',
f77: 'fortran-fixed-form',
f90: 'fortran-free-form',
f95: 'fortran-free-form',
fennel: 'fennel',
fish: 'fish',
fluent: 'fluent',
for: 'fortran-fixed-form',
'fortran-fixed-form': 'fortran-fixed-form',
'fortran-free-form': 'fortran-free-form',
fs: 'fsharp',
fsharp: 'fsharp',
fsl: 'jssm',
ftl: 'fluent',
gdresource: 'gdresource',
gdscript: 'gdscript',
gdshader: 'gdshader',
genie: 'genie',
gherkin: 'gherkin',
'git-commit': 'git-commit',
'git-rebase': 'git-rebase',
gjs: 'glimmer-js',
gleam: 'gleam',
'glimmer-js': 'glimmer-js',
'glimmer-ts': 'glimmer-ts',
glsl: 'glsl',
gn: 'gn',
gnuplot: 'gnuplot',
go: 'go',
gql: 'graphql',
graphql: 'graphql',
groovy: 'groovy',
gts: 'glimmer-ts',
hack: 'hack',
haml: 'haml',
handlebars: 'handlebars',
haskell: 'haskell',
haxe: 'haxe',
hbs: 'handlebars',
hcl: 'hcl',
hjson: 'hjson',
hlsl: 'hlsl',
hs: 'haskell',
html: 'html',
'html-derivative': 'html-derivative',
http: 'http',
hurl: 'hurl',
hxml: 'hxml',
hy: 'hy',
imba: 'imba',
ini: 'ini',
jade: 'pug',
java: 'java',
javascript: 'javascript',
jinja: 'jinja',
jison: 'jison',
jl: 'julia',
js: 'javascript',
json: 'json',
json5: 'json5',
jsonc: 'jsonc',
jsonl: 'jsonl',
jsonnet: 'jsonnet',
jssm: 'jssm',
jsx: 'jsx',
julia: 'julia',
kdl: 'kdl',
kotlin: 'kotlin',
kql: 'kusto',
kt: 'kotlin',
kts: 'kotlin',
kusto: 'kusto',
latex: 'latex',
lean: 'lean',
lean4: 'lean',
less: 'less',
liquid: 'liquid',
lisp: 'common-lisp',
lit: 'ts-tags',
llvm: 'llvm',
log: 'log',
logo: 'logo',
lua: 'lua',
luau: 'luau',
make: 'make',
makefile: 'make',
markdown: 'markdown',
marko: 'marko',
matlab: 'matlab',
mbt: 'moonbit',
mbti: 'moonbit',
md: 'markdown',
mdc: 'mdc',
mdx: 'mdx',
mediawiki: 'wikitext',
mermaid: 'mermaid',
mips: 'mipsasm',
mipsasm: 'mipsasm',
mjs: 'javascript',
mmd: 'mermaid',
mojo: 'mojo',
moonbit: 'moonbit',
move: 'move',
mts: 'typescript',
nar: 'narrat',
narrat: 'narrat',
nextflow: 'nextflow',
nf: 'nextflow',
nginx: 'nginx',
nim: 'nim',
nix: 'nix',
nu: 'nushell',
nushell: 'nushell',
objc: 'objective-c',
'objective-c': 'objective-c',
'objective-cpp': 'objective-cpp',
ocaml: 'ocaml',
openscad: 'openscad',
pascal: 'pascal',
perl: 'perl',
perl6: 'raku',
php: 'php',
pkl: 'pkl',
plsql: 'plsql',
po: 'po',
polar: 'polar',
postcss: 'postcss',
pot: 'po',
potx: 'po',
powerquery: 'powerquery',
powershell: 'powershell',
prisma: 'prisma',
prolog: 'prolog',
properties: 'ini',
proto: 'proto',
protobuf: 'proto',
ps: 'powershell',
ps1: 'powershell',
pug: 'pug',
puppet: 'puppet',
purescript: 'purescript',
py: 'python',
python: 'python',
ql: 'codeql',
qml: 'qml',
qmldir: 'qmldir',
qss: 'qss',
r: 'r',
racket: 'racket',
raku: 'raku',
razor: 'razor',
rb: 'ruby',
reg: 'reg',
regex: 'regexp',
regexp: 'regexp',
rel: 'rel',
riscv: 'riscv',
rosmsg: 'rosmsg',
rs: 'rust',
rst: 'rst',
ruby: 'ruby',
rust: 'rust',
sas: 'sas',
sass: 'sass',
scad: 'openscad',
scala: 'scala',
scheme: 'scheme',
scss: 'scss',
sdbl: 'sdbl',
sh: 'shellscript',
shader: 'shaderlab',
shaderlab: 'shaderlab',
shell: 'shellscript',
shellscript: 'shellscript',
shellsession: 'shellsession',
smalltalk: 'smalltalk',
solidity: 'solidity',
soy: 'soy',
sparql: 'sparql',
spl: 'splunk',
splunk: 'splunk',
sql: 'sql',
'ssh-config': 'ssh-config',
stata: 'stata',
styl: 'stylus',
stylus: 'stylus',
svelte: 'svelte',
swift: 'swift',
'system-verilog': 'system-verilog',
systemd: 'systemd',
talon: 'talonscript',
talonscript: 'talonscript',
tasl: 'tasl',
tcl: 'tcl',
templ: 'templ',
terraform: 'terraform',
tex: 'tex',
tf: 'terraform',
tfvars: 'terraform',
toml: 'toml',
ts: 'typescript',
'ts-tags': 'ts-tags',
tsp: 'typespec',
tsv: 'tsv',
tsx: 'tsx',
turtle: 'turtle',
twig: 'twig',
typ: 'typst',
typescript: 'typescript',
typespec: 'typespec',
typst: 'typst',
v: 'v',
vala: 'vala',
vb: 'vb',
verilog: 'verilog',
vhdl: 'vhdl',
vim: 'viml',
viml: 'viml',
vimscript: 'viml',
vue: 'vue',
'vue-html': 'vue-html',
'vue-vine': 'vue-vine',
vy: 'vyper',
vyper: 'vyper',
wasm: 'wasm',
wenyan: 'wenyan',
wgsl: 'wgsl',
wiki: 'wikitext',
wikitext: 'wikitext',
wit: 'wit',
wl: 'wolfram',
wolfram: 'wolfram',
xml: 'xml',
xsl: 'xsl',
yaml: 'yaml',
yml: 'yaml',
zenscript: 'zenscript',
zig: 'zig',
zsh: 'shellscript',
文言: 'wenyan',
};
/** Grammars to register for each language, embedded ones first. */
export const SHIKI_LANGUAGE_GRAMMARS: Record<string, string[]> = {
abap: ['abap'],
'actionscript-3': ['actionscript-3'],
ada: ['ada'],
'angular-html': [
'javascript',
'css',
'html',
'angular-expression',
'angular-expression',
'angular-let-declaration',
'angular-expression',
'angular-template',
'angular-expression',
'angular-expression',
'angular-template',
'angular-template-blocks',
'angular-html',
],
'angular-ts': [
'angular-expression',
'css',
'scss',
'angular-inline-style',
'javascript',
'css',
'html',
'angular-expression',
'angular-expression',
'angular-let-declaration',
'angular-expression',
'angular-template',
'angular-expression',
'angular-expression',
'angular-template',
'angular-template-blocks',
'angular-html',
'angular-expression',
'angular-template',
'angular-inline-template',
'angular-expression',
'angular-let-declaration',
'angular-expression',
'angular-template',
'angular-expression',
'angular-expression',
'angular-template',
'angular-template-blocks',
'angular-ts',
],
apache: ['apache'],
apex: ['apex'],
apl: ['javascript', 'css', 'html', 'java', 'xml', 'css', 'javascript', 'json', 'apl'],
applescript: ['applescript'],
ara: ['ara'],
asciidoc: ['asciidoc'],
asm: ['asm'],
astro: ['json', 'javascript', 'typescript', 'css', 'postcss', 'tsx', 'astro'],
awk: ['awk'],
ballerina: ['ballerina'],
bat: ['bat'],
beancount: ['beancount'],
berry: ['berry'],
bibtex: ['bibtex'],
bicep: ['bicep'],
blade: [
'javascript',
'css',
'html',
'html-derivative',
'javascript',
'css',
'html',
'java',
'xml',
'sql',
'javascript',
'json',
'css',
'blade',
],
bsl: ['sdbl', 'bsl'],
c: ['c'],
c3: ['c3'],
cadence: ['cadence'],
cairo: ['python', 'cairo'],
clarity: ['clarity'],
clojure: ['clojure'],
cmake: ['cmake'],
cobol: ['javascript', 'css', 'html', 'java', 'cobol'],
codeowners: ['codeowners'],
codeql: ['codeql'],
coffee: ['javascript', 'coffee'],
'common-lisp': ['common-lisp'],
coq: ['coq'],
cpp: ['regexp', 'c', 'glsl', 'sql', 'cpp-macro', 'regexp', 'c', 'glsl', 'sql', 'cpp'],
crystal: [
'javascript',
'css',
'html',
'sql',
'css',
'c',
'javascript',
'shellscript',
'crystal',
],
csharp: ['csharp'],
css: ['css'],
csv: ['csv'],
cue: ['cue'],
cypher: ['cypher'],
d: ['d'],
dart: ['dart'],
dax: ['dax'],
desktop: ['desktop'],
diff: ['diff'],
docker: ['docker'],
dotenv: ['dotenv'],
'dream-maker': ['dream-maker'],
edge: [
'typescript',
'javascript',
'css',
'html',
'javascript',
'css',
'html',
'html-derivative',
'edge',
],
elixir: ['javascript', 'css', 'html', 'elixir'],
elm: ['c', 'glsl', 'elm'],
'emacs-lisp': ['emacs-lisp'],
erb: [
'javascript',
'css',
'html',
'javascript',
'css',
'html',
'javascript',
'css',
'haml',
'java',
'xml',
'sql',
'javascript',
'typescript',
'jsx',
'tsx',
'graphql',
'css',
'regexp',
'c',
'glsl',
'sql',
'cpp-macro',
'regexp',
'c',
'glsl',
'sql',
'cpp',
'c',
'javascript',
'shellscript',
'c',
'lua',
'yaml',
'ruby',
'erb',
],
erlang: ['markdown', 'erlang'],
fennel: ['fennel'],
fish: ['fish'],
fluent: ['fluent'],
'fortran-fixed-form': ['fortran-free-form', 'fortran-fixed-form'],
'fortran-free-form': ['fortran-free-form'],
fsharp: ['markdown', 'fsharp'],
gdresource: ['gdshader', 'gdscript', 'gdresource'],
gdscript: ['gdscript'],
gdshader: ['gdshader'],
genie: ['genie'],
gherkin: ['gherkin'],
'git-commit': ['diff', 'git-commit'],
'git-rebase': ['shellscript', 'git-rebase'],
gleam: ['gleam'],
'glimmer-js': ['javascript', 'typescript', 'css', 'javascript', 'css', 'html', 'glimmer-js'],
'glimmer-ts': ['typescript', 'css', 'javascript', 'javascript', 'css', 'html', 'glimmer-ts'],
glsl: ['c', 'glsl'],
gn: ['gn'],
gnuplot: ['gnuplot'],
go: ['go'],
graphql: ['javascript', 'typescript', 'jsx', 'tsx', 'graphql'],
groovy: ['groovy'],
hack: ['javascript', 'css', 'html', 'sql', 'hack'],
haml: ['javascript', 'css', 'haml'],
handlebars: ['javascript', 'css', 'html', 'css', 'javascript', 'yaml', 'handlebars'],
haskell: ['haskell'],
haxe: ['haxe'],
hcl: ['hcl'],
hjson: ['hjson'],
hlsl: ['hlsl'],
html: ['javascript', 'css', 'html'],
'html-derivative': ['javascript', 'css', 'html', 'html-derivative'],
http: [
'shellscript',
'json',
'java',
'xml',
'javascript',
'typescript',
'jsx',
'tsx',
'graphql',
'http',
],
hurl: ['javascript', 'typescript', 'jsx', 'tsx', 'graphql', 'java', 'xml', 'csv', 'hurl'],
hxml: ['haxe', 'hxml'],
hy: ['hy'],
imba: ['imba'],
ini: ['ini'],
java: ['java'],
javascript: ['javascript'],
jinja: ['javascript', 'css', 'html', 'jinja-html', 'jinja'],
jison: ['javascript', 'jison'],
json: ['json'],
json5: ['json5'],
jsonc: ['jsonc'],
jsonl: ['jsonl'],
jsonnet: ['jsonnet'],
jssm: ['jssm'],
jsx: ['jsx'],
julia: [
'regexp',
'c',
'glsl',
'sql',
'cpp-macro',
'regexp',
'c',
'glsl',
'sql',
'cpp',
'python',
'javascript',
'r',
'sql',
'julia',
],
kdl: ['kdl'],
kotlin: ['kotlin'],
kusto: ['kusto'],
latex: ['r', 'tex', 'latex'],
lean: ['lean'],
less: ['less'],
liquid: ['javascript', 'css', 'html', 'css', 'json', 'javascript', 'liquid'],
llvm: ['llvm'],
log: ['log'],
logo: ['logo'],
lua: ['c', 'lua'],
luau: ['luau'],
make: ['make'],
markdown: ['markdown'],
marko: ['css', 'less', 'css', 'scss', 'typescript', 'marko'],
matlab: ['matlab'],
mdc: ['markdown', 'yaml', 'javascript', 'css', 'html', 'html-derivative', 'mdc'],
mdx: ['mdx'],
mermaid: ['mermaid'],
mipsasm: ['mipsasm'],
mojo: ['mojo'],
moonbit: ['moonbit'],
move: ['move'],
narrat: ['narrat'],
nextflow: ['nextflow'],
nginx: ['c', 'lua', 'nginx'],
nim: [
'c',
'javascript',
'css',
'html',
'java',
'xml',
'javascript',
'css',
'c',
'glsl',
'markdown',
'nim',
],
nix: ['markdown-nix', 'nix'],
nushell: ['nushell'],
'objective-c': ['objective-c'],
'objective-cpp': ['objective-cpp'],
ocaml: ['ocaml'],
openscad: ['openscad'],
pascal: ['pascal'],
perl: ['javascript', 'css', 'html', 'java', 'xml', 'css', 'javascript', 'sql', 'perl'],
php: ['javascript', 'css', 'html', 'java', 'xml', 'sql', 'javascript', 'json', 'css', 'php'],
pkl: ['pkl'],
plsql: ['plsql'],
po: ['po'],
polar: ['polar'],
postcss: ['postcss'],
powerquery: ['powerquery'],
powershell: ['powershell'],
prisma: ['prisma'],
prolog: ['prolog'],
proto: ['proto'],
pug: ['javascript', 'css', 'javascript', 'css', 'html', 'pug'],
puppet: ['puppet'],
purescript: ['purescript'],
python: ['python'],
qml: ['javascript', 'qml'],
qmldir: ['qmldir'],
qss: ['qss'],
r: ['r'],
racket: ['racket'],
raku: ['raku'],
razor: ['javascript', 'css', 'html', 'csharp', 'razor'],
reg: ['reg'],
regexp: ['regexp'],
rel: ['rel'],
riscv: ['riscv'],
rosmsg: ['rosmsg'],
rst: [
'javascript',
'css',
'html',
'html-derivative',
'regexp',
'c',
'glsl',
'sql',
'cpp-macro',
'regexp',
'c',
'glsl',
'sql',
'cpp',
'python',
'javascript',
'shellscript',
'yaml',
'cmake',
'javascript',
'css',
'html',
'javascript',
'css',
'haml',
'java',
'xml',
'sql',
'javascript',
'typescript',
'jsx',
'tsx',
'graphql',
'css',
'regexp',
'c',
'glsl',
'sql',
'cpp-macro',
'regexp',
'c',
'glsl',
'sql',
'cpp',
'c',
'javascript',
'shellscript',
'c',
'lua',
'yaml',
'ruby',
'rst',
],
ruby: [
'javascript',
'css',
'html',
'javascript',
'css',
'haml',
'java',
'xml',
'sql',
'javascript',
'typescript',
'jsx',
'tsx',
'graphql',
'css',
'regexp',
'c',
'glsl',
'sql',
'cpp-macro',
'regexp',
'c',
'glsl',
'sql',
'cpp',
'c',
'javascript',
'shellscript',
'c',
'lua',
'yaml',
'ruby',
],
rust: ['rust'],
sas: ['sql', 'sas'],
sass: ['sass'],
scala: ['scala'],
scheme: ['scheme'],
scss: ['css', 'scss'],
sdbl: ['sdbl'],
shaderlab: ['hlsl', 'shaderlab'],
shellscript: ['shellscript'],
shellsession: ['shellscript', 'shellsession'],
smalltalk: ['smalltalk'],
solidity: ['solidity'],
soy: ['javascript', 'css', 'html', 'soy'],
sparql: ['turtle', 'sparql'],
splunk: ['splunk'],
sql: ['sql'],
'ssh-config': ['ssh-config'],
stata: ['sql', 'stata'],
stylus: ['stylus'],
svelte: ['javascript', 'typescript', 'css', 'postcss', 'svelte'],
swift: ['swift'],
'system-verilog': ['system-verilog'],
systemd: ['systemd'],
talonscript: ['talonscript'],
tasl: ['tasl'],
tcl: ['tcl'],
templ: ['go', 'javascript', 'css', 'templ'],
terraform: ['terraform'],
tex: ['r', 'tex'],
toml: ['toml'],
'ts-tags': [
'typescript',
'typescript',
'css',
'javascript',
'es-tag-css',
'typescript',
'c',
'glsl',
'javascript',
'es-tag-glsl',
'typescript',
'javascript',
'css',
'html',
'javascript',
'es-tag-html',
'typescript',
'sql',
'es-tag-sql',
'java',
'xml',
'es-tag-xml',
'ts-tags',
],
tsv: ['tsv'],
tsx: ['tsx'],
turtle: ['turtle'],
twig: [
'css',
'javascript',
'css',
'scss',
'javascript',
'css',
'html',
'java',
'xml',
'sql',
'javascript',
'json',
'css',
'php',
'python',
'javascript',
'css',
'html',
'javascript',
'css',
'haml',
'java',
'xml',
'sql',
'javascript',
'typescript',
'jsx',
'tsx',
'graphql',
'css',
'regexp',
'c',
'glsl',
'sql',
'cpp-macro',
'regexp',
'c',
'glsl',
'sql',
'cpp',
'c',
'javascript',
'shellscript',
'c',
'lua',
'yaml',
'ruby',
'twig',
],
typescript: ['typescript'],
typespec: ['typespec'],
typst: ['typst'],
v: ['v'],
vala: ['vala'],
vb: ['vb'],
verilog: ['verilog'],
vhdl: ['vhdl'],
viml: ['viml'],
vue: [
'css',
'javascript',
'typescript',
'json',
'javascript',
'css',
'html',
'javascript',
'css',
'html',
'html-derivative',
'markdown-vue',
'vue-directives',
'vue-interpolations',
'javascript',
'vue-sfc-style-variable-injection',
'vue',
],
'vue-html': ['javascript', 'vue-html'],
'vue-vine': ['css', 'css', 'scss', 'less', 'stylus', 'postcss', 'javascript', 'vue-vine'],
vyper: ['vyper'],
wasm: ['wasm'],
wenyan: ['wenyan'],
wgsl: ['wgsl'],
wikitext: ['wikitext'],
wit: ['wit'],
wolfram: ['wolfram'],
xml: ['java', 'xml'],
xsl: ['java', 'xml', 'xsl'],
yaml: ['yaml'],
zenscript: ['zenscript'],
zig: ['zig'],
};
export function getShikiGrammarAssetPath(name: string): string {
return `${SHIKI_ASSETS_PATH}/grammars/${name}.json`;
}
export function getShikiThemeAssetPath(id: string): string {
return `${SHIKI_ASSETS_PATH}/themes/${id}.json`;
}
@@ -1,185 +0,0 @@
// Generated by scripts/generate-shiki-assets.ts, do not edit.
/** Every bundled Shiki theme id, with its type. */
export const SHIKI_THEMES: Record<string, { type: 'light' | 'dark' }> = {
andromeeda: {
type: 'dark',
},
'aurora-x': {
type: 'dark',
},
'ayu-dark': {
type: 'dark',
},
'catppuccin-frappe': {
type: 'dark',
},
'catppuccin-latte': {
type: 'light',
},
'catppuccin-macchiato': {
type: 'dark',
},
'catppuccin-mocha': {
type: 'dark',
},
'dark-plus': {
type: 'dark',
},
dracula: {
type: 'dark',
},
'dracula-soft': {
type: 'dark',
},
'everforest-dark': {
type: 'dark',
},
'everforest-light': {
type: 'light',
},
'github-dark': {
type: 'dark',
},
'github-dark-default': {
type: 'dark',
},
'github-dark-dimmed': {
type: 'dark',
},
'github-dark-high-contrast': {
type: 'dark',
},
'github-light': {
type: 'light',
},
'github-light-default': {
type: 'light',
},
'github-light-high-contrast': {
type: 'light',
},
'gruvbox-dark-hard': {
type: 'dark',
},
'gruvbox-dark-medium': {
type: 'dark',
},
'gruvbox-dark-soft': {
type: 'dark',
},
'gruvbox-light-hard': {
type: 'light',
},
'gruvbox-light-medium': {
type: 'light',
},
'gruvbox-light-soft': {
type: 'light',
},
houston: {
type: 'dark',
},
'kanagawa-dragon': {
type: 'dark',
},
'kanagawa-lotus': {
type: 'light',
},
'kanagawa-wave': {
type: 'dark',
},
laserwave: {
type: 'dark',
},
'light-plus': {
type: 'light',
},
'material-theme': {
type: 'dark',
},
'material-theme-darker': {
type: 'dark',
},
'material-theme-lighter': {
type: 'light',
},
'material-theme-ocean': {
type: 'dark',
},
'material-theme-palenight': {
type: 'dark',
},
'min-dark': {
type: 'dark',
},
'min-light': {
type: 'light',
},
monokai: {
type: 'dark',
},
'night-owl': {
type: 'dark',
},
nord: {
type: 'dark',
},
'one-dark-pro': {
type: 'dark',
},
'one-light': {
type: 'light',
},
plastic: {
type: 'dark',
},
poimandres: {
type: 'dark',
},
red: {
type: 'dark',
},
'rose-pine': {
type: 'dark',
},
'rose-pine-dawn': {
type: 'light',
},
'rose-pine-moon': {
type: 'dark',
},
'slack-dark': {
type: 'dark',
},
'slack-ochin': {
type: 'light',
},
'snazzy-light': {
type: 'light',
},
'solarized-dark': {
type: 'dark',
},
'solarized-light': {
type: 'light',
},
'synthwave-84': {
type: 'dark',
},
'tokyo-night': {
type: 'dark',
},
vesper: {
type: 'dark',
},
'vitesse-black': {
type: 'dark',
},
'vitesse-dark': {
type: 'dark',
},
'vitesse-light': {
type: 'light',
},
};
@@ -39,7 +39,6 @@ export type OpenAPIBlockClientContextProps = {
headingNode: React.ReactNode;
descriptionNode: React.ReactNode;
scalarRuntimeURL: string;
staticAssetsURL: string;
};
type OpenAPIBlockVariant =
@@ -66,13 +65,7 @@ export function OpenAPIBlockClient(props: OpenAPIBlockClientProps) {
id: props.id,
blockKey: props.blockKey,
renderCodeBlock: ({ code, syntax }) => (
<ClientPlainCodeBlock
code={code}
syntax={syntax}
mode={mode}
themes={codeTheme}
staticAssetsURL={props.staticAssetsURL}
/>
<ClientPlainCodeBlock code={code} syntax={syntax} mode={mode} themes={codeTheme} />
),
renderDocument: () => descriptionNode,
renderHeading: () => headingNode,
@@ -166,7 +166,6 @@ export function getOpenAPIBlockClientProps(args: {
return {
...serializable,
mode: props.context.mode,
staticAssetsURL: getAssetURL(''),
codeTheme:
context && 'customization' in context
? context.customization.styling.codeTheme.openapi
+10
View File
@@ -1,5 +1,15 @@
# @gitbook/icons
## 0.6.0
### Minor Changes
- 9fcde5f: Add a `@gitbook/icons/validateIconName` entry that validates icon names without loading the icon labels and search terms.
### Patch Changes
- 265ca4b: Add a skip link, keyboard navigation between content tabs, focusable table of contents toggles, and hide decorative icons from assistive technologies.
## 0.5.0
### Minor Changes
+1 -1
View File
@@ -39,7 +39,7 @@
}
},
"sideEffects": false,
"version": "0.5.0",
"version": "0.6.0",
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^7.2.0",
"@gitbook/fontawesome-pro": "1.0.23"
+8
View File
@@ -1,5 +1,13 @@
# @gitbook/react-contentkit
## 0.7.19
### Patch Changes
- Updated dependencies [9fcde5f]
- Updated dependencies [265ca4b]
- @gitbook/icons@0.6.0
## 0.7.18
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@gitbook/react-contentkit",
"version": "0.7.18",
"version": "0.7.19",
"type": "module",
"exports": {
".": {
+6
View File
@@ -1,5 +1,11 @@
# @gitbook/react-openapi
## 2.0.2
### Patch Changes
- 262749a: Copy the current spec's server in OpenAPI endpoint URLs instead of a server kept from a previously visited page.
## 2.0.1
### Patch Changes
+1 -1
View File
@@ -7,7 +7,7 @@
"default": "./dist/index.js"
}
},
"version": "2.0.1",
"version": "2.0.2",
"sideEffects": false,
"dependencies": {
"@base-ui/react": "catalog:",