SLOPSHOPPER

skin-code

Real syntax highlighting for code blocks in Claude Code replies: VS Code's grammars and themes through Shiki, following your skins skin or a theme you pick…

panerowscommand
★ 3v0.5.1MITupdated 2026-10-18webdevnerdstuff/claude-skin-code
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · skin-code
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /skin-code ⎿ skin-code: skin-code settings ⎿ skin-code: ⎿ skin-code: | Setting | Now | ⎿ skin-code: | ------------ | ----------------- | ⎿ skin-code: | Theme | auto: neon-bunny | ⎿ skin-code: | Header | on | ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

<h1 align="center"> <img alt="skin-code" src="docs/brand/banner-light.svg" width="720"> </h1>

Real syntax highlighting for code blocks in Claude Code replies. skin-code highlights each fenced block with VS Code's own grammars through Shiki and colours it with VS Code themes, so code in Claude Code looks the way it does in your editor.

  • 29 themes, dark and light, including Neon Bunny and Neon Bunny Carrot, plus any VS Code theme you add
  • 39 languages, with PHP, Blade, Vue, TypeScript and JavaScript first among them
  • Follows the skins mod when it is installed: change your skin and the code colours follow, light or dark
  • In the desktop app and the terminal, with line numbers, the language and a copy button

Install

In a Claude Code terminal session:

/plugin install skin-code --marketplace webdevnerdstuff/claude-skin-code

Answer y to add the marketplace, then pick a scope (user scope loads it in every session, the desktop app's included).

Needs Claude Code 2.1.287 or newer. skins is optional; with it, use skins 0.5.8 or newer.

Update and remove

To update, refresh the marketplace, then update the plugin and restart Claude Code:

claude plugin marketplace update claude-skin-code
claude plugin update skin-code@claude-skin-code

To remove it:

claude plugin uninstall skin-code@claude-skin-code

Use

CommandWhat it does
/skin-code or /skin-code statusShows what everything is set to
/skin-code autoFollows your skins skin, light or dark (the default)
/skin-code <skin>A skin's dark and light themes, e.g. /skin-code catppuccin
/skin-code <theme>One theme, always, e.g. /skin-code github-dark
/skin-code offLeaves code blocks to skins or the app
/skin-code list or /skin-code themesEvery skin and theme
`/skin-code gallery [dark\light]`Opens a pane with the same snippet drawn in every theme, six to a page, the current one marked; on the terminal, only the themes that read on its background
/skin-code add <url or path>Adds a VS Code theme .json
/skin-code remove <name>Removes a theme you added
`/skin-code header on\off`The bar with the language and line count
`/skin-code numbers on\off`The line numbers
`/skin-code style text\card`Desktop blocks as selectable text (the default), or as a card in the code font
/skin-code helpLists the commands

Your settings and the themes you add are kept across sessions. Without skins, auto draws Neon Bunny; set SKIN_CODE_THEME=light or dark to pick the lightness yourself.

Add your own theme

Any VS Code color theme works: the .json file a theme extension ships in its themes/ folder. A GitHub file link or a local path both work, and skin-code switches to the theme once it is added:

/skin-code add https://github.com/you/your-theme/blob/main/themes/your-theme.json

For mod authors

Other mods can add themes and leave replies to skin-code through $.skinCode; the API is in types/index.d.ts.

Develop

pnpm build  # bundles Shiki, the grammars and the themes into hooks/vendor
pnpm check  # validates and tests

Load it from the folder while you work on it: claude --plugin-dir .. To add a theme or a language to the bundle, see AGENTS.md.

Credits

  • Shiki and the TextMate grammars and themes it bundles
  • skins by hellosverre, which skin-code follows and draws prose through
  • Neon Bunny themes by WebDevNerdStuff

License

MIT © WebDevNerdStuff. The bundled Shiki code, grammars and themes keep their own licences: see THIRD_PARTY_NOTICES.md.

Source 7 files
hooks/register.tsx 1055 lines
1import { atom, read, update } from 'claude-code';
2import type { EngineInterface, Register, RenderChildren } from 'claude-code';
3import type { AddedTheme, Gallery, GalleryCard, GalleryRun } from '../types';
4import { drawsReply, expandTabs, split } from './fences';
5import {
6	COMMAND,
7	GALLERY_SAMPLE,
8	galleryThemes,
9	helpText,
10	isUrl,
11	listText,
12	optionText,
13	parse,
14	rawUrl,
15	settingText,
16	skinsOf,
17	statusText,
18	styleText,
19} from './settings';
20import type { Pairs, Style } from './settings';
21import { MAX_LINES, cardWidth, codeCard } from './card';
22import { DEFAULT_PAIR, SKIN_THEMES, TERMINAL_FALLBACK } from './themes';
23import type { ThemePair } from './themes';
24import {
25	addTheme,
26	colorsOf,
27	displayNameOf,
28	hasTheme,
29	parseTheme,
30	themeNames,
31	tokenize,
32} from './vendor/shiki';
33import type { ThemedToken, VsCodeTheme } from './vendor/shiki';
34
35// skin-code: fenced code in replies drawn with VS Code's grammars and themes through Shiki.
36// `auto` follows the active skins skin, light or dark; `/skin-code <name>` picks one;
37// `/skin-code add` and `$.skinCode.addTheme` bring more themes.
38
39const mode = atom({ plugin: 'skin-code', key: 'mode' } as const, 'auto');
40const added = atom({ plugin: 'skin-code', key: 'added' } as const, {});
41const pairs = atom({ plugin: 'skin-code', key: 'pairs' } as const, {});
42// The block just copied, whose control shows a checkmark for COPIED_MS.
43const copied = atom({ plugin: 'skin-code', key: 'copied' } as const, '');
44const COPIED_MS = 2000;
45// The desktop control's label: blank cells over the icon drawn beneath it, so the press and
46// the hover background land on the icon. Non-breaking, so the surface keeps their width.
47const HIT_TARGET = '\u00a0\u00a0\u00a0\u00a0\u00a0';
48// The desktop control's icon, drawn as the app draws its own: outline strokes on a 24-unit
49// grid, round caps and joins, 12 pixels square in the middle of the control.
50const COPY_ICON =
51	'<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>';
52const CHECK_ICON = '<path d="M20 6 9 17l-5-5"/>';
53const ICON_WIDTH = 24;
54const ICON_HEIGHT = 20;
55
56// The line under the header: one pixel DIVIDER_LINE down a strip of DIVIDER_HEIGHT under the
57// header row, so the header sits about as far above it as below the block's edge, and the
58// code a step below. Pixels, not cells, which are too coarse here. Wider than any block and
59// stretched to its width; an Svg, so a selection never takes it in.
60const DIVIDER_HEIGHT = 11;
61const DIVIDER_LINE = 6;
62// Cells of padding added before a line per column of its indent. The desktop's font draws
63// a space at about a quarter of a cell, so an indent alone reads shallower than in the code
64// font; the spaces stay in the text, so a copy keeps the indent exactly.
65const INDENT_PAD = 0.375;
66
67// The divider's strip with nothing drawn: room at the top of the line numbers' column.
68const DIVIDER_SPACER = `<svg xmlns="http://www.w3.org/2000/svg" width="1" height="${DIVIDER_HEIGHT}"/>`;
69
70const DIVIDER_SVG = (color: string): string =>
71	`<svg xmlns="http://www.w3.org/2000/svg" width="4000" height="${DIVIDER_HEIGHT}" viewBox="0 0 4000 ${DIVIDER_HEIGHT}" preserveAspectRatio="none"><rect y="${DIVIDER_LINE}" width="4000" height="1" fill="${color}" fill-opacity=".35"/></svg>`;
72
73const iconSvg = (isCopied: boolean, color: string): string =>
74	`<svg xmlns="http://www.w3.org/2000/svg" width="${ICON_WIDTH}" height="${ICON_HEIGHT}" viewBox="0 0 ${ICON_WIDTH} ${ICON_HEIGHT}"><g transform="translate(6 4) scale(.5)" fill="none" stroke="${color}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">${isCopied ? CHECK_ICON : COPY_ICON}</g></svg>`;
75const options = atom({ plugin: 'skin-code', key: 'options' } as const, {
76	header: true,
77	numbers: true,
78});
79// The pane /skin-code gallery opens, and which themes it shows.
80const GALLERY = 'skin-code-gallery';
81// Blocks per page of the gallery: every theme at once was too large a tree for the desktop's
82// pane, which then drew nothing.
83const GALLERY_PAGE = 6;
84const gallery = atom({ plugin: 'skin-code', key: 'gallery' } as const, {
85	filter: 'all',
86	page: 0,
87	current: '',
88	light: false,
89	cards: [],
90} as Gallery);
91// How the desktop draws a block: rows of selectable text by default, or the card.
92const style = atom({ plugin: 'skin-code', key: 'style' } as const, 'text' as Style);
93
94// skins' own values, read when it is installed: the skin in use, the skins made from a
95// built-in one, and whether Claude Code is drawing light.
96const skinsPrefs = { plugin: 'skins', key: 'prefs' } as const;
97const skinsCustom = { plugin: 'skins', key: 'custom' } as const;
98const skinsLight = { plugin: 'skins', key: 'isLight' } as const;
99
100type Surface = 'terminal' | 'desktop' | 'vscode' | 'mobile';
101
102// Another plugin's value, undefined when that plugin is not installed.
103async function readOther<T>(
104	get: () => Promise<unknown>,
105): Promise<T | undefined> {
106	try {
107		return ((await get()) as { value?: T; }).value;
108	} catch {
109		return undefined;
110	}
111}
112
113// Themes added since load live in state; a reload of this module loads them again.
114async function loadAdded(
115	$: EngineInterface,
116): Promise<Record<string, AddedTheme>> {
117	const all = await read($, added);
118
119	for (const [name, entry] of Object.entries(all)) {
120		if (!hasTheme(name)) {
121			try {
122				addTheme({ ...entry.theme, name });
123			} catch { }
124		}
125	}
126
127	return all;
128}
129
130async function pairsOf($: EngineInterface): Promise<Pairs> {
131	return { ...SKIN_THEMES, ...(await read($, pairs)) };
132}
133
134// Light when skins says so, else when SKIN_CODE_THEME or Claude Code's theme names light.
135async function isLight($: EngineInterface): Promise<boolean> {
136	const fromSkins = await readOther<boolean>(() =>
137		$.state.get(skinsLight as never),
138	);
139
140	if (fromSkins !== undefined) {
141		return fromSkins;
142	}
143
144	try {
145		const theme =
146			(await $.env.get('SKIN_CODE_THEME')) ??
147			(await $.config.list()).find((row) => row.key === 'theme')?.value;
148
149		return (
150			typeof theme === 'string' && theme.toLowerCase().includes('light')
151		);
152	} catch {
153		return false;
154	}
155}
156
157// The pair the active skin maps to: its own name first, then the built-in it was made from.
158// The skins skin in use, undefined when skins is off or not installed.
159async function activeSkinOf($: EngineInterface): Promise<string | undefined> {
160	const skin = (
161		await readOther<{ skin?: string; }>(() =>
162			$.state.get(skinsPrefs as never),
163		)
164	)?.skin;
165
166	return skin === 'off' ? undefined : skin;
167}
168
169// The person's own skins skins, each by the built-in skin it was made from.
170async function customSkinsOf(
171	$: EngineInterface,
172): Promise<Record<string, string | undefined>> {
173	const custom = await readOther<Record<string, { base?: string; }>>(() =>
174		$.state.get(skinsCustom as never),
175	);
176
177	return Object.fromEntries(
178		Object.entries(custom ?? {}).map(([name, skin]) => [name, skin.base]),
179	);
180}
181
182async function skinPair($: EngineInterface, all: Pairs): Promise<ThemePair> {
183	const skin = await activeSkinOf($);
184
185	if (skin === undefined) {
186		return DEFAULT_PAIR;
187	}
188
189	const base = (await customSkinsOf($))[skin];
190
191	return (
192		all[skin] ??
193		(base === undefined ? undefined : all[base]) ??
194		DEFAULT_PAIR
195	);
196}
197
198// The theme to draw with now, or undefined while skin-code is off. On the terminal the code
199// sits on the terminal's own background, so a theme of the wrong lightness gives way.
200async function themeOf(
201	$: EngineInterface,
202	setting: string,
203	surface: Surface,
204): Promise<string | undefined> {
205	if (setting === 'off') {
206		return undefined;
207	}
208
209	await loadAdded($);
210	const all = await pairsOf($);
211	const light = await isLight($);
212	const pair = setting === 'auto' ? await skinPair($, all) : all[setting];
213	const chosen = pair === undefined ? setting : pair[light ? 1 : 0];
214	const theme = hasTheme(chosen) ? chosen : DEFAULT_PAIR[light ? 1 : 0];
215
216	return surface === 'terminal' && colorsOf(theme).isLight !== light
217		? TERMINAL_FALLBACK[light ? 1 : 0]
218		: theme;
219}
220
221// The columns of space a line starts with; a footer row, or none, starts with none.
222const indentOf = (tokens: readonly ThemedToken[] | undefined): number =>
223	/^ */.exec((tokens ?? []).map((token) => token.content).join(''))?.[0].length ?? 0;
224
225// A line's tokens joined where they look the same, so the gallery sends one Text per run of
226// a colour: a remote surface takes a tree of at most 100,000 characters, and every theme's
227// sample drawn token by token passed it.
228function runsOf(tokens: readonly ThemedToken[], foreground: string): GalleryRun[] {
229	const runs: GalleryRun[] = [];
230
231	for (const token of tokens) {
232		const color = token.color ?? foreground;
233		const italic = ((token.fontStyle ?? 0) & 1) !== 0;
234		const bold = ((token.fontStyle ?? 0) & 2) !== 0;
235		const last = runs[runs.length - 1];
236		// Spaces take any style: only their background would show it, and they have none.
237		const isBlank = token.content.trim() === '';
238
239		if (last !== undefined && (isBlank || (last.color === color && last.italic === italic && last.bold === bold))) {
240			last.text += token.content;
241			continue;
242		}
243
244		runs.push({ text: token.content, color, italic, bold });
245	}
246
247	return runs;
248}
249
250// A reply redraws as it streams; the same block tokenizes once per theme.
251const tokenCache = new Map<string, ThemedToken[][]>();
252
253function tokensOf(code: string, lang: string, theme: string): ThemedToken[][] {
254	const key = `${theme}\u0000${lang}\u0000${code}`;
255	const kept = tokenCache.get(key);
256
257	if (kept !== undefined) {
258		return kept;
259	}
260
261	const tokens = tokenize(expandTabs(code), lang, theme);
262
263	if (tokenCache.size > 300) {
264		tokenCache.clear();
265	}
266
267	tokenCache.set(key, tokens);
268
269	return tokens;
270}
271
272// A theme file's text from a URL (a GitHub page link reads its raw file) or a path.
273async function themeText($: EngineInterface, source: string): Promise<string> {
274	if (isUrl(source)) {
275		const response = await $.http.fetch(rawUrl(source));
276
277		if (!response.ok) {
278			throw new Error(`${source} answered ${response.status}`);
279		}
280
281		return response.text;
282	}
283
284	const home = (await $.env.get('HOME')) ?? '';
285	const path = source.startsWith('~/')
286		? `${home}${source.slice(1)}`
287		: source.startsWith('/')
288			? source
289			: `${await $.session.cwd()}/${source}`;
290
291	return $.fs.read(path);
292}
293
294// Records a theme for the session (and, from the user, for later sessions) and loads it.
295async function keepTheme(
296	$: EngineInterface,
297	theme: VsCodeTheme,
298	by: string,
299): Promise<string> {
300	const name = addTheme(theme);
301
302	await update($, added, (all) => ({
303		...all,
304		[name]: { theme: { ...theme, name }, by },
305	}));
306
307	if (by === 'user') {
308		const stored = (await $.store.get('themes')) as
309			| Record<string, VsCodeTheme>
310			| undefined;
311
312		await $.store.set('themes', {
313			...(stored ?? {}),
314			[name]: { ...theme, name },
315		});
316	}
317
318	return name;
319}
320
321export const register: Register = (on) => {
322	// Adds `$.skinCode` for other mods. Each call is the event of its name, answered below;
323	// the methods here are the chain's floor.
324	on('engine.create', async ($, e, next) => {
325		const built = await next(e);
326
327		return {
328			...built,
329			skinCode: {
330				addTheme: async () => '',
331				themes: async () => [],
332				draws: async () => false,
333			},
334		};
335	});
336
337	on('skinCode.addTheme', async ($, e) => {
338		const name = await keepTheme($, e.theme, 'plugin');
339
340		if (e.skin !== undefined) {
341			const lightness =
342				e.lightness ?? (colorsOf(name).isLight ? 'light' : 'dark');
343			const skin = e.skin.toLowerCase();
344
345			await update($, pairs, (all) => {
346				const was: ThemePair = all[skin] ??
347					SKIN_THEMES[skin] ?? [name, name];
348				const pair: ThemePair =
349					lightness === 'light' ? [was[0], name] : [name, was[1]];
350
351				return { ...all, [skin]: pair };
352			});
353		}
354
355		return { value: name };
356	});
357
358	on('skinCode.themes', async ($) => {
359		await loadAdded($);
360
361		return { value: themeNames() };
362	});
363
364	on('skinCode.draws', async ($, e) => ({
365		value:
366			typeof e.text === 'string' && drawsReply(e.text, await read($, mode)),
367	}));
368
369	on('session.start', async ($, e, next) => {
370		await $.command.register({
371			name: COMMAND,
372			description:
373				'Colour code blocks with VS Code themes: auto, off, list, add, or a theme',
374			argumentHint:
375				'[status | auto | off | list | themes | gallery [dark|light] | help | add <url or path> | remove <name> | style text|card | <theme>]',
376			immediate: true,
377		});
378
379		const layout = (await $.store.get('options')) as
380			| Partial<Record<'header' | 'numbers', boolean>>
381			| undefined;
382
383		if (layout !== undefined) {
384			await update($, options, (current) => ({ ...current, ...layout }));
385		}
386
387		const drawn = await $.store.get('style');
388
389		if (drawn === 'text' || drawn === 'card') {
390			await update($, style, () => drawn);
391		}
392
393		const stored = await $.store.get('mode');
394
395		if (typeof stored === 'string') {
396			await update($, mode, () => stored);
397		}
398
399		// The themes the person added in earlier sessions.
400		const themes = (await $.store.get('themes')) as
401			| Record<string, VsCodeTheme>
402			| undefined;
403
404		for (const theme of Object.values(themes ?? {})) {
405			try {
406				await keepTheme($, theme, 'user');
407			} catch { }
408		}
409
410		return next(e);
411	});
412
413	on('command.run', { command: COMMAND }, async ($, e) => {
414		const all = await pairsOf($);
415		const loaded = await loadAdded($);
416		const asked = parse(e.args, themeNames(), all);
417
418		if (asked.kind === 'help') {
419			return { text: helpText() };
420		}
421
422		if (asked.kind === 'list') {
423			const current = await read($, mode);
424
425			return {
426				text: listText({
427					themes: themeNames(),
428					pairs: all,
429					added: Object.keys(loaded),
430					current,
431					drawing: await themeOf($, current, 'desktop'),
432					activeSkin: await activeSkinOf($),
433					customSkins: await customSkinsOf($),
434					options: await read($, options),
435					isLight: (theme) => colorsOf(theme).isLight,
436				}),
437			};
438		}
439
440		if (asked.kind === 'gallery') {
441			// The command works the whole gallery out, tokenizing each theme's sample (about a
442			// second in all), and keeps it in state: the pane only draws it, at once.
443			const cards: GalleryCard[] = galleryThemes(
444				themeNames(),
445				asked.filter,
446				(name) => colorsOf(name).isLight,
447			).map((theme) => {
448				const colors = colorsOf(theme);
449				const skins = skinsOf(theme, all);
450
451				return {
452					theme,
453					name: displayNameOf(theme),
454					caption: skins.length === 0 ? theme : `${theme} · skin ${skins.join(', ')}`,
455					isLight: colors.isLight,
456					foreground: colors.foreground,
457					background: colors.background,
458					gutter: colors.gutter,
459					lines: tokensOf(GALLERY_SAMPLE.code, GALLERY_SAMPLE.lang, theme).map(
460						(tokens) => runsOf(tokens, colors.foreground),
461					),
462				};
463			});
464
465			const current = (await themeOf($, await read($, mode), 'desktop')) ?? '';
466			const light = await isLight($);
467
468			await update($, gallery, () => ({ filter: asked.filter, page: 0, current, light, cards }));
469			// The pane draws the gallery; the command shows nothing of its own, as skins' does.
470			await $.ui.open({
471				id: GALLERY,
472				title: 'Code theme gallery',
473				focus: true,
474				closeOnEscape: true,
475			});
476
477			return {};
478		}
479
480		if (asked.kind === 'status') {
481			const current = await read($, mode);
482			const drawing = await themeOf($, current, 'desktop');
483
484			return {
485				text: statusText(
486					current,
487					drawing,
488					all,
489					displayNameOf,
490					await activeSkinOf($),
491					await read($, options),
492					await read($, style),
493				),
494			};
495		}
496
497		if (asked.kind === 'add') {
498			try {
499				const name = await keepTheme(
500					$,
501					parseTheme(await themeText($, asked.source)),
502					'user',
503				);
504
505				// Adding a theme is asking to see it: switch to it, as /skin-code <name> would.
506				await update($, mode, () => name);
507				await $.store.set('mode', name);
508
509				return {
510					text: `Added ${displayNameOf(name)} and switched to it. /skin-code auto goes back to following your skin.`,
511				};
512			} catch (error) {
513				return {
514					text: `Could not add a theme from ${asked.source}: ${error instanceof Error ? error.message : String(error)}`,
515				};
516			}
517		}
518
519		if (asked.kind === 'remove') {
520			if (loaded[asked.name]?.by !== 'user') {
521				return {
522					text: `${asked.name} is not a theme you added. /skin-code list marks those "(added)".`,
523				};
524			}
525
526			const stored = ((await $.store.get('themes')) ?? {}) as Record<
527				string,
528				VsCodeTheme
529			>;
530			const { [asked.name]: _gone, ...kept } = stored;
531
532			await $.store.set('themes', kept);
533			await update($, added, (current) =>
534				Object.fromEntries(
535					Object.entries(current).filter(
536						([name]) => name !== asked.name,
537					),
538				),
539			);
540
541			if ((await read($, mode)) === asked.name) {
542				await update($, mode, () => 'auto');
543				await $.store.set('mode', 'auto');
544			}
545
546			return {
547				text: `Removed ${asked.name}. It stays drawable until the session ends.`,
548			};
549		}
550
551		if (asked.kind === 'unknown') {
552			return {
553				text: `No theme named "${asked.word}". /skin-code list shows the themes.`,
554			};
555		}
556
557		if (asked.kind === 'option') {
558			await update($, options, (current) => ({
559				...current,
560				[asked.option]: asked.value,
561			}));
562			await $.store.set('options', await read($, options));
563
564			return { text: optionText(asked.option, asked.value) };
565		}
566
567		if (asked.kind === 'style') {
568			await update($, style, () => asked.style);
569			await $.store.set('style', asked.style);
570
571			return { text: styleText(asked.style) };
572		}
573
574		await update($, mode, () => asked.setting);
575		await $.store.set('mode', asked.setting);
576
577		return {
578			text: settingText(
579				asked.setting,
580				await themeOf($, asked.setting, 'desktop'),
581				all,
582				displayNameOf,
583				await activeSkinOf($),
584			),
585		};
586	});
587
588	// /skin-code gallery's pane: the same snippet in every theme, as small blocks laid side by
589	// side, the theme drawing now marked.
590	// Matched on the component alone, the pane told by its id here: on the desktop a matcher
591	// naming `requestId` never ran this hook, and the pane stayed empty.
592	on('ui.render', { component: 'Pane' }, async ($, e, next) => {
593		if (e.requestId !== GALLERY) {
594			return next(e);
595		}
596
597		const { Box, Button, Text } = $.ui.resolve(e);
598		const { filter, page, current, light, cards: every } = await read($, gallery);
599		const isTerminal = e.surface === 'terminal';
600		// The terminal paints no block background, so a theme of the other lightness would
601		// draw on the wrong ground: it shows only the themes that read there.
602		const cards = isTerminal ? every.filter((card) => card.isLight === light) : every;
603		const hidden = every.length - cards.length;
604		const pages = Math.max(1, Math.ceil(cards.length / GALLERY_PAGE));
605		const at = Math.min(page, pages - 1);
606		const shown = cards.slice(at * GALLERY_PAGE, (at + 1) * GALLERY_PAGE);
607		const turn = (by: number) => () =>
608			void update($, gallery, (was) => ({
609				...was,
610				page: Math.min(Math.max(0, at + by), pages - 1),
611			}));
612		const which = filter === 'all' ? '' : ` ${filter}`;
613		const away =
614			hidden === 0 ? '' : ` · ${hidden} ${light ? 'dark' : 'light'} hidden on this terminal`;
615
616		return (
617			<Box flexDirection="column" marginY={1}>
618				<Text bold>
619					{`Code theme gallery · ${cards.length}${which} theme${cards.length === 1 ? '' : 's'}${away}`}
620				</Text>
621				<Box flexDirection="row" gap={1}>
622					<Button key="skin-code-gallery-prev" label=" Previous " onPress={turn(-1)} />
623					<Text dimColor>{`page ${at + 1} of ${pages}`}</Text>
624					<Button key="skin-code-gallery-next" label=" Next " onPress={turn(1)} />
625				</Box>
626				<Box flexDirection="column" marginY={1}>
627					{shown.map((card) => {
628						const isCurrent = card.theme === current;
629
630						return (
631							<Box
632								key={`skin-code-gallery-${card.theme}`}
633								flexDirection="column"
634								marginBottom={1}
635								borderStyle="round"
636								borderColor={isCurrent ? card.foreground : card.gutter}
637								backgroundColor={isTerminal ? undefined : card.background}
638								paddingX={1}
639							>
640								<Box flexDirection="row" justifyContent="space-between">
641									<Text color={card.foreground} bold wrap="truncate-end">
642										{card.name}
643									</Text>
644									{isCurrent ? <Text color={card.foreground}>current</Text> : ''}
645								</Box>
646								<Text color={card.gutter} wrap="truncate-end">
647									{card.caption}
648								</Text>
649								<Text> </Text>
650								{card.lines.map((runs) => (
651									<Text wrap="truncate-end">
652										{runs.length === 0
653											? ' '
654											: runs.map((run) => (
655												<Text
656													color={run.color}
657													italic={run.italic || undefined}
658													bold={run.bold || undefined}
659												>
660													{run.text}
661												</Text>
662											))}
663									</Text>
664								))}
665							</Box>
666						);
667					})}
668				</Box>
669				<Text dimColor>
670					{'/skin-code <theme> picks one · /skin-code gallery dark|light narrows it · Esc closes'}
671				</Text>
672			</Box>
673		);
674	});
675
676	on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
677		const text = e.props.text;
678		const segments =
679			typeof text === 'string' && /```|~~~/.test(text)
680				? split(text)
681				: null;
682
683		if (segments === null) {
684			return next(e);
685		}
686
687		const theme = await themeOf($, await read($, mode), e.surface);
688
689		if (theme === undefined) {
690			return next(e);
691		}
692
693		const ui = $.ui.resolve(e);
694		const { Box, Button, Markdown, Text } = ui;
695		const isTerminal = e.surface === 'terminal';
696		// Every surface's table names Svg, but the terminal draws it as nothing.
697		const Svg = !isTerminal && 'Svg' in ui ? ui.Svg : undefined;
698		const columns = e.viewport?.columns ?? 100;
699		const colors = colorsOf(theme);
700		const { header, numbers } = await read($, options);
701		const drawStyle = await read($, style);
702		const justCopied = await read($, copied);
703		// As the app's own copy control: a checkmark for a moment, a toast only on failure.
704		const copy = async (text: string, block: string) => {
705			const result = await $.ui.copy({ text, surface: e.surface });
706
707			if (!result.isCopied) {
708				await $.ui.toast('Could not copy here');
709				return;
710			}
711
712			await update($, copied, () => block);
713			await $.clock.sleep(COPIED_MS);
714			await update($, copied, (current) =>
715				current === block ? '' : current,
716			);
717		};
718		// The control's background under the pointer, a step off the block's own.
719		const hoverBackground = colors.isLight ? '#0000000f' : '#ffffff14';
720
721		const drawn = await Promise.all(
722			segments.map(async (segment, i): Promise<RenderChildren> => {
723				if (segment.kind === 'text') {
724					if (segment.text.trim() === '') {
725						return '';
726					}
727
728					let prose: RenderChildren | undefined;
729
730					try {
731						prose = await $.skins.markdown({
732							surface: e.surface,
733							text: segment.text,
734							columns,
735						});
736					} catch { }
737
738					return prose ?? <Markdown text={segment.text} />;
739				}
740
741				const label = segment.tag || segment.lang;
742				const lines = tokensOf(segment.code, segment.lang, theme);
743				const block = `${e.requestId}:${i}`;
744				const isCopied = justCopied === block;
745				const press = () => void copy(segment.code, block);
746				// On the terminal the control is a word, as skins writes it (a glyph is drawn
747				// wider than its cell in many fonts), with no hover: a terminal has no
748				// translucent colours, and it inverts a button under the pointer by itself.
749				const copyButton = (
750					<Button
751						key={`skin-code-copy-${i}`}
752						label={isCopied ? ' Copied ' : ' Copy '}
753						plain
754						dimColor
755						onPress={press}
756					/>
757				);
758				// Elsewhere it is the app's copy icon, a checkmark just after a copy, under a
759				// blank target with a hover of its own.
760				const copyIcon =
761					Svg === undefined ? (
762						copyButton
763					) : (
764						<Box key={`skin-code-copy-scope-${i}`}>
765							<Svg
766								source={iconSvg(isCopied, colors.foreground)}
767								alt={isCopied ? 'Copied' : 'Copy'}
768								width={ICON_WIDTH}
769								height={ICON_HEIGHT}
770							/>
771							<Box position="absolute" top={0} left={0}>
772								<Button
773									key={`skin-code-copy-${i}`}
774									label={HIT_TARGET}
775									plain
776									dimColor
777									hover={{
778										backgroundColor: hoverBackground,
779										dimColor: false,
780									}}
781									onPress={press}
782								/>
783							</Box>
784						</Box>
785					);
786				const shown = lines.slice(0, MAX_LINES);
787				// Every surface draws the code as text, so it selects as the app's own code
788				// blocks do. In an SVG a row was only as wide as its glyphs, and a drag that
789				// ended past a line's end selected from the top. The numbers are a column of
790				// their own beside the code, so a drag through the code never takes them in.
791				const lineTexts = shown.map((tokens) => (
792						<Text wrap="truncate-end">
793							{tokens.length === 0
794								? ' '
795								: tokens.map((token) => (
796									// Every token unwrapped too: a desktop wraps a line between its
797									// tokens, which a one-row line then cuts in half.
798									<Text
799										wrap="truncate-end"
800										color={token.color ?? colors.foreground}
801										italic={((token.fontStyle ?? 0) & 1) !== 0}
802										bold={((token.fontStyle ?? 0) & 2) !== 0}
803										underline={
804											((token.fontStyle ?? 0) & 4) !== 0
805										}
806									>
807										{token.content}
808									</Text>
809								))}
810						</Text>
811				));
812				const more =
813					lines.length > shown.length ? (
814						<Text
815							color={colors.gutter}
816						>{`${lines.length - shown.length} more lines (copy takes all of it)`}</Text>
817					) : (
818						''
819					);
820				const digits = String(shown.length).length;
821				const code = [...lineTexts, more];
822				// Right-aligned by the column, not padded with spaces: in the desktop's font a space
823				// is narrower than a digit.
824				const gutter = shown.map((_tokens, n) => (
825					<Text color={colors.gutter}>{String(n + 1)}</Text>
826				));
827				// The terminal's rows: the numbers a column beside the code.
828				const rows = (
829					<Box flexDirection="row">
830						{numbers ? (
831							<Box
832								flexDirection="column"
833								alignItems="flex-end"
834								flexShrink={0}
835								marginRight={1}
836							>
837								{gutter}
838							</Box>
839						) : (
840							''
841						)}
842						<Box
843							flexDirection="column"
844							flexGrow={1}
845							flexShrink={1}
846							overflow="hidden"
847						>
848							{code}
849						</Box>
850					</Box>
851				);
852
853				const count = `${lines.length} line${lines.length === 1 ? '' : 's'}`;
854
855				if (drawStyle === 'card' && Svg !== undefined) {
856					// The card: the block drawn whole, in the theme's code font, and shown as a
857					// frame, not an image, so its text can be selected (card.ts says how). The
858					// control and its icon lie over it, outside the drawing, so a copy redraws
859					// them alone: a new drawing of the card would reload its frame, a flash.
860					const card = codeCard(lines, label, colors, cardWidth(columns), {
861						header,
862						numbers,
863						hasControl: true,
864					});
865
866					return (
867						<Box marginY={1} alignSelf="flex-start">
868							<Svg
869								isInteractive
870								source={card.source}
871								alt={`${label}:\n${segment.code.slice(0, 4000)}`}
872								width={card.width}
873								height={card.height}
874							/>
875							<Box position="absolute" top={1} right={1}>
876								{copyIcon}
877							</Box>
878						</Box>
879					);
880				}
881
882				if (!isTerminal) {
883					// The remote surfaces: the theme's own background, so a dark theme reads in a
884					// light app, and a header row with the language, the line count and the copy
885					// control, ruled off from the code. Without the header the control sits at
886					// the top right on its own.
887					//
888					// No element offers user-select, so the line numbers are kept out of reach:
889					// - They come first in the block, before the header, so no drag between the
890					//   header and the code passes over them.
891					// - The code is a layer over them, absolute and later, so painted on top: the
892					//   pointer over a number is over the code, and a drag starting there selects
893					//   code. An empty Box as tall as the code holds its room in the block.
894					// - The head, every number and every line of code are whole rows, so the
895					//   numbers, placed by row, line up with the code.
896					// - All of it sits in a plain Box inside the bordered one: a desktop insets a
897					//   bordered Box's content (about a cell across, less down) but places an
898					//   absolute child from its outer edge, so placed there the numbers drifted
899					//   up and left, out from under the code.
900					const headRows = 1;
901					const codeRows = more === '' ? lineTexts : [...lineTexts, more];
902
903					return (
904						<Box
905							flexDirection="column"
906							marginY={1}
907							borderStyle="round"
908							borderColor={colors.gutter}
909							backgroundColor={colors.background}
910						>
911							<Box flexDirection="column">
912								{numbers ? (
913									// Left-aligned and inset by padding, as the header's label is, so every
914									// number starts under the language label.
915									<Box
916										position="absolute"
917										top={headRows}
918										left={0}
919										paddingLeft={1}
920										flexDirection="column"
921										alignItems="flex-start"
922									>
923										{/* The divider's strip, in pixels, which an offset in rows cannot say. */}
924										{header && Svg !== undefined ? (
925											<Svg
926												source={DIVIDER_SPACER}
927												alt="Divider"
928												width={1}
929												height={DIVIDER_HEIGHT}
930											/>
931										) : (
932											''
933										)}
934										{shown.map((_tokens, n) => (
935											<Box height={1} flexDirection="row" alignItems="center">
936												<Text color={colors.gutter}>{String(n + 1)}</Text>
937											</Box>
938										))}
939									</Box>
940								) : (
941									''
942								)}
943								<Box flexDirection="column">
944									<Box
945										height={1}
946										flexDirection="row"
947										justifyContent={header ? 'space-between' : 'flex-end'}
948										alignItems="center"
949										paddingX={1}
950									>
951										{header ? (
952											<Text color={colors.gutter} bold>
953												{label.toUpperCase()}
954											</Text>
955										) : (
956											''
957										)}
958										<Box flexDirection="row" gap={1}>
959											{header ? (
960												<Text color={colors.gutter}>{count}</Text>
961											) : (
962												''
963											)}
964											{copyIcon}
965										</Box>
966									</Box>
967									{/* The line under the header runs edge to edge: the block has no padding
968									    of its own, only the header and the code do. */}
969									{header && Svg !== undefined ? (
970										<Box width="100%">
971											<Svg
972												source={DIVIDER_SVG(colors.gutter)}
973												alt="Divider"
974												height={DIVIDER_HEIGHT}
975											/>
976										</Box>
977									) : (
978										''
979									)}
980								</Box>
981								<Box flexDirection="column">
982									<Box height={codeRows.length} />
983									<Box
984										position="absolute"
985										top={0}
986										left={0}
987										right={0}
988										flexDirection="column"
989										paddingLeft={numbers ? digits + 2 : 1}
990										paddingRight={1}
991									>
992										{codeRows.map((row, n) => (
993											<Box
994												height={1}
995												flexDirection="row"
996												alignItems="center"
997												overflow="hidden"
998												paddingLeft={Math.round(
999													indentOf(shown[n]) * INDENT_PAD,
1000												)}
1001											>
1002												{row}
1003											</Box>
1004										))}
1005									</Box>
1006								</Box>
1007							</Box>
1008						</Box>
1009					);
1010				}
1011
1012				// The terminal: a rounded frame, the language on its top border, a dim gutter. The
1013				// label and copy mark are laid over the border from a plain Box around the frame:
1014				// inside the bordered Box, the border was drawn over them.
1015				return (
1016					<Box flexDirection="column" marginY={1}>
1017						<Box flexDirection="column">
1018							<Box
1019								flexDirection="column"
1020								borderStyle="round"
1021								borderColor={colors.gutter}
1022								paddingX={1}
1023							>
1024								{rows}
1025							</Box>
1026							{header ? (
1027								<Box position="absolute" top={0} left={2}>
1028									<Text color={colors.gutter}>{` ${label} `}</Text>
1029								</Box>
1030							) : (
1031								''
1032							)}
1033							{/* Only the fullscreen layout reports clicks; on the main screen the control could not be pressed. */}
1034							{e.viewport?.isFullscreen === false ? (
1035								''
1036							) : (
1037								<Box
1038									key={`skin-code-copy-scope-${i}`}
1039									position="absolute"
1040									top={0}
1041									right={2}
1042								>
1043									{copyButton}
1044								</Box>
1045							)}
1046						</Box>
1047					</Box>
1048				);
1049			}),
1050		);
1051
1052		return <Box flexDirection="column">{drawn}</Box>;
1053	});
1054};
1055
hooks/fences.ts 128 lines
1import { resolveLang } from './vendor/shiki';
2
3// A reply split on the fences skin-code draws: everything else stays text for skins or the
4// app to draw.
5
6export type Segment =
7	| { kind: 'text'; text: string }
8	| { kind: 'code'; lang: string; tag: string; code: string };
9
10// Fences these tags open are left alone: shell keeps the desktop's Run button, and
11// diagrams, formulas and diffs have cards of their own in skins.
12const LEFT_ALONE = new Set([
13	'bash',
14	'sh',
15	'shell',
16	'zsh',
17	'fish',
18	'cmd',
19	'bat',
20	'shellscript',
21	'console',
22	'mermaid',
23	'math',
24	'diff',
25	'patch',
26]);
27
28// A fence in a language skin-code does not bundle, or with none named, is still its block:
29// the theme's colours, with no highlighting.
30const PLAIN = 'text';
31
32const OPEN = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/;
33
34// The reply's segments, or null when it holds no fence skin-code draws. An unclosed fence
35// (a reply still streaming) runs to the end.
36export function split(text: string): Segment[] | null {
37	const lines = text.split('\n');
38	const segments: Segment[] = [];
39	let prose: string[] = [];
40	let isDrawn = false;
41
42	for (let i = 0; i < lines.length; i++) {
43		const line = lines[i] ?? '';
44		const open = OPEN.exec(line);
45		const tag = open?.[2] ?? '';
46		const lang = open === null ? undefined : (resolveLang(tag) ?? PLAIN);
47
48		if (
49			open === null ||
50			lang === undefined ||
51			LEFT_ALONE.has(tag.toLowerCase()) ||
52			LEFT_ALONE.has(lang)
53		) {
54			prose.push(line);
55
56			// A fence left alone keeps its body as text, so a fence-looking line inside it is not read as an opener.
57			if (open !== null) {
58				const close = closerOf(open[1] ?? '```');
59				let end = i + 1;
60
61				while (end < lines.length && !close.test(lines[end] ?? '')) {
62					end++;
63				}
64
65				prose.push(...lines.slice(i + 1, end + 1));
66				i = end;
67			}
68
69			continue;
70		}
71
72		const close = closerOf(open[1] ?? '```');
73		let end = i + 1;
74
75		while (end < lines.length && !close.test(lines[end] ?? '')) {
76			end++;
77		}
78
79		if (prose.length > 0) {
80			segments.push({ kind: 'text', text: prose.join('\n') });
81			prose = [];
82		}
83
84		segments.push({
85			kind: 'code',
86			lang,
87			tag,
88			code: lines.slice(i + 1, end).join('\n'),
89		});
90		isDrawn = true;
91		i = end;
92	}
93
94	if (prose.length > 0) {
95		segments.push({ kind: 'text', text: prose.join('\n') });
96	}
97
98	return isDrawn ? segments : null;
99}
100
101// Whether skin-code draws a reply under the /skin-code setting `mode`: the render hook's own
102// test, answered to other mods by `$.skinCode.draws`.
103export function drawsReply(text: string, mode: string): boolean {
104	return mode !== 'off' && split(text) !== null;
105}
106
107function closerOf(fence: string): RegExp {
108	return new RegExp(
109		`^ {0,3}${fence[0] === '`' ? '`' : '~'}{${fence.length},}\\s*$`,
110	);
111}
112
113// Tabs to the next stop, as an editor lays them, so tab-aligned columns line up.
114export function expandTabs(code: string, size = 4): string {
115	return code
116		.split('\n')
117		.map((line) => {
118			let out = '';
119
120			for (const char of line) {
121				out += char === '\t' ? ' '.repeat(size - (out.length % size)) : char;
122			}
123
124			return out;
125		})
126		.join('\n');
127}
128
hooks/settings.ts 441 lines
1import { DEFAULT_PAIR, SKIN_THEMES } from './themes';
2import type { ThemePair } from './themes';
3
4// The words /skin-code takes, and what it answers: pure, so the tests read them directly.
5
6export const COMMAND = 'skin-code';
7
8// The parts of a code block that can be switched off, as /skin-code names them.
9export type Option = 'header' | 'numbers';
10
11export type Options = Readonly<Record<Option, boolean>>;
12
13// How a code block is drawn on the desktop: 'text', rows of selectable text in the app's
14// font, or 'card', a drawing in the theme's code font whose text selects less cleanly.
15export type Style = 'text' | 'card';
16
17export type Pairs = Readonly<Record<string, ThemePair>>;
18
19// Which themes /skin-code gallery shows: every one, or those of one lightness.
20export type GalleryFilter = 'all' | 'dark' | 'light';
21
22export type Parsed =
23	| { kind: 'status' }
24	| { kind: 'list' }
25	| { kind: 'gallery'; filter: GalleryFilter }
26	| { kind: 'help' }
27	| { kind: 'set'; setting: string }
28	| { kind: 'add'; source: string }
29	| { kind: 'remove'; name: string }
30	| { kind: 'option'; option: Option; value: boolean }
31	| { kind: 'style'; style: Style }
32	| { kind: 'unknown'; word: string };
33
34// The setting a word names: a skin's pair, one theme, auto or off; `on` and nothing are auto.
35export function settingOf(
36	word: string,
37	themes: readonly string[],
38	pairs: Pairs = SKIN_THEMES,
39): string | undefined {
40	const name = word.trim().toLowerCase();
41
42	if (name === '' || name === 'on') {
43		return 'auto';
44	}
45
46	return name === 'auto' ||
47		name === 'off' ||
48		pairs[name] !== undefined ||
49		themes.includes(name)
50		? name
51		: undefined;
52}
53
54export function parse(
55	args: string,
56	themes: readonly string[],
57	pairs: Pairs = SKIN_THEMES,
58): Parsed {
59	const [first = '', ...rest] = args.trim().split(/\s+/);
60	const word = first.toLowerCase();
61	const tail = rest.join(' ').trim();
62
63	if (word === '' || word === 'status') {
64		return { kind: 'status' };
65	}
66
67	if (word === 'list' || word === 'themes') {
68		return { kind: 'list' };
69	}
70
71	if (word === 'help') {
72		return { kind: 'help' };
73	}
74
75	const filter = tail.toLowerCase() || 'all';
76
77	if (
78		word === 'gallery' &&
79		(filter === 'all' || filter === 'dark' || filter === 'light')
80	) {
81		return { kind: 'gallery', filter };
82	}
83
84	if (word === 'add' && tail !== '') {
85		return { kind: 'add', source: tail };
86	}
87
88	if (word === 'remove' && tail !== '') {
89		return { kind: 'remove', name: tail.toLowerCase() };
90	}
91
92	if (
93		(word === 'header' || word === 'numbers') &&
94		(tail === 'on' || tail === 'off')
95	) {
96		return { kind: 'option', option: word, value: tail === 'on' };
97	}
98
99	if (word === 'style' && (tail === 'text' || tail === 'card')) {
100		return { kind: 'style', style: tail };
101	}
102
103	const setting = settingOf(word, themes, pairs);
104
105	return setting === undefined
106		? { kind: 'unknown', word: first }
107		: { kind: 'set', setting };
108}
109
110// A theme's name in prose (`One Dark Pro`); the id itself when nothing better is known.
111export type Names = (theme: string) => string;
112
113const asIs: Names = (theme) => theme;
114
115// What a setting draws, in words: the reply to /skin-code <setting>.
116export function describe(
117	setting: string,
118	pairs: Pairs = SKIN_THEMES,
119	names: Names = asIs,
120): string {
121	if (setting === 'off') {
122		return 'Code theme: off. Code blocks are left to skins or the app.';
123	}
124
125	if (setting === 'auto') {
126		return 'Code theme: auto, following your skin.';
127	}
128
129	const pair = pairs[setting];
130
131	if (pair === undefined) {
132		return `Code theme: ${names(setting)}.`;
133	}
134
135	return pair[0] === pair[1]
136		? `Code theme: ${names(pair[0])}.`
137		: `Code theme: ${names(pair[0])} (${names(pair[1])} in light mode).`;
138}
139
140// The reply to /skin-code alone: the setting, and the theme drawing when auto picks it.
141// A setting, and the theme it draws with now when it could be more than one: auto, or a
142// skin whose light half differs. `skin` is the skins skin auto followed.
143export function settingText(
144	setting: string,
145	drawing: string | undefined,
146	pairs: Pairs = SKIN_THEMES,
147	names: Names = asIs,
148	skin?: string,
149): string {
150	const pair = pairs[setting];
151	const varies =
152		setting === 'auto' || (pair !== undefined && pair[0] !== pair[1]);
153	const from =
154		setting === 'auto' && skin !== undefined ? ` (from your skin ${skin})` : '';
155	const now =
156		varies && drawing !== undefined
157			? ` Drawing with ${names(drawing)}${from} now.`
158			: '';
159
160	return `${describe(setting, pairs, names)}${now}`;
161}
162
163// How the code blocks are laid out, in words.
164export const optionsText = (options: Options): string =>
165	`Header ${options.header ? 'on' : 'off'} · line numbers ${options.numbers ? 'on' : 'off'}.`;
166
167// The reply to an option change.
168export const optionText = (option: Option, value: boolean): string =>
169	`${option === 'header' ? 'Code block header' : 'Line numbers'} ${value ? 'on' : 'off'}.`;
170
171// How the desktop draws code blocks, in words: the reply to /skin-code style, and a line of
172// the status.
173export const styleText = (style: Style): string =>
174	style === 'card'
175		? 'Desktop code blocks: card, drawn in the code font.'
176		: "Desktop code blocks: text, selectable as the app's own.";
177
178// The theme in a few words, for the status table: the setting and, when it could be more
179// than one, the theme it draws with now.
180export function themeNow(
181	setting: string,
182	drawing: string | undefined,
183	pairs: Pairs = SKIN_THEMES,
184	names: Names = asIs,
185	skin?: string,
186): string {
187	if (setting === 'off') {
188		return 'off (left to skins or the app)';
189	}
190
191	if (setting === 'auto') {
192		const from = skin === undefined ? '' : `, from your skin ${skin}`;
193
194		return drawing === undefined ? 'auto' : `auto: ${names(drawing)}${from}`;
195	}
196
197	const pair = pairs[setting];
198
199	if (pair === undefined || pair[0] === pair[1]) {
200		return names(pair?.[0] ?? setting);
201	}
202
203	const now = drawing === undefined ? '' : `, now ${names(drawing)}`;
204
205	return `${names(pair[0])} / ${names(pair[1])} in light${now}`;
206}
207
208// The reply to /skin-code alone: what everything is set to, as a table. It opens with a
209// line of text, as help does: Claude Code puts the plugin's name before a reply's first line.
210export function statusText(
211	setting: string,
212	drawing: string | undefined,
213	pairs: Pairs = SKIN_THEMES,
214	names: Names = asIs,
215	skin?: string,
216	options: Options = { header: true, numbers: true },
217	style: Style = 'text',
218): string {
219	const onOff = (on: boolean) => (on ? 'on' : 'off');
220
221	return [
222		'skin-code settings',
223		'',
224		markdownTable(
225			['Setting', 'Now'],
226			[
227				['Theme', themeNow(setting, drawing, pairs, names, skin)],
228				['Header', onOff(options.header)],
229				['Line numbers', onOff(options.numbers)],
230				['Style', style === 'card' ? 'card (code font)' : 'text (selectable)'],
231			],
232		),
233		'',
234		'`/skin-code help` shows the commands.',
235		'',
236		'`/skin-code list` shows every theme.',
237	].join('\n');
238}
239
240// A markdown table whose cells are padded to line up: the desktop draws it as a table,
241// the terminal shows it as text with its columns aligned.
242export function markdownTable(
243	head: readonly string[],
244	rows: readonly (readonly string[])[],
245): string {
246	const widths = head.map((title, column) =>
247		Math.max(title.length, ...rows.map((row) => (row[column] ?? '').length)),
248	);
249	const line = (cells: readonly string[]) =>
250		`| ${widths.map((width, column) => (cells[column] ?? '').padEnd(width)).join(' | ')} |`;
251
252	return [
253		line(head),
254		line(widths.map((width) => '-'.repeat(width))),
255		...rows.map(line),
256	].join('\n');
257}
258
259export type ListArgs = {
260	// Every theme loaded, the themes /skin-code add brought, and the setting.
261	themes: readonly string[];
262	pairs: Pairs;
263	added: readonly string[];
264	current: string;
265	// While `auto`: the theme drawing now and the skins skin that picked it.
266	drawing?: string;
267	activeSkin?: string;
268	// The person's own skins skins, each by the built-in skin it was made from.
269	customSkins?: Readonly<Record<string, string | undefined>>;
270	isLight?: (theme: string) => boolean;
271	options?: Options;
272};
273
274type Row = { key: string; label: string; dark: string; light: string };
275
276const neonFirst = (a: string, b: string) =>
277	a.startsWith('neon-bunny') === b.startsWith('neon-bunny')
278		? a.localeCompare(b)
279		: a.startsWith('neon-bunny')
280			? -1
281			: 1;
282
283// Every theme: one row per skin with its dark and light themes, then the person's own
284// skins with the themes they resolve to, then each theme no skin uses (an added one says
285// so) in the column of its lightness, then how to pick one. The row in use says so.
286export function listText({
287	themes,
288	pairs,
289	added,
290	current,
291	drawing,
292	activeSkin,
293	customSkins = {},
294	isLight = () => false,
295	options = { header: true, numbers: true },
296}: ListArgs): string {
297	const skinRows: Row[] = Object.keys(pairs)
298		.sort(neonFirst)
299		.map((skin) => {
300			const [dark, light] = pairs[skin] ?? [skin, skin];
301
302			return { key: skin, label: skin, dark, light };
303		});
304	const customRows: Row[] = Object.keys(customSkins)
305		.filter((skin) => pairs[skin] === undefined)
306		.sort()
307		.map((skin) => {
308			const base = customSkins[skin];
309			const [dark, light] =
310				(base === undefined ? undefined : pairs[base]) ?? DEFAULT_PAIR;
311
312			return {
313				key: skin,
314				label: `${skin} (your skin${base === undefined ? '' : `, ${base}`})`,
315				dark,
316				light,
317			};
318		});
319	const used = new Set(Object.values(pairs).flat());
320	const looseRows: Row[] = themes
321		.filter((name) => !used.has(name))
322		.sort(
323			(a, b) =>
324				Number(added.includes(a)) - Number(added.includes(b)) ||
325				a.localeCompare(b),
326		)
327		.map((name) => {
328			const label = `${name}${added.includes(name) ? ' (added)' : ''}`;
329
330			return isLight(name)
331				? { key: name, label, dark: '', light: name }
332				: { key: name, label, dark: name, light: name };
333		});
334	const rows = [...skinRows, ...customRows, ...looseRows];
335
336	// The row in use: the skin set, else the one auto follows, else the first holding the theme.
337	const holding = (theme: string | undefined) =>
338		rows.find((row) => row.dark === theme || row.light === theme)?.key;
339	const inUse =
340		current === 'auto'
341			? rows.some((row) => row.key === activeSkin)
342				? activeSkin
343				: holding(drawing)
344			: rows.some((row) => row.key === current)
345				? current
346				: holding(current);
347	const now =
348		current === 'auto' && drawing !== undefined ? `auto (${drawing})` : current;
349
350	return [
351		`Code themes · now: ${now} · ${optionsText(options).toLowerCase()}`,
352		'',
353		markdownTable(
354			['Skin', 'Dark', 'Light'],
355			rows.map((row) => [
356				`${row.label}${row.key === inUse ? ' (current)' : ''}`,
357				row.dark,
358				row.light === row.dark ? '(same)' : row.light,
359			]),
360		),
361		'',
362		'`/skin-code status` shows what everything is set to.',
363		'',
364		'`/skin-code help` shows the commands.',
365	].join('\n');
366}
367
368// The snippet every theme in the gallery draws: a comment, keywords, a type, a string, a
369// number and a call, so the themes differ where they differ most.
370export const GALLERY_SAMPLE = {
371	lang: 'typescript',
372	code: [
373		'// Pick the crunchiest snack',
374		'type Snack = { name: string; crunch: number };',
375		'const pick = (all: Snack[]) =>',
376		"  all.find((s) => s.crunch > 7)?.name ?? 'carrot';",
377	].join('\n'),
378} as const;
379
380// The themes /skin-code gallery shows, Neon Bunny first, then by name.
381export function galleryThemes(
382	themes: readonly string[],
383	filter: GalleryFilter,
384	isLight: (theme: string) => boolean,
385): string[] {
386	return themes
387		.filter((theme) => filter === 'all' || isLight(theme) === (filter === 'light'))
388		.sort(neonFirst);
389}
390
391// The skins whose dark or light half is this theme, for a caption under its name.
392export const skinsOf = (theme: string, pairs: Pairs): string[] =>
393	Object.keys(pairs)
394		.filter((skin) => pairs[skin]?.includes(theme))
395		.sort();
396
397// Every /skin-code command and what it does: the reply to /skin-code help. It opens with a
398// line of text: Claude Code puts the plugin's name before a reply's first line, which would
399// break a table that started there.
400export function helpText(): string {
401	return [
402		'skin-code commands',
403		'',
404		markdownTable(
405			['Command', 'What it does'],
406			[
407				['`/skin-code` (or `status`)', 'what everything is set to'],
408				['`/skin-code <skin>`', 'follows light and dark'],
409				['`/skin-code <theme>`', 'that theme, always'],
410				['`/skin-code auto`', 'follow your skins skin'],
411				['`/skin-code off`', 'leave code blocks to skins or the app'],
412				['`/skin-code list` (or `themes`)', 'every skin and theme'],
413				['`/skin-code gallery [dark/light]`', 'a sample of code in every theme'],
414				['`/skin-code add <url or path>`', 'add a VS Code theme .json'],
415				['`/skin-code remove <name>`', 'remove a theme you added'],
416				['`/skin-code header on/off`', 'the language and line count bar'],
417				['`/skin-code numbers on/off`', 'the line numbers'],
418				['`/skin-code style text/card`', 'desktop blocks as selectable text, or a card in the code font'],
419			],
420		),
421		'',
422		'`/skin-code status` shows what everything is set to.',
423		'',
424		'`/skin-code list` shows every theme.',
425	].join('\n');
426}
427
428// A GitHub page link to a file, as its raw file; any other URL as given.
429export function rawUrl(url: string): string {
430	const blob = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/blob\/(.+)$/.exec(
431		url.trim(),
432	);
433
434	return blob === null
435		? url.trim()
436		: `https://raw.githubusercontent.com/${blob[1]}/${blob[2]}/${blob[3]}`;
437}
438
439export const isUrl = (source: string): boolean =>
440	/^https?:\/\//i.test(source.trim());
441
hooks/card.ts 182 lines
1import type { ThemedToken } from './vendor/shiki';
2
3// A code block as a vector card for the surfaces that draw Svg: the theme's own background,
4// a header with the language and line count, line numbers, and each token in its colour.
5// The header and the numbers can be left out.
6
7export type Colors = { background: string; foreground: string; gutter: string };
8
9export type CardOptions = {
10	header: boolean;
11	numbers: boolean;
12	// A copy control is laid over the card's top right; the card keeps room for it. Its
13	// icon is drawn by the control, not the card: the card is a frame, and a new drawing of
14	// it on each copy would reload the frame, a visible flash.
15	hasControl: boolean;
16};
17
18const MONO = `ui-monospace, 'SF Mono', 'Cascadia Code', 'JetBrains Mono', Menlo, Consolas, monospace`;
19const FONT = `ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Inter, sans-serif`;
20// Where the copy control, laid one text row down, centres in the image, in pixels. Rows
21// come in whole cells, so the card starts INSET below the image's top (a transparent strip)
22// to put that line at the middle of a compact header; without a header the first line of
23// code sits on it.
24const CONTROL_MID = 29;
25const INSET = 10;
26const LINE_MID = CONTROL_MID - INSET;
27const HEADER_H = LINE_MID * 2;
28const LINE_H = 20;
29// The padding's size: a monospace cell this size is about a row tall.
30const PAD = 22;
31const CODE = 12.5;
32const RADIUS = 12;
33const MAX_SOURCE = 131072;
34
35// Room on the card's right for the copy control laid over it.
36export const CONTROL_SLOT = 40;
37
38// Space above the first line when there is no header: its middle on the control's line.
39const BARE_TOP = LINE_MID - 10;
40
41export const MAX_LINES = 80;
42
43const escape = (text: string): string =>
44	text
45		.replace(/&/g, '&amp;')
46		.replace(/</g, '&lt;')
47		.replace(/>/g, '&gt;')
48		.replace(/"/g, '&quot;');
49
50export const cardWidth = (columns: number): number =>
51	Math.round(Math.min(1600, Math.max(480, columns * 6.4)));
52
53function spansOf(
54	tokens: readonly ThemedToken[],
55	maxChars: number,
56	foreground: string,
57): string {
58	let room = maxChars;
59	const spans: string[] = [];
60
61	for (const token of tokens) {
62		if (room <= 0) {
63			break;
64		}
65
66		const chars = [...token.content];
67		const text =
68			chars.length > room
69				? `${chars.slice(0, Math.max(0, room - 1)).join('')}…`
70				: token.content;
71		const style = token.fontStyle ?? 0;
72		const extra = `${style & 1 ? ';font-style:italic' : ''}${style & 2 ? ';font-weight:600' : ''}${style & 4 ? ';text-decoration:underline' : ''}`;
73
74		room -= chars.length;
75		spans.push(
76			`<tspan style="fill:${token.color ?? foreground}${extra}">${escape(text)}</tspan>`,
77		);
78	}
79
80	return spans.join('');
81}
82
83// Where the first line's box starts, and the card's height for `kept` lines of `total`.
84const topOf = (header: boolean): number => (header ? HEADER_H + 8 : BARE_TOP);
85
86const heightOf = (header: boolean, kept: number, total: number): number =>
87	topOf(header) + kept * LINE_H + (total > kept ? 28 : 10);
88
89function draw(
90	lines: readonly (readonly ThemedToken[])[],
91	lang: string,
92	colors: Colors,
93	width: number,
94	shown: number,
95	{ header, numbers, hasControl }: CardOptions,
96): string {
97	const { background, foreground, gutter } = colors;
98	const kept = lines.slice(0, shown);
99	const gutterW = numbers ? String(lines.length).length * 8 + 24 : 16;
100	// Without a header the copy control sits beside the code, so lines stop short of it.
101	const reserve = !header && hasControl ? CONTROL_SLOT : 0;
102	const maxChars = Math.floor((width - gutterW - 24 - reserve) / (CODE * 0.6));
103	const hidden = lines.length - kept.length;
104	const top = topOf(header);
105	const height = heightOf(header, kept.length, lines.length);
106	const clip = `skin-code-${width}x${height}`;
107	const mid = LINE_MID + 4;
108
109	// Each line is one <text> across the whole card: unselectable padding before the code
110	// (over the numbers) and after it, at PAD size so the line is as tall as its row. A drag
111	// that ends anywhere in a row lands on that row, never on the drawing beneath.
112	const lead = ' '.repeat(Math.ceil(gutterW / (PAD * 0.6)));
113	const rows = kept.map((tokens, i) => {
114		const y = top + i * LINE_H + 14;
115		const number = numbers
116			? `<text class="chrome" x="${gutterW - 12}" y="${y}" text-anchor="end" font-family="${MONO}" font-size="11" style="fill:${gutter}">${i + 1}</text>`
117			: '';
118
119		// After the code, two spaces stretched to the card's edge, one over the other: a tall
120		// unselectable one that fills the row, so a drag ending in the gap between rows lands
121		// on it, and a selectable one at the code's size, so a drag can start right of a line
122		// and the highlight is as tall as the code's. A copy takes that single space, no more.
123		const chars = Math.min(maxChars, tokens.reduce((n, token) => n + [...token.content].length, 0));
124		const end = gutterW + chars * CODE * 0.6;
125		const room = Math.max(1, width - end);
126
127		return `${number}<text x="0" y="${y}" font-family="${MONO}" font-size="${CODE}" xml:space="preserve" pointer-events="bounding-box"><tspan class="pad" font-size="${PAD}">${lead}</tspan><tspan x="${gutterW}">${spansOf(tokens, maxChars, foreground)}</tspan><tspan class="pad" x="${end}" font-size="${PAD}" textLength="${room}" lengthAdjust="spacingAndGlyphs"> </tspan><tspan x="${end}" textLength="${room}" lengthAdjust="spacingAndGlyphs"> </tspan></text>`;
128	});
129	const footer =
130		hidden > 0
131			? `<text class="chrome" x="${gutterW}" y="${top + kept.length * LINE_H + 14}" font-size="11.5" style="fill:${gutter}">${hidden} more line${hidden === 1 ? '' : 's'} (copy takes all of it)</text>`
132			: '';
133	const head = header
134		? [
135				`<text class="chrome" x="16" y="${mid}" font-size="11" style="fill:${gutter};letter-spacing:.1em;font-weight:600">${escape(lang.toUpperCase())}</text>`,
136				`<text class="chrome" x="${width - 16 - (hasControl ? CONTROL_SLOT : 0)}" y="${mid}" text-anchor="end" font-size="11" style="fill:${gutter}">${lines.length} line${lines.length === 1 ? '' : 's'}</text>`,
137				`<line x1="0" y1="${HEADER_H - 0.5}" x2="${width}" y2="${HEADER_H - 0.5}" stroke="${gutter}" stroke-opacity=".35"/>`,
138			].join('')
139		: '';
140
141	return [
142		`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height + INSET}" viewBox="0 0 ${width} ${height + INSET}">`,
143		`<defs><clipPath id="${clip}"><rect width="${width}" height="${height}" rx="${RADIUS}"/></clipPath></defs>`,
144		`<style>text{fill:${foreground}}text:not([font-family]){font-family:${FONT}}.chrome,.pad{-webkit-user-select:none;user-select:none}</style>`,
145		`<g transform="translate(0 ${INSET})">`,
146		`<g clip-path="url(#${clip})">`,
147		`<rect width="${width}" height="${height}" fill="${background}"/>`,
148		head,
149		rows.join(''),
150		footer,
151		`</g>`,
152		`<rect x=".5" y=".5" width="${width - 1}" height="${height - 1}" rx="${RADIUS - 0.5}" fill="none" stroke="${foreground}" stroke-opacity=".16"/>`,
153		`</g>`,
154		`</svg>`,
155	].join('');
156}
157
158// The card at most MAX_LINES long, and shorter while its markup runs past the Svg limit.
159export function codeCard(
160	lines: readonly (readonly ThemedToken[])[],
161	lang: string,
162	colors: Colors,
163	width: number,
164	options: CardOptions,
165) {
166	let shown = MAX_LINES;
167	let source = draw(lines, lang, colors, width, shown, options);
168
169	while (source.length > MAX_SOURCE && shown > 10) {
170		shown = Math.floor(shown * 0.7);
171		source = draw(lines, lang, colors, width, shown, options);
172	}
173
174	const kept = Math.min(shown, lines.length);
175
176	return {
177		source,
178		width,
179		height: INSET + heightOf(options.header, kept, lines.length),
180	};
181}
182
hooks/themes.ts 32 lines
1// Which code theme each skins skin gets, dark first, then light. A skin with no light
2// counterpart keeps its dark theme: a code block carries its own background on the desktop.
3// Neon Bunny is one of those.
4
5export type ThemePair = readonly [dark: string, light: string];
6
7export const DEFAULT_PAIR: ThemePair = ['neon-bunny', 'neon-bunny'];
8
9export const SKIN_THEMES: Readonly<Record<string, ThemePair>> = {
10	'neon-bunny': DEFAULT_PAIR,
11	'neon-bunny-carrot': ['neon-bunny-carrot', 'neon-bunny-carrot'],
12	ayu: ['ayu-dark', 'ayu-light'],
13	catppuccin: ['catppuccin-mocha', 'catppuccin-latte'],
14	dracula: ['dracula', 'dracula'],
15	everforest: ['everforest-dark', 'everforest-light'],
16	github: ['github-dark', 'github-light'],
17	gruvbox: ['gruvbox-dark-medium', 'gruvbox-light-medium'],
18	kanagawa: ['kanagawa-wave', 'kanagawa-lotus'],
19	mono: ['min-dark', 'min-light'],
20	'night-owl': ['night-owl', 'night-owl-light'],
21	noir: ['vitesse-black', 'vitesse-light'],
22	nord: ['nord', 'nord'],
23	'one-dark': ['one-dark-pro', 'one-light'],
24	'rose-pine': ['rose-pine', 'rose-pine-dawn'],
25	solarized: ['solarized-dark', 'solarized-light'],
26	'tokyo-night': ['tokyo-night', 'tokyo-night'],
27};
28
29// On the terminal the code sits on the terminal's own background, so a theme of the wrong
30// lightness gives way to one that reads there.
31export const TERMINAL_FALLBACK: ThemePair = ['github-dark', 'github-light'];
32
hooks/vendor/shiki.js 153 lines
1var Ho=Object.defineProperty;var qo=(e,t)=>{for(var n in t)Ho(e,n,{get:t[n],enumerable:!0})};var E=class extends Error{constructor(t){super(t),this.name="ShikiError"}};function Vo(e){return Dt(e)}function Dt(e){return Array.isArray(e)?Xo(e):e instanceof RegExp?e:typeof e=="object"?Ko(e):e}function Xo(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=Dt(e[n]);return t}function Ko(e){let t={};for(let n in e)t[n]=Dt(e[n]);return t}function Dn(e,...t){return t.forEach(n=>{for(let r in n)e[r]=n[r]}),e}function Fn(e){let t=~e.lastIndexOf("/")||~e.lastIndexOf("\\");return t===0?e:~t===e.length-1?Fn(e.substring(0,e.length-1)):e.substr(~t+1)}var Nt=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,qe=class{static hasCaptures(e){return e===null?!1:(Nt.lastIndex=0,Nt.test(e))}static replaceCaptures(e,t,n){return e.replace(Nt,(r,o,s,a)=>{let l=n[parseInt(o||s,10)];if(l){let i=t.substring(l.start,l.end);for(;i[0]===".";)i=i.substring(1);switch(a){case"downcase":return i.toLowerCase();case"upcase":return i.toUpperCase();default:return i}}else return r})}};function Un(e,t){return e<t?-1:e>t?1:0}function jn(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,r=t.length;if(n===r){for(let o=0;o<n;o++){let s=Un(e[o],t[o]);if(s!==0)return s}return 0}return n-r}function Ln(e){return!!(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{8}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e)||/^#[0-9a-f]{4}$/i.test(e))}function zn(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,"\\$&")}var Wn=class{constructor(e){this.fn=e}cache=new Map;get(e){if(this.cache.has(e))return this.cache.get(e);let t=this.fn(e);return this.cache.set(e,t),t}},Re=class{constructor(e,t,n){this._colorMap=e,this._defaults=t,this._root=n}static createFromRawTheme(e,t){return this.createFromParsedTheme(Yo(e),t)}static createFromParsedTheme(e,t){return es(e,t)}_cachedMatchRoot=new Wn(e=>this._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,r=this._cachedMatchRoot.get(t).find(o=>Qo(e.parent,o.parentScopes));return r?new Hn(r.fontStyle,r.foreground,r.background):null}},Lt=class Ve{constructor(t,n){this.parent=t,this.scopeName=n}static push(t,n){for(let r of n)t=new Ve(t,r);return t}static from(...t){let n=null;for(let r=0;r<t.length;r++)n=new Ve(n,t[r]);return n}push(t){return new Ve(this,t)}getSegments(){let t=this,n=[];for(;t;)n.push(t.scopeName),t=t.parent;return n.reverse(),n}toString(){return this.getSegments().join(" ")}extends(t){return this===t?!0:this.parent===null?!1:this.parent.extends(t)}getExtensionIfDefined(t){let n=[],r=this;for(;r&&r!==t;)n.push(r.scopeName),r=r.parent;return r===t?n.reverse():void 0}};function Qo(e,t){if(t.length===0)return!0;for(let n=0;n<t.length;n++){let r=t[n],o=!1;if(r===">"){if(n===t.length-1)return!1;r=t[++n],o=!0}for(;e&&!Jo(e.scopeName,r);){if(o)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function Jo(e,t){return t===e||e.startsWith(t)&&e[t.length]==="."}var Hn=class{constructor(e,t,n){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n}};function Yo(e){if(!e)return[];if(!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,n=[],r=0;for(let o=0,s=t.length;o<s;o++){let a=t[o];if(!a.settings)continue;let l;if(typeof a.scope=="string"){let h=a.scope;h=h.replace(/^[,]+/,""),h=h.replace(/[,]+$/,""),l=h.split(",")}else Array.isArray(a.scope)?l=a.scope:l=[""];let i=-1;if(typeof a.settings.fontStyle=="string"){i=0;let h=a.settings.fontStyle.split(" ");for(let p=0,d=h.length;p<d;p++)switch(h[p]){case"italic":i=i|1;break;case"bold":i=i|2;break;case"underline":i=i|4;break;case"strikethrough":i=i|8;break}}let c=null;typeof a.settings.foreground=="string"&&Ln(a.settings.foreground)&&(c=a.settings.foreground);let u=null;typeof a.settings.background=="string"&&Ln(a.settings.background)&&(u=a.settings.background);for(let h=0,p=l.length;h<p;h++){let f=l[h].trim().split(" "),b=f[f.length-1],w=null;f.length>1&&(w=f.slice(0,f.length-1),w.reverse()),n[r++]=new Zo(b,w,o,i,c,u)}}return n}var Zo=class{constructor(e,t,n,r,o,s){this.scope=e,this.parentScopes=t,this.index=n,this.fontStyle=r,this.foreground=o,this.background=s}},P=(e=>(e[e.NotSet=-1]="NotSet",e[e.None=0]="None",e[e.Italic=1]="Italic",e[e.Bold=2]="Bold",e[e.Underline=4]="Underline",e[e.Strikethrough=8]="Strikethrough",e))(P||{});function es(e,t){e.sort((i,c)=>{let u=Un(i.scope,c.scope);return u!==0||(u=jn(i.parentScopes,c.parentScopes),u!==0)?u:i.index-c.index});let n=0,r="#000000",o="#ffffff";for(;e.length>=1&&e[0].scope==="";){let i=e.shift();i.fontStyle!==-1&&(n=i.fontStyle),i.foreground!==null&&(r=i.foreground),i.background!==null&&(o=i.background)}let s=new ts(t),a=new Hn(n,s.getId(r),s.getId(o)),l=new rs(new Pt(0,null,-1,0,0),[]);for(let i=0,c=e.length;i<c;i++){let u=e[i];l.insert(0,u.scope,u.parentScopes,u.fontStyle,s.getId(u.foreground),s.getId(u.background))}return new Re(s,a,l)}var ts=class{_isFrozen;_lastColorId;_id2color;_color2id;constructor(e){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(e)){this._isFrozen=!0;for(let t=0,n=e.length;t<n;t++)this._color2id[e[t]]=t,this._id2color[t]=e[t]}else this._isFrozen=!1}getId(e){if(e===null)return 0;e=e.toUpperCase();let t=this._color2id[e];if(t)return t;if(this._isFrozen)throw new Error(`Missing color in color map - ${e}`);return t=++this._lastColorId,this._color2id[e]=t,this._id2color[t]=e,t}getColorMap(){return this._id2color.slice(0)}},ns=Object.freeze([]),Pt=class qn{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(t,n,r,o,s){this.scopeDepth=t,this.parentScopes=n||ns,this.fontStyle=r,this.foreground=o,this.background=s}clone(){return new qn(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background)}static cloneArr(t){let n=[];for(let r=0,o=t.length;r<o;r++)n[r]=t[r].clone();return n}acceptOverwrite(t,n,r,o){this.scopeDepth>t?console.log("how did this happen?"):this.scopeDepth=t,n!==-1&&(this.fontStyle=n),r!==0&&(this.foreground=r),o!==0&&(this.background=o)}},rs=class $t{constructor(t,n=[],r={}){this._mainRule=t,this._children=r,this._rulesWithParentScopes=n}_rulesWithParentScopes;static _cmpBySpecificity(t,n){if(t.scopeDepth!==n.scopeDepth)return n.scopeDepth-t.scopeDepth;let r=0,o=0;for(;t.parentScopes[r]===">"&&r++,n.parentScopes[o]===">"&&o++,!(r>=t.parentScopes.length||o>=n.parentScopes.length);){let s=n.parentScopes[o].length-t.parentScopes[r].length;if(s!==0)return s;r++,o++}return n.parentScopes.length-t.parentScopes.length}match(t){if(t!==""){let r=t.indexOf("."),o,s;if(r===-1?(o=t,s=""):(o=t.substring(0,r),s=t.substring(r+1)),this._children.hasOwnProperty(o))return this._children[o].match(s)}let n=this._rulesWithParentScopes.concat(this._mainRule);return n.sort($t._cmpBySpecificity),n}insert(t,n,r,o,s,a){if(n===""){this._doInsertHere(t,r,o,s,a);return}let l=n.indexOf("."),i,c;l===-1?(i=n,c=""):(i=n.substring(0,l),c=n.substring(l+1));let u;this._children.hasOwnProperty(i)?u=this._children[i]:(u=new $t(this._mainRule.clone(),Pt.cloneArr(this._rulesWithParentScopes)),this._children[i]=u),u.insert(t+1,c,r,o,s,a)}_doInsertHere(t,n,r,o,s){if(n===null){this._mainRule.acceptOverwrite(t,r,o,s);return}for(let a=0,l=this._rulesWithParentScopes.length;a<l;a++){let i=this._rulesWithParentScopes[a];if(jn(i.parentScopes,n)===0){i.acceptOverwrite(t,r,o,s);return}}r===-1&&(r=this._mainRule.fontStyle),o===0&&(o=this._mainRule.foreground),s===0&&(s=this._mainRule.background),this._rulesWithParentScopes.push(new Pt(t,n,r,o,s))}},ce=class F{static toBinaryStr(t){return t.toString(2).padStart(32,"0")}static print(t){let n=F.getLanguageId(t),r=F.getTokenType(t),o=F.getFontStyle(t),s=F.getForeground(t),a=F.getBackground(t);console.log({languageId:n,tokenType:r,fontStyle:o,foreground:s,background:a})}static getLanguageId(t){return(t&255)>>>0}static getTokenType(t){return(t&768)>>>8}static containsBalancedBrackets(t){return(t&1024)!==0}static getFontStyle(t){return(t&30720)>>>11}static getForeground(t){return(t&16744448)>>>15}static getBackground(t){return(t&4278190080)>>>24}static set(t,n,r,o,s,a,l){let i=F.getLanguageId(t),c=F.getTokenType(t),u=F.containsBalancedBrackets(t)?1:0,h=F.getFontStyle(t),p=F.getForeground(t),d=F.getBackground(t);return n!==0&&(i=n),r!==8&&(c=r),o!==null&&(u=o?1:0),s!==-1&&(h=s),a!==0&&(p=a),l!==0&&(d=l),(i<<0|c<<8|u<<10|h<<11|p<<15|d<<24)>>>0}};function Ke(e,t){let n=[],r=os(e),o=r.next();for(;o!==null;){let i=0;if(o.length===2&&o.charAt(1)===":"){switch(o.charAt(0)){case"R":i=1;break;case"L":i=-1;break;default:console.log(`Unknown priority ${o} in scope selector`)}o=r.next()}let c=a();if(n.push({matcher:c,priority:i}),o!==",")break;o=r.next()}return n;function s(){if(o==="-"){o=r.next();let i=s();return c=>!!i&&!i(c)}if(o==="("){o=r.next();let i=l();return o===")"&&(o=r.next()),i}if(Tn(o)){let i=[];do i.push(o),o=r.next();while(Tn(o));return c=>t(i,c)}return null}function a(){let i=[],c=s();for(;c;)i.push(c),c=s();return u=>i.every(h=>h(u))}function l(){let i=[],c=a();for(;c&&(i.push(c),o==="|"||o===",");){do o=r.next();while(o==="|"||o===",");c=a()}return u=>i.some(h=>h(u))}}function Tn(e){return!!e&&!!e.match(/[\w\.:]+/)}function os(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,n=t.exec(e);return{next:()=>{if(!n)return null;let r=n[0];return n=t.exec(e),r}}}function Vn(e){typeof e.dispose=="function"&&e.dispose()}var Ne=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},ss=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},as=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},is=class{constructor(e,t){this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new Ne(this.initialScopeName)]}seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){let e=this.Q;this.Q=[];let t=new as;for(let n of e)ls(n,this.initialScopeName,this.repo,t);for(let n of t.references)if(n instanceof Ne){if(this.seenFullScopeRequests.has(n.scopeName))continue;this.seenFullScopeRequests.add(n.scopeName),this.Q.push(n)}else{if(this.seenFullScopeRequests.has(n.scopeName)||this.seenPartialScopeRequests.has(n.toKey()))continue;this.seenPartialScopeRequests.add(n.toKey()),this.Q.push(n)}}};function ls(e,t,n,r){let o=n.lookup(e.scopeName);if(!o){if(e.scopeName===t)throw new Error(`No grammar provided for <${t}>`);return}let s=n.lookup(t);e instanceof Ne?Xe({baseGrammar:s,selfGrammar:o},r):Mt(e.ruleName,{baseGrammar:s,selfGrammar:o,repository:o.repository},r);let a=n.injections(e.scopeName);if(a)for(let l of a)r.add(new Ne(l))}function Mt(e,t,n){if(t.repository&&t.repository[e]){let r=t.repository[e];Qe([r],t,n)}}function Xe(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&Qe(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&Qe(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function Qe(e,t,n){for(let r of e){if(n.visitedRule.has(r))continue;n.visitedRule.add(r);let o=r.repository?Dn({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&Qe(r.patterns,{...t,repository:o},n);let s=r.include;if(!s)continue;let a=Xn(s);switch(a.kind){case 0:Xe({...t,selfGrammar:t.baseGrammar},n);break;case 1:Xe(t,n);break;case 2:Mt(a.ruleName,{...t,repository:o},n);break;case 3:case 4:let l=a.scopeName===t.selfGrammar.scopeName?t.selfGrammar:a.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(l){let i={baseGrammar:t.baseGrammar,selfGrammar:l,repository:o};a.kind===4?Mt(a.ruleName,i,n):Xe(i,n)}else a.kind===4?n.add(new ss(a.scopeName,a.ruleName)):n.add(new Ne(a.scopeName));break}}}var cs=class{kind=0},us=class{kind=1},hs=class{constructor(e){this.ruleName=e}kind=2},ps=class{constructor(e){this.scopeName=e}kind=3},fs=class{constructor(e,t){this.scopeName=e,this.ruleName=t}kind=4};function Xn(e){if(e==="$base")return new cs;if(e==="$self")return new us;let t=e.indexOf("#");if(t===-1)return new ps(e);if(t===0)return new hs(e.substring(1));{let n=e.substring(0,t),r=e.substring(t+1);return new fs(n,r)}}var ds=/\\(\d+)/,Pn=/\\(\d+)/g,Zc=Symbol("RuleId"),gs=-1,Kn=-2;var Pe=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,n,r){this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=qe.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=qe.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${Fn(this.$location.filename)}:${this.$location.line}`:"unknown";return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:qe.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:qe.replaceCaptures(this._contentName,e,t)}},ms=class extends Pe{retokenizeCapturedWithRuleId;constructor(e,t,n,r,o){super(e,t,n,r),this.retokenizeCapturedWithRuleId=o}dispose(){}collectPatterns(e,t){throw new Error("Not supported!")}compile(e,t){throw new Error("Not supported!")}compileAG(e,t,n,r){throw new Error("Not supported!")}},ys=class extends Pe{_match;captures;_cachedCompiledPatterns;constructor(e,t,n,r,o){super(e,t,n,null),this._match=new Le(r,this.id),this.captures=o,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(e,t){t.push(this._match)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Te,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},$n=class extends Pe{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,o){super(e,t,n,r),this.patterns=o.patterns,this.hasMissingPatterns=o.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}collectPatterns(e,t){for(let n of this.patterns)e.getRule(n).collectPatterns(e,t)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Te,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},Ot=class extends Pe{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,o,s,a,l,i,c){super(e,t,n,r),this._begin=new Le(o,this.id),this.beginCaptures=s,this._end=new Le(a||"\uFFFF",-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=l,this.applyEndPatternLast=i||!1,this.patterns=c.patterns,this.hasMissingPatterns=c.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(e,t){return this._end.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e,t).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e,t).compileAG(e,n,r)}_getCachedCompiledPatterns(e,t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Te;for(let n of this.patterns)e.getRule(n).collectPatterns(e,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,t):this._cachedCompiledPatterns.setSource(0,t)),this._cachedCompiledPatterns}},Je=class extends Pe{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(e,t,n,r,o,s,a,l,i){super(e,t,n,r),this._begin=new Le(o,this.id),this.beginCaptures=s,this.whileCaptures=l,this._while=new Le(a,Kn),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=i.patterns,this.hasMissingPatterns=i.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null),this._cachedCompiledWhilePatterns&&(this._cachedCompiledWhilePatterns.dispose(),this._cachedCompiledWhilePatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(e,t){return this._while.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Te;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(e,t){return this._getCachedCompiledWhilePatterns(e,t).compile(e)}compileWhileAG(e,t,n,r){return this._getCachedCompiledWhilePatterns(e,t).compileAG(e,n,r)}_getCachedCompiledWhilePatterns(e,t){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new Te,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||"\uFFFF"),this._cachedCompiledWhilePatterns}},Qn=class ${static createCaptureRule(t,n,r,o,s){return t.registerRule(a=>new ms(n,a,r,o,s))}static getCompiledRuleId(t,n,r){return t.id||n.registerRule(o=>{if(t.id=o,t.match)return new ys(t.$vscodeTextmateLocation,t.id,t.name,t.match,$._compileCaptures(t.captures,n,r));if(typeof t.begin>"u"){t.repository&&(r=Dn({},r,t.repository));let s=t.patterns;return typeof s>"u"&&t.include&&(s=[{include:t.include}]),new $n(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,$._compilePatterns(s,n,r))}return t.while?new Je(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,$._compileCaptures(t.beginCaptures||t.captures,n,r),t.while,$._compileCaptures(t.whileCaptures||t.captures,n,r),$._compilePatterns(t.patterns,n,r)):new Ot(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,$._compileCaptures(t.beginCaptures||t.captures,n,r),t.end,$._compileCaptures(t.endCaptures||t.captures,n,r),t.applyEndPatternLast,$._compilePatterns(t.patterns,n,r))}),t.id}static _compileCaptures(t,n,r){let o=[];if(t){let s=0;for(let a in t){if(a==="$vscodeTextmateLocation")continue;let l=parseInt(a,10);l>s&&(s=l)}for(let a=0;a<=s;a++)o[a]=null;for(let a in t){if(a==="$vscodeTextmateLocation")continue;let l=parseInt(a,10),i=0;t[a].patterns&&(i=$.getCompiledRuleId(t[a],n,r)),o[l]=$.createCaptureRule(n,t[a].$vscodeTextmateLocation,t[a].name,t[a].contentName,i)}}return o}static _compilePatterns(t,n,r){let o=[];if(t)for(let s=0,a=t.length;s<a;s++){let l=t[s],i=-1;if(l.include){let c=Xn(l.include);switch(c.kind){case 0:case 1:i=$.getCompiledRuleId(r[l.include],n,r);break;case 2:let u=r[c.ruleName];u&&(i=$.getCompiledRuleId(u,n,r));break;case 3:case 4:let h=c.scopeName,p=c.kind===4?c.ruleName:null,d=n.getExternalGrammar(h,r);if(d)if(p){let f=d.repository[p];f&&(i=$.getCompiledRuleId(f,n,d.repository))}else i=$.getCompiledRuleId(d.repository.$self,n,d.repository);break}}else i=$.getCompiledRuleId(l,n,r);if(i!==-1){let c=n.getRule(i),u=!1;if((c instanceof $n||c instanceof Ot||c instanceof Je)&&c.hasMissingPatterns&&c.patterns.length===0&&(u=!0),u)continue;o.push(i)}}return{patterns:o,hasMissingPatterns:(t?t.length:0)!==o.length}}},Le=class Jn{source;ruleId;hasAnchor;hasBackReferences;_anchorCache;constructor(t,n){if(t&&typeof t=="string"){let r=t.length,o=0,s=[],a=!1;for(let l=0;l<r;l++)if(t.charAt(l)==="\\"&&l+1<r){let c=t.charAt(l+1);c==="z"?(s.push(t.substring(o,l)),s.push("$(?!\\n)(?<!\\n)"),o=l+2):(c==="A"||c==="G")&&(a=!0),l++}this.hasAnchor=a,o===0?this.source=t:(s.push(t.substring(o,r)),this.source=s.join(""))}else this.hasAnchor=!1,this.source=t;this.hasAnchor?this._anchorCache=this._buildAnchorCache():this._anchorCache=null,this.ruleId=n,typeof this.source=="string"?this.hasBackReferences=ds.test(this.source):this.hasBackReferences=!1}clone(){return new Jn(this.source,this.ruleId)}setSource(t){this.source!==t&&(this.source=t,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(t,n){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let r=n.map(o=>t.substring(o.start,o.end));return Pn.lastIndex=0,this.source.replace(Pn,(o,s)=>zn(r[parseInt(s,10)]||""))}_buildAnchorCache(){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let t=[],n=[],r=[],o=[],s,a,l,i;for(s=0,a=this.source.length;s<a;s++)l=this.source.charAt(s),t[s]=l,n[s]=l,r[s]=l,o[s]=l,l==="\\"&&s+1<a&&(i=this.source.charAt(s+1),i==="A"?(t[s+1]="\uFFFF",n[s+1]="\uFFFF",r[s+1]="A",o[s+1]="A"):i==="G"?(t[s+1]="\uFFFF",n[s+1]="G",r[s+1]="\uFFFF",o[s+1]="G"):(t[s+1]=i,n[s+1]=i,r[s+1]=i,o[s+1]=i),s++);return{A0_G0:t.join(""),A0_G1:n.join(""),A1_G0:r.join(""),A1_G1:o.join("")}}resolveAnchors(t,n){return!this.hasAnchor||!this._anchorCache||typeof this.source!="string"?this.source:t?n?this._anchorCache.A1_G1:this._anchorCache.A1_G0:n?this._anchorCache.A0_G1:this._anchorCache.A0_G0}},Te=class{_items;_hasAnchors;_cached;_anchorCache;constructor(){this._items=[],this._hasAnchors=!1,this._cached=null,this._anchorCache={A0_G0:null,A0_G1:null,A1_G0:null,A1_G1:null}}dispose(){this._disposeCaches()}_disposeCaches(){this._cached&&(this._cached.dispose(),this._cached=null),this._anchorCache.A0_G0&&(this._anchorCache.A0_G0.dispose(),this._anchorCache.A0_G0=null),this._anchorCache.A0_G1&&(this._anchorCache.A0_G1.dispose(),this._anchorCache.A0_G1=null),this._anchorCache.A1_G0&&(this._anchorCache.A1_G0.dispose(),this._anchorCache.A1_G0=null),this._anchorCache.A1_G1&&(this._anchorCache.A1_G1.dispose(),this._anchorCache.A1_G1=null)}push(e){this._items.push(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}unshift(e){this._items.unshift(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}length(){return this._items.length}setSource(e,t){this._items[e].source!==t&&(this._disposeCaches(),this._items[e].setSource(t))}compile(e){if(!this._cached){let t=this._items.map(n=>n.source);this._cached=new Mn(e,t,this._items.map(n=>n.ruleId))}return this._cached}compileAG(e,t,n){return this._hasAnchors?t?n?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G0):n?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,n){let r=this._items.map(o=>o.resolveAnchors(t,n));return new Mn(e,r,this._items.map(o=>o.ruleId))}},Mn=class{constructor(e,t,n){this.regExps=t,this.rules=n,this.scanner=e.createOnigScanner(t)}scanner;dispose(){typeof this.scanner.dispose=="function"&&this.scanner.dispose()}toString(){let e=[];for(let t=0,n=this.rules.length;t<n;t++)e.push("   - "+this.rules[t]+": "+this.regExps[t]);return e.join(`
2`)}findNextMatchSync(e,t,n){let r=this.scanner.findNextMatchSync(e,t,n);return r?{ruleId:this.rules[r.index],captureIndices:r.captureIndices}:null}},Tt=class{constructor(e,t){this.languageId=e,this.tokenType=t}},bs=class Gt{_defaultAttributes;_embeddedLanguagesMatcher;constructor(t,n){this._defaultAttributes=new Tt(t,8),this._embeddedLanguagesMatcher=new ws(Object.entries(n||{}))}getDefaultAttributes(){return this._defaultAttributes}getBasicScopeAttributes(t){return t===null?Gt._NULL_SCOPE_METADATA:this._getBasicScopeAttributes.get(t)}static _NULL_SCOPE_METADATA=new Tt(0,0);_getBasicScopeAttributes=new Wn(t=>{let n=this._scopeToLanguage(t),r=this._toStandardTokenType(t);return new Tt(n,r)});_scopeToLanguage(t){return this._embeddedLanguagesMatcher.match(t)||0}_toStandardTokenType(t){let n=t.match(Gt.STANDARD_TOKEN_TYPE_REGEXP);if(!n)return 8;switch(n[1]){case"comment":return 1;case"string":return 2;case"regex":return 3;case"meta.embedded":return 0}throw new Error("Unexpected match for standard token type!")}static STANDARD_TOKEN_TYPE_REGEXP=/\b(comment|string|regex|meta\.embedded)\b/},ws=class{values;scopesRegExp;constructor(e){if(e.length===0)this.values=null,this.scopesRegExp=null;else{this.values=new Map(e);let t=e.map(([n,r])=>zn(n));t.sort(),t.reverse(),this.scopesRegExp=new RegExp(`^((${t.join(")|(")}))($|\\.)`,"")}}match(e){if(!this.scopesRegExp)return;let t=e.match(this.scopesRegExp);if(t)return this.values.get(t[1])}},eu={InDebugMode:typeof process<"u"&&!!process.env.VSCODE_TEXTMATE_DEBUG},Yn=!1,On=class{constructor(e,t){this.stack=e,this.stoppedEarly=t}};function Zn(e,t,n,r,o,s,a,l){let i=t.content.length,c=!1,u=-1;if(a){let d=Cs(e,t,n,r,o,s);o=d.stack,r=d.linePos,n=d.isFirstLine,u=d.anchorPosition}let h=Date.now();for(;!c;){if(l!==0&&Date.now()-h>l)return new On(o,!0);p()}return new On(o,!1);function p(){let d=_s(e,t,n,r,o,u);if(!d){s.produce(o,i),c=!0;return}let f=d.captureIndices,b=d.matchedRuleId,w=f&&f.length>0?f[0].end>r:!1;if(b===gs){let m=o.getRule(e);s.produce(o,f[0].start),o=o.withContentNameScopesList(o.nameScopesList),Ee(e,t,n,o,s,m.endCaptures,f),s.produce(o,f[0].end);let C=o;if(o=o.parent,u=C.getAnchorPos(),!w&&C.getEnterPos()===r){o=C,s.produce(o,i),c=!0;return}}else{let m=e.getRule(b);s.produce(o,f[0].start);let C=o,y=m.getName(t.content,f),_=o.contentNameScopesList.pushAttributed(y,e);if(o=o.push(b,r,u,f[0].end===i,null,_,_),m instanceof Ot){let x=m;Ee(e,t,n,o,s,x.beginCaptures,f),s.produce(o,f[0].end),u=f[0].end;let M=x.getContentName(t.content,f),O=_.pushAttributed(M,e);if(o=o.withContentNameScopesList(O),x.endHasBackReferences&&(o=o.withEndRule(x.getEndWithResolvedBackReferences(t.content,f))),!w&&C.hasSameRuleAs(o)){o=o.pop(),s.produce(o,i),c=!0;return}}else if(m instanceof Je){let x=m;Ee(e,t,n,o,s,x.beginCaptures,f),s.produce(o,f[0].end),u=f[0].end;let M=x.getContentName(t.content,f),O=_.pushAttributed(M,e);if(o=o.withContentNameScopesList(O),x.whileHasBackReferences&&(o=o.withEndRule(x.getWhileWithResolvedBackReferences(t.content,f))),!w&&C.hasSameRuleAs(o)){o=o.pop(),s.produce(o,i),c=!0;return}}else if(Ee(e,t,n,o,s,m.captures,f),s.produce(o,f[0].end),o=o.pop(),!w){o=o.safePop(),s.produce(o,i),c=!0;return}}f[0].end>r&&(r=f[0].end,n=!1)}}function Cs(e,t,n,r,o,s){let a=o.beginRuleCapturedEOL?0:-1,l=[];for(let i=o;i;i=i.pop()){let c=i.getRule(e);c instanceof Je&&l.push({rule:c,stack:i})}for(let i=l.pop();i;i=l.pop()){let{ruleScanner:c,findOptions:u}=xs(i.rule,e,i.stack.endRule,n,r===a),h=c.findNextMatchSync(t,r,u);if(h){if(h.ruleId!==Kn){o=i.stack.pop();break}h.captureIndices&&h.captureIndices.length&&(s.produce(i.stack,h.captureIndices[0].start),Ee(e,t,n,i.stack,s,i.rule.whileCaptures,h.captureIndices),s.produce(i.stack,h.captureIndices[0].end),a=h.captureIndices[0].end,h.captureIndices[0].end>r&&(r=h.captureIndices[0].end,n=!1))}else{o=i.stack.pop();break}}return{stack:o,linePos:r,anchorPosition:a,isFirstLine:n}}function _s(e,t,n,r,o,s){let a=ks(e,t,n,r,o,s),l=e.getInjections();if(l.length===0)return a;let i=Ss(l,e,t,n,r,o,s);if(!i)return a;if(!a)return i;let c=a.captureIndices[0].start,u=i.captureIndices[0].start;return u<c||i.priorityMatch&&u===c?i:a}function ks(e,t,n,r,o,s){let a=o.getRule(e),{ruleScanner:l,findOptions:i}=er(a,e,o.endRule,n,r===s),c=l.findNextMatchSync(t,r,i);return c?{captureIndices:c.captureIndices,matchedRuleId:c.ruleId}:null}function Ss(e,t,n,r,o,s,a){let l=Number.MAX_VALUE,i=null,c,u=0,h=s.contentNameScopesList.getScopeNames();for(let p=0,d=e.length;p<d;p++){let f=e[p];if(!f.matcher(h))continue;let b=t.getRule(f.ruleId),{ruleScanner:w,findOptions:m}=er(b,t,null,r,o===a),C=w.findNextMatchSync(n,o,m);if(!C)continue;let y=C.captureIndices[0].start;if(!(y>=l)&&(l=y,i=C.captureIndices,c=C.ruleId,u=f.priority,l===o))break}return i?{priorityMatch:u===-1,captureIndices:i,matchedRuleId:c}:null}function er(e,t,n,r,o){if(Yn){let a=e.compile(t,n),l=tr(r,o);return{ruleScanner:a,findOptions:l}}return{ruleScanner:e.compileAG(t,n,r,o),findOptions:0}}function xs(e,t,n,r,o){if(Yn){let a=e.compileWhile(t,n),l=tr(r,o);return{ruleScanner:a,findOptions:l}}return{ruleScanner:e.compileWhileAG(t,n,r,o),findOptions:0}}function tr(e,t){let n=0;return e||(n|=1),t||(n|=4),n}function Ee(e,t,n,r,o,s,a){if(s.length===0)return;let l=t.content,i=Math.min(s.length,a.length),c=[],u=a[0].end;for(let h=0;h<i;h++){let p=s[h];if(p===null)continue;let d=a[h];if(d.length===0)continue;if(d.start>u)break;for(;c.length>0&&c[c.length-1].endPos<=d.start;)o.produceFromScopes(c[c.length-1].scopes,c[c.length-1].endPos),c.pop();if(c.length>0?o.produceFromScopes(c[c.length-1].scopes,d.start):o.produce(r,d.start),p.retokenizeCapturedWithRuleId){let b=p.getName(l,a),w=r.contentNameScopesList.pushAttributed(b,e),m=p.getContentName(l,a),C=w.pushAttributed(m,e),y=r.push(p.retokenizeCapturedWithRuleId,d.start,-1,!1,null,w,C),_=e.createOnigString(l.substring(0,d.end));Zn(e,_,n&&d.start===0,d.start,y,o,!1,0),Vn(_);continue}let f=p.getName(l,a);if(f!==null){let w=(c.length>0?c[c.length-1].scopes:r.contentNameScopesList).pushAttributed(f,e);c.push(new vs(w,d.end))}}for(;c.length>0;)o.produceFromScopes(c[c.length-1].scopes,c[c.length-1].endPos),c.pop()}var vs=class{scopes;endPos;constructor(e,t){this.scopes=e,this.endPos=t}};function As(e,t,n,r,o,s,a,l){return new Is(e,t,n,r,o,s,a,l)}function Gn(e,t,n,r,o){let s=Ke(t,Ye),a=Qn.getCompiledRuleId(n,r,o.repository);for(let l of s)e.push({debugSelector:t,matcher:l.matcher,ruleId:a,grammar:o,priority:l.priority})}function Ye(e,t){if(t.length<e.length)return!1;let n=0;return e.every(r=>{for(let o=n;o<t.length;o++)if(Es(t[o],r))return n=o+1,!0;return!1})}function Es(e,t){if(!e)return!1;if(e===t)return!0;let n=t.length;return e.length>n&&e.substr(0,n)===t&&e[n]==="."}var Is=class{constructor(e,t,n,r,o,s,a,l){if(this._rootScopeName=e,this.balancedBracketSelectors=s,this._onigLib=l,this._basicScopeAttributesProvider=new bs(n,r),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=a,this._grammar=Bn(t,null),this._injections=null,this._tokenTypeMatchers=[],o)for(let i of Object.keys(o)){let c=Ke(i,Ye);for(let u of c)this._tokenTypeMatchers.push({matcher:u.matcher,type:o[i]})}}_rootId;_lastRuleId;_ruleId2desc;_includedGrammars;_grammarRepository;_grammar;_injections;_basicScopeAttributesProvider;_tokenTypeMatchers;get themeProvider(){return this._grammarRepository}dispose(){for(let e of this._ruleId2desc)e&&e.dispose()}createOnigScanner(e){return this._onigLib.createOnigScanner(e)}createOnigString(e){return this._onigLib.createOnigString(e)}getMetadataForScope(e){return this._basicScopeAttributesProvider.getBasicScopeAttributes(e)}_collectInjections(){let e={lookup:o=>o===this._rootScopeName?this._grammar:this.getExternalGrammar(o),injections:o=>this._grammarRepository.injections(o)},t=[],n=this._rootScopeName,r=e.lookup(n);if(r){let o=r.injections;if(o)for(let a in o)Gn(t,a,o[a],this,r);let s=this._grammarRepository.injections(n);s&&s.forEach(a=>{let l=this.getExternalGrammar(a);if(l){let i=l.injectionSelector;i&&Gn(t,i,l,this,l)}})}return t.sort((o,s)=>o.priority-s.priority),t}getInjections(){return this._injections===null&&(this._injections=this._collectInjections()),this._injections}registerRule(e){let t=++this._lastRuleId,n=e(t);return this._ruleId2desc[t]=n,n}getRule(e){return this._ruleId2desc[e]}getExternalGrammar(e,t){if(this._includedGrammars[e])return this._includedGrammars[e];if(this._grammarRepository){let n=this._grammarRepository.lookup(e);if(n)return this._includedGrammars[e]=Bn(n,t&&t.$base),this._includedGrammars[e]}}tokenizeLine(e,t,n=0){let r=this._tokenize(e,t,!1,n);return{tokens:r.lineTokens.getResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}tokenizeLine2(e,t,n=0){let r=this._tokenize(e,t,!0,n);return{tokens:r.lineTokens.getBinaryResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}_tokenize(e,t,n,r){this._rootId===-1&&(this._rootId=Qn.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections());let o;if(!t||t===Bt.NULL){o=!0;let c=this._basicScopeAttributesProvider.getDefaultAttributes(),u=this.themeProvider.getDefaults(),h=ce.set(0,c.languageId,c.tokenType,null,u.fontStyle,u.foregroundId,u.backgroundId),p=this.getRule(this._rootId).getName(null,null),d;p?d=Ie.createRootAndLookUpScopeName(p,h,this):d=Ie.createRoot("unknown",h),t=new Bt(null,this._rootId,-1,-1,!1,null,d,d)}else o=!1,t.reset();e=e+`
3`;let s=this.createOnigString(e),a=s.content.length,l=new Ns(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),i=Zn(this,s,o,0,t,l,!0,r);return Vn(s),{lineLength:a,lineTokens:l,ruleStack:i.stack,stoppedEarly:i.stoppedEarly}}};function Bn(e,t){return e=Vo(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var Ie=class W{constructor(t,n,r){this.parent=t,this.scopePath=n,this.tokenAttributes=r}static fromExtension(t,n){let r=t,o=t?.scopePath??null;for(let s of n)o=Lt.push(o,s.scopeNames),r=new W(r,o,s.encodedTokenAttributes);return r}static createRoot(t,n){return new W(null,new Lt(null,t),n)}static createRootAndLookUpScopeName(t,n,r){let o=r.getMetadataForScope(t),s=new Lt(null,t),a=r.themeProvider.themeMatch(s),l=W.mergeAttributes(n,o,a);return new W(null,s,l)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(" ")}equals(t){return W.equals(this,t)}static equals(t,n){do{if(t===n||!t&&!n)return!0;if(!t||!n||t.scopeName!==n.scopeName||t.tokenAttributes!==n.tokenAttributes)return!1;t=t.parent,n=n.parent}while(!0)}static mergeAttributes(t,n,r){let o=-1,s=0,a=0;return r!==null&&(o=r.fontStyle,s=r.foregroundId,a=r.backgroundId),ce.set(t,n.languageId,n.tokenType,null,o,s,a)}pushAttributed(t,n){if(t===null)return this;if(t.indexOf(" ")===-1)return W._pushAttributed(this,t,n);let r=t.split(/ /g),o=this;for(let s of r)o=W._pushAttributed(o,s,n);return o}static _pushAttributed(t,n,r){let o=r.getMetadataForScope(n),s=t.scopePath.push(n),a=r.themeProvider.themeMatch(s),l=W.mergeAttributes(t.tokenAttributes,o,a);return new W(t,s,l)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(t){let n=[],r=this;for(;r&&r!==t;)n.push({encodedTokenAttributes:r.tokenAttributes,scopeNames:r.scopePath.getExtensionIfDefined(r.parent?.scopePath??null)}),r=r.parent;return r===t?n.reverse():void 0}},Bt=class le{constructor(t,n,r,o,s,a,l,i){this.parent=t,this.ruleId=n,this.beginRuleCapturedEOL=s,this.endRule=a,this.nameScopesList=l,this.contentNameScopesList=i,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=r,this._anchorPos=o}_stackElementBrand=void 0;static NULL=new le(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(t){return t===null?!1:le._equals(this,t)}static _equals(t,n){return t===n?!0:this._structuralEquals(t,n)?Ie.equals(t.contentNameScopesList,n.contentNameScopesList):!1}static _structuralEquals(t,n){do{if(t===n||!t&&!n)return!0;if(!t||!n||t.depth!==n.depth||t.ruleId!==n.ruleId||t.endRule!==n.endRule)return!1;t=t.parent,n=n.parent}while(!0)}clone(){return this}static _reset(t){for(;t;)t._enterPos=-1,t._anchorPos=-1,t=t.parent}reset(){le._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,n,r,o,s,a,l){return new le(this,t,n,r,o,s,a,l)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(t){return t.getRule(this.ruleId)}toString(){let t=[];return this._writeString(t,0),"["+t.join(",")+"]"}_writeString(t,n){return this.parent&&(n=this.parent._writeString(t,n)),t[n++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,n}withContentNameScopesList(t){return this.contentNameScopesList===t?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,t)}withEndRule(t){return this.endRule===t?this:new le(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(t){let n=this;for(;n&&n._enterPos===t._enterPos;){if(n.ruleId===t.ruleId)return!0;n=n.parent}return!1}toStateStackFrame(){return{ruleId:this.ruleId,beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,n){let r=Ie.fromExtension(t?.nameScopesList??null,n.nameScopesList);return new le(t,n.ruleId,n.enterPos??-1,n.anchorPos??-1,n.beginRuleCapturedEOL,n.endRule,r,Ie.fromExtension(r,n.contentNameScopesList))}},Rs=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(n=>n==="*"?(this.allowAny=!0,[]):Ke(n,Ye).map(r=>r.matcher)),this.unbalancedBracketScopes=t.flatMap(n=>Ke(n,Ye).map(r=>r.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},Ns=class{constructor(e,t,n,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=n,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}_emitBinaryTokens;_lineText;_tokens;_binaryTokens;_lastTokenEndIndex;_tokenTypeOverrides;produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(this._lastTokenEndIndex>=t)return;if(this._emitBinaryTokens){let r=e?.tokenAttributes??0,o=!1;if(this.balancedBracketSelectors?.matchesAlways&&(o=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){let s=e?.getScopeNames()??[];for(let a of this._tokenTypeOverrides)a.matcher(s)&&(r=ce.set(r,0,a.type,null,-1,0,0));this.balancedBracketSelectors&&(o=this.balancedBracketSelectors.match(s))}if(o&&(r=ce.set(r,0,8,o,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===r){this._lastTokenEndIndex=t;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(r),this._lastTokenEndIndex=t;return}let n=e?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:t,scopes:n}),this._lastTokenEndIndex=t}getResult(e,t){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===t-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(e,t){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===t-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._binaryTokens[this._binaryTokens.length-2]=0);let n=new Uint32Array(this._binaryTokens.length);for(let r=0,o=this._binaryTokens.length;r<o;r++)n[r]=this._binaryTokens[r];return n}},Ls=class{constructor(e,t){this._onigLib=t,this._theme=e}_grammars=new Map;_rawGrammars=new Map;_injectionGrammars=new Map;_theme;dispose(){for(let e of this._grammars.values())e.dispose()}setTheme(e){this._theme=e}getColorMap(){return this._theme.getColorMap()}addGrammar(e,t){this._rawGrammars.set(e.scopeName,e),t&&this._injectionGrammars.set(e.scopeName,t)}lookup(e){return this._rawGrammars.get(e)}injections(e){return this._injectionGrammars.get(e)}getDefaults(){return this._theme.getDefaults()}themeMatch(e){return this._theme.match(e)}grammarForScopeName(e,t,n,r,o){if(!this._grammars.has(e)){let s=this._rawGrammars.get(e);if(!s)return null;this._grammars.set(e,As(e,s,t,n,r,o,this,this._onigLib))}return this._grammars.get(e)}},nr=class{_options;_syncRegistry;_ensureGrammarCache;constructor(e){this._options=e,this._syncRegistry=new Ls(Re.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,t){this._syncRegistry.setTheme(Re.createFromRawTheme(e,t))}getColorMap(){return this._syncRegistry.getColorMap()}loadGrammarWithEmbeddedLanguages(e,t,n){return this.loadGrammarWithConfiguration(e,t,{embeddedLanguages:n})}loadGrammarWithConfiguration(e,t,n){return this._loadGrammar(e,t,n.embeddedLanguages,n.tokenTypes,new Rs(n.balancedBracketSelectors||[],n.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}_loadGrammar(e,t,n,r,o){let s=new is(this._syncRegistry,e);for(;s.Q.length>0;)s.Q.map(a=>this._loadSingleGrammar(a.scopeName)),s.processQueue();return this._grammarForScopeName(e,t,n,r,o)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){let t=this._options.loadGrammar(e);if(t){let n=typeof this._options.getInjections=="function"?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,n)}}addGrammar(e,t=[],n=0,r=null){return this._syncRegistry.addGrammar(e,t),this._grammarForScopeName(e.scopeName,n,r)}_grammarForScopeName(e,t=0,n=null,r=null,o=null){return this._syncRegistry.grammarForScopeName(e,t,n,r,o)}},Ze=Bt.NULL;var rr=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","keygen","link","meta","param","source","track","wbr"];var V=class{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}};V.prototype.normal={};V.prototype.property={};V.prototype.space=void 0;function Ft(e,t){let n={},r={};for(let o of e)Object.assign(n,o.property),Object.assign(r,o.normal);return new V(n,r,t)}function $e(e){return e.toLowerCase()}var T=class{constructor(t,n){this.attribute=n,this.property=t}};T.prototype.attribute="";T.prototype.booleanish=!1;T.prototype.boolean=!1;T.prototype.commaOrSpaceSeparated=!1;T.prototype.commaSeparated=!1;T.prototype.defined=!1;T.prototype.mustUseProperty=!1;T.prototype.number=!1;T.prototype.overloadedBoolean=!1;T.prototype.property="";T.prototype.spaceSeparated=!1;T.prototype.space=void 0;var Me={};qo(Me,{boolean:()=>k,booleanish:()=>A,commaOrSpaceSeparated:()=>G,commaSeparated:()=>X,number:()=>g,overloadedBoolean:()=>et,spaceSeparated:()=>v});var Ts=0,k=ue(),A=ue(),et=ue(),g=ue(),v=ue(),X=ue(),G=ue();function ue(){return 2**++Ts}var Ut=Object.keys(Me),he=class extends T{constructor(t,n,r,o){let s=-1;if(super(t,n),or(this,"space",o),typeof r=="number")for(;++s<Ut.length;){let a=Ut[s];or(this,Ut[s],(r&Me[a])===Me[a])}}};he.prototype.defined=!0;function or(e,t,n){n&&(e[t]=n)}function U(e){let t={},n={};for(let[r,o]of Object.entries(e.properties)){let s=new he(r,e.transform(e.attributes||{},r),o,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(s.mustUseProperty=!0),t[r]=s,n[$e(r)]=r,n[$e(s.attribute)]=r}return new V(t,n,e.space)}var jt=U({properties:{ariaActiveDescendant:null,ariaAtomic:A,ariaAutoComplete:null,ariaBusy:A,ariaChecked:A,ariaColCount:g,ariaColIndex:g,ariaColSpan:g,ariaControls:v,ariaCurrent:null,ariaDescribedBy:v,ariaDetails:null,ariaDisabled:A,ariaDropEffect:v,ariaErrorMessage:null,ariaExpanded:A,ariaFlowTo:v,ariaGrabbed:A,ariaHasPopup:null,ariaHidden:A,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:v,ariaLevel:g,ariaLive:null,ariaModal:A,ariaMultiLine:A,ariaMultiSelectable:A,ariaOrientation:null,ariaOwns:v,ariaPlaceholder:null,ariaPosInSet:g,ariaPressed:A,ariaReadOnly:A,ariaRelevant:null,ariaRequired:A,ariaRoleDescription:v,ariaRowCount:g,ariaRowIndex:g,ariaRowSpan:g,ariaSelected:A,ariaSetSize:g,ariaSort:null,ariaValueMax:g,ariaValueMin:g,ariaValueNow:g,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function tt(e,t){return t in e?e[t]:t}function nt(e,t){return tt(e,t.toLowerCase())}var sr=U({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:X,acceptCharset:v,accessKey:v,action:null,allow:null,allowFullScreen:k,allowPaymentRequest:k,allowUserMedia:k,alpha:k,alt:null,as:null,async:k,autoCapitalize:null,autoComplete:v,autoFocus:k,autoPlay:k,blocking:v,capture:null,charSet:null,checked:k,cite:null,className:v,closedBy:null,colorSpace:null,cols:g,colSpan:g,command:null,commandFor:null,content:null,contentEditable:A,controls:k,controlsList:v,coords:g|X,crossOrigin:null,data:null,dateTime:null,decoding:null,default:k,defer:k,dir:null,dirName:null,disabled:k,download:et,draggable:A,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:k,formTarget:null,headers:v,height:g,hidden:et,high:g,href:null,hrefLang:null,htmlFor:v,httpEquiv:v,id:null,imageSizes:null,imageSrcSet:null,inert:k,inputMode:null,integrity:null,is:null,isMap:k,itemId:null,itemProp:v,itemRef:v,itemScope:k,itemType:v,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:k,low:g,manifest:null,max:null,maxLength:g,media:null,method:null,min:null,minLength:g,multiple:k,muted:k,name:null,nonce:null,noModule:k,noValidate:k,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:k,optimum:g,pattern:null,ping:v,placeholder:null,playsInline:k,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:k,referrerPolicy:null,rel:v,required:k,reversed:k,rows:g,rowSpan:g,sandbox:v,scope:null,scoped:k,seamless:k,selected:k,shadowRootClonable:k,shadowRootCustomElementRegistry:k,shadowRootDelegatesFocus:k,shadowRootMode:null,shadowRootSerializable:k,shape:null,size:g,sizes:null,slot:null,span:g,spellCheck:A,src:null,srcDoc:null,srcLang:null,srcSet:null,start:g,step:null,style:null,tabIndex:g,target:null,title:null,translate:null,type:null,typeMustMatch:k,useMap:null,value:A,width:g,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:v,axis:null,background:null,bgColor:null,border:g,borderColor:null,bottomMargin:g,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:k,declare:k,event:null,face:null,frame:null,frameBorder:null,hSpace:g,leftMargin:g,link:null,longDesc:null,lowSrc:null,marginHeight:g,marginWidth:g,noResize:k,noHref:k,noShade:k,noWrap:k,object:null,profile:null,prompt:null,rev:null,rightMargin:g,rules:null,scheme:null,scrolling:A,standby:null,summary:null,text:null,topMargin:g,valueType:null,version:null,vAlign:null,vLink:null,vSpace:g,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:k,disablePictureInPicture:k,disableRemotePlayback:k,exportParts:X,part:v,prefix:null,property:null,results:g,security:null,unselectable:null},space:"html",transform:nt});var ar=U({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",maskType:"mask-type",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:G,accentHeight:g,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:g,amplitude:g,arabicForm:null,ascent:g,attributeName:null,attributeType:null,azimuth:g,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:g,by:null,calcMode:null,capHeight:g,className:v,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:g,diffuseConstant:g,direction:null,display:null,dur:null,divisor:g,dominantBaseline:null,download:k,dx:null,dy:null,edgeMode:null,editable:null,elevation:g,enableBackground:null,end:null,event:null,exponent:g,externalResourcesRequired:null,fill:null,fillOpacity:g,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:X,g2:X,glyphName:X,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:g,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:g,horizOriginX:g,horizOriginY:g,id:null,ideographic:g,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:g,k:g,k1:g,k2:g,k3:g,k4:g,kernelMatrix:G,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:g,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskType:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:g,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:g,overlineThickness:g,paintOrder:null,panose1:null,path:null,pathLength:g,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:v,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:g,pointsAtY:g,pointsAtZ:g,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:G,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:G,rev:G,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:G,requiredFeatures:G,requiredFonts:G,requiredFormats:G,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:g,specularExponent:g,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:g,strikethroughThickness:g,string:null,stroke:null,strokeDashArray:G,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:g,strokeOpacity:g,strokeWidth:null,style:null,surfaceScale:g,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:G,tabIndex:g,tableValues:null,target:null,targetX:g,targetY:g,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:G,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:g,underlineThickness:g,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:g,values:null,vAlphabetic:g,vMathematical:g,vectorEffect:null,vHanging:g,vIdeographic:g,version:null,vertAdvY:g,vertOriginX:g,vertOriginY:g,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:g,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:tt});var zt=U({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}});var Wt=U({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:nt});var Ht=U({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}});var Ps=/[A-Z]/g,ir=/-[a-z]/g,$s=/^data[-\w.:]+$/i;function qt(e,t){let n=$e(t),r=t,o=T;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&$s.test(t)){if(t.charAt(4)==="-"){let s=t.slice(5).replace(ir,Os);r="data"+s.charAt(0).toUpperCase()+s.slice(1)}else{let s=t.slice(4);if(!ir.test(s)){let a=s.replace(Ps,Ms);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}o=he}return new o(r,t)}function Ms(e){return"-"+e.toLowerCase()}function Os(e){return e.charAt(1).toUpperCase()}var lr=Ft([jt,sr,zt,Wt,Ht],"html"),rt=Ft([jt,ar,zt,Wt,Ht],"svg");var cr={}.hasOwnProperty;function ur(e,t){let n=t||{};function r(o,...s){let a=r.invalid,l=r.handlers;if(o&&cr.call(o,e)){let i=String(o[e]);a=cr.call(l,i)?l[i]:r.unknown}if(a)return a.call(this,o,...s)}return r.handlers=n.handlers||{},r.invalid=n.invalid,r.unknown=n.unknown,r}var Gs=/["&'<>`]/g,Bs=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,Ds=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,Fs=/[|\\{}()[\]^$+*?.]/g,hr=new WeakMap;function pr(e,t){if(e=e.replace(t.subset?Us(t.subset):Gs,r),t.subset||t.escapeOnly)return e;return e.replace(Bs,n).replace(Ds,r);function n(o,s,a){return t.format((o.charCodeAt(0)-55296)*1024+o.charCodeAt(1)-56320+65536,a.charCodeAt(s+2),t)}function r(o,s,a){return t.format(o.charCodeAt(0),a.charCodeAt(s+1),t)}}function Us(e){let t=hr.get(e);return t||(t=js(e),hr.set(e,t)),t}function js(e){let t=[],n=-1;for(;++n<e.length;)t.push(e[n].replace(Fs,"\\$&"));return new RegExp("(?:"+t.join("|")+")","g")}var zs=/[\dA-Fa-f]/;function fr(e,t,n){let r="&#x"+e.toString(16).toUpperCase();return n&&t&&!zs.test(String.fromCharCode(t))?r:r+";"}var Ws=/\d/;function dr(e,t,n){let r="&#"+String(e);return n&&t&&!Ws.test(String.fromCharCode(t))?r:r+";"}var gr=["AElig","AMP","Aacute","Acirc","Agrave","Aring","Atilde","Auml","COPY","Ccedil","ETH","Eacute","Ecirc","Egrave","Euml","GT","Iacute","Icirc","Igrave","Iuml","LT","Ntilde","Oacute","Ocirc","Ograve","Oslash","Otilde","Ouml","QUOT","REG","THORN","Uacute","Ucirc","Ugrave","Uuml","Yacute","aacute","acirc","acute","aelig","agrave","amp","aring","atilde","auml","brvbar","ccedil","cedil","cent","copy","curren","deg","divide","eacute","ecirc","egrave","eth","euml","frac12","frac14","frac34","gt","iacute","icirc","iexcl","igrave","iquest","iuml","laquo","lt","macr","micro","middot","nbsp","not","ntilde","oacute","ocirc","ograve","ordf","ordm","oslash","otilde","ouml","para","plusmn","pound","quot","raquo","reg","sect","shy","sup1","sup2","sup3","szlig","thorn","times","uacute","ucirc","ugrave","uml","uuml","yacute","yen","yuml"];var ot={nbsp:"\xA0",iexcl:"\xA1",cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",frac34:"\xBE",iquest:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acirc:"\xC2",Atilde:"\xC3",Auml:"\xC4",Aring:"\xC5",AElig:"\xC6",Ccedil:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecirc:"\xCA",Euml:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icirc:"\xCE",Iuml:"\xCF",ETH:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocirc:"\xD4",Otilde:"\xD5",Ouml:"\xD6",times:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucirc:"\xDB",Uuml:"\xDC",Yacute:"\xDD",THORN:"\xDE",szlig:"\xDF",agrave:"\xE0",aacute:"\xE1",acirc:"\xE2",atilde:"\xE3",auml:"\xE4",aring:"\xE5",aelig:"\xE6",ccedil:"\xE7",egrave:"\xE8",eacute:"\xE9",ecirc:"\xEA",euml:"\xEB",igrave:"\xEC",iacute:"\xED",icirc:"\xEE",iuml:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocirc:"\xF4",otilde:"\xF5",ouml:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucirc:"\xFB",uuml:"\xFC",yacute:"\xFD",thorn:"\xFE",yuml:"\xFF",fnof:"\u0192",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039A",Lambda:"\u039B",Mu:"\u039C",Nu:"\u039D",Xi:"\u039E",Omicron:"\u039F",Pi:"\u03A0",Rho:"\u03A1",Sigma:"\u03A3",Tau:"\u03A4",Upsilon:"\u03A5",Phi:"\u03A6",Chi:"\u03A7",Psi:"\u03A8",Omega:"\u03A9",alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",rho:"\u03C1",sigmaf:"\u03C2",sigma:"\u03C3",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",thetasym:"\u03D1",upsih:"\u03D2",piv:"\u03D6",bull:"\u2022",hellip:"\u2026",prime:"\u2032",Prime:"\u2033",oline:"\u203E",frasl:"\u2044",weierp:"\u2118",image:"\u2111",real:"\u211C",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21B5",lArr:"\u21D0",uArr:"\u21D1",rArr:"\u21D2",dArr:"\u21D3",hArr:"\u21D4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220B",prod:"\u220F",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221A",prop:"\u221D",infin:"\u221E",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222A",int:"\u222B",there4:"\u2234",sim:"\u223C",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22A5",sdot:"\u22C5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230A",rfloor:"\u230B",lang:"\u2329",rang:"\u232A",loz:"\u25CA",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666",quot:'"',amp:"&",lt:"<",gt:">",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",circ:"\u02C6",tilde:"\u02DC",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",permil:"\u2030",lsaquo:"\u2039",rsaquo:"\u203A",euro:"\u20AC"};var mr=["cent","copy","divide","gt","lt","not","para","times"];var yr={}.hasOwnProperty,Vt={},st;for(st in ot)yr.call(ot,st)&&(Vt[ot[st]]=st);var Hs=/[^\dA-Za-z]/;function br(e,t,n,r){let o=String.fromCharCode(e);if(yr.call(Vt,o)){let s=Vt[o],a="&"+s;return n&&gr.includes(s)&&!mr.includes(s)&&(!r||t&&t!==61&&Hs.test(String.fromCharCode(t)))?a:a+";"}return""}function wr(e,t,n){let r=fr(e,t,n.omitOptionalSemicolons),o;if((n.useNamedReferences||n.useShortestReferences)&&(o=br(e,t,n.omitOptionalSemicolons,n.attribute)),(n.useShortestReferences||!o)&&n.useShortestReferences){let s=dr(e,t,n.omitOptionalSemicolons);s.length<r.length&&(r=s)}return o&&(!n.useShortestReferences||o.length<r.length)?o:r}function K(e,t){return pr(e,Object.assign({format:wr},t))}var qs=/^>|^->|<!--|-->|--!>|<!-$/g,Vs=[">"],Xs=["<",">"];function Cr(e,t,n,r){return r.settings.bogusComments?"<?"+K(e.value,Object.assign({},r.settings.characterReferences,{subset:Vs}))+">":"<!--"+e.value.replace(qs,o)+"-->";function o(s){return K(s,Object.assign({},r.settings.characterReferences,{subset:Xs}))}}function _r(e,t,n,r){return"<!"+(r.settings.upperDoctype?"DOCTYPE":"doctype")+(r.settings.tightDoctype?"":" ")+"html>"}function Xt(e,t){let n=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,o=n.indexOf(t);for(;o!==-1;)r++,o=n.indexOf(t,o+t.length);return r}function kr(e,t){let n=t||{};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}function Sr(e){return e.join(" ").trim()}var Ks=/[ \t\n\f\r]/g;function pe(e){return typeof e=="object"?e.type==="text"?xr(e.value):!1:xr(e)}function xr(e){return e.replace(Ks,"")===""}var I=vr(1),Kt=vr(-1),Qs=[];function vr(e){return t;function t(n,r,o){let s=n?n.children:Qs,a=(r||0)+e,l=s[a];if(!o)for(;l&&pe(l);)a+=e,l=s[a];return l}}var Js={}.hasOwnProperty;function at(e){return t;function t(n,r,o){return Js.call(e,n.tagName)&&e[n.tagName](n,r,o)}}var Oe=at({body:Zs,caption:Qt,colgroup:Qt,dd:ra,dt:na,head:Qt,html:Ys,li:ta,optgroup:oa,option:sa,p:ea,rp:Ar,rt:Ar,tbody:ia,td:Er,tfoot:la,th:Er,thead:aa,tr:ca});function Qt(e,t,n){let r=I(n,t,!0);return!r||r.type!=="comment"&&!(r.type==="text"&&pe(r.value.charAt(0)))}function Ys(e,t,n){let r=I(n,t);return!r||r.type!=="comment"}function Zs(e,t,n){let r=I(n,t);return!r||r.type!=="comment"}function ea(e,t,n){let r=I(n,t);return r?r.type==="element"&&(r.tagName==="address"||r.tagName==="article"||r.tagName==="aside"||r.tagName==="blockquote"||r.tagName==="details"||r.tagName==="div"||r.tagName==="dl"||r.tagName==="fieldset"||r.tagName==="figcaption"||r.tagName==="figure"||r.tagName==="footer"||r.tagName==="form"||r.tagName==="h1"||r.tagName==="h2"||r.tagName==="h3"||r.tagName==="h4"||r.tagName==="h5"||r.tagName==="h6"||r.tagName==="header"||r.tagName==="hgroup"||r.tagName==="hr"||r.tagName==="main"||r.tagName==="menu"||r.tagName==="nav"||r.tagName==="ol"||r.tagName==="p"||r.tagName==="pre"||r.tagName==="section"||r.tagName==="table"||r.tagName==="ul"):!n||!(n.type==="element"&&(n.tagName==="a"||n.tagName==="audio"||n.tagName==="del"||n.tagName==="ins"||n.tagName==="map"||n.tagName==="noscript"||n.tagName==="video"))}function ta(e,t,n){let r=I(n,t);return!r||r.type==="element"&&r.tagName==="li"}function na(e,t,n){let r=I(n,t);return!!(r&&r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd"))}function ra(e,t,n){let r=I(n,t);return!r||r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd")}function Ar(e,t,n){let r=I(n,t);return!r||r.type==="element"&&(r.tagName==="rp"||r.tagName==="rt")}function oa(e,t,n){let r=I(n,t);return!r||r.type==="element"&&r.tagName==="optgroup"}function sa(e,t,n){let r=I(n,t);return!r||r.type==="element"&&(r.tagName==="option"||r.tagName==="optgroup")}function aa(e,t,n){let r=I(n,t);return!!(r&&r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot"))}function ia(e,t,n){let r=I(n,t);return!r||r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot")}function la(e,t,n){return!I(n,t)}function ca(e,t,n){let r=I(n,t);return!r||r.type==="element"&&r.tagName==="tr"}function Er(e,t,n){let r=I(n,t);return!r||r.type==="element"&&(r.tagName==="td"||r.tagName==="th")}var Ir=at({body:pa,colgroup:fa,head:ha,html:ua,tbody:da});function ua(e){let t=I(e,-1);return!t||t.type!=="comment"}function ha(e){let t=new Set;for(let r of e.children)if(r.type==="element"&&(r.tagName==="base"||r.tagName==="title")){if(t.has(r.tagName))return!1;t.add(r.tagName)}let n=e.children[0];return!n||n.type==="element"}function pa(e){let t=I(e,-1,!0);return!t||t.type!=="comment"&&!(t.type==="text"&&pe(t.value.charAt(0)))&&!(t.type==="element"&&(t.tagName==="meta"||t.tagName==="link"||t.tagName==="script"||t.tagName==="style"||t.tagName==="template"))}function fa(e,t,n){let r=Kt(n,t),o=I(e,-1,!0);return n&&r&&r.type==="element"&&r.tagName==="colgroup"&&Oe(r,n.children.indexOf(r),n)?!1:!!(o&&o.type==="element"&&o.tagName==="col")}function da(e,t,n){let r=Kt(n,t),o=I(e,-1);return n&&r&&r.type==="element"&&(r.tagName==="thead"||r.tagName==="tbody")&&Oe(r,n.children.indexOf(r),n)?!1:!!(o&&o.type==="element"&&o.tagName==="tr")}var it={name:[[`	
4\f\r &/=>`.split(""),`	
5\f\r "&'/=>\``.split("")],[`\0	
6\f\r "&'/<=>`.split(""),`\0	
7\f\r "&'/<=>\``.split("")]],unquoted:[[`	
8\f\r &>`.split(""),`\0	
9\f\r "&'<=>\``.split("")],[`\0	
10\f\r "&'<=>\``.split(""),`\0	
11\f\r "&'<=>\``.split("")]],single:[["&'".split(""),"\"&'`".split("")],["\0&'".split(""),"\0\"&'`".split("")]],double:[['"&'.split(""),"\"&'`".split("")],['\0"&'.split(""),"\0\"&'`".split("")]]};function Rr(e,t,n,r){let o=r.schema,s=o.space==="svg"?!1:r.settings.omitOptionalTags,a=o.space==="svg"?r.settings.closeEmptyElements:r.settings.voids.includes(e.tagName.toLowerCase()),l=[],i;o.space==="html"&&e.tagName==="svg"&&(r.schema=rt);let c=ga(r,e.properties),u=r.all(o.space==="html"&&e.tagName==="template"?e.content:e);return r.schema=o,u&&(a=!1),(c||!s||!Ir(e,t,n))&&(l.push("<",e.tagName,c?" "+c:""),a&&(o.space==="svg"||r.settings.closeSelfClosing)&&(i=c.charAt(c.length-1),(!r.settings.tightSelfClosing||i==="/"||i&&i!=='"'&&i!=="'")&&l.push(" "),l.push("/")),l.push(">")),l.push(u),!a&&(!s||!Oe(e,t,n))&&l.push("</"+e.tagName+">"),l.join("")}function ga(e,t){let n=[],r=-1,o;if(t){for(o in t)if(t[o]!==null&&t[o]!==void 0){let s=ma(e,o,t[o]);s&&n.push(s)}}for(;++r<n.length;){let s=e.settings.tightAttributes?n[r].charAt(n[r].length-1):void 0;r!==n.length-1&&s!=='"'&&s!=="'"&&(n[r]+=" ")}return n.join("")}function ma(e,t,n){let r=qt(e.schema,t),o=e.settings.allowParseErrors&&e.schema.space==="html"?0:1,s=e.settings.allowDangerousCharacters?0:1,a=e.quote,l;if(r.overloadedBoolean&&(n===r.attribute||n==="")?n=!0:(r.boolean||r.overloadedBoolean)&&(typeof n!="string"||n===r.attribute||n==="")&&(n=!!n),n==null||n===!1||typeof n=="number"&&Number.isNaN(n))return"";let i=K(r.attribute,Object.assign({},e.settings.characterReferences,{subset:it.name[o][s]}));return n===!0||(n=Array.isArray(n)?(r.commaSeparated?kr:Sr)(n,{padLeft:!e.settings.tightCommaSeparatedLists}):String(n),e.settings.collapseEmptyAttributes&&!n)?i:(e.settings.preferUnquoted&&(l=K(n,Object.assign({},e.settings.characterReferences,{attribute:!0,subset:it.unquoted[o][s]}))),l!==n&&(e.settings.quoteSmart&&Xt(n,a)>Xt(n,e.alternative)&&(a=e.alternative),l=a+K(n,Object.assign({},e.settings.characterReferences,{subset:(a==="'"?it.single:it.double)[o][s],attribute:!0}))+a),i+(l&&"="+l))}var ya=["<","&"];function lt(e,t,n,r){return n&&n.type==="element"&&(n.tagName==="script"||n.tagName==="style")?e.value:K(e.value,Object.assign({},r.settings.characterReferences,{subset:ya}))}function Nr(e,t,n,r){return r.settings.allowDangerousHtml?e.value:lt(e,t,n,r)}function Lr(e,t,n,r){return r.all(e)}var Tr=ur("type",{invalid:ba,unknown:wa,handlers:{comment:Cr,doctype:_r,element:Rr,raw:Nr,root:Lr,text:lt}});function ba(e){throw new Error("Expected node, not `"+e+"`")}function wa(e){let t=e;throw new Error("Cannot compile unknown node `"+t.type+"`")}var Ca={},_a={},ka=[];function Jt(e,t){let n=t||Ca,r=n.quote||'"',o=r==='"'?"'":'"';if(r!=='"'&&r!=="'")throw new Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:Sa,all:xa,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||rr,characterReferences:n.characterReferences||_a,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space==="svg"?rt:lr,quote:r,alternative:o}.one(Array.isArray(e)?{type:"root",children:e}:e,void 0,void 0)}function Sa(e,t,n){return Tr(e,t,n,this)}function xa(e){let t=[],n=e&&e.children||ka,r=-1;for(;++r<n.length;)t[r]=this.one(n[r],r,e);return t.join("")}function ct(e,t){let n=typeof e=="string"?{}:{...e.colorReplacements},r=typeof e=="string"?e:e.name;for(let[o,s]of Object.entries(t?.colorReplacements||{}))typeof s=="string"?n[o]=s:o===r&&Object.assign(n,s);return n}function re(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function va(e){return Array.isArray(e)?e:[e]}async function Dr(e){return Promise.resolve(typeof e=="function"?e():e).then(t=>t.default||t)}function nn(e){return!e||["plaintext","txt","text","plain"].includes(e)}function Aa(e){return e==="ansi"||nn(e)}function rn(e){return e==="none"}function Ea(e){return rn(e)}function Fr(e,t){if(!t)return e;e.properties||={},e.properties.class||=[],typeof e.properties.class=="string"&&(e.properties.class=e.properties.class.split(/\s+/g)),Array.isArray(e.properties.class)||(e.properties.class=[]);let n=Array.isArray(t)?t:t.split(/\s+/g);for(let r of n)r&&!e.properties.class.includes(r)&&e.properties.class.push(r);return e}function dt(e,t=!1){if(e.length===0)return[["",0]];let n=e.split(/(\r?\n)/g),r=0,o=[];for(let s=0;s<n.length;s+=2){let a=t?n[s]+(n[s+1]||""):n[s];o.push([a,r]),r+=n[s].length,r+=n[s+1]?.length||0}return o}function Ia(e){let t=dt(e,!0).map(([o])=>o);function n(o){if(o===e.length)return{line:t.length-1,character:t[t.length-1].length};let s=o,a=0;for(let l of t){if(s<l.length)break;s-=l.length,a++}return{line:a,character:s}}function r(o,s){let a=0;for(let l=0;l<o;l++)a+=t[l].length;return a+=s,a}return{lines:t,indexToPos:n,posToIndex:r}}var on="light-dark()",Ra=["color","background-color"];function Na(e,t){let n=0,r=[];for(let o of t)o>n&&r.push({...e,content:e.content.slice(n,o),offset:e.offset+n}),n=o;return n<e.content.length&&r.push({...e,content:e.content.slice(n),offset:e.offset+n}),r}function La(e,t){let n=Array.from(t instanceof Set?t:new Set(t)).sort((r,o)=>r-o);return n.length?e.map(r=>r.flatMap(o=>{let s=n.filter(a=>o.offset<a&&a<o.offset+o.content.length).map(a=>a-o.offset).sort((a,l)=>a-l);return s.length?Na(o,s):o})):e}function Ta(e,t,n,r,o="css-vars"){let s={content:e.content,explanation:e.explanation,offset:e.offset},a=t.map(u=>ut(e.variants[u])),l=new Set(a.flatMap(u=>Object.keys(u))),i={},c=(u,h)=>{let p=h==="color"?"":h==="background-color"?"-bg":`-${h}`;return n+t[u]+(h==="color"?"":p)};return a.forEach((u,h)=>{for(let p of l){let d=u[p]||"inherit";if(h===0&&r&&Ra.includes(p))if(r===on&&a.length>1){let f=t.findIndex(C=>C==="light"),b=t.findIndex(C=>C==="dark");if(f===-1||b===-1)throw new E('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');let w=a[f][p]||"inherit",m=a[b][p]||"inherit";i[p]=`light-dark(${w}, ${m})`,o==="css-vars"&&(i[c(h,p)]=d)}else i[p]=d;else o==="css-vars"&&(i[c(h,p)]=d)}}),s.htmlStyle=i,s}function ut(e){let t={};if(e.color&&(t.color=e.color),e.bgColor&&(t["background-color"]=e.bgColor),e.fontStyle){e.fontStyle&P.Italic&&(t["font-style"]="italic"),e.fontStyle&P.Bold&&(t["font-weight"]="bold");let n=[];e.fontStyle&P.Underline&&n.push("underline"),e.fontStyle&P.Strikethrough&&n.push("line-through"),n.length&&(t["text-decoration"]=n.join(" "))}return t}function Zt(e){return typeof e=="string"?e:Object.entries(e).map(([t,n])=>`${t}:${n}`).join(";")}var Ur=new WeakMap;function gt(e,t){Ur.set(e,t)}function Be(e){return Ur.get(e)}var we=class e{_stacks={};lang;get themes(){return Object.keys(this._stacks)}get theme(){return this.themes[0]}get _stack(){return this._stacks[this.theme]}static initial(t,n){return new e(Object.fromEntries(va(n).map(r=>[r,Ze])),t)}constructor(...t){if(t.length===2){let[n,r]=t;this.lang=r,this._stacks=n}else{let[n,r,o]=t;this.lang=r,this._stacks={[o]:n}}}getInternalStack(t=this.theme){return this._stacks[t]}getScopes(t=this.theme){return Pa(this._stacks[t])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function Pa(e){let t=[],n=new Set;function r(o){if(n.has(o))return;n.add(o);let s=o?.nameScopesList?.scopeName;s&&t.push(s),o.parent&&r(o.parent)}return r(e),t}function $a(e,t){if(!(e instanceof we))throw new E("Invalid grammar state");return e.getInternalStack(t)}function Ma(){let e=new WeakMap;function t(n){if(!e.has(n.meta)){let r=function(a){if(typeof a=="number"){if(a<0||a>n.source.length)throw new E(`Invalid decoration offset: ${a}. Code length: ${n.source.length}`);return{...o.indexToPos(a),offset:a}}else{let l=o.lines[a.line];if(l===void 0)throw new E(`Invalid decoration position ${JSON.stringify(a)}. Lines length: ${o.lines.length}`);let i=a.character;if(i<0&&(i=l.length+i),i<0||i>l.length)throw new E(`Invalid decoration position ${JSON.stringify(a)}. Line ${a.line} length: ${l.length}`);return{...a,character:i,offset:o.posToIndex(a.line,i)}}},o=Ia(n.source),s=(n.options.decorations||[]).map(a=>({...a,start:r(a.start),end:r(a.end)}));Oa(s),e.set(n.meta,{decorations:s,converter:o,source:n.source})}return e.get(n.meta)}return{name:"shiki:decorations",tokens(n){if(!this.options.decorations?.length)return;let o=t(this).decorations.flatMap(a=>[a.start.offset,a.end.offset]);return La(n,o)},code(n){if(!this.options.decorations?.length)return;let r=t(this),o=Array.from(n.children).filter(u=>u.type==="element"&&u.tagName==="span");if(o.length!==r.converter.lines.length)throw new E(`Number of lines in code element (${o.length}) does not match the number of lines in the source (${r.converter.lines.length}). Failed to apply decorations.`);function s(u,h,p,d){let f=o[u],b="",w=-1,m=-1;if(h===0&&(w=0),p===0&&(m=0),p===Number.POSITIVE_INFINITY&&(m=f.children.length),w===-1||m===-1)for(let y=0;y<f.children.length;y++)b+=jr(f.children[y]),w===-1&&b.length===h&&(w=y+1),m===-1&&b.length===p&&(m=y+1);if(w===-1)throw new E(`Failed to find start index for decoration ${JSON.stringify(d.start)}`);if(m===-1)throw new E(`Failed to find end index for decoration ${JSON.stringify(d.end)}`);let C=f.children.slice(w,m);if(!d.alwaysWrap&&C.length===f.children.length)l(f,d,"line");else if(!d.alwaysWrap&&C.length===1&&C[0].type==="element")l(C[0],d,"token");else{let y={type:"element",tagName:"span",properties:{},children:C};l(y,d,"wrapper"),f.children.splice(w,C.length,y)}}function a(u,h){o[u]=l(o[u],h,"line")}function l(u,h,p){let d=h.properties||{},f=h.transform||(b=>b);return u.tagName=h.tagName||"span",u.properties={...u.properties,...d,class:u.properties.class},h.properties?.class&&Fr(u,h.properties.class),u=f(u,p)||u,u}let i=[],c=r.decorations.sort((u,h)=>h.start.offset-u.start.offset||u.end.offset-h.end.offset);for(let u of c){let{start:h,end:p}=u;if(h.line===p.line)s(h.line,h.character,p.character,u);else if(h.line<p.line){s(h.line,h.character,Number.POSITIVE_INFINITY,u);for(let d=h.line+1;d<p.line;d++)i.unshift(()=>a(d,u));s(p.line,0,p.character,u)}}i.forEach(u=>u())}}}function Oa(e){for(let t=0;t<e.length;t++){let n=e[t];if(n.start.offset>n.end.offset)throw new E(`Invalid decoration range: ${JSON.stringify(n.start)} - ${JSON.stringify(n.end)}`);for(let r=t+1;r<e.length;r++){let o=e[r],s=n.start.offset<=o.start.offset&&o.start.offset<n.end.offset,a=n.start.offset<o.end.offset&&o.end.offset<=n.end.offset,l=o.start.offset<=n.start.offset&&n.start.offset<o.end.offset,i=o.start.offset<n.end.offset&&n.end.offset<=o.end.offset;if(s||a||l||i){if(s&&a||l&&i||l&&n.start.offset===n.end.offset||a&&o.start.offset===o.end.offset)continue;throw new E(`Decorations ${JSON.stringify(n.start)} and ${JSON.stringify(o.start)} intersect.`)}}}}function jr(e){return e.type==="text"?e.value:e.type==="element"?e.children.map(jr).join(""):""}var Ga=[Ma()];function ht(e){let t=Ba(e.transformers||[]);return[...t.pre,...t.normal,...t.post,...Ga]}function Ba(e){let t=[],n=[],r=[];for(let o of e)switch(o.enforce){case"pre":t.push(o);break;case"post":n.push(o);break;default:r.push(o)}return{pre:t,post:n,normal:r}}var fe=["black","red","green","yellow","blue","magenta","cyan","white","brightBlack","brightRed","brightGreen","brightYellow","brightBlue","brightMagenta","brightCyan","brightWhite"],Yt={1:"bold",2:"dim",3:"italic",4:"underline",7:"reverse",8:"hidden",9:"strikethrough"};function Da(e,t){let n=e.indexOf("\x1B",t);if(n!==-1&&e[n+1]==="["){let r=e.indexOf("m",n);if(r!==-1)return{sequence:e.substring(n+2,r).split(";"),startPosition:n,position:r+1}}return{position:e.length}}function Pr(e){let t=e.shift();if(t==="2"){let n=e.splice(0,3).map(r=>Number.parseInt(r));return n.length!==3||n.some(r=>Number.isNaN(r))?void 0:{type:"rgb",rgb:n}}else if(t==="5"){let n=e.shift();if(n)return{type:"table",index:Number(n)}}}function Fa(e){let t=[];for(;e.length>0;){let n=e.shift();if(!n)continue;let r=Number.parseInt(n);if(!Number.isNaN(r))if(r===0)t.push({type:"resetAll"});else if(r<=9)Yt[r]&&t.push({type:"setDecoration",value:Yt[r]});else if(r<=29){let o=Yt[r-20];o&&(t.push({type:"resetDecoration",value:o}),o==="dim"&&t.push({type:"resetDecoration",value:"bold"}))}else if(r<=37)t.push({type:"setForegroundColor",value:{type:"named",name:fe[r-30]}});else if(r===38){let o=Pr(e);o&&t.push({type:"setForegroundColor",value:o})}else if(r===39)t.push({type:"resetForegroundColor"});else if(r<=47)t.push({type:"setBackgroundColor",value:{type:"named",name:fe[r-40]}});else if(r===48){let o=Pr(e);o&&t.push({type:"setBackgroundColor",value:o})}else r===49?t.push({type:"resetBackgroundColor"}):r===53?t.push({type:"setDecoration",value:"overline"}):r===55?t.push({type:"resetDecoration",value:"overline"}):r>=90&&r<=97?t.push({type:"setForegroundColor",value:{type:"named",name:fe[r-90+8]}}):r>=100&&r<=107&&t.push({type:"setBackgroundColor",value:{type:"named",name:fe[r-100+8]}})}return t}function Ua(){let e=null,t=null,n=new Set;return{parse(r){let o=[],s=0;do{let a=Da(r,s),l=a.sequence?r.substring(s,a.startPosition):r.substring(s);if(l.length>0&&o.push({value:l,foreground:e,background:t,decorations:new Set(n)}),a.sequence){let i=Fa(a.sequence);for(let c of i)c.type==="resetAll"?(e=null,t=null,n.clear()):c.type==="resetForegroundColor"?e=null:c.type==="resetBackgroundColor"?t=null:c.type==="resetDecoration"&&n.delete(c.value);for(let c of i)c.type==="setForegroundColor"?e=c.value:c.type==="setBackgroundColor"?t=c.value:c.type==="setDecoration"&&n.add(c.value)}s=a.position}while(s<r.length);return o}}}var ja={black:"#000000",red:"#bb0000",green:"#00bb00",yellow:"#bbbb00",blue:"#0000bb",magenta:"#ff00ff",cyan:"#00bbbb",white:"#eeeeee",brightBlack:"#555555",brightRed:"#ff5555",brightGreen:"#00ff00",brightYellow:"#ffff55",brightBlue:"#5555ff",brightMagenta:"#ff55ff",brightCyan:"#55ffff",brightWhite:"#ffffff"};function za(e=ja){function t(l){return e[l]}function n(l){return`#${l.map(i=>Math.max(0,Math.min(i,255)).toString(16).padStart(2,"0")).join("")}`}let r;function o(){if(r)return r;r=[];for(let c=0;c<fe.length;c++)r.push(t(fe[c]));let l=[0,95,135,175,215,255];for(let c=0;c<6;c++)for(let u=0;u<6;u++)for(let h=0;h<6;h++)r.push(n([l[c],l[u],l[h]]));let i=8;for(let c=0;c<24;c++,i+=10)r.push(n([i,i,i]));return r}function s(l){return o()[l]}function a(l){switch(l.type){case"named":return t(l.name);case"rgb":return n(l.rgb);case"table":return s(l.index)}}return{value:a}}var Wa={black:"#000000",red:"#cd3131",green:"#0DBC79",yellow:"#E5E510",blue:"#2472C8",magenta:"#BC3FBC",cyan:"#11A8CD",white:"#E5E5E5",brightBlack:"#666666",brightRed:"#F14C4C",brightGreen:"#23D18B",brightYellow:"#F5F543",brightBlue:"#3B8EEA",brightMagenta:"#D670D6",brightCyan:"#29B8DB",brightWhite:"#FFFFFF"};function Ha(e,t,n){let r=ct(e,n),o=dt(t),s=Object.fromEntries(fe.map(i=>{let c=`terminal.ansi${i[0].toUpperCase()}${i.substring(1)}`,u=e.colors?.[c];return[i,u||Wa[i]]})),a=za(s),l=Ua();return o.map(i=>l.parse(i[0]).map(c=>{let u,h;c.decorations.has("reverse")?(u=c.background?a.value(c.background):e.bg,h=c.foreground?a.value(c.foreground):e.fg):(u=c.foreground?a.value(c.foreground):e.fg,h=c.background?a.value(c.background):void 0),u=re(u,r),h=re(h,r),c.decorations.has("dim")&&(u=qa(u));let p=P.None;return c.decorations.has("bold")&&(p|=P.Bold),c.decorations.has("italic")&&(p|=P.Italic),c.decorations.has("underline")&&(p|=P.Underline),c.decorations.has("strikethrough")&&(p|=P.Strikethrough),{content:c.value,offset:i[1],color:u,bgColor:h,fontStyle:p}}))}function qa(e){let t=e.match(/#([0-9a-f]{3,8})/i);if(t){let r=t[1];if(r.length===8){let o=Math.round(Number.parseInt(r.slice(6,8),16)/2).toString(16).padStart(2,"0");return`#${r.slice(0,6)}${o}`}else{if(r.length===6)return`#${r}80`;if(r.length===4){let o=r[0],s=r[1],a=r[2],l=r[3],i=Math.round(Number.parseInt(`${l}${l}`,16)/2).toString(16).padStart(2,"0");return`#${o}${o}${s}${s}${a}${a}${i}`}else if(r.length===3){let o=r[0],s=r[1],a=r[2];return`#${o}${o}${s}${s}${a}${a}80`}}}let n=e.match(/var\((--[\w-]+-ansi-[\w-]+)\)/);return n?`var(${n[1]}-dim)`:e}function sn(e,t,n={}){let{theme:r=e.getLoadedThemes()[0]}=n,o=e.resolveLangAlias(n.lang||"text");if(nn(o)||rn(r))return dt(t).map(i=>[{content:i[0],offset:i[1]}]);let{theme:s,colorMap:a}=e.setTheme(r);if(o==="ansi")return Ha(s,t,n);let l=e.getLanguage(n.lang||"text");if(n.grammarState){if(n.grammarState.lang!==l.name)throw new E(`Grammar state language "${n.grammarState.lang}" does not match highlight language "${l.name}"`);if(!n.grammarState.themes.includes(s.name))throw new E(`Grammar state themes "${n.grammarState.themes}" do not contain highlight theme "${s.name}"`)}return Xa(t,l,s,a,n)}function Va(...e){if(e.length===2)return Be(e[1]);let[t,n,r={}]=e,{lang:o="text",theme:s=t.getLoadedThemes()[0]}=r;if(nn(o)||rn(s))throw new E("Plain language does not have grammar state");if(o==="ansi")throw new E("ANSI language does not have grammar state");let{theme:a,colorMap:l}=t.setTheme(s),i=t.getLanguage(o);return new we(an(n,i,a,l,r).stateStack,i.name,a.name)}function Xa(e,t,n,r,o){let s=an(e,t,n,r,o),a=new we(s.stateStack,t.name,n.name);return gt(s.tokens,a),s.tokens}function an(e,t,n,r,o){let s=ct(n,o),{tokenizeMaxLineLength:a=0,tokenizeTimeLimit:l=500}=o,i=dt(e),c=o.grammarState?$a(o.grammarState,n.name)??Ze:o.grammarContextCode!=null?an(o.grammarContextCode,t,n,r,{...o,grammarState:void 0,grammarContextCode:void 0}).stateStack:Ze,u=[],h=[];for(let p=0,d=i.length;p<d;p++){let[f,b]=i[p];if(f===""){u=[],h.push([]);continue}if(a>0&&f.length>=a){u=[],h.push([{content:f,offset:b,color:"",fontStyle:0}]);continue}let w,m,C;o.includeExplanation&&(w=t.tokenizeLine(f,c,l),m=w.tokens,C=0);let y=t.tokenizeLine2(f,c,l),_=y.tokens.length/2;for(let x=0;x<_;x++){let M=y.tokens[2*x],O=x+1<_?y.tokens[2*x+2]:f.length;if(M===O)continue;let H=y.tokens[2*x+1],He=re(r[ce.getForeground(H)],s),It=ce.getFontStyle(H),Ae={content:f.substring(M,O),offset:b+M,color:He,fontStyle:It};if(o.includeExplanation){let te=[];if(o.includeExplanation!=="scopeName")for(let q of n.settings){let be;switch(typeof q.scope){case"string":be=q.scope.split(/,/).map(Rt=>Rt.trim());break;case"object":be=q.scope;break;default:continue}te.push({settings:q,selectors:be.map(Rt=>Rt.split(/ /))})}Ae.explanation=[];let Nn=0;for(;M+Nn<O;){let q=m[C],be=f.substring(q.startIndex,q.endIndex);Nn+=be.length,Ae.explanation.push({content:be,scopes:o.includeExplanation==="scopeName"?Ka(q.scopes):Qa(te,q.scopes)}),C+=1}}u.push(Ae)}h.push(u),u=[],c=y.ruleStack}return{tokens:h,stateStack:c}}function Ka(e){return e.map(t=>({scopeName:t}))}function Qa(e,t){let n=[];for(let r=0,o=t.length;r<o;r++){let s=t[r];n[r]={scopeName:s,themeMatches:Ya(e,s,t.slice(0,r))}}return n}function $r(e,t){return e===t||t.substring(0,e.length)===e&&t[e.length]==="."}function Ja(e,t,n){if(!$r(e[e.length-1],t))return!1;let r=e.length-2,o=n.length-1;for(;r>=0&&o>=0;)$r(e[r],n[o])&&(r-=1),o-=1;return r===-1}function Ya(e,t,n){let r=[];for(let{selectors:o,settings:s}of e)for(let a of o)if(Ja(a,t,n)){r.push(s);break}return r}function zr(e,t,n){let r=Object.entries(n.themes).filter(i=>i[1]).map(i=>({color:i[0],theme:i[1]})),o=r.map(i=>{let c=sn(e,t,{...n,theme:i.theme}),u=Be(c),h=typeof i.theme=="string"?i.theme:i.theme.name;return{tokens:c,state:u,theme:h}}),s=Za(...o.map(i=>i.tokens)),a=s[0].map((i,c)=>i.map((u,h)=>{let p={content:u.content,variants:{},offset:u.offset};return"includeExplanation"in n&&n.includeExplanation&&(p.explanation=u.explanation),s.forEach((d,f)=>{let{content:b,explanation:w,offset:m,...C}=d[c][h];p.variants[r[f].color]=C}),p})),l=o[0].state?new we(Object.fromEntries(o.map(i=>[i.theme,i.state?.getInternalStack(i.theme)])),o[0].state.lang):void 0;return l&&gt(a,l),a}function Za(...e){let t=e.map(()=>[]),n=e.length;for(let r=0;r<e[0].length;r++){let o=e.map(i=>i[r]),s=t.map(()=>[]);t.forEach((i,c)=>i.push(s[c]));let a=o.map(()=>0),l=o.map(i=>i[0]);for(;l.every(i=>i);){let i=Math.min(...l.map(c=>c.content.length));for(let c=0;c<n;c++){let u=l[c];u.content.length===i?(s[c].push(u),a[c]+=1,l[c]=o[c][a[c]]):(s[c].push({...u,content:u.content.slice(0,i)}),l[c]={...u,content:u.content.slice(i),offset:u.offset+i})}}}return t}function pt(e,t,n){let r,o,s,a,l,i;if("themes"in n){let{defaultColor:c="light",cssVariablePrefix:u="--shiki-",colorsRendering:h="css-vars"}=n,p=Object.entries(n.themes).filter(m=>m[1]).map(m=>({color:m[0],theme:m[1]})).sort((m,C)=>m.color===c?-1:C.color===c?1:0);if(p.length===0)throw new E("`themes` option must not be empty");let d=zr(e,t,n);if(i=Be(d),c&&on!==c&&!p.find(m=>m.color===c))throw new E(`\`themes\` option must contain the defaultColor key \`${c}\``);let f=p.map(m=>e.getTheme(m.theme)),b=p.map(m=>m.color);s=d.map(m=>m.map(C=>Ta(C,b,u,c,h))),i&&gt(s,i);let w=p.map(m=>ct(m.theme,n));o=Mr(p,f,w,u,c,"fg",h),r=Mr(p,f,w,u,c,"bg",h),a=`shiki-themes ${f.map(m=>m.name).join(" ")}`,l=c?void 0:[o,r].join(";")}else if("theme"in n){let c=ct(n.theme,n);s=sn(e,t,n);let u=e.getTheme(n.theme);r=re(u.bg,c),o=re(u.fg,c),a=u.name,i=Be(s)}else throw new E("Invalid options, either `theme` or `themes` must be provided");return{tokens:s,fg:o,bg:r,themeName:a,rootStyle:l,grammarState:i}}function Mr(e,t,n,r,o,s,a){return e.map((l,i)=>{let c=re(t[i][s],n[i])||"inherit",u=`${r+l.color}${s==="bg"?"-bg":""}:${c}`;if(i===0&&o){if(o===on&&e.length>1){let h=e.findIndex(b=>b.color==="light"),p=e.findIndex(b=>b.color==="dark");if(h===-1||p===-1)throw new E('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');let d=re(t[h][s],n[h])||"inherit",f=re(t[p][s],n[p])||"inherit";return`light-dark(${d}, ${f});${u}`}return c}return a==="css-vars"?u:null}).filter(l=>!!l).join(";")}function ft(e,t,n,r={meta:{},options:n,codeToHast:(o,s)=>ft(e,o,s),codeToTokens:(o,s)=>pt(e,o,s)}){let o=t;for(let f of ht(n))o=f.preprocess?.call(r,o,n)||o;let{tokens:s,fg:a,bg:l,themeName:i,rootStyle:c,grammarState:u}=pt(e,o,n),{mergeWhitespaces:h=!0,mergeSameStyleTokens:p=!1}=n;h===!0?s=ti(s):h==="never"&&(s=ni(s)),p&&(s=ri(s));let d={...r,get source(){return o}};for(let f of ht(n))s=f.tokens?.call(d,s)||s;return ei(s,{...n,fg:a,bg:l,themeName:i,rootStyle:n.rootStyle===!1?!1:n.rootStyle??c},d,u)}function ei(e,t,n,r=Be(e)){let o=ht(t),s=[],a={type:"root",children:[]},{structure:l="classic",tabindex:i="0"}=t,c={class:`shiki ${t.themeName||""}`};t.rootStyle!==!1&&(t.rootStyle!=null?c.style=t.rootStyle:c.style=`background-color:${t.bg};color:${t.fg}`),i!==!1&&i!=null&&(c.tabindex=i.toString());for(let[b,w]of Object.entries(t.meta||{}))b.startsWith("_")||(c[b]=w);let u={type:"element",tagName:"pre",properties:c,children:[],data:t.data},h={type:"element",tagName:"code",properties:{},children:s},p=[],d={...n,structure:l,addClassToHast:Fr,get source(){return n.source},get tokens(){return e},get options(){return t},get root(){return a},get pre(){return u},get code(){return h},get lines(){return p}};if(e.forEach((b,w)=>{w&&(l==="inline"?a.children.push({type:"element",tagName:"br",properties:{},children:[]}):l==="classic"&&s.push({type:"text",value:`
12`}));let m={type:"element",tagName:"span",properties:{class:"line"},children:[]},C=0;for(let y of b){let _={type:"element",tagName:"span",properties:{...y.htmlAttrs},children:[{type:"text",value:y.content}]},x=Zt(y.htmlStyle||ut(y));x&&(_.properties.style=x);for(let M of o)_=M?.span?.call(d,_,w+1,C,m,y)||_;l==="inline"?a.children.push(_):l==="classic"&&m.children.push(_),C+=y.content.length}if(l==="classic"){for(let y of o)m=y?.line?.call(d,m,w+1)||m;p.push(m),s.push(m)}else l==="inline"&&p.push(m)}),l==="classic"){for(let b of o)h=b?.code?.call(d,h)||h;u.children.push(h);for(let b of o)u=b?.pre?.call(d,u)||u;a.children.push(u)}else if(l==="inline"){let b=[],w={type:"element",tagName:"span",properties:{class:"line"},children:[]};for(let y of a.children)y.type==="element"&&y.tagName==="br"?(b.push(w),w={type:"element",tagName:"span",properties:{class:"line"},children:[]}):(y.type==="element"||y.type==="text")&&w.children.push(y);b.push(w);let C={type:"element",tagName:"code",properties:{},children:b};for(let y of o)C=y?.code?.call(d,C)||C;a.children=[];for(let y=0;y<C.children.length;y++){y>0&&a.children.push({type:"element",tagName:"br",properties:{},children:[]});let _=C.children[y];_.type==="element"&&a.children.push(..._.children)}}let f=a;for(let b of o)f=b?.root?.call(d,f)||f;return r&&gt(f,r),f}function ti(e){return e.map(t=>{let n=[],r="",o;return t.forEach((s,a)=>{let i=!(s.fontStyle&&(s.fontStyle&P.Underline||s.fontStyle&P.Strikethrough));i&&s.content.match(/^\s+$/)&&t[a+1]?(o===void 0&&(o=s.offset),r+=s.content):r?(i?n.push({...s,offset:o,content:r+s.content}):n.push({content:r,offset:o},s),o=void 0,r=""):n.push(s)}),n})}function ni(e){return e.map(t=>t.flatMap(n=>{if(n.content.match(/^\s+$/))return n;let r=n.content.match(/^(\s*)(.*?)(\s*)$/);if(!r)return n;let[,o,s,a]=r;if(!o&&!a)return n;let l=[{...n,offset:n.offset+o.length,content:s}];return o&&l.unshift({content:o,offset:n.offset}),a&&l.push({content:a,offset:n.offset+o.length+s.length}),l}))}function ri(e){return e.map(t=>{let n=[];for(let r of t){if(n.length===0){n.push({...r});continue}let o=n[n.length-1],s=Zt(o.htmlStyle||ut(o)),a=Zt(r.htmlStyle||ut(r)),l=o.fontStyle&&(o.fontStyle&P.Underline||o.fontStyle&P.Strikethrough),i=r.fontStyle&&(r.fontStyle&P.Underline||r.fontStyle&P.Strikethrough);!l&&!i&&s===a?o.content+=r.content:n.push({...r})}return n})}var oi=Jt;function si(e,t,n){let r={meta:{},options:n,codeToHast:(s,a)=>ft(e,s,a),codeToTokens:(s,a)=>pt(e,s,a)},o=oi(ft(e,t,n,r));for(let s of ht(n))o=s.postprocess?.call(r,o,n)||o;return o}var Or={light:"#333333",dark:"#bbbbbb"},Gr={light:"#fffffe",dark:"#1e1e1e"},Br="__shiki_resolved";function ln(e){if(e?.[Br])return e;let t={...e};t.tokenColors&&!t.settings&&(t.settings=t.tokenColors,delete t.tokenColors),t.type||="dark",t.colorReplacements={...t.colorReplacements},t.settings||=[];let{bg:n,fg:r}=t;if(!n||!r){let l=t.settings?t.settings.find(i=>!i.name&&!i.scope):void 0;l?.settings?.foreground&&(r=l.settings.foreground),l?.settings?.background&&(n=l.settings.background),!r&&t?.colors?.["editor.foreground"]&&(r=t.colors["editor.foreground"]),!n&&t?.colors?.["editor.background"]&&(n=t.colors["editor.background"]),r||(r=t.type==="light"?Or.light:Or.dark),n||(n=t.type==="light"?Gr.light:Gr.dark),t.fg=r,t.bg=n}t.settings[0]&&t.settings[0].settings&&!t.settings[0].scope||t.settings.unshift({settings:{foreground:t.fg,background:t.bg}});let o=0,s=new Map;function a(l){if(s.has(l))return s.get(l);o+=1;let i=`#${o.toString(16).padStart(8,"0").toLowerCase()}`;return t.colorReplacements?.[`#${i}`]?a(l):(s.set(l,i),i)}t.settings=t.settings.map(l=>{let i=l.settings?.foreground&&!l.settings.foreground.startsWith("#"),c=l.settings?.background&&!l.settings.background.startsWith("#");if(!i&&!c)return l;let u={...l,settings:{...l.settings}};if(i){let h=a(l.settings.foreground);t.colorReplacements[h]=l.settings.foreground,u.settings.foreground=h}if(c){let h=a(l.settings.background);t.colorReplacements[h]=l.settings.background,u.settings.background=h}return u});for(let l of Object.keys(t.colors||{}))if((l==="editor.foreground"||l==="editor.background"||l.startsWith("terminal.ansi"))&&!t.colors[l]?.startsWith("#")){let i=a(t.colors[l]);t.colorReplacements[i]=t.colors[l],t.colors[l]=i}return Object.defineProperty(t,Br,{enumerable:!1,writable:!1,value:!0}),t}async function ai(e){return Array.from(new Set((await Promise.all(e.filter(t=>!Aa(t)).map(async t=>await Dr(t).then(n=>Array.isArray(n)?n:[n])))).flat()))}async function ii(e){return(await Promise.all(e.map(async n=>Ea(n)?null:ln(await Dr(n))))).filter(n=>!!n)}var ne=class extends Error{constructor(t){super(t),this.name="ShikiError"}};function Wr(e,t){if(!t)return e;if(t[e]){let n=new Set([e]);for(;t[e];){if(e=t[e],n.has(e))throw new ne(`Circular alias \`${Array.from(n).join(" -> ")} -> ${e}\``);n.add(e)}}return e}var en=class extends nr{constructor(t,n,r,o={}){super(t),this._resolver=t,this._themes=n,this._langs=r,this._alias=o,this._themes.map(s=>this.loadTheme(s)),this.loadLanguages(this._langs)}_resolvedThemes=new Map;_resolvedGrammars=new Map;_langMap=new Map;_langGraph=new Map;_textmateThemeCache=new WeakMap;_loadedThemesCache=null;_loadedLanguagesCache=null;getTheme(t){return typeof t=="string"?this._resolvedThemes.get(t):this.loadTheme(t)}loadTheme(t){let n=ln(t);return n.name&&(this._resolvedThemes.set(n.name,n),this._loadedThemesCache=null),n}getLoadedThemes(){return this._loadedThemesCache||(this._loadedThemesCache=[...this._resolvedThemes.keys()]),this._loadedThemesCache}setTheme(t){let n=this._textmateThemeCache.get(t);n||(n=Re.createFromRawTheme(t),this._textmateThemeCache.set(t,n)),this._syncRegistry.setTheme(n)}getGrammar(t){return t=Wr(t,this._alias),this._resolvedGrammars.get(t)}loadLanguage(t){if(this.getGrammar(t.name))return;let n=new Set([...this._langMap.values()].filter(s=>s.embeddedLangsLazy?.includes(t.name)));this._resolver.addLanguage(t);let r={balancedBracketSelectors:t.balancedBracketSelectors||["*"],unbalancedBracketSelectors:t.unbalancedBracketSelectors||[]};this._syncRegistry._rawGrammars.set(t.scopeName,t);let o=this.loadGrammarWithConfiguration(t.scopeName,1,r);if(o.name=t.name,this._resolvedGrammars.set(t.name,o),t.aliases&&t.aliases.forEach(s=>{this._alias[s]=t.name}),this._loadedLanguagesCache=null,n.size)for(let s of n)this._resolvedGrammars.delete(s.name),this._loadedLanguagesCache=null,this._syncRegistry?._injectionGrammars?.delete(s.scopeName),this._syncRegistry?._grammars?.delete(s.scopeName),this.loadLanguage(this._langMap.get(s.name))}dispose(){super.dispose(),this._resolvedThemes.clear(),this._resolvedGrammars.clear(),this._langMap.clear(),this._langGraph.clear(),this._loadedThemesCache=null}loadLanguages(t){for(let o of t)this.resolveEmbeddedLanguages(o);let n=Array.from(this._langGraph.entries()),r=n.filter(([o,s])=>!s);if(r.length){let o=n.filter(([s,a])=>a?(a.embeddedLanguages||a.embeddedLangs)?.some(i=>r.map(([c])=>c).includes(i)):!1).filter(s=>!r.includes(s));throw new ne(`Missing languages ${r.map(([s])=>`\`${s}\``).join(", ")}, required by ${o.map(([s])=>`\`${s}\``).join(", ")}`)}for(let[o,s]of n)this._resolver.addLanguage(s);for(let[o,s]of n)this.loadLanguage(s)}getLoadedLanguages(){return this._loadedLanguagesCache||(this._loadedLanguagesCache=[...new Set([...this._resolvedGrammars.keys(),...Object.keys(this._alias)])]),this._loadedLanguagesCache}resolveEmbeddedLanguages(t){this._langMap.set(t.name,t),this._langGraph.set(t.name,t);let n=t.embeddedLanguages??t.embeddedLangs;if(n)for(let r of n)this._langGraph.set(r,this._langMap.get(r))}},tn=class{_langs=new Map;_scopeToLang=new Map;_injections=new Map;_onigLib;constructor(t,n){this._onigLib={createOnigScanner:r=>t.createScanner(r),createOnigString:r=>t.createString(r)},n.forEach(r=>this.addLanguage(r))}get onigLib(){return this._onigLib}getLangRegistration(t){return this._langs.get(t)}loadGrammar(t){return this._scopeToLang.get(t)}addLanguage(t){this._langs.set(t.name,t),t.aliases&&t.aliases.forEach(n=>{this._langs.set(n,t)}),this._scopeToLang.set(t.scopeName,t),t.injectTo&&t.injectTo.forEach(n=>{this._injections.get(n)||this._injections.set(n,[]),this._injections.get(n).push(t.scopeName)})}getInjections(t){let n=t.split("."),r=[];for(let o=1;o<=n.length;o++){let s=n.slice(0,o).join(".");r=[...r,...this._injections.get(s)||[]]}return r}},Ge=0;function li(e){Ge+=1,e.warnings!==!1&&Ge>=10&&Ge%10===0&&console.warn(`[Shiki] ${Ge} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);let t=!1;if(!e.engine)throw new ne("`engine` option is required for synchronous mode");let n=(e.langs||[]).flat(1),r=(e.themes||[]).flat(1).map(ln),o=new tn(e.engine,n),s=new en(o,r,n,e.langAlias),a;function l(y){return Wr(y,e.langAlias)}function i(y){m();let _=s.getGrammar(typeof y=="string"?y:y.name);if(!_)throw new ne(`Language \`${y}\` not found, you may need to load it first`);return _}function c(y){if(y==="none")return{bg:"",fg:"",name:"none",settings:[],type:"dark"};m();let _=s.getTheme(y);if(!_)throw new ne(`Theme \`${y}\` not found, you may need to load it first`);return _}function u(y){m();let _=c(y);a!==y&&(s.setTheme(_),a=y);let x=s.getColorMap();return{theme:_,colorMap:x}}function h(){return m(),s.getLoadedThemes()}function p(){return m(),s.getLoadedLanguages()}function d(...y){m(),s.loadLanguages(y.flat(1))}async function f(...y){return d(await ai(y))}function b(...y){m();for(let _ of y.flat(1))s.loadTheme(_)}async function w(...y){return m(),b(await ii(y))}function m(){if(t)throw new ne("Shiki instance has been disposed")}function C(){t||(t=!0,s.dispose(),Ge-=1)}return{setTheme:u,getTheme:c,getLanguage:i,getLoadedThemes:h,getLoadedLanguages:p,resolveLangAlias:l,loadLanguage:f,loadLanguageSync:d,loadTheme:w,loadThemeSync:b,dispose:C,[Symbol.dispose]:C}}function Hr(e){let t=li(e);return{getLastGrammarState:(...n)=>Va(t,...n),codeToTokensBase:(n,r)=>sn(t,n,r),codeToTokensWithThemes:(n,r)=>zr(t,n,r),codeToTokens:(n,r)=>pt(t,n,r),codeToHast:(n,r)=>ft(t,n,r),codeToHtml:(n,r)=>si(t,n,r),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}function oe(e){if([...e].length!==1)throw new Error(`Expected "${e}" to be a single code point`);return e.codePointAt(0)}function qr(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}var De=new Set(["alnum","alpha","ascii","blank","cntrl","digit","graph","lower","print","punct","space","upper","word","xdigit"]),N=String.raw;function Q(e,t){if(e==null)throw new Error(t??"Value expected");return e}var Yr=N`\[\^?`,Zr=`c.? | C(?:-.?)?|${N`[pP]\{(?:\^?[-\x20_]*[A-Za-z][-\x20\w]*\})?`}|${N`x[89A-Fa-f]\p{AHex}(?:\\x[89A-Fa-f]\p{AHex})*`}|${N`u(?:\p{AHex}{4})? | x\{[^\}]*\}? | x\p{AHex}{0,2}`}|${N`o\{[^\}]*\}?`}|${N`\d{1,3}`}`,un=/[?*+][?+]?|\{(?:\d+(?:,\d*)?|,\d+)\}\??/,mt=new RegExp(N`
13  \\ (?:
14    ${Zr}
15    | [gk]<[^>]*>?
16    | [gk]'[^']*'?
17    | .
18  )
19  | \( (?:
20    \? (?:
21      [:=!>({]
22      | <[=!]
23      | <[^>]*>
24      | '[^']*'
25      | ~\|?
26      | #(?:[^)\\]|\\.?)*
27      | [^:)]*[:)]
28    )?
29    | \*[^\)]*\)?
30  )?
31  | (?:${un.source})+
32  | ${Yr}
33  | .
34`.replace(/\s+/g,""),"gsu"),cn=new RegExp(N`
35  \\ (?:
36    ${Zr}
37    | .
38  )
39  | \[:(?:\^?\p{Alpha}+|\^):\]
40  | ${Yr}
41  | &&
42  | .
43`.replace(/\s+/g,""),"gsu");function eo(e,t={}){let n={flags:"",...t,rules:{captureGroup:!1,singleline:!1,...t.rules}};if(typeof e!="string")throw new Error("String expected as pattern");let r=Ei(n.flags),o=[r.extended],s={captureGroup:n.rules.captureGroup,getCurrentModX(){return o.at(-1)},numOpenGroups:0,popModX(){o.pop()},pushModX(h){o.push(h)},replaceCurrentModX(h){o[o.length-1]=h},singleline:n.rules.singleline},a=[],l;for(mt.lastIndex=0;l=mt.exec(e);){let h=ci(s,e,l[0],mt.lastIndex);h.tokens?a.push(...h.tokens):h.token&&a.push(h.token),h.lastIndex!==void 0&&(mt.lastIndex=h.lastIndex)}let i=[],c=0;a.filter(h=>h.type==="GroupOpen").forEach(h=>{h.kind==="capturing"?h.number=++c:h.raw==="("&&i.push(h)}),c||i.forEach((h,p)=>{h.kind="capturing",h.number=p+1});let u=c||i.length;return{tokens:a.map(h=>h.type==="EscapedNumber"?Ri(h,u):h).flat(),flags:r}}function ci(e,t,n,r){let[o,s]=n;if(n==="["||n==="[^"){let a=ui(t,n,r);return{tokens:a.tokens,lastIndex:a.lastIndex}}if(o==="\\"){if("AbBGyYzZ".includes(s))return{token:Vr(n,n)};if(/^\\g[<']/.test(n)){if(!/^\\g(?:<[^>]+>|'[^']+')$/.test(n))throw new Error(`Invalid group name "${n}"`);return{token:Ci(n)}}if(/^\\k[<']/.test(n)){if(!/^\\k(?:<[^>]+>|'[^']+')$/.test(n))throw new Error(`Invalid group name "${n}"`);return{token:no(n)}}if(s==="K")return{token:ro("keep",n)};if(s==="N"||s==="R")return{token:de("newline",n,{negate:s==="N"})};if(s==="O")return{token:de("any",n)};if(s==="X")return{token:de("text_segment",n)};let a=to(n,{inCharClass:!1});return Array.isArray(a)?{tokens:a}:{token:a}}if(o==="("){if(s==="*")return{token:xi(n)};if(n==="(?{")throw new Error(`Unsupported callout "${n}"`);if(n.startsWith("(?#")){if(t[r]!==")")throw new Error('Unclosed comment group "(?#"');return{lastIndex:r+1}}if(/^\(\?[-imx]+[:)]$/.test(n))return{token:Si(n,e)};if(e.pushModX(e.getCurrentModX()),e.numOpenGroups++,n==="("&&!e.captureGroup||n==="(?:")return{token:Ce("group",n)};if(n==="(?>")return{token:Ce("atomic",n)};if(n==="(?="||n==="(?!"||n==="(?<="||n==="(?<!")return{token:Ce(n[2]==="<"?"lookbehind":"lookahead",n,{negate:n.endsWith("!")})};if(n==="("&&e.captureGroup||n.startsWith("(?<")&&n.endsWith(">")||n.startsWith("(?'")&&n.endsWith("'"))return{token:Ce("capturing",n,{...n!=="("&&{name:n.slice(3,-1)}})};if(n.startsWith("(?~")){if(n==="(?~|")throw new Error(`Unsupported absence function kind "${n}"`);return{token:Ce("absence_repeater",n)}}throw n==="(?("?new Error(`Unsupported conditional "${n}"`):new Error(`Invalid or unsupported group option "${n}"`)}if(n===")"){if(e.popModX(),e.numOpenGroups--,e.numOpenGroups<0)throw new Error('Unmatched ")"');return{token:yi(n)}}if(e.getCurrentModX()){if(n==="#"){let a=t.indexOf(`
44`,r);return{lastIndex:a===-1?t.length:a}}if(/^\s$/.test(n)){let a=/\s+/y;return a.lastIndex=r,{lastIndex:a.exec(t)?a.lastIndex:r}}}if(n===".")return{token:de("dot",n)};if(n==="^"||n==="$"){let a=e.singleline?{"^":N`\A`,$:N`\Z`}[n]:n;return{token:Vr(a,n)}}return n==="|"?{token:pi(n)}:un.test(n)?{tokens:Ni(n)}:{token:J(oe(n),n)}}function ui(e,t,n){let r=[Xr(t[1]==="^",t)],o=1,s;for(cn.lastIndex=n;s=cn.exec(e);){let a=s[0];if(a[0]==="["&&a[1]!==":")o++,r.push(Xr(a[1]==="^",a));else if(a==="]"){if(r.at(-1).type==="CharacterClassOpen")r.push(J(93,a));else if(o--,r.push(fi(a)),!o)break}else{let l=hi(a);Array.isArray(l)?r.push(...l):r.push(l)}}return{tokens:r,lastIndex:cn.lastIndex||e.length}}function hi(e){if(e[0]==="\\")return to(e,{inCharClass:!0});if(e[0]==="["){let t=/\[:(?<negate>\^?)(?<name>[a-z]+):\]/.exec(e);if(!t||!De.has(t.groups.name))throw new Error(`Invalid POSIX class "${e}"`);return de("posix",e,{value:t.groups.name,negate:!!t.groups.negate})}return e==="-"?di(e):e==="&&"?gi(e):J(oe(e),e)}function to(e,{inCharClass:t}){let n=e[1];if(n==="c"||n==="C")return ki(e);if("dDhHsSwW".includes(n))return vi(e);if(e.startsWith(N`\o{`))throw new Error(`Incomplete, invalid, or unsupported octal code point "${e}"`);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw new Error(`Incomplete or invalid Unicode property "${e}"`);return Ai(e)}if(/^\\x[89A-Fa-f]\p{AHex}/u.test(e))try{let r=e.split(/\\x/).slice(1).map(a=>parseInt(a,16)),o=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}).decode(new Uint8Array(r)),s=new TextEncoder;return[...o].map(a=>{let l=[...s.encode(a)].map(i=>`\\x${i.toString(16)}`).join("");return J(oe(a),l)})}catch{throw new Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n==="u"||n==="x")return J(Ii(e),e);if(Kr.has(n))return J(Kr.get(n),e);if(/\d/.test(n))return mi(t,e);if(e==="\\")throw new Error(N`Incomplete escape "\"`);if(n==="M")throw new Error(`Unsupported meta "${e}"`);if([...e].length===2)return J(e.codePointAt(1),e);throw new Error(`Unexpected escape "${e}"`)}function pi(e){return{type:"Alternator",raw:e}}function Vr(e,t){return{type:"Assertion",kind:e,raw:t}}function no(e){return{type:"Backreference",raw:e}}function J(e,t){return{type:"Character",value:e,raw:t}}function fi(e){return{type:"CharacterClassClose",raw:e}}function di(e){return{type:"CharacterClassHyphen",raw:e}}function gi(e){return{type:"CharacterClassIntersector",raw:e}}function Xr(e,t){return{type:"CharacterClassOpen",negate:e,raw:t}}function de(e,t,n={}){return{type:"CharacterSet",kind:e,...n,raw:t}}function ro(e,t,n={}){return e==="keep"?{type:"Directive",kind:e,raw:t}:{type:"Directive",kind:e,flags:Q(n.flags),raw:t}}function mi(e,t){return{type:"EscapedNumber",inCharClass:e,raw:t}}function yi(e){return{type:"GroupClose",raw:e}}function Ce(e,t,n={}){return{type:"GroupOpen",kind:e,...n,raw:t}}function bi(e,t,n,r){return{type:"NamedCallout",kind:e,tag:t,arguments:n,raw:r}}function wi(e,t,n,r){return{type:"Quantifier",kind:e,min:t,max:n,raw:r}}function Ci(e){return{type:"Subroutine",raw:e}}var _i=new Set(["COUNT","CMP","ERROR","FAIL","MAX","MISMATCH","SKIP","TOTAL_COUNT"]),Kr=new Map([["a",7],["b",8],["e",27],["f",12],["n",10],["r",13],["t",9],["v",11]]);function ki(e){let t=e[1]==="c"?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw new Error(`Unsupported control character "${e}"`);return J(oe(t.toUpperCase())-64,e)}function Si(e,t){let{on:n,off:r}=/^\(\?(?<on>[imx]*)(?:-(?<off>[-imx]*))?/.exec(e).groups;r??="";let o=(t.getCurrentModX()||n.includes("x"))&&!r.includes("x"),s=Jr(n),a=Jr(r),l={};if(s&&(l.enable=s),a&&(l.disable=a),e.endsWith(")"))return t.replaceCurrentModX(o),ro("flags",e,{flags:l});if(e.endsWith(":"))return t.pushModX(o),t.numOpenGroups++,Ce("group",e,{...(s||a)&&{flags:l}});throw new Error(`Unexpected flag modifier "${e}"`)}function xi(e){let t=/\(\*(?<name>[A-Za-z_]\w*)?(?:\[(?<tag>(?:[A-Za-z_]\w*)?)\])?(?:\{(?<args>[^}]*)\})?\)/.exec(e);if(!t)throw new Error(`Incomplete or invalid named callout "${e}"`);let{name:n,tag:r,args:o}=t.groups;if(!n)throw new Error(`Invalid named callout "${e}"`);if(r==="")throw new Error(`Named callout tag with empty value not allowed "${e}"`);let s=o?o.split(",").filter(u=>u!=="").map(u=>/^[+-]?\d+$/.test(u)?+u:u):[],[a,l,i]=s,c=_i.has(n)?n.toLowerCase():"custom";switch(c){case"fail":case"mismatch":case"skip":if(s.length>0)throw new Error(`Named callout arguments not allowed "${s}"`);break;case"error":if(s.length>1)throw new Error(`Named callout allows only one argument "${s}"`);if(typeof a=="string")throw new Error(`Named callout argument must be a number "${a}"`);break;case"max":if(!s.length||s.length>2)throw new Error(`Named callout must have one or two arguments "${s}"`);if(typeof a=="string"&&!/^[A-Za-z_]\w*$/.test(a))throw new Error(`Named callout argument one must be a tag or number "${a}"`);if(s.length===2&&(typeof l=="number"||!/^[<>X]$/.test(l)))throw new Error(`Named callout optional argument two must be '<', '>', or 'X' "${l}"`);break;case"count":case"total_count":if(s.length>1)throw new Error(`Named callout allows only one argument "${s}"`);if(s.length===1&&(typeof a=="number"||!/^[<>X]$/.test(a)))throw new Error(`Named callout optional argument must be '<', '>', or 'X' "${a}"`);break;case"cmp":if(s.length!==3)throw new Error(`Named callout must have three arguments "${s}"`);if(typeof a=="string"&&!/^[A-Za-z_]\w*$/.test(a))throw new Error(`Named callout argument one must be a tag or number "${a}"`);if(typeof l=="number"||!/^(?:[<>!=]=|[<>])$/.test(l))throw new Error(`Named callout argument two must be '==', '!=', '>', '<', '>=', or '<=' "${l}"`);if(typeof i=="string"&&!/^[A-Za-z_]\w*$/.test(i))throw new Error(`Named callout argument three must be a tag or number "${i}"`);break;case"custom":throw new Error(`Undefined callout name "${n}"`);default:throw new Error(`Unexpected named callout kind "${c}"`)}return bi(c,r??null,o?.split(",")??null,e)}function Qr(e){let t=null,n,r;if(e[0]==="{"){let{minStr:o,maxStr:s}=/^\{(?<minStr>\d*)(?:,(?<maxStr>\d*))?/.exec(e).groups,a=1e5;if(+o>a||s&&+s>a)throw new Error("Quantifier value unsupported in Oniguruma");if(n=+o,r=s===void 0?+o:s===""?1/0:+s,n>r&&(t="possessive",[n,r]=[r,n]),e.endsWith("?")){if(t==="possessive")throw new Error('Unsupported possessive interval quantifier chain with "?"');t="lazy"}else t||(t="greedy")}else n=e[0]==="+"?1:0,r=e[0]==="?"?1:1/0,t=e[1]==="+"?"possessive":e[1]==="?"?"lazy":"greedy";return wi(t,n,r,e)}function vi(e){let t=e[1].toLowerCase();return de({d:"digit",h:"hex",s:"space",w:"word"}[t],e,{negate:e[1]!==t})}function Ai(e){let{p:t,neg:n,value:r}=/^\\(?<p>[pP])\{(?<neg>\^?)(?<value>[^}]+)/.exec(e).groups;return de("property",e,{value:r,negate:t==="P"&&!n||t==="p"&&!!n})}function Jr(e){let t={};return e.includes("i")&&(t.ignoreCase=!0),e.includes("m")&&(t.dotAll=!0),e.includes("x")&&(t.extended=!0),Object.keys(t).length?t:null}function Ei(e){let t={ignoreCase:!1,dotAll:!1,extended:!1,digitIsAscii:!1,posixIsAscii:!1,spaceIsAscii:!1,wordIsAscii:!1,textSegmentMode:null};for(let n=0;n<e.length;n++){let r=e[n];if(!"imxDPSWy".includes(r))throw new Error(`Invalid flag "${r}"`);if(r==="y"){if(!/^y{[gw]}/.test(e.slice(n)))throw new Error('Invalid or unspecified flag "y" mode');t.textSegmentMode=e[n+2]==="g"?"grapheme":"word",n+=3;continue}t[{i:"ignoreCase",m:"dotAll",x:"extended",D:"digitIsAscii",P:"posixIsAscii",S:"spaceIsAscii",W:"wordIsAscii"}[r]]=!0}return t}function Ii(e){if(/^(?:\\u(?!\p{AHex}{4})|\\x(?!\p{AHex}{1,2}|\{\p{AHex}{1,8}\}))/u.test(e))throw new Error(`Incomplete or invalid escape "${e}"`);let t=e[2]==="{"?/^\\x\{\s*(?<hex>\p{AHex}+)/u.exec(e).groups.hex:e.slice(2);return parseInt(t,16)}function Ri(e,t){let{raw:n,inCharClass:r}=e,o=n.slice(1);if(!r&&(o!=="0"&&o.length===1||o[0]!=="0"&&+o<=t))return[no(n)];let s=[],a=o.match(/^[0-7]+|\d/g);for(let l=0;l<a.length;l++){let i=a[l],c;if(l===0&&i!=="8"&&i!=="9"){if(c=parseInt(i,8),c>127)throw new Error(N`Octal encoded byte above 177 unsupported "${n}"`)}else c=oe(i);s.push(J(c,(l===0?"\\":"")+i))}return s}function Ni(e){let t=[],n=new RegExp(un,"gy"),r;for(;r=n.exec(e);){let o=r[0];if(o[0]==="{"){let s=/^\{(?<min>\d+),(?<max>\d+)\}\??$/.exec(o);if(s){let{min:a,max:l}=s.groups;if(+a>+l&&o.endsWith("?")){n.lastIndex--,t.push(Qr(o.slice(0,-1)));continue}}}t.push(Qr(o))}return t}function yt(e,t){if(!Array.isArray(e.body))throw new Error("Expected node with body array");if(e.body.length!==1)return!1;let n=e.body[0];return!t||Object.keys(t).every(r=>t[r]===n[r])}function oo(e){return Li.has(e.type)}var Li=new Set(["AbsenceFunction","Backreference","CapturingGroup","Character","CharacterClass","CharacterSet","Group","Quantifier","Subroutine"]);function wt(e,t={}){let n={flags:"",normalizeUnknownPropertyNames:!1,skipBackrefValidation:!1,skipLookbehindValidation:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}},r=eo(e,{flags:n.flags,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline}}),o=(p,d)=>{let f=r.tokens[s.nextIndex];switch(s.parent=p,s.nextIndex++,f.type){case"Alternator":return Y();case"Assertion":return Ti(f);case"Backreference":return Pi(f,s);case"Character":return _e(f.value,{useLastValid:!!d.isCheckingRangeEnd});case"CharacterClassHyphen":return $i(f,s,d);case"CharacterClassOpen":return Mi(f,s,d);case"CharacterSet":return Oi(f,s);case"Directive":return ji(f.kind,{flags:f.flags});case"GroupOpen":return Gi(f,s,d);case"NamedCallout":return Wi(f.kind,f.tag,f.arguments);case"Quantifier":return Bi(f,s);case"Subroutine":return Di(f,s);default:throw new Error(`Unexpected token type "${f.type}"`)}},s={capturingGroups:[],hasNumberedRef:!1,namedGroupsByName:new Map,nextIndex:0,normalizeUnknownPropertyNames:n.normalizeUnknownPropertyNames,parent:null,skipBackrefValidation:n.skipBackrefValidation,skipLookbehindValidation:n.skipLookbehindValidation,skipPropertyNameValidation:n.skipPropertyNameValidation,subroutines:[],tokens:r.tokens,unicodePropertyMap:n.unicodePropertyMap,walk:o},a=qi(zi(r.flags)),l=a.body[0];for(;s.nextIndex<r.tokens.length;){let p=o(l,{});p.type==="Alternative"?(a.body.push(p),l=p):l.body.push(p)}let{capturingGroups:i,hasNumberedRef:c,namedGroupsByName:u,subroutines:h}=s;if(c&&u.size&&!n.rules.captureGroup)throw new Error("Numbered backref/subroutine not allowed when using named capture");for(let{ref:p}of h)if(typeof p=="number"){if(p>i.length)throw new Error("Subroutine uses a group number that's not defined");p&&(i[p-1].isSubroutined=!0)}else if(u.has(p)){if(u.get(p).length>1)throw new Error(N`Subroutine uses a duplicate group name "\g<${p}>"`);u.get(p)[0].isSubroutined=!0}else throw new Error(N`Subroutine uses a group name that's not defined "\g<${p}>"`);return a}function Ti({kind:e}){return Ct(Q({"^":"line_start",$:"line_end","\\A":"string_start","\\b":"word_boundary","\\B":"word_boundary","\\G":"search_start","\\y":"text_segment_boundary","\\Y":"text_segment_boundary","\\z":"string_end","\\Z":"string_end_newline"}[e],`Unexpected assertion kind "${e}"`),{negate:e===N`\B`||e===N`\Y`})}function Pi({raw:e},t){let n=/^\\k[<']/.test(e),r=n?e.slice(3,-1):e.slice(1),o=(s,a=!1)=>{let l=t.capturingGroups.length,i=!1;if(s>l)if(t.skipBackrefValidation)i=!0;else throw new Error(`Not enough capturing groups defined to the left "${e}"`);return t.hasNumberedRef=!0,bt(a?l+1-s:s,{orphan:i})};if(n){let s=/^(?<sign>-?)0*(?<num>[1-9]\d*)$/.exec(r);if(s)return o(+s.groups.num,!!s.groups.sign);if(/[-+]/.test(r))throw new Error(`Invalid backref name "${e}"`);if(!t.namedGroupsByName.has(r))throw new Error(`Group name not defined to the left "${e}"`);return bt(r)}return o(+r)}function $i(e,t,n){let{tokens:r,walk:o}=t,s=t.parent,a=s.body.at(-1),l=r[t.nextIndex];if(!n.isCheckingRangeEnd&&a&&a.type!=="CharacterClass"&&a.type!=="CharacterClassRange"&&l&&l.type!=="CharacterClassOpen"&&l.type!=="CharacterClassClose"&&l.type!=="CharacterClassIntersector"){let i=o(s,{...n,isCheckingRangeEnd:!0});if(a.type==="Character"&&i.type==="Character")return s.body.pop(),Ui(a,i);throw new Error("Invalid character class range")}return _e(oe("-"))}function Mi({negate:e},t,n){let{tokens:r,walk:o}=t,s=[Fe()],a=r[t.nextIndex],l=io(a);for(;l.type!=="CharacterClassClose";){if(l.type==="CharacterClassIntersector")s.push(Fe()),t.nextIndex++;else{let c=s.at(-1);c.body.push(o(c,n))}l=io(r[t.nextIndex],a)}let i=Fe({negate:e});return s.length===1?i.body=s[0].body:(i.kind="intersection",i.body=s.map(c=>c.body.length===1?c.body[0]:c)),t.nextIndex++,i}function Oi({kind:e,negate:t,value:n},r){let{normalizeUnknownPropertyNames:o,skipPropertyNameValidation:s,unicodePropertyMap:a}=r;if(e==="property"){let l=ke(n);if(De.has(l)&&!a?.has(l))e="posix",n=l;else return ge(n,{negate:t,normalizeUnknownPropertyNames:o,skipPropertyNameValidation:s,unicodePropertyMap:a})}return e==="posix"?Hi(n,{negate:t}):_t(e,{negate:t})}function Gi(e,t,n){let{tokens:r,capturingGroups:o,namedGroupsByName:s,skipLookbehindValidation:a,walk:l}=t,i=Vi(e),c=i.type==="AbsenceFunction",u=ao(i),h=u&&i.negate;if(i.type==="CapturingGroup"&&(o.push(i),i.name&&qr(s,i.name,[]).push(i)),c&&n.isInAbsenceFunction)throw new Error("Nested absence function not supported by Oniguruma");let p=lo(r[t.nextIndex]);for(;p.type!=="GroupClose";){if(p.type==="Alternator")i.body.push(Y()),t.nextIndex++;else{let d=i.body.at(-1),f=l(d,{...n,isInAbsenceFunction:n.isInAbsenceFunction||c,isInLookbehind:n.isInLookbehind||u,isInNegLookbehind:n.isInNegLookbehind||h});if(d.body.push(f),(u||n.isInLookbehind)&&!a){let b="Lookbehind includes a pattern not allowed by Oniguruma";if(h||n.isInNegLookbehind){if(so(f)||f.type==="CapturingGroup")throw new Error(b)}else if(so(f)||ao(f)&&f.negate)throw new Error(b)}}p=lo(r[t.nextIndex])}return t.nextIndex++,i}function Bi({kind:e,min:t,max:n},r){let o=r.parent,s=o.body.at(-1);if(!s||!oo(s))throw new Error("Quantifier requires a repeatable token");let a=pn(e,t,n,s);return o.body.pop(),a}function Di({raw:e},t){let{capturingGroups:n,subroutines:r}=t,o=e.slice(3,-1),s=/^(?<sign>[-+]?)0*(?<num>[1-9]\d*)$/.exec(o);if(s){let l=+s.groups.num,i=n.length;if(t.hasNumberedRef=!0,o={"":l,"+":i+l,"-":i+1-l}[s.groups.sign],o<1)throw new Error("Invalid subroutine number")}else o==="0"&&(o=0);let a=fn(o);return r.push(a),a}function Fi(e,t){if(e!=="repeater")throw new Error(`Unexpected absence function kind "${e}"`);return{type:"AbsenceFunction",kind:e,body:Ue(t?.body)}}function Y(e){return{type:"Alternative",body:co(e?.body)}}function Ct(e,t){let n={type:"Assertion",kind:e};return(e==="word_boundary"||e==="text_segment_boundary")&&(n.negate=!!t?.negate),n}function bt(e,t){let n=!!t?.orphan;return{type:"Backreference",ref:e,...n&&{orphan:n}}}function hn(e,t){let n={name:void 0,isSubroutined:!1,...t};if(n.name!==void 0&&!Xi(n.name))throw new Error(`Group name "${n.name}" invalid in Oniguruma`);return{type:"CapturingGroup",number:e,...n.name&&{name:n.name},...n.isSubroutined&&{isSubroutined:n.isSubroutined},body:Ue(t?.body)}}function _e(e,t){let n={useLastValid:!1,...t};if(e>1114111){let r=e.toString(16);if(n.useLastValid)e=1114111;else throw e>1310719?new Error(`Invalid code point out of range "\\x{${r}}"`):new Error(`Invalid code point out of range in JS "\\x{${r}}"`)}return{type:"Character",value:e}}function Fe(e){let t={kind:"union",negate:!1,...e};return{type:"CharacterClass",kind:t.kind,negate:t.negate,body:co(e?.body)}}function Ui(e,t){if(t.value<e.value)throw new Error("Character class range out of order");return{type:"CharacterClassRange",min:e,max:t}}function _t(e,t){let n=!!t?.negate,r={type:"CharacterSet",kind:e};return(e==="digit"||e==="hex"||e==="newline"||e==="space"||e==="word")&&(r.negate=n),(e==="text_segment"||e==="newline"&&!n)&&(r.variableLength=!0),r}function ji(e,t={}){if(e==="keep")return{type:"Directive",kind:e};if(e==="flags")return{type:"Directive",kind:e,flags:Q(t.flags)};throw new Error(`Unexpected directive kind "${e}"`)}function zi(e){return{type:"Flags",...e}}function D(e){let t=e?.atomic,n=e?.flags;if(t&&n)throw new Error("Atomic group cannot have flags");return{type:"Group",...t&&{atomic:t},...n&&{flags:n},body:Ue(e?.body)}}function se(e){let t={behind:!1,negate:!1,...e};return{type:"LookaroundAssertion",kind:t.behind?"lookbehind":"lookahead",negate:t.negate,body:Ue(e?.body)}}function Wi(e,t,n){return{type:"NamedCallout",kind:e,tag:t,arguments:n}}function Hi(e,t){let n=!!t?.negate;if(!De.has(e))throw new Error(`Invalid POSIX class "${e}"`);return{type:"CharacterSet",kind:"posix",value:e,negate:n}}function pn(e,t,n,r){if(t>n)throw new Error("Invalid reversed quantifier range");return{type:"Quantifier",kind:e,min:t,max:n,body:r}}function qi(e,t){return{type:"Regex",body:Ue(t?.body),flags:e}}function fn(e){return{type:"Subroutine",ref:e}}function ge(e,t){let n={negate:!1,normalizeUnknownPropertyNames:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t},r=n.unicodePropertyMap?.get(ke(e));if(!r){if(n.normalizeUnknownPropertyNames)r=Ki(e);else if(n.unicodePropertyMap&&!n.skipPropertyNameValidation)throw new Error(N`Invalid Unicode property "\p{${e}}"`)}return{type:"CharacterSet",kind:"property",value:r??e,negate:n.negate}}function Vi({flags:e,kind:t,name:n,negate:r,number:o}){switch(t){case"absence_repeater":return Fi("repeater");case"atomic":return D({atomic:!0});case"capturing":return hn(o,{name:n});case"group":return D({flags:e});case"lookahead":case"lookbehind":return se({behind:t==="lookbehind",negate:r});default:throw new Error(`Unexpected group kind "${t}"`)}}function Ue(e){if(e===void 0)e=[Y()];else if(!Array.isArray(e)||!e.length||!e.every(t=>t.type==="Alternative"))throw new Error("Invalid body; expected array of one or more Alternative nodes");return e}function co(e){if(e===void 0)e=[];else if(!Array.isArray(e)||!e.every(t=>!!t.type))throw new Error("Invalid body; expected array of nodes");return e}function so(e){return e.type==="LookaroundAssertion"&&e.kind==="lookahead"}function ao(e){return e.type==="LookaroundAssertion"&&e.kind==="lookbehind"}function Xi(e){return/^[\p{Alpha}\p{Pc}][^)]*$/u.test(e)}function Ki(e){return e.trim().replace(/[- _]+/g,"_").replace(/[A-Z][a-z]+(?=[A-Z])/g,"$&_").replace(/[A-Za-z]+/g,t=>t[0].toUpperCase()+t.slice(1).toLowerCase())}function ke(e){return e.replace(/[- _]+/g,"").toLowerCase()}function io(e,t){let n=t;return Q(e,`Unclosed character class${n?.type==="Character"&&n.value===93&&n.raw==="]"?' (started with "]")':""}`)}function lo(e){return Q(e,"Unclosed group")}function me(e,t,n=null){function r(s,a){for(let l=0;l<s.length;l++){let i=o(s[l],a,l,s);l=Math.max(-1,l+i)}}function o(s,a=null,l=null,i=null){let c=0,u=!1,h={node:s,parent:a,key:l,container:i,root:e,remove(){kt(i).splice(Math.max(0,Se(l)+c),1),c--,u=!0},removeAllNextSiblings(){return kt(i).splice(Se(l)+1)},removeAllPrevSiblings(){let m=Se(l)+c;return c-=m,kt(i).splice(0,Math.max(0,m))},replaceWith(m,C={}){let y=!!C.traverse;i?i[Math.max(0,Se(l)+c)]=m:Q(a,"Can't replace root node")[l]=m,y&&o(m,a,l,i),u=!0},replaceWithMultiple(m,C={}){let y=!!C.traverse;if(kt(i).splice(Math.max(0,Se(l)+c),1,...m),c+=m.length-1,y){let _=0;for(let x=0;x<m.length;x++)_+=o(m[x],a,Se(l)+x+_,i)}u=!0},skip(){u=!0}},{type:p}=s,d=t["*"],f=t[p],b=typeof d=="function"?d:d?.enter,w=typeof f=="function"?f:f?.enter;if(b?.(h,n),w?.(h,n),!u)switch(p){case"AbsenceFunction":case"Alternative":case"CapturingGroup":case"CharacterClass":case"Group":case"LookaroundAssertion":r(s.body,s);break;case"Assertion":case"Backreference":case"Character":case"CharacterSet":case"Directive":case"Flags":case"NamedCallout":case"Subroutine":break;case"CharacterClassRange":o(s.min,s,"min"),o(s.max,s,"max");break;case"Quantifier":o(s.body,s,"body");break;case"Regex":r(s.body,s),o(s.flags,s,"flags");break;default:throw new Error(`Unexpected node type "${p}"`)}return f?.exit?.(h,n),d?.exit?.(h,n),c}return o(e),e}function kt(e){if(!Array.isArray(e))throw new Error("Container expected");return e}function Se(e){if(typeof e!="number")throw new Error("Numeric key expected");return e}var uo=String.raw`\(\?(?:[:=!>A-Za-z\-]|<[=!]|\(DEFINE\))`;function ho(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function po(e,t,n,r){return e.slice(0,t)+r+e.slice(t+n.length)}var B=Object.freeze({DEFAULT:"DEFAULT",CHAR_CLASS:"CHAR_CLASS"});function je(e,t,n,r){let o=new RegExp(String.raw`${t}|(?<$skip>\[\^?|\\?.)`,"gsu"),s=[!1],a=0,l="";for(let i of e.matchAll(o)){let{0:c,groups:{$skip:u}}=i;if(!u&&(!r||r===B.DEFAULT==!a)){n instanceof Function?l+=n(i,{context:a?B.CHAR_CLASS:B.DEFAULT,negated:s[s.length-1]}):l+=n;continue}c[0]==="["?(a++,s.push(c[1]==="^")):c==="]"&&a&&(a--,s.pop()),l+=c}return l}function dn(e,t,n,r){je(e,t,n,r)}function Qi(e,t,n=0,r){if(!new RegExp(t,"su").test(e))return null;let o=new RegExp(`${t}|(?<$skip>\\\\?.)`,"gsu");o.lastIndex=n;let s=0,a;for(;a=o.exec(e);){let{0:l,groups:{$skip:i}}=a;if(!i&&(!r||r===B.DEFAULT==!s))return a;l==="["?s++:l==="]"&&s&&s--,o.lastIndex==a.index&&o.lastIndex++}return null}function ze(e,t,n){return!!Qi(e,t,0,n)}function fo(e,t){let n=/\\?./gsu;n.lastIndex=t;let r=e.length,o=0,s=1,a;for(;a=n.exec(e);){let[l]=a;if(l==="[")o++;else if(o)l==="]"&&o--;else if(l==="(")s++;else if(l===")"&&(s--,!s)){r=a.index;break}}return e.slice(t,r)}var go=new RegExp(String.raw`(?<noncapturingStart>${uo})|(?<capturingStart>\((?:\?<[^>]+>)?)|\\?.`,"gsu");function mn(e,t){let n=t?.hiddenCaptures??[],r=t?.captureTransfers??new Map;if(!/\(\?>/.test(e))return{pattern:e,captureTransfers:r,hiddenCaptures:n};let o="(?>",s="(?:(?=(",a=[0],l=[],i=0,c=0,u=NaN,h;do{h=!1;let p=0,d=0,f=!1,b;for(go.lastIndex=Number.isNaN(u)?0:u+s.length;b=go.exec(e);){let{0:w,index:m,groups:{capturingStart:C,noncapturingStart:y}}=b;if(w==="[")p++;else if(p)w==="]"&&p--;else if(w===o&&!f)u=m,f=!0;else if(f&&y)d++;else if(C)f?d++:(i++,a.push(i+c));else if(w===")"&&f){if(!d){c++;let _=i+c;if(e=`${e.slice(0,u)}${s}${e.slice(u+o.length,m)}))<$$${_}>)${e.slice(m+1)}`,h=!0,l.push(_),ho(n,_),r.size){let x=new Map;r.forEach((M,O)=>{x.set(O>=_?O+1:O,M.map(H=>H>=_?H+1:H))}),r=x}break}d--}}}while(h);return n.push(...l),e=je(e,String.raw`\\(?<backrefNum>[1-9]\d*)|<\$\$(?<wrappedBackrefNum>\d+)>`,({0:p,groups:{backrefNum:d,wrappedBackrefNum:f}})=>{if(d){let b=+d;if(b>a.length-1)throw new Error(`Backref "${p}" greater than number of captures`);return`\\${a[b]}`}return`\\${f}`},B.DEFAULT),{pattern:e,captureTransfers:r,hiddenCaptures:n}}var mo=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,gn=new RegExp(String.raw`
45\\(?: \d+
46  | c[A-Za-z]
47  | [gk]<[^>]+>
48  | [pPu]\{[^\}]+\}
49  | u[A-Fa-f\d]{4}
50  | x[A-Fa-f\d]{2}
51  )
52| \((?: \? (?: [:=!>]
53  | <(?:[=!]|[^>]+>)
54  | [A-Za-z\-]+:
55  | \(DEFINE\)
56  ))?
57| (?<qBase>${mo})(?<qMod>[?+]?)(?<invalidQ>[?*+\{]?)
58| \\?.
59`.replace(/\s+/g,""),"gsu");function yn(e){if(!new RegExp(`${mo}\\+`).test(e))return{pattern:e};let t=[],n=null,r=null,o="",s=0,a;for(gn.lastIndex=0;a=gn.exec(e);){let{0:l,index:i,groups:{qBase:c,qMod:u,invalidQ:h}}=a;if(l==="[")s||(r=i),s++;else if(l==="]")s?s--:r=null;else if(!s)if(u==="+"&&o&&!o.startsWith("(")){if(h)throw new Error(`Invalid quantifier "${l}"`);let p=-1;if(/^\{\d+\}$/.test(c))e=po(e,i+c.length,u,"");else{if(o===")"||o==="]"){let d=o===")"?n:r;if(d===null)throw new Error(`Invalid unmatched "${o}"`);e=`${e.slice(0,d)}(?>${e.slice(d,i)}${c})${e.slice(i+l.length)}`}else e=`${e.slice(0,i-o.length)}(?>${o}${c})${e.slice(i+l.length)}`;p+=4}gn.lastIndex+=p}else l[0]==="("?t.push(i):l===")"&&(n=t.length?t.pop():null);o=l}return{pattern:e}}var j=String.raw,Ji=j`\\g<(?<gRNameOrNum>[^>&]+)&R=(?<gRDepth>[^>]+)>`,wn=j`\(\?R=(?<rDepth>[^\)]+)\)|${Ji}`,St=j`\(\?<(?![=!])(?<captureName>[^>]+)>`,_o=j`${St}|(?<unnamed>\()(?!\?)`,ye=new RegExp(j`${St}|${wn}|\(\?|\\?.`,"gsu"),bn="Cannot use multiple overlapping recursions";function ko(e,t){let{hiddenCaptures:n,mode:r}={hiddenCaptures:[],mode:"plugin",...t},o=t?.captureTransfers??new Map;if(!new RegExp(wn,"su").test(e))return{pattern:e,captureTransfers:o,hiddenCaptures:n};if(r==="plugin"&&ze(e,j`\(\?\(DEFINE\)`,B.DEFAULT))throw new Error("DEFINE groups cannot be used with recursion");let s=[],a=ze(e,j`\\[1-9]`,B.DEFAULT),l=new Map,i=[],c=!1,u=0,h=0,p;for(ye.lastIndex=0;p=ye.exec(e);){let{0:d,groups:{captureName:f,rDepth:b,gRNameOrNum:w,gRDepth:m}}=p;if(d==="[")u++;else if(u)d==="]"&&u--;else if(b){if(yo(b),c)throw new Error(bn);if(a)throw new Error(`${r==="external"?"Backrefs":"Numbered backrefs"} cannot be used with global recursion`);let C=e.slice(0,p.index),y=e.slice(ye.lastIndex);if(ze(y,wn,B.DEFAULT))throw new Error(bn);let _=+b-1;e=bo(C,y,_,!1,n,s,h),o=Co(o,C,_,s.length,0,h);break}else if(w){yo(m);let C=!1;for(let te of i)if(te.name===w||te.num===+w){if(C=!0,te.hasRecursedWithin)throw new Error(bn);break}if(!C)throw new Error(j`Recursive \g cannot be used outside the referenced group "${r==="external"?w:j`\g<${w}&R=${m}>`}"`);let y=l.get(w),_=fo(e,y);if(a&&ze(_,j`${St}|\((?!\?)`,B.DEFAULT))throw new Error(`${r==="external"?"Backrefs":"Numbered backrefs"} cannot be used with recursion of capturing groups`);let x=e.slice(y,p.index),M=_.slice(x.length+d.length),O=s.length,H=+m-1,He=bo(x,M,H,!0,n,s,h);o=Co(o,x,H,s.length-O,O,h);let It=e.slice(0,y),Ae=e.slice(y+_.length);e=`${It}${He}${Ae}`,ye.lastIndex+=He.length-d.length-x.length-M.length,i.forEach(te=>te.hasRecursedWithin=!0),c=!0}else if(f)h++,l.set(String(h),ye.lastIndex),l.set(f,ye.lastIndex),i.push({num:h,name:f});else if(d[0]==="("){let C=d==="(";C&&(h++,l.set(String(h),ye.lastIndex)),i.push(C?{num:h}:{})}else d===")"&&i.pop()}return n.push(...s),{pattern:e,captureTransfers:o,hiddenCaptures:n}}function yo(e){let t=`Max depth must be integer between 2 and 100; used ${e}`;if(!/^[1-9]\d*$/.test(e))throw new Error(t);if(e=+e,e<2||e>100)throw new Error(t)}function bo(e,t,n,r,o,s,a){let l=new Set;r&&dn(e+t,St,({groups:{captureName:c}})=>{l.add(c)},B.DEFAULT);let i=[n,r?l:null,o,s,a];return`${e}${wo(`(?:${e}`,"forward",...i)}(?:)${wo(`${t})`,"backward",...i)}${t}`}function wo(e,t,n,r,o,s,a){let i=u=>t==="forward"?u+2:n-u+2-1,c="";for(let u=0;u<n;u++){let h=i(u);c+=je(e,j`${_o}|\\k<(?<backref>[^>]+)>`,({0:p,groups:{captureName:d,unnamed:f,backref:b}})=>{if(b&&r&&!r.has(b))return p;let w=`_$${h}`;if(f||d){let m=a+s.length+1;return s.push(m),Yi(o,m),f?p:`(?<${d}${w}>`}return j`\k<${b}${w}>`},B.DEFAULT)}return c}function Yi(e,t){for(let n=0;n<e.length;n++)e[n]>=t&&e[n]++}function Co(e,t,n,r,o,s){if(e.size&&r){let a=0;dn(t,_o,()=>a++,B.DEFAULT);let l=s-a+o,i=new Map;return e.forEach((c,u)=>{let h=(r-a*n)/n,p=a*n,d=u>l+a?u+r:u,f=[];for(let b of c)if(b<=l)f.push(b);else if(b>l+a+h)f.push(b+r);else if(b<=l+a)for(let w=0;w<=n;w++)f.push(b+a*w);else for(let w=0;w<=n;w++)f.push(b+p+h*w);i.set(d,f)}),i}return e}var L=String.fromCodePoint,S=String.raw,z={},vt=globalThis.RegExp;z.flagGroups=(()=>{try{new vt("(?i:)")}catch{return!1}return!0})();z.unicodeSets=(()=>{try{new vt("[[]]","v")}catch{return!1}return!0})();z.bugFlagVLiteralHyphenIsRange=z.unicodeSets?(()=>{try{new vt(S`[\d\-a]`,"v")}catch{return!0}return!1})():!1;z.bugNestedClassIgnoresNegation=z.unicodeSets&&new vt("[[^a]]","v").test("a");function xt(e,{enable:t,disable:n}){return{dotAll:!n?.dotAll&&!!(t?.dotAll||e.dotAll),ignoreCase:!n?.ignoreCase&&!!(t?.ignoreCase||e.ignoreCase)}}function We(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}function xn(e,t){return So[e]>=So[t]}function Zi(e,t){if(e==null)throw new Error(t??"Value expected");return e}var So={ES2025:2025,ES2024:2024,ES2018:2018},el={auto:"auto",ES2025:"ES2025",ES2024:"ES2024",ES2018:"ES2018"};function Io(e={}){if({}.toString.call(e)!=="[object Object]")throw new Error("Unexpected options");if(e.target!==void 0&&!el[e.target])throw new Error(`Unexpected target "${e.target}"`);let t={accuracy:"default",avoidSubclass:!1,flags:"",global:!1,hasIndices:!1,lazyCompileLength:1/0,target:"auto",verbose:!1,...e,rules:{allowOrphanBackrefs:!1,asciiWordBoundaries:!1,captureGroup:!1,recursionLimit:20,singleline:!1,...e.rules}};return t.target==="auto"&&(t.target=z.flagGroups?"ES2025":z.unicodeSets?"ES2024":"ES2018"),t}var tl="[	-\r ]",nl=new Set([L(304),L(305)]),Z=S`[\p{L}\p{M}\p{N}\p{Pc}]`;function Ro(e){if(nl.has(e))return[e];let t=new Set,n=e.toLowerCase(),r=n.toUpperCase(),o=sl.get(n),s=rl.get(n),a=ol.get(n);return[...r].length===1&&t.add(r),a&&t.add(a),o&&t.add(o),t.add(n),s&&t.add(s),[...t]}var An=new Map(`C Other
60Cc Control cntrl
61Cf Format
62Cn Unassigned
63Co Private_Use
64Cs Surrogate
65L Letter
66LC Cased_Letter
67Ll Lowercase_Letter
68Lm Modifier_Letter
69Lo Other_Letter
70Lt Titlecase_Letter
71Lu Uppercase_Letter
72M Mark Combining_Mark
73Mc Spacing_Mark
74Me Enclosing_Mark
75Mn Nonspacing_Mark
76N Number
77Nd Decimal_Number digit
78Nl Letter_Number
79No Other_Number
80P Punctuation punct
81Pc Connector_Punctuation
82Pd Dash_Punctuation
83Pe Close_Punctuation
84Pf Final_Punctuation
85Pi Initial_Punctuation
86Po Other_Punctuation
87Ps Open_Punctuation
88S Symbol
89Sc Currency_Symbol
90Sk Modifier_Symbol
91Sm Math_Symbol
92So Other_Symbol
93Z Separator
94Zl Line_Separator
95Zp Paragraph_Separator
96Zs Space_Separator
97ASCII
98ASCII_Hex_Digit AHex
99Alphabetic Alpha
100Any
101Assigned
102Bidi_Control Bidi_C
103Bidi_Mirrored Bidi_M
104Case_Ignorable CI
105Cased
106Changes_When_Casefolded CWCF
107Changes_When_Casemapped CWCM
108Changes_When_Lowercased CWL
109Changes_When_NFKC_Casefolded CWKCF
110Changes_When_Titlecased CWT
111Changes_When_Uppercased CWU
112Dash
113Default_Ignorable_Code_Point DI
114Deprecated Dep
115Diacritic Dia
116Emoji
117Emoji_Component EComp
118Emoji_Modifier EMod
119Emoji_Modifier_Base EBase
120Emoji_Presentation EPres
121Extended_Pictographic ExtPict
122Extender Ext
123Grapheme_Base Gr_Base
124Grapheme_Extend Gr_Ext
125Hex_Digit Hex
126IDS_Binary_Operator IDSB
127IDS_Trinary_Operator IDST
128ID_Continue IDC
129ID_Start IDS
130Ideographic Ideo
131Join_Control Join_C
132Logical_Order_Exception LOE
133Lowercase Lower
134Math
135Noncharacter_Code_Point NChar
136Pattern_Syntax Pat_Syn
137Pattern_White_Space Pat_WS
138Quotation_Mark QMark
139Radical
140Regional_Indicator RI
141Sentence_Terminal STerm
142Soft_Dotted SD
143Terminal_Punctuation Term
144Unified_Ideograph UIdeo
145Uppercase Upper
146Variation_Selector VS
147White_Space space
148XID_Continue XIDC
149XID_Start XIDS`.split(/\s/).map(e=>[ke(e),e])),rl=new Map([["s",L(383)],[L(383),"s"]]),ol=new Map([[L(223),L(7838)],[L(107),L(8490)],[L(229),L(8491)],[L(969),L(8486)]]),sl=new Map([ae(453),ae(456),ae(459),ae(498),...Cn(8072,8079),...Cn(8088,8095),...Cn(8104,8111),ae(8124),ae(8140),ae(8188)]),al=new Map([["alnum",S`[\p{Alpha}\p{Nd}]`],["alpha",S`\p{Alpha}`],["ascii",S`\p{ASCII}`],["blank",S`[\p{Zs}\t]`],["cntrl",S`\p{Cc}`],["digit",S`\p{Nd}`],["graph",S`[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]`],["lower",S`\p{Lower}`],["print",S`[[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]\p{Zs}]`],["punct",S`[\p{P}\p{S}]`],["space",S`\p{space}`],["upper",S`\p{Upper}`],["word",S`[\p{Alpha}\p{M}\p{Nd}\p{Pc}]`],["xdigit",S`\p{AHex}`]]);function il(e,t){let n=[];for(let r=e;r<=t;r++)n.push(r);return n}function ae(e){let t=L(e);return[t.toLowerCase(),t]}function Cn(e,t){return il(e,t).map(n=>ae(n))}var No=new Set(["Lower","Lowercase","Upper","Uppercase","Ll","Lowercase_Letter","Lt","Titlecase_Letter","Lu","Uppercase_Letter"]);function ll(e,t){let n={accuracy:"default",asciiWordBoundaries:!1,avoidSubclass:!1,bestEffortTarget:"ES2025",...t};Lo(e);let r={accuracy:n.accuracy,asciiWordBoundaries:n.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,flagDirectivesByAlt:new Map,jsGroupNameMap:new Map,minTargetEs2024:xn(n.bestEffortTarget,"ES2024"),passedLookbehind:!1,strategy:null,subroutineRefMap:new Map,supportedGNodes:new Set,digitIsAscii:e.flags.digitIsAscii,spaceIsAscii:e.flags.spaceIsAscii,wordIsAscii:e.flags.wordIsAscii};me(e,cl,r);let o={dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},s={currentFlags:o,prevFlags:null,globalFlags:o,groupOriginByCopy:new Map,groupsByName:new Map,multiplexCapturesToLeftByRef:new Map,openRefs:new Map,reffedNodesByReferencer:new Map,subroutineRefMap:r.subroutineRefMap};me(e,ul,s);let a={groupsByName:s.groupsByName,highestOrphanBackref:0,numCapturesToLeft:0,reffedNodesByReferencer:s.reffedNodesByReferencer};return me(e,hl,a),e._originMap=s.groupOriginByCopy,e._strategy=r.strategy,e}var cl={AbsenceFunction({node:e,parent:t,replaceWith:n}){let{body:r,kind:o}=e;if(o==="repeater"){let s=D();s.body[0].body.push(se({negate:!0,body:r}),ge("Any"));let a=D();a.body[0].body.push(pn("greedy",0,1/0,s)),n(R(a,t),{traverse:!0})}else throw new Error('Unsupported absence function "(?~|"')},Alternative:{enter({node:e,parent:t,key:n},{flagDirectivesByAlt:r}){let o=e.body.filter(s=>s.kind==="flags");for(let s=n+1;s<t.body.length;s++){let a=t.body[s];We(r,a,[]).push(...o)}},exit({node:e},{flagDirectivesByAlt:t}){if(t.get(e)?.length){let n=Po(t.get(e));if(n){let r=D({flags:n});r.body[0].body=e.body,e.body=[R(r,e)]}}}},Assertion({node:e,parent:t,key:n,container:r,root:o,remove:s,replaceWith:a},l){let{kind:i,negate:c}=e,{asciiWordBoundaries:u,avoidSubclass:h,supportedGNodes:p,wordIsAscii:d}=l;if(i==="text_segment_boundary")throw new Error(`Unsupported text segment boundary "\\${c?"Y":"y"}"`);if(i==="line_end")a(R(se({body:[Y({body:[Ct("string_end")]}),Y({body:[_e(10)]})]}),t));else if(i==="line_start")a(R(ee(S`(?<=\A|\n(?!\z))`,{skipLookbehindValidation:!0}),t));else if(i==="search_start")if(p.has(e))o.flags.sticky=!0,s();else{let f=r[n-1];if(f&&yl(f))a(R(se({negate:!0}),t));else{if(h)throw new Error(S`Uses "\G" in a way that requires a subclass`);a(ie(Ct("string_start"),t)),l.strategy="clip_search"}}else if(!(i==="string_end"||i==="string_start"))if(i==="string_end_newline")a(R(ee(S`(?=\n?\z)`),t));else if(i==="word_boundary"){if(!d&&!u){let f=`(?:(?<=${Z})(?!${Z})|(?<!${Z})(?=${Z}))`,b=`(?:(?<=${Z})(?=${Z})|(?<!${Z})(?!${Z}))`;a(R(ee(c?b:f),t))}}else throw new Error(`Unexpected assertion kind "${i}"`)},Backreference({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n=="string"&&!kn(n)&&(n=_n(n,t),e.ref=n)},CapturingGroup({node:e},{jsGroupNameMap:t,subroutineRefMap:n}){let{name:r}=e;r&&!kn(r)&&(r=_n(r,t),e.name=r),n.set(e.number,e),r&&n.set(r,e)},CharacterClassRange({node:e,parent:t,replaceWith:n}){if(t.kind==="intersection"){let r=Fe({body:[e]});n(R(r,t),{traverse:!0})}},CharacterSet({node:e,parent:t,replaceWith:n},{accuracy:r,minTargetEs2024:o,digitIsAscii:s,spaceIsAscii:a,wordIsAscii:l}){let{kind:i,negate:c,value:u}=e;if(s&&(i==="digit"||u==="digit")){n(ie(_t("digit",{negate:c}),t));return}if(a&&(i==="space"||u==="space")){n(R(Sn(ee(tl),c),t));return}if(l&&(i==="word"||u==="word")){n(ie(_t("word",{negate:c}),t));return}if(i==="any")n(ie(ge("Any"),t));else if(i==="digit")n(ie(ge("Nd",{negate:c}),t));else if(i!=="dot")if(i==="text_segment"){if(r==="strict")throw new Error(S`Use of "\X" requires non-strict accuracy`);let h="\\p{Emoji}(?:\\p{EMod}|\\uFE0F\\u20E3?|[\\x{E0020}-\\x{E007E}]+\\x{E007F})?",p=S`\p{RI}{2}|${h}(?:\u200D${h})*`;n(R(ee(S`(?>\r\n|${o?S`\p{RGI_Emoji}`:p}|\P{M}\p{M}*)`,{skipPropertyNameValidation:!0}),t))}else if(i==="hex")n(ie(ge("AHex",{negate:c}),t));else if(i==="newline")n(R(ee(c?`[^
150]`:`(?>\r
151?|[
152\v\f\x85\u2028\u2029])`),t));else if(i==="posix")if(!o&&(u==="graph"||u==="print")){if(r==="strict")throw new Error(`POSIX class "${u}" requires min target ES2024 or non-strict accuracy`);let h={graph:"!-~",print:" -~"}[u];c&&(h=`\0-${L(h.codePointAt(0)-1)}${L(h.codePointAt(2)+1)}-\u{10FFFF}`),n(R(ee(`[${h}]`),t))}else n(R(Sn(ee(al.get(u)),c),t));else if(i==="property")An.has(ke(u))||(e.key="sc");else if(i==="space")n(ie(ge("space",{negate:c}),t));else if(i==="word")n(R(Sn(ee(Z),c),t));else throw new Error(`Unexpected character set kind "${i}"`)},Directive({node:e,parent:t,root:n,remove:r,replaceWith:o,removeAllPrevSiblings:s,removeAllNextSiblings:a}){let{kind:l,flags:i}=e;if(l==="flags")if(!i.enable&&!i.disable)r();else{let c=D({flags:i});c.body[0].body=a(),o(R(c,t),{traverse:!0})}else if(l==="keep"){let c=n.body[0],h=n.body.length===1&&yt(c,{type:"Group"})&&c.body[0].body.length===1?c.body[0]:n;if(t.parent!==h||h.body.length>1)throw new Error(S`Uses "\K" in a way that's unsupported`);let p=se({behind:!0});p.body[0].body=s(),o(R(p,t))}else throw new Error(`Unexpected directive kind "${l}"`)},Flags({node:e,parent:t}){if(e.posixIsAscii)throw new Error('Unsupported flag "P"');if(e.textSegmentMode==="word")throw new Error('Unsupported flag "y{w}"');["digitIsAscii","extended","posixIsAscii","spaceIsAscii","wordIsAscii","textSegmentMode"].forEach(n=>delete e[n]),Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;let{enable:t,disable:n}=e.flags;t?.extended&&delete t.extended,n?.extended&&delete n.extended,t?.dotAll&&n?.dotAll&&delete t.dotAll,t?.ignoreCase&&n?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,n&&!Object.keys(n).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},LookaroundAssertion({node:e},t){let{kind:n}=e;n==="lookbehind"&&(t.passedLookbehind=!0)},NamedCallout({node:e,parent:t,replaceWith:n}){let{kind:r}=e;if(r==="fail")n(R(se({negate:!0}),t));else throw new Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type==="Quantifier"){let t=D();t.body[0].body.push(e.body),e.body=R(t,e)}},Regex:{enter({node:e},{supportedGNodes:t}){let n=[],r=!1,o=!1;for(let s of e.body)if(s.body.length===1&&s.body[0].kind==="search_start")s.body.pop();else{let a=Mo(s.body);a?(r=!0,Array.isArray(a)?n.push(...a):n.push(a)):o=!0}r&&!o&&n.forEach(s=>t.add(s))},exit(e,{accuracy:t,passedLookbehind:n,strategy:r}){if(t==="strict"&&n&&r)throw new Error(S`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n=="string"&&!kn(n)&&(n=_n(n,t),e.ref=n)}},ul={Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByReferencer:n}){let{orphan:r,ref:o}=e;r||n.set(e,[...t.get(o).map(({node:s})=>s)])},CapturingGroup:{enter({node:e,parent:t,replaceWith:n,skip:r},{groupOriginByCopy:o,groupsByName:s,multiplexCapturesToLeftByRef:a,openRefs:l,reffedNodesByReferencer:i}){let c=o.get(e);if(c&&l.has(e.number)){let h=ie(xo(e.number),t);i.set(h,l.get(e.number)),n(h);return}l.set(e.number,e),a.set(e.number,[]),e.name&&We(a,e.name,[]);let u=a.get(e.name??e.number);for(let h=0;h<u.length;h++){let p=u[h];if(c===p.node||c&&c===p.origin||e===p.origin){u.splice(h,1);break}}if(a.get(e.number).push({node:e,origin:c}),e.name&&a.get(e.name).push({node:e,origin:c}),e.name){let h=We(s,e.name,new Map),p=!1;if(c)p=!0;else for(let d of h.values())if(!d.hasDuplicateNameToRemove){p=!0;break}s.get(e.name).set(e,{node:e,hasDuplicateNameToRemove:p})}},exit({node:e},{openRefs:t}){t.get(e.number)===e&&t.delete(e.number)}},Group:{enter({node:e},t){t.prevFlags=t.currentFlags,e.flags&&(t.currentFlags=xt(t.currentFlags,e.flags))},exit(e,t){t.currentFlags=t.prevFlags}},Subroutine({node:e,parent:t,replaceWith:n},r){let{isRecursive:o,ref:s}=e;if(o){let u=t;for(;(u=u.parent)&&!(u.type==="CapturingGroup"&&(u.name===s||u.number===s)););r.reffedNodesByReferencer.set(e,u);return}let a=r.subroutineRefMap.get(s),l=s===0,i=l?xo(0):To(a,r.groupOriginByCopy,null),c=i;if(!l){let u=Po(dl(a,p=>p.type==="Group"&&!!p.flags)),h=u?xt(r.globalFlags,u):r.globalFlags;pl(h,r.currentFlags)||(c=D({flags:gl(h)}),c.body[0].body.push(i))}n(R(c,t),{traverse:!l})}},hl={Backreference({node:e,parent:t,replaceWith:n},r){if(e.orphan){r.highestOrphanBackref=Math.max(r.highestOrphanBackref,e.ref);return}let s=r.reffedNodesByReferencer.get(e).filter(a=>fl(a,e));if(!s.length)n(R(se({negate:!0}),t));else if(s.length>1){let a=D({atomic:!0,body:s.reverse().map(l=>Y({body:[bt(l.number)]}))});n(R(a,t))}else e.ref=s[0].number},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,e.name&&t.groupsByName.get(e.name).get(e).hasDuplicateNameToRemove&&delete e.name},Regex:{exit({node:e},t){let n=Math.max(t.highestOrphanBackref-t.numCapturesToLeft,0);for(let r=0;r<n;r++){let o=hn();e.body.at(-1).body.push(o)}}},Subroutine({node:e},t){!e.isRecursive||e.ref===0||(e.ref=t.reffedNodesByReferencer.get(e).number)}};function Lo(e){me(e,{"*"({node:t,parent:n}){t.parent=n}})}function pl(e,t){return e.dotAll===t.dotAll&&e.ignoreCase===t.ignoreCase}function fl(e,t){let n=t;do{if(n.type==="Regex")return!1;if(n.type==="Alternative")continue;if(n===e)return!1;let r=$o(n.parent);for(let o of r){if(o===n)break;if(o===e||Oo(o,e))return!0}}while(n=n.parent);throw new Error("Unexpected path")}function To(e,t,n,r){let o=Array.isArray(e)?[]:{};for(let[s,a]of Object.entries(e))s==="parent"?o.parent=Array.isArray(n)?r:n:a&&typeof a=="object"?o[s]=To(a,t,o,n):(s==="type"&&a==="CapturingGroup"&&t.set(o,t.get(e)??e),o[s]=a);return o}function xo(e){let t=fn(e);return t.isRecursive=!0,t}function dl(e,t){let n=[];for(;e=e.parent;)(!t||t(e))&&n.push(e);return n}function _n(e,t){if(t.has(e))return t.get(e);let n=`$${t.size}_${e.replace(/^[^$_\p{IDS}]|[^$\u200C\u200D\p{IDC}]/ug,"_")}`;return t.set(e,n),n}function Po(e){let t=["dotAll","ignoreCase"],n={enable:{},disable:{}};return e.forEach(({flags:r})=>{t.forEach(o=>{r.enable?.[o]&&(delete n.disable[o],n.enable[o]=!0),r.disable?.[o]&&(n.disable[o]=!0)})}),Object.keys(n.enable).length||delete n.enable,Object.keys(n.disable).length||delete n.disable,n.enable||n.disable?n:null}function gl({dotAll:e,ignoreCase:t}){let n={};return(e||t)&&(n.enable={},e&&(n.enable.dotAll=!0),t&&(n.enable.ignoreCase=!0)),(!e||!t)&&(n.disable={},!e&&(n.disable.dotAll=!0),!t&&(n.disable.ignoreCase=!0)),n}function $o(e){if(!e)throw new Error("Node expected");let{body:t}=e;return Array.isArray(t)?t:t?[t]:null}function Mo(e){let t=e.find(n=>n.kind==="search_start"||bl(n,{negate:!1})||!ml(n));if(!t)return null;if(t.kind==="search_start")return t;if(t.type==="LookaroundAssertion")return t.body[0].body[0];if(t.type==="CapturingGroup"||t.type==="Group"){let n=[];for(let r of t.body){let o=Mo(r.body);if(!o)return null;Array.isArray(o)?n.push(...o):n.push(o)}return n}return null}function Oo(e,t){let n=$o(e)??[];for(let r of n)if(r===t||Oo(r,t))return!0;return!1}function ml({type:e}){return e==="Assertion"||e==="Directive"||e==="LookaroundAssertion"}function yl(e){let t=["Character","CharacterClass","CharacterSet"];return t.includes(e.type)||e.type==="Quantifier"&&e.min&&t.includes(e.body.type)}function bl(e,t){let n={negate:null,...t};return e.type==="LookaroundAssertion"&&(n.negate===null||e.negate===n.negate)&&e.body.length===1&&yt(e.body[0],{type:"Assertion",kind:"search_start"})}function kn(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function ee(e,t){let r=wt(e,{...t,unicodePropertyMap:An}).body;return r.length>1||r[0].body.length>1?D({body:r}):r[0].body[0]}function Sn(e,t){return e.negate=t,e}function ie(e,t){return e.parent=t,e}function R(e,t){return Lo(e),e.parent=t,e}function wl(e,t){let n=Io(t),r=xn(n.target,"ES2024"),o=xn(n.target,"ES2025"),s=n.rules.recursionLimit;if(!Number.isInteger(s)||s<2||s>20)throw new Error("Invalid recursionLimit; use 2-20");let a=null,l=null;if(!o){let d=[e.flags.ignoreCase];me(e,Cl,{getCurrentModI:()=>d.at(-1),popModI(){d.pop()},pushModI(f){d.push(f)},setHasCasedChar(){d.at(-1)?a=!0:l=!0}})}let i={dotAll:e.flags.dotAll,ignoreCase:!!((e.flags.ignoreCase||a)&&!l)},c=e,u={accuracy:n.accuracy,appliedGlobalFlags:i,captureMap:new Map,currentFlags:{dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},inCharClass:!1,lastNode:c,originMap:e._originMap,recursionLimit:s,useAppliedIgnoreCase:!!(!o&&a&&l),useFlagMods:o,useFlagV:r,verbose:n.verbose};function h(d){return u.lastNode=c,c=d,Zi(_l[d.type],`Unexpected node type "${d.type}"`)(d,u,h)}let p={pattern:e.body.map(h).join("|"),flags:h(e.flags),options:{...e.options}};return r||(delete p.options.force.v,p.options.disable.v=!0,p.options.unicodeSetsPlugin=null),p._captureTransfers=new Map,p._hiddenCaptures=[],u.captureMap.forEach((d,f)=>{d.hidden&&p._hiddenCaptures.push(f),d.transferTo&&We(p._captureTransfers,d.transferTo,[]).push(f)}),p}var Cl={"*":{enter({node:e},t){if(Ao(e)){let n=t.getCurrentModI();t.pushModI(e.flags?xt({ignoreCase:n},e.flags).ignoreCase:n)}},exit({node:e},t){Ao(e)&&t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){En(L(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},n){t(),Go(e,{firstOnly:!0}).length&&n.setHasCasedChar()},CharacterSet({node:e},t){e.kind==="property"&&No.has(e.value)&&t.setHasCasedChar()}},_l={Alternative({body:e},t,n){return e.map(n).join("")},Assertion({kind:e,negate:t}){if(e==="string_end")return"$";if(e==="string_start")return"^";if(e==="word_boundary")return t?S`\B`:S`\b`;throw new Error(`Unexpected assertion kind "${e}"`)},Backreference({ref:e},t){if(typeof e!="number")throw new Error("Unexpected named backref in transformed AST");if(!t.useFlagMods&&t.accuracy==="strict"&&t.currentFlags.ignoreCase&&!t.captureMap.get(e).ignoreCase)throw new Error("Use of case-insensitive backref to case-sensitive group requires target ES2025 or non-strict accuracy");return"\\"+e},CapturingGroup(e,t,n){let{body:r,name:o,number:s}=e,a={ignoreCase:t.currentFlags.ignoreCase},l=t.originMap.get(e);return l&&(a.hidden=!0,s>l.number&&(a.transferTo=l.number)),t.captureMap.set(s,a),`(${o?`?<${o}>`:""}${r.map(n).join("|")})`},Character({value:e},t){let n=L(e),r=xe(e,{escDigit:t.lastNode.type==="Backreference",inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(r!==n)return r;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&En(n)){let o=Ro(n);return t.inCharClass?o.join(""):o.length>1?`[${o.join("")}]`:o[0]}return n},CharacterClass(e,t,n){let{kind:r,negate:o,parent:s}=e,{body:a}=e;if(r==="intersection"&&!t.useFlagV)throw new Error("Use of character class intersection requires min target ES2024");z.bugFlagVLiteralHyphenIsRange&&t.useFlagV&&a.some(Eo)&&(a=[_e(45),...a.filter(c=>!Eo(c))]);let l=()=>`[${o?"^":""}${a.map(n).join(r==="intersection"?"&&":"")}]`;if(!t.inCharClass){if((!t.useFlagV||z.bugNestedClassIgnoresNegation)&&!o){let u=a.filter(h=>h.type==="CharacterClass"&&h.kind==="union"&&h.negate);if(u.length){let h=D(),p=h.body[0];return h.parent=s,p.parent=h,a=a.filter(d=>!u.includes(d)),e.body=a,a.length?(e.parent=p,p.body.push(e)):h.body.pop(),u.forEach(d=>{let f=Y({body:[d]});d.parent=f,f.parent=h,h.body.push(f)}),n(h)}}t.inCharClass=!0;let c=l();return t.inCharClass=!1,c}let i=a[0];if(r==="union"&&!o&&i&&((!t.useFlagV||!t.verbose)&&s.kind==="union"&&!(z.bugFlagVLiteralHyphenIsRange&&t.useFlagV)||!t.verbose&&s.kind==="intersection"&&a.length===1&&i.type!=="CharacterClassRange"))return a.map(n).join("");if(!t.useFlagV&&s.type==="CharacterClass")throw new Error("Uses nested character class in a way that requires min target ES2024");return l()},CharacterClassRange(e,t){let n=e.min.value,r=e.max.value,o={escDigit:!1,inCharClass:!0,useFlagV:t.useFlagV},s=xe(n,o),a=xe(r,o),l=new Set;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase){let i=Go(e);Al(i).forEach(u=>{l.add(Array.isArray(u)?`${xe(u[0],o)}-${xe(u[1],o)}`:xe(u,o))})}return`${s}-${a}${[...l].join("")}`},CharacterSet({kind:e,negate:t,value:n,key:r},o){if(e==="dot")return o.currentFlags.dotAll?o.appliedGlobalFlags.dotAll||o.useFlagMods?".":"[^]":S`[^\n]`;if(e==="digit")return t?S`\D`:S`\d`;if(e==="property"){if(o.useAppliedIgnoreCase&&o.currentFlags.ignoreCase&&No.has(n))throw new Error(`Unicode property "${n}" can't be case-insensitive when other chars have specific case`);return`${t?S`\P`:S`\p`}{${r?`${r}=`:""}${n}}`}if(e==="word")return t?S`\W`:S`\w`;throw new Error(`Unexpected character set kind "${e}"`)},Flags(e,t){return(t.appliedGlobalFlags.ignoreCase?"i":"")+(e.dotAll?"s":"")+(e.sticky?"y":"")},Group({atomic:e,body:t,flags:n,parent:r},o,s){let a=o.currentFlags;n&&(o.currentFlags=xt(a,n));let l=t.map(s).join("|"),i=!o.verbose&&t.length===1&&r.type!=="Quantifier"&&!e&&(!o.useFlagMods||!n)?l:`(?${El(e,n,o.useFlagMods)}${l})`;return o.currentFlags=a,i},LookaroundAssertion({body:e,kind:t,negate:n},r,o){return`(?${`${t==="lookahead"?"":"<"}${n?"!":"="}`}${e.map(o).join("|")})`},Quantifier(e,t,n){return n(e.body)+Il(e)},Subroutine({isRecursive:e,ref:t},n){if(!e)throw new Error("Unexpected non-recursive subroutine in transformed AST");let r=n.recursionLimit;return t===0?`(?R=${r})`:S`\g<${t}&R=${r}>`}},kl=new Set(["$","(",")","*","+",".","?","[","\\","]","^","{","|","}"]),Sl=new Set(["-","\\","]","^","["]),xl=new Set(["(",")","-","/","[","\\","]","^","{","|","}","!","#","$","%","&","*","+",",",".",":",";","<","=",">","?","@","`","~"]),vo=new Map([[9,S`\t`],[10,S`\n`],[11,S`\v`],[12,S`\f`],[13,S`\r`],[8232,S`\u2028`],[8233,S`\u2029`],[65279,S`\uFEFF`]]),vl=/^\p{Cased}$/u;function En(e){return vl.test(e)}function Go(e,t){let n=!!t?.firstOnly,r=e.min.value,o=e.max.value,s=[];if(r<65&&(o===65535||o>=131071)||r===65536&&o>=131071)return s;for(let a=r;a<=o;a++){let l=L(a);if(!En(l))continue;let i=Ro(l).filter(c=>{let u=c.codePointAt(0);return u<r||u>o});if(i.length&&(s.push(...i),n))break}return s}function xe(e,{escDigit:t,inCharClass:n,useFlagV:r}){if(vo.has(e))return vo.get(e);if(e<32||e>126&&e<160||e>262143||t&&Rl(e))return e>255?`\\u{${e.toString(16).toUpperCase()}}`:`\\x${e.toString(16).toUpperCase().padStart(2,"0")}`;let o=n?r?xl:Sl:kl,s=L(e);return(o.has(s)?"\\":"")+s}function Al(e){let t=e.map(o=>o.codePointAt(0)).sort((o,s)=>o-s),n=[],r=null;for(let o=0;o<t.length;o++)t[o+1]===t[o]+1?r??=t[o]:r===null?n.push(t[o]):(n.push([r,t[o]]),r=null);return n}function El(e,t,n){if(e)return">";let r="";if(t&&n){let{enable:o,disable:s}=t;r=(o?.ignoreCase?"i":"")+(o?.dotAll?"s":"")+(s?"-":"")+(s?.ignoreCase?"i":"")+(s?.dotAll?"s":"")}return`${r}:`}function Il({kind:e,max:t,min:n}){let r;return!n&&t===1?r="?":!n&&t===1/0?r="*":n===1&&t===1/0?r="+":n===t?r=`{${n}}`:r=`{${n},${t===1/0?"":t}}`,r+{greedy:"",lazy:"?",possessive:"+"}[e]}function Ao({type:e}){return e==="CapturingGroup"||e==="Group"||e==="LookaroundAssertion"}function Rl(e){return e>47&&e<58}function Eo({type:e,value:t}){return e==="Character"&&t===45}var Nl=class vn extends RegExp{#t=new Map;#e=null;#r;#n=null;#o=null;rawOptions={};get source(){return this.#r||"(?:)"}constructor(t,n,r){let o=!!r?.lazyCompile;if(t instanceof RegExp){if(r)throw new Error("Cannot provide options when copying a regexp");let s=t;super(s,n),this.#r=s.source,s instanceof vn&&(this.#t=s.#t,this.#n=s.#n,this.#o=s.#o,this.rawOptions=s.rawOptions)}else{let s={hiddenCaptures:[],strategy:null,transfers:[],...r};super(o?"":t,n),this.#r=t,this.#t=Tl(s.hiddenCaptures,s.transfers),this.#o=s.strategy,this.rawOptions=r??{}}o||(this.#e=this)}exec(t){if(!this.#e){let{lazyCompile:o,...s}=this.rawOptions;this.#e=new vn(this.#r,this.flags,s)}let n=this.global||this.sticky,r=this.lastIndex;if(this.#o==="clip_search"&&n&&r){this.lastIndex=0;let o=this.#s(t.slice(r));return o&&(Ll(o,r,t,this.hasIndices),this.lastIndex+=r),o}return this.#s(t)}#s(t){this.#e.lastIndex=this.lastIndex;let n=super.exec.call(this.#e,t);if(this.lastIndex=this.#e.lastIndex,!n||!this.#t.size)return n;let r=[...n];n.length=1;let o;this.hasIndices&&(o=[...n.indices],n.indices.length=1);let s=[0];for(let a=1;a<r.length;a++){let{hidden:l,transferTo:i}=this.#t.get(a)??{};if(l?s.push(null):(s.push(n.length),n.push(r[a]),this.hasIndices&&n.indices.push(o[a])),i&&r[a]!==void 0){let c=s[i];if(!c)throw new Error(`Invalid capture transfer to "${c}"`);if(n[c]=r[a],this.hasIndices&&(n.indices[c]=o[a]),n.groups){this.#n||(this.#n=Pl(this.source));let u=this.#n.get(i);u&&(n.groups[u]=r[a],this.hasIndices&&(n.indices.groups[u]=o[a]))}}}return n}};function Ll(e,t,n,r){if(e.index+=t,e.input=n,r){let o=e.indices;for(let a=0;a<o.length;a++){let l=o[a];l&&(o[a]=[l[0]+t,l[1]+t])}let s=o.groups;s&&Object.keys(s).forEach(a=>{let l=s[a];l&&(s[a]=[l[0]+t,l[1]+t])})}}function Tl(e,t){let n=new Map;for(let r of e)n.set(r,{hidden:!0});for(let[r,o]of t)for(let s of o)We(n,s,{}).transferTo=r;return n}function Pl(e){let t=/(?<capture>\((?:\?<(?![=!])(?<name>[^>]+)>|(?!\?)))|\\?./gsu,n=new Map,r=0,o=0,s;for(;s=t.exec(e);){let{0:a,groups:{capture:l,name:i}}=s;a==="["?r++:r?a==="]"&&r--:l&&(o++,i&&n.set(o,i))}return n}function Bo(e,t){let n=$l(e,t);return n.options?new Nl(n.pattern,n.flags,n.options):new RegExp(n.pattern,n.flags)}function $l(e,t){let n=Io(t),r=wt(e,{flags:n.flags,normalizeUnknownPropertyNames:!0,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline},skipBackrefValidation:n.rules.allowOrphanBackrefs,unicodePropertyMap:An}),o=ll(r,{accuracy:n.accuracy,asciiWordBoundaries:n.rules.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,bestEffortTarget:n.target}),s=wl(o,n),a=ko(s.pattern,{captureTransfers:s._captureTransfers,hiddenCaptures:s._hiddenCaptures,mode:"external"}),l=yn(a.pattern),i=mn(l.pattern,{captureTransfers:a.captureTransfers,hiddenCaptures:a.hiddenCaptures}),c={pattern:i.pattern,flags:`${n.hasIndices?"d":""}${n.global?"g":""}${s.flags}${s.options.disable.v?"u":"v"}`};if(n.avoidSubclass){if(n.lazyCompileLength!==1/0)throw new Error("Lazy compilation requires subclass")}else{let u=i.hiddenCaptures.sort((f,b)=>f-b),h=Array.from(i.captureTransfers),p=o._strategy,d=c.pattern.length>=n.lazyCompileLength;(u.length||h.length||p||d)&&(c.options={...u.length&&{hiddenCaptures:u},...h.length&&{transfers:h},...p&&{strategy:p},...d&&{lazyCompile:d}})}return c}var At=class{constructor(t,n={}){this.patterns=t,this.options=n;let{forgiving:r=!1,cache:o,regexConstructor:s}=n;if(!s)throw new Error("Option `regexConstructor` is not provided");this.regexps=t.map(a=>{if(typeof a!="string")return a;let l=o?.get(a);if(l){if(l instanceof RegExp)return l;if(r)return null;throw l}try{let i=s(a);return o?.set(a,i),i}catch(i){if(o?.set(a,i),r)return null;throw i}})}regexps;findNextMatchSync(t,n,r){let o=typeof t=="string"?t:t.content,s=[];function a(l,i,c=0){return{index:l,captureIndices:i.indices.map(u=>u==null?{start:4294967295,end:4294967295,length:0}:{start:u[0]+c,end:u[1]+c,length:u[1]-u[0]})}}for(let l=0;l<this.regexps.length;l++){let i=this.regexps[l];if(i)try{i.lastIndex=n;let c=i.exec(o);if(!c)continue;if(c.index===n)return a(l,c,0);s.push([l,c,0])}catch(c){if(this.options.forgiving)continue;throw c}}if(s.length){let l=Math.min(...s.map(i=>i[1].index));for(let[i,c,u]of s)if(c.index===l)return a(i,c,u)}return null}};function Do(e,t){return Bo(e,{global:!0,hasIndices:!0,lazyCompileLength:3e3,rules:{allowOrphanBackrefs:!0,asciiWordBoundaries:!0,captureGroup:!0,recursionLimit:5,singleline:!0},...t})}function In(e={}){let t=Object.assign({target:"auto",cache:new Map},e);return t.regexConstructor||=n=>Do(n,{target:t.target}),{createScanner(n){return new At(n,t)},createString(n){return{content:n}}}}import Ml from"./langs/astro.mjs";import Ol from"./langs/blade.mjs";import Gl from"./langs/c.mjs";import Bl from"./langs/cpp.mjs";import Dl from"./langs/csharp.mjs";import Fl from"./langs/css.mjs";import Ul from"./langs/diff.mjs";import jl from"./langs/dockerfile.mjs";import zl from"./langs/go.mjs";import Wl from"./langs/graphql.mjs";import Hl from"./langs/hcl.mjs";import ql from"./langs/html.mjs";import Vl from"./langs/ini.mjs";import Xl from"./langs/java.mjs";import Kl from"./langs/javascript.mjs";import Ql from"./langs/json.mjs";import Jl from"./langs/jsonc.mjs";import Yl from"./langs/jsx.mjs";import Zl from"./langs/kotlin.mjs";import ec from"./langs/less.mjs";import tc from"./langs/lua.mjs";import nc from"./langs/make.mjs";import rc from"./langs/markdown.mjs";import oc from"./langs/php.mjs";import sc from"./langs/powershell.mjs";import ac from"./langs/python.mjs";import ic from"./langs/ruby.mjs";import lc from"./langs/rust.mjs";import cc from"./langs/scss.mjs";import uc from"./langs/shellscript.mjs";import hc from"./langs/sql.mjs";import pc from"./langs/svelte.mjs";import fc from"./langs/swift.mjs";import dc from"./langs/toml.mjs";import gc from"./langs/tsx.mjs";import mc from"./langs/typescript.mjs";import yc from"./langs/vue.mjs";import bc from"./langs/xml.mjs";import wc from"./langs/yaml.mjs";var Fo=[Ml,Ol,Gl,Bl,Dl,Fl,Ul,jl,zl,Wl,Hl,ql,Vl,Xl,Kl,Ql,Jl,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,uc,hc,pc,fc,dc,gc,mc,yc,bc,wc];import Cc from"./themes/neon-bunny.mjs";import _c from"./themes/neon-bunny-carrot.mjs";import kc from"./themes/ayu-dark.mjs";import Sc from"./themes/ayu-light.mjs";import xc from"./themes/catppuccin-latte.mjs";import vc from"./themes/catppuccin-mocha.mjs";import Ac from"./themes/dracula.mjs";import Ec from"./themes/everforest-dark.mjs";import Ic from"./themes/everforest-light.mjs";import Rc from"./themes/github-dark.mjs";import Nc from"./themes/github-light.mjs";import Lc from"./themes/gruvbox-dark-medium.mjs";import Tc from"./themes/gruvbox-light-medium.mjs";import Pc from"./themes/kanagawa-lotus.mjs";import $c from"./themes/kanagawa-wave.mjs";import Mc from"./themes/min-dark.mjs";import Oc from"./themes/min-light.mjs";import Gc from"./themes/night-owl.mjs";import Bc from"./themes/night-owl-light.mjs";import Dc from"./themes/nord.mjs";import Fc from"./themes/one-dark-pro.mjs";import Uc from"./themes/one-light.mjs";import jc from"./themes/rose-pine.mjs";import zc from"./themes/rose-pine-dawn.mjs";import Wc from"./themes/solarized-dark.mjs";import Hc from"./themes/solarized-light.mjs";import qc from"./themes/tokyo-night.mjs";import Vc from"./themes/vitesse-black.mjs";import Xc from"./themes/vitesse-light.mjs";var Uo=[Cc,_c,kc,Sc,xc,vc,Ac,Ec,Ic,Rc,Nc,Lc,Tc,Pc,$c,Mc,Oc,Gc,Bc,Dc,Fc,Uc,jc,zc,Wc,Hc,qc,Vc,Xc];var jo=/(^|\s)text\.html\.php(?=\s|$)/;function zo(e){let t=(e.tokenColors??e.settings??[]).map(n=>{if(n.scope===void 0)return n;let r=(Array.isArray(n.scope)?n.scope:n.scope.split(",")).map(s=>s.trim()),o=r.filter(s=>jo.test(s)).map(s=>s.replace(new RegExp(jo,"g"),"$1source.php"));return o.length===0?n:{...n,scope:[...r,...o]}});return{...e,tokenColors:t}}var Wo=Uo.map(zo),ve=new Map(Wo.map(e=>[e.name,e])),Kd=()=>[...ve.keys()].sort(),Qd=e=>ve.has(e),Jd=e=>ve.get(e)?.displayName??e;function Yd(e){let t=e.replace(/("(?:[^"\\]|\\.)*")|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g,(n,r)=>r??"").replace(/,(\s*[}\]])/g,"$1");return JSON.parse(t)}function Zd(e){if(e===null||typeof e!="object"||!Array.isArray(e.tokenColors??e.settings))throw new Error("A theme needs a tokenColors list, as a VS Code theme file has");let t=String(e.name??"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");if(t==="")throw new Error("A theme needs a name");let n=e.type==="light"||e.type==="hc-light"?"light":"dark",r=String(e.displayName??e.name??t),o=zo({...e,name:t,displayName:r,type:n});return Et().loadThemeSync(o),ve.set(t,o),t}var Rn;function Et(){return Rn===void 0&&(Rn=Hr({themes:Wo,langs:Fo,engine:In({forgiving:!0})})),Rn}function eg(e){let t=ve.get(e),n=t?.colors??{},r=t?.type==="light",o=t===void 0?void 0:Et().getTheme(e),s=n["editor.background"]??o?.bg??(r?"#ffffff":"#1e1e1e"),a=n["editor.foreground"]??o?.fg??(r?"#333333":"#d4d4d4");return{background:s,foreground:a,gutter:n["editorLineNumber.foreground"]??(r?"#999999":"#858585"),isLight:r}}function tg(e){let t=(e||"").toLowerCase().trim();return t!==""&&Et().getLoadedLanguages().includes(t)?t:void 0}function Kc(e){return ve.get(e)?.tokenColors.find(n=>[].concat(n.scope??[]).join(",").includes("punctuation.section.embedded.begin"))?.settings?.foreground}function Qc(e,t){let n=e.map(i=>i.content).join(""),r=/^(\s*)<\?(php|=)?/.exec(n);if(r===null)return e;let o=r[0].length,s=[],a=0;for(let i of e){let c=a;a+=i.content.length,!(a<=o)&&s.push(c>=o?i:{...i,content:i.content.slice(o-c)})}return[...r[1]===""?[]:[{content:r[1],fontStyle:0}],{content:r[0].slice(r[1].length),color:t,fontStyle:0},...s]}function ng(e,t,n){let r=Et().codeToTokensBase(e,{lang:t,theme:n}),o=t==="php"?Kc(n):void 0;return o===void 0?r:r.map(s=>Qc(s,o))}export{Zd as addTheme,eg as colorsOf,Jd as displayNameOf,Qd as hasTheme,Yd as parseTheme,tg as resolveLang,Kd as themeNames,ng as tokenize};
153
types/index.d.ts 103 lines
1// A VS Code color theme, as its .json file holds it.
2export type VsCodeTheme = {
3	name?: string;
4	type?: 'dark' | 'light' | 'hc-dark' | 'hc-light';
5	colors?: Record<string, string>;
6	tokenColors?: unknown[];
7	[key: string]: unknown;
8};
9
10// What /skin-code is set to: 'auto' follows the active skins skin, 'off' leaves code blocks
11// to skins or the app, and any other value names a skin's theme pair or one theme.
12export type Mode = string;
13
14// What a code block shows besides the code: the header bar and the line numbers.
15export type CardOptions = { header: boolean; numbers: boolean };
16
17// How a code block is drawn on the desktop: rows of selectable text, or a card drawn in the
18// theme's code font.
19export type Style = 'text' | 'card';
20
21// Which themes /skin-code gallery shows: every one, or those of one lightness.
22export type GalleryFilter = 'all' | 'dark' | 'light';
23
24// One theme's block in /skin-code gallery, worked out by the command so the pane only draws:
25// its names, its colours and the sample's lines as runs of one style.
26export type GalleryRun = { text: string; color: string; italic: boolean; bold: boolean };
27
28export type GalleryCard = {
29	theme: string;
30	name: string;
31	caption: string;
32	isLight: boolean;
33	foreground: string;
34	background: string;
35	gutter: string;
36	lines: GalleryRun[][];
37};
38
39// What the gallery pane draws: the themes asked for, the one drawing now, and whether
40// Claude Code is drawing light, which the terminal's pane filters by.
41export type Gallery = {
42	filter: GalleryFilter;
43	// The page of blocks shown, from 0.
44	page: number;
45	current: string;
46	light: boolean;
47	cards: GalleryCard[];
48};
49
50// A theme for each lightness: [dark, light].
51export type ThemePair = readonly [dark: string, light: string];
52
53// A theme added after load, and who added it: 'user' through /skin-code add, else the plugin.
54export type AddedTheme = { theme: VsCodeTheme; by: string };
55
56// `$.skinCode.addTheme`'s argument. `skin` makes the theme that skin's code theme, for
57// `lightness` ('dark' unless the theme says light).
58export type AddThemeArgs = {
59	theme: VsCodeTheme;
60	skin?: string;
61	lightness?: 'dark' | 'light';
62};
63
64// `$.skinCode.draws`'s argument: a reply's whole text.
65export type DrawsArgs = { text: string };
66
67// skins' markdown, when skins is installed: skin-code draws a reply's prose with it.
68export type SkinsMarkdownArgs = {
69	surface: 'terminal' | 'desktop' | 'vscode' | 'mobile';
70	text: string;
71	columns: number;
72};
73
74declare module 'claude-code' {
75	interface EngineInterface {
76		skinCode: {
77			// Adds a VS Code theme for this session and resolves to the name it is listed under.
78			addTheme: (args: AddThemeArgs) => Promise<string>;
79			// Every theme skin-code can draw with.
80			themes: (args?: Record<string, never>) => Promise<string[]>;
81			// Whether skin-code draws this reply: it is on, and the reply holds a fence it draws.
82			// Another mod that draws replies leaves these to skin-code.
83			draws: (args: DrawsArgs) => Promise<boolean>;
84		};
85		skins: {
86			markdown: (args: SkinsMarkdownArgs) => Promise<RenderElement | undefined>;
87		};
88	}
89
90	interface PluginState {
91		'skin-code': {
92			mode: Mode;
93			added: Record<string, AddedTheme>;
94			pairs: Record<string, ThemePair>;
95			options: CardOptions;
96			style: Style;
97			// The block whose copy control shows its checkmark: `<message id>:<block>`, or ''.
98			copied: string;
99			gallery: Gallery;
100		};
101	}
102}
103