import { getSingletonHighlighter, type BundledLanguage } from 'shiki';
const langs = {
ts: 'ts',
js: 'js',
mjs: 'js',
svelte: 'svelte',
css: 'css',
json: 'json',
md: 'markdown',
html: 'html',
sh: 'shellscript',
yaml: 'yaml',
yml: 'yaml',
rs: 'rust',
toml: 'toml',
sql: 'sql',
mdx: 'mdx'
} satisfies Record<string, BundledLanguage>;
export type Token = { text: string; color: string | null };
const plain = (text: string): Token[][] => text.split('\n').map((line) => [{ text: line, color: null }]);
export const highlight = async (path: string, text: string): Promise<Token[][]> => {
const body = text.endsWith('\n') ? text.slice(0, -1) : text;
const ext = path.split('.').pop()?.toLowerCase() ?? '';
if (!Object.hasOwn(langs, ext)) return plain(body);
const lang: BundledLanguage = langs[ext as keyof typeof langs];
const highlighter = await getSingletonHighlighter({ themes: ['github-light'], langs: Object.values(langs) });
const { tokens } = highlighter.codeToTokens(body, { lang, theme: 'github-light' });
return tokens.map((line) => line.map((t) => ({ text: t.content, color: t.color ?? null })));
};