mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-27 10:43:32 +00:00
Load Shiki grammars and themes from static assets (#4848)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Load Shiki languages and themes from static assets instead of bundling them.
|
||||
@@ -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