// one adapter per highlighter under comparison. // // an adapter exposes the narrowest entry point doing the same STAGE of work // as its neighbours - `tokenize` is tokens-out for everyone, `html` is // string-out for everyone - and declares its languages explicitly rather than // letting the library fall back. otherwise a library that returns escaped // plaintext for a language it does not know benchmarks as spectacularly fast. // // token granularity is NOT equalised, because it cannot be. twinkleplop emits // a finer stream than most of these, which is more work per byte; the runner // records a token count per cell so that is visible rather than hidden. import { existsSync, readdirSync, readFileSync } from "node:fs"; import { createRequire } from "node:module"; import { dirname, join } from "node:path"; const require_ = createRequire(import.meta.url); // a comparison that cannot say which version it measured is not // reproducible, so "unknown" is a real defect. two lookups because neither // works everywhere: `/package.json` is blocked when `exports` does not // list it (sugar-high), and walking up from the entry point fails for a // package with no main export. const version_of = (name) => { try { return require_(`${name}/package.json`).version; } catch { // check the name matches, so a parent package's manifest in a hoisted // tree cannot be mistaken for this one. try { let dir = dirname(require_.resolve(name)); for (let up = 0; up < 10; up++) { const manifest = join(dir, "package.json"); if (existsSync(manifest)) { const pkg = JSON.parse(readFileSync(manifest, "utf8")); if (pkg.name === name) return pkg.version; } const parent = dirname(dir); if (parent === dir) break; dir = parent; } } catch { // fall through } return "unknown"; } }; const core_version = (root) => { try { return JSON.parse(readFileSync(join(root, "lib/core/package.json"), "utf8")).version; } catch { return "unknown"; } }; // our language id -> that library's id. absent means "this library does not // do this language", and the cell is simply not measured. const SHIKI_LANGS = { bash: "bash", c: "c", cpp: "cpp", css: "css", diff: "diff", dockerfile: "docker", dotenv: "dotenv", go: "go", graphql: "graphql", html: "html", http: "http", ini: "ini", javascript: "javascript", json: "json", jsonc: "jsonc", markdown: "markdown", powershell: "powershell", python: "python", rust: "rust", shellsession: "shellsession", sql: "sql", svelte: "svelte", toml: "toml", tsx: "tsx", typescript: "typescript", yaml: "yaml", }; // no dotenv grammar, its json grammar matches comments so it reads jsonc for real const PRISM_LANGS = { bash: "bash", c: "c", cpp: "cpp", css: "css", diff: "diff", dockerfile: "docker", go: "go", graphql: "graphql", html: "markup", http: "http", ini: "ini", javascript: "javascript", json: "json", jsonc: "json", markdown: "markdown", powershell: "powershell", python: "python", rust: "rust", shellsession: "shell-session", sql: "sql", toml: "toml", tsx: "tsx", typescript: "typescript", yaml: "yaml", }; // sugar-high has no grammar registry at all: one JS-shaped tokenizer, no // language argument. listing it against js/ts/tsx is the honest reading of // what it supports, and its absence everywhere else is a real limitation of // the library rather than a gap in this suite. const SUGAR_HIGH_LANGS = { javascript: "javascript", typescript: "typescript", tsx: "tsx", }; // no tsx or svelte grammar. its `ts` grammar is not a stand-in for tsx: jsx // would tokenize as comparisons and the chart would be measuring a // misparse. // same for c against cpp and json against jsonc, and no graphql, powershell, dotenv or shellsession grammar const SPEED_HIGHLIGHT_LANGS = { bash: "bash", c: "c", css: "css", diff: "diff", dockerfile: "docker", go: "go", html: "html", http: "http", ini: "ini", javascript: "js", json: "json", markdown: "md", python: "py", rust: "rs", sql: "sql", toml: "toml", typescript: "ts", yaml: "yaml", }; const SHIKI_THEME = "github-light"; async function shiki_adapter({ id, label, note, engine_factory }) { const { createHighlighter } = await import("shiki"); const highlighter = await createHighlighter({ themes: [SHIKI_THEME], langs: [...new Set(Object.values(SHIKI_LANGS))], engine: await engine_factory(), }); return { id, label, version: version_of("shiki"), note, supports: (lang) => lang in SHIKI_LANGS, tokenize: (code, lang) => highlighter.codeToTokens(code, { lang: SHIKI_LANGS[lang], theme: SHIKI_THEME }), html: (code, lang) => highlighter.codeToHtml(code, { lang: SHIKI_LANGS[lang], theme: SHIKI_THEME }), count_tokens: (out) => out.tokens.reduce((n, line) => n + line.length, 0), }; } export const ADAPTERS = { // the library under test. measured on the path a consumer actually gets: // `tokenize()` runs the language's full reclassifier stack, not the bare // grammar. the bare `core.tokenize` path is faster and would make a nicer // chart, but nobody ships it. twinkleplop: async ({ arm }) => ({ id: "twinkleplop", label: "twinkleplop", // read from the ARM's own package.json, not this checkout's. the arm can // be any built root - a frozen reference, another worktree - and // labelling its numbers with the version of whatever tree happens to // contain this file would attach the chart to the wrong commit. version: core_version(arm.root), note: "full pipeline: grammar plus the language's reclassifier stack, as shipped.", supports: (lang) => { const mod = arm.languages[lang]; return typeof mod?.tokenize === "function" && typeof mod?.language === "function"; }, bind: (lang) => { const mod = arm.languages[lang]; return { tokenize: mod.tokenize(), html: mod.language() }; }, // tokens is a flat array of type, start, end triples count_tokens: (out) => (out?.tokens?.length ?? 0) / 3, }), "shiki-wasm": async () => { const { createOnigurumaEngine } = await import("shiki"); return shiki_adapter({ id: "shiki-wasm", label: "Shiki (wasm)", note: "Oniguruma wasm engine, shiki's default. HTML output carries inline styles rather than classes.", engine_factory: () => createOnigurumaEngine(() => import("shiki/wasm")), }); }, "shiki-js": async () => { const { createJavaScriptRegexEngine } = await import("shiki"); return shiki_adapter({ id: "shiki-js", label: "Shiki (JS engine)", note: "same grammars, RegExp engine instead of wasm. Shiki's own benchmark treats these as separate arms, the wasm payload is a real deployment cost the JS engine avoids.", engine_factory: () => createJavaScriptRegexEngine(), }); }, prism: async () => { const Prism = (await import("prismjs")).default; const { default: load_languages } = await import("prismjs/components/index.js"); load_languages([...new Set(Object.values(PRISM_LANGS))]); return { id: "prism", label: "Prism", version: version_of("prismjs"), note: "class-based HTML output, same as twinkleplop's.", supports: (lang) => lang in PRISM_LANGS && Boolean(Prism.languages[PRISM_LANGS[lang]]), tokenize: (code, lang) => Prism.tokenize(code, Prism.languages[PRISM_LANGS[lang]], PRISM_LANGS[lang]), html: (code, lang) => Prism.highlight(code, Prism.languages[PRISM_LANGS[lang]], PRISM_LANGS[lang]), count_tokens: (out) => (Array.isArray(out) ? out.length : 0), }; }, "sugar-high": async () => { const { highlight, tokenize } = await import("sugar-high"); return { id: "sugar-high", label: "sugar-high", version: version_of("sugar-high"), note: "JavaScript-shaped tokenizer with no grammar registry: it has no language argument, so it appears only in the JS-family charts. Coarser output than the others.", supports: (lang) => lang in SUGAR_HIGH_LANGS, tokenize: (code) => tokenize(code), html: (code) => highlight(code), count_tokens: (out) => (Array.isArray(out) ? out.length : 0), }; }, // the public `tokenize` and `highlightHTML` are async only because they // lazy-load grammars, awaiting between every nested language. preloading // every grammar and driving the sync `tokenizeWith` is the same tokenizer // with the loader taken out, so what is timed is highlighting rather than // microtask turns. the html arm reuses its escaping and span shape // verbatim, in inline mode so no line-number wrapper is built. "speed-highlight": async () => { const { tokenizeWith } = await import("@speed-highlight/core/tokenize"); // its exports map hides package.json, so find the grammar directory // through the languages barrel instead. const dir = dirname(require_.resolve("@speed-highlight/core/languages")); // sub-grammars (jsdoc, regex, xml, ...) are requested by name mid-scan, // so every grammar goes in the table, not just the ones mapped above. const languages = {}; for (const file of readdirSync(dir)) { if (!file.endsWith(".js") || file === "index.js") continue; const mod = await import(`@speed-highlight/core/languages/${file}`); languages[file.slice(0, -3)] = mod.default; } const options = { languages }; const escape = (text) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">"); return { id: "speed-highlight", label: "speed-highlight", version: version_of("@speed-highlight/core"), note: "regex grammars, class-based HTML output. driven through its sync tokenizer with grammars preloaded; the public API is async. No tsx, svelte, diff-basic, cpp, jsonc, graphql, powershell, dotenv or shellsession grammar, so it is missing from those charts.", supports: (lang) => lang in SPEED_HIGHLIGHT_LANGS, tokenize: (code, lang) => { const out = []; tokenizeWith( code, SPEED_HIGHLIGHT_LANGS[lang], (text, type) => { if (text) out.push([text, type]); }, options, ); return out; }, html: (code, lang) => { let out = ""; tokenizeWith( code, SPEED_HIGHLIGHT_LANGS[lang], (text, type) => { out += type ? `${escape(text)}` : escape(text); }, options, ); return out; }, count_tokens: (out) => (Array.isArray(out) ? out.length : 0), }; }, // opt in, KIRARI_DIR names an installed @vortexlabs/kirari package directory kirari: async () => { const dir = process.env.KIRARI_DIR; if (!dir) throw new Error("kirari: set KIRARI_DIR to an installed @vortexlabs/kirari"); const { tokenize, highlight } = await import(join(dir, "dist/index.js")); // index.d.ts declares every language but index.js exports none, and // tokenize falls back to javascript on undefined const k = await import(join(dir, "dist/languages.js")); const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); // no http or shell session grammar, its shell grammar is bash const LANGS = { bash: k.shell, c: k.c, cpp: k.cpp, css: k.css, diff: k.diff, dockerfile: k.dockerfile, dotenv: k.dotenv, go: k.go, graphql: k.graphql, html: k.html, ini: k.ini, javascript: k.javascript, json: k.json, jsonc: k.jsonc, markdown: k.markdown, powershell: k.powershell, python: k.python, rust: k.rust, sql: k.sql, svelte: k.svelte, toml: k.toml, tsx: k.tsx, typescript: k.typescript, yaml: k.yaml, }; return { id: "kirari", label: "kirari", version: pkg.version, note: "regex lexer, class-based HTML output. Emits whitespace as `text` tokens; those are not counted.", supports: (lang) => Boolean(LANGS[lang]), tokenize: (code, lang) => tokenize(code, LANGS[lang]), html: (code, lang) => highlight(code, { language: LANGS[lang] }), count_tokens: (out) => { if (!Array.isArray(out)) return 0; let n = 0; for (const t of out) if (t.type !== "text") n++; return n; }, }; }, // opt in, PIERRE_DIR names an installed @pierre/highlights package directory "pierre-highlights": async () => { const dir = process.env.PIERRE_DIR; if (!dir) throw new Error("pierre-highlights: set PIERRE_DIR to an installed @pierre/highlights"); const { codeToTokens, codeToHtml } = await import(join(dir, "dist/default.js")); const { githubLight } = await import(join(dir, "dist/themes.js")); const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); // its shellsession alias is the bash grammar, which misreads prompts and // output, no dotenv, http or ini grammar const LANGS = { bash: "bash", c: "c", cpp: "cpp", css: "css", diff: "diff", dockerfile: "dockerfile", go: "go", graphql: "graphql", html: "html", javascript: "javascript", json: "json", jsonc: "jsonc", markdown: "markdown", powershell: "powershell", python: "python", rust: "rust", sql: "sql", svelte: "svelte", toml: "toml", tsx: "tsx", typescript: "typescript", yaml: "yaml", }; const decoder = new TextDecoder(); return { id: "pierre-highlights", label: "Pierre highlights", version: pkg.version, note: "WebAssembly highlighter with Zed themes. Like Shiki its tokens are theme-coloured runs and its HTML carries inline styles; the html arm decodes the returned UTF-8 bytes to a string.", supports: (lang) => lang in LANGS, tokenize: (code, lang) => codeToTokens(code, { lang: LANGS[lang], theme: githubLight }), html: (code, lang) => decoder.decode(codeToHtml(code, { lang: LANGS[lang], theme: githubLight })), count_tokens: (out) => out.tokens.reduce((n, line) => n + line.length, 0), }; }, }; export const DEFAULT_LIBRARIES = [ "twinkleplop", "shiki-wasm", "shiki-js", "prism", "sugar-high", "speed-highlight", ]; /** * Instantiate the requested adapters. * * `twinkleplop` needs the loaded arm; the rest take nothing. A library that * fails to load is a hard error rather than a silent omission - a chart * missing a competitor because its import threw is worse than no chart. */ export async function load_libraries(ids, { arm }) { const out = []; for (const id of ids) { const make = ADAPTERS[id]; if (!make) { throw new Error(`unknown library "${id}" (have: ${Object.keys(ADAPTERS).join(", ")})`); } out.push(await make({ arm })); } return out; }