mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-26 02:02:32 +00:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c44efc3460 | |||
| cac0684247 | |||
| 41779f668b | |||
| b00040d467 | |||
| cd6d35c3f0 | |||
| 461b1675c0 | |||
| 7741627af3 | |||
| 9f6e35da87 | |||
| 5cab25764f | |||
| 412cd06c7d |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Load Shiki languages and themes from static assets instead of bundling them.
|
||||
@@ -0,0 +1,104 @@
|
||||
# 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).
|
||||
@@ -0,0 +1,291 @@
|
||||
# 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`.
|
||||
@@ -0,0 +1,61 @@
|
||||
# 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).
|
||||
@@ -120,6 +120,11 @@ 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,6 +12,13 @@
|
||||
"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",
|
||||
},
|
||||
|
||||
@@ -119,9 +119,9 @@
|
||||
},
|
||||
"scripts": {
|
||||
"generate": "./scripts/generate.sh",
|
||||
"generate:assets": "bun ./scripts/generate-mermaid-runtime.ts && bun ./scripts/generate-scalar-runtime.ts && bun ./scripts/download-fonts.ts",
|
||||
"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: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",
|
||||
"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",
|
||||
"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",
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
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))),
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
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));
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
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,6 +23,8 @@ 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;
|
||||
@@ -35,8 +37,17 @@ 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, embedded, commentKey } =
|
||||
props;
|
||||
const {
|
||||
block,
|
||||
mode,
|
||||
style,
|
||||
inlines,
|
||||
evaluateInlineExpression,
|
||||
themes,
|
||||
staticAssetsURL,
|
||||
embedded,
|
||||
commentKey,
|
||||
} = props;
|
||||
const blockRef = useRef<HTMLDivElement>(null);
|
||||
const isInViewportRef = useRef(false);
|
||||
const [isInViewport, setIsInViewport] = useState(false);
|
||||
@@ -50,8 +61,10 @@ export function ClientCodeBlock(props: ClientBlockProps) {
|
||||
|
||||
// Preload the highlighter when the block is mounted.
|
||||
useEffect(() => {
|
||||
import('./highlight').then(({ preloadHighlight }) => preloadHighlight(block, themes));
|
||||
}, [block, themes]);
|
||||
import('./highlight-client').then(({ getClientHighlight }) =>
|
||||
getClientHighlight(staticAssetsURL).preloadHighlight(block, themes)
|
||||
);
|
||||
}, [block, themes, staticAssetsURL]);
|
||||
|
||||
// When user scrolls, we need to wait for the scroll to finish before running the highlight
|
||||
const isScrollingRef = useRef(false);
|
||||
@@ -99,7 +112,8 @@ export function ClientCodeBlock(props: ClientBlockProps) {
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
setHighlighting(true);
|
||||
import('./highlight').then(({ highlight }) => {
|
||||
import('./highlight-client').then(({ getClientHighlight }) => {
|
||||
const { highlight } = getClientHighlight(staticAssetsURL);
|
||||
highlight(block, inlines, { evaluateInlineExpression, themes }).then(
|
||||
(theme) => {
|
||||
if (cancelled) {
|
||||
@@ -120,7 +134,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]);
|
||||
}, [isInViewport, block, inlines, evaluateInlineExpression, themes, staticAssetsURL]);
|
||||
|
||||
const expandable = block.data.expandable;
|
||||
|
||||
|
||||
@@ -15,8 +15,9 @@ export function ClientPlainCodeBlock(props: {
|
||||
syntax: string;
|
||||
mode?: DocumentContext['mode'];
|
||||
themes?: CustomizationThemedCodeTheme;
|
||||
staticAssetsURL: string;
|
||||
}) {
|
||||
const { code, syntax, mode = 'default', themes } = props;
|
||||
const { code, syntax, mode = 'default', themes, staticAssetsURL } = props;
|
||||
const id = useId();
|
||||
|
||||
const block = convertCodeStringToBlock({ key: id, code, syntax });
|
||||
@@ -28,6 +29,7 @@ export function ClientPlainCodeBlock(props: {
|
||||
inlineExprVariables={{}}
|
||||
mode={mode}
|
||||
themes={themes}
|
||||
staticAssetsURL={staticAssetsURL}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -122,6 +122,7 @@ export async function CodeBlock(
|
||||
inlineExprVariables: variables,
|
||||
mode: context.mode,
|
||||
themes,
|
||||
staticAssetsURL: getAssetURL(''),
|
||||
embedded,
|
||||
...getCommentKeyProp(context, block.key),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
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']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
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,178 +1,7 @@
|
||||
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';
|
||||
import { createHighlight } from './highlighter';
|
||||
import { loadShikiAssetOnServer } from './shiki-assets.server';
|
||||
|
||||
export * from './highlight-tokens';
|
||||
export { getLanguageForSyntax } from './highlighter';
|
||||
|
||||
// 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;
|
||||
}
|
||||
export const { highlight, preloadHighlight } = createHighlight(loadShikiAssetOnServer);
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
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
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
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,5 +1,3 @@
|
||||
import { bundledThemesInfo } from 'shiki/themes';
|
||||
|
||||
import type { CustomizationThemedCodeTheme, DocumentBlockCode } from '@gitbook/api';
|
||||
|
||||
import { customThemes } from './customThemes';
|
||||
@@ -11,6 +9,7 @@ import {
|
||||
parseDiffNotation,
|
||||
truncateHighlightTokens,
|
||||
} from './highlight-tokens';
|
||||
import { SHIKI_THEMES } from './shiki-themes';
|
||||
import { getNodeText } from '@/lib/document';
|
||||
|
||||
/**
|
||||
@@ -29,11 +28,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: bundledThemesInfo.find((theme) => theme.id === options?.themes?.light) ??
|
||||
light: getBundledThemeInfo(options?.themes?.light) ??
|
||||
Object.values(customThemes).find((theme) => theme.name === options?.themes?.light) ?? {
|
||||
type: 'light',
|
||||
},
|
||||
dark: bundledThemesInfo.find((theme) => theme.id === options?.themes?.dark) ??
|
||||
dark: getBundledThemeInfo(options?.themes?.dark) ??
|
||||
Object.values(customThemes).find((theme) => theme.name === options?.themes?.dark) ?? {
|
||||
type: 'dark',
|
||||
},
|
||||
@@ -82,3 +81,8 @@ export function plainHighlight(
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function getBundledThemeInfo(name: string | undefined) {
|
||||
const info = name ? SHIKI_THEMES[name] : undefined;
|
||||
return info ? { name, type: info.type } : undefined;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
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'));
|
||||
};
|
||||
@@ -0,0 +1,69 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,902 @@
|
||||
// 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`;
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
// 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,6 +39,7 @@ export type OpenAPIBlockClientContextProps = {
|
||||
headingNode: React.ReactNode;
|
||||
descriptionNode: React.ReactNode;
|
||||
scalarRuntimeURL: string;
|
||||
staticAssetsURL: string;
|
||||
};
|
||||
|
||||
type OpenAPIBlockVariant =
|
||||
@@ -65,7 +66,13 @@ export function OpenAPIBlockClient(props: OpenAPIBlockClientProps) {
|
||||
id: props.id,
|
||||
blockKey: props.blockKey,
|
||||
renderCodeBlock: ({ code, syntax }) => (
|
||||
<ClientPlainCodeBlock code={code} syntax={syntax} mode={mode} themes={codeTheme} />
|
||||
<ClientPlainCodeBlock
|
||||
code={code}
|
||||
syntax={syntax}
|
||||
mode={mode}
|
||||
themes={codeTheme}
|
||||
staticAssetsURL={props.staticAssetsURL}
|
||||
/>
|
||||
),
|
||||
renderDocument: () => descriptionNode,
|
||||
renderHeading: () => headingNode,
|
||||
|
||||
@@ -166,6 +166,7 @@ export function getOpenAPIBlockClientProps(args: {
|
||||
return {
|
||||
...serializable,
|
||||
mode: props.context.mode,
|
||||
staticAssetsURL: getAssetURL(''),
|
||||
codeTheme:
|
||||
context && 'customization' in context
|
||||
? context.customization.styling.codeTheme.openapi
|
||||
|
||||
Reference in New Issue
Block a user