import { ShikiError as e } from "../../types/dist/index.js";
import { FontStyle as t } from "../../vscode-textmate/dist/index.js";
import { applyColorReplacements as n, codeToTokensBase as r, codeToTokensWithThemes as i, createShikiPrimitiveAsync as a, getLastGrammarState as o, getLastGrammarStateFromMap as s, isNoneTheme as c, isPlainLang as l, isSpecialLang as u, isSpecialTheme as d, resolveColorReplacements as f, setLastGrammarStateToMap as p, splitLines as m } from "../../primitive/dist/index.js";
import { toHtml as h } from "../../../hast-util-to-html/lib/index.js";
//#region ../../node_modules/@shikijs/core/dist/index.mjs
function g(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 t of n) t && !e.properties.class.includes(t) && e.properties.class.push(t);
	return e;
}
function _(e) {
	let t = m(e, !0).map(([e]) => e);
	function n(n) {
		if (n === e.length) return {
			line: t.length - 1,
			character: t[t.length - 1].length
		};
		let r = n, i = 0;
		for (let e of t) {
			if (r < e.length) break;
			r -= e.length, i++;
		}
		return {
			line: i,
			character: r
		};
	}
	function r(e, n) {
		let r = 0;
		for (let n = 0; n < e; n++) r += t[n].length;
		return r += n, r;
	}
	return {
		lines: t,
		indexToPos: n,
		posToIndex: r
	};
}
function v(e, t, n) {
	let r = /* @__PURE__ */ new Set();
	for (let t of e.matchAll(/:?lang=["']([^"']+)["']/g)) {
		let e = t[1].toLowerCase().trim();
		e && r.add(e);
	}
	for (let t of e.matchAll(/(?:```|~~~)([\w-]+)/g)) {
		let e = t[1].toLowerCase().trim();
		e && r.add(e);
	}
	for (let t of e.matchAll(/\\begin\{([\w-]+)\}/g)) {
		let e = t[1].toLowerCase().trim();
		e && r.add(e);
	}
	for (let t of e.matchAll(/<script\s+(?:type|lang)=["']([^"']+)["']/gi)) {
		let e = t[1].toLowerCase().trim(), n = e.includes("/") ? e.split("/").pop() : e;
		n && r.add(n);
	}
	if (!n) return Array.from(r);
	let i = n.getBundledLanguages();
	return Array.from(r).filter((e) => e && i[e]);
}
var y = "light-dark()", b = ["color", "background-color"];
function x(e, t) {
	let n = 0, r = [];
	for (let i of t) i > n && r.push({
		...e,
		content: e.content.slice(n, i),
		offset: e.offset + n
	}), n = i;
	return n < e.content.length && r.push({
		...e,
		content: e.content.slice(n),
		offset: e.offset + n
	}), r;
}
function S(e, t) {
	let n = Array.from(t instanceof Set ? t : new Set(t)).sort((e, t) => e - t);
	return n.length ? e.map((e) => e.flatMap((e) => {
		let t = n.filter((t) => e.offset < t && t < e.offset + e.content.length).map((t) => t - e.offset).sort((e, t) => e - t);
		return t.length ? x(e, t) : e;
	})) : e;
}
function C(t, n, r, i, a = "css-vars") {
	let o = {
		content: t.content,
		explanation: t.explanation,
		offset: t.offset
	}, s = n.map((e) => w(t.variants[e])), c = new Set(s.flatMap((e) => Object.keys(e))), l = {}, u = (e, t) => {
		let i = t === "color" ? "" : t === "background-color" ? "-bg" : `-${t}`;
		return r + n[e] + (t === "color" ? "" : i);
	};
	return s.forEach((t, r) => {
		for (let o of c) {
			let c = t[o] || "inherit";
			if (r === 0 && i && b.includes(o)) if (i === y && s.length > 1) {
				let t = n.findIndex((e) => e === "light"), i = n.findIndex((e) => e === "dark");
				if (t === -1 || i === -1) throw new e("When using `defaultColor: \"light-dark()\"`, you must provide both `light` and `dark` themes");
				l[o] = `light-dark(${s[t][o] || "inherit"}, ${s[i][o] || "inherit"})`, a === "css-vars" && (l[u(r, o)] = c);
			} else l[o] = c;
			else a === "css-vars" && (l[u(r, o)] = c);
		}
	}), o.htmlStyle = l, o;
}
function w(e) {
	let n = {};
	if (e.color && (n.color = e.color), e.bgColor && (n["background-color"] = e.bgColor), e.fontStyle) {
		e.fontStyle & t.Italic && (n["font-style"] = "italic"), e.fontStyle & t.Bold && (n["font-weight"] = "bold");
		let r = [];
		e.fontStyle & t.Underline && r.push("underline"), e.fontStyle & t.Strikethrough && r.push("line-through"), r.length && (n["text-decoration"] = r.join(" "));
	}
	return n;
}
function T(e) {
	return typeof e == "string" ? e : Object.entries(e).map(([e, t]) => `${e}:${t}`).join(";");
}
function E() {
	let t = /* @__PURE__ */ new WeakMap();
	function n(n) {
		if (!t.has(n.meta)) {
			let r = _(n.source);
			function i(t) {
				if (typeof t == "number") {
					if (t < 0 || t > n.source.length) throw new e(`Invalid decoration offset: ${t}. Code length: ${n.source.length}`);
					return {
						...r.indexToPos(t),
						offset: t
					};
				} else {
					let n = r.lines[t.line];
					if (n === void 0) throw new e(`Invalid decoration position ${JSON.stringify(t)}. Lines length: ${r.lines.length}`);
					let i = t.character;
					if (i < 0 && (i = n.length + i), i < 0 || i > n.length) throw new e(`Invalid decoration position ${JSON.stringify(t)}. Line ${t.line} length: ${n.length}`);
					return {
						...t,
						character: i,
						offset: r.posToIndex(t.line, i)
					};
				}
			}
			let a = (n.options.decorations || []).map((e) => ({
				...e,
				start: i(e.start),
				end: i(e.end)
			}));
			D(a), t.set(n.meta, {
				decorations: a,
				converter: r,
				source: n.source
			});
		}
		return t.get(n.meta);
	}
	return {
		name: "shiki:decorations",
		tokens(e) {
			if (this.options.decorations?.length) return S(e, n(this).decorations.flatMap((e) => [e.start.offset, e.end.offset]));
		},
		code(t) {
			if (!this.options.decorations?.length) return;
			let r = n(this), i = Array.from(t.children).filter((e) => e.type === "element" && e.tagName === "span");
			if (i.length !== r.converter.lines.length) throw new e(`Number of lines in code element (${i.length}) does not match the number of lines in the source (${r.converter.lines.length}). Failed to apply decorations.`);
			function a(t, n, r, a) {
				let o = i[t], c = "", l = -1, u = -1;
				if (n === 0 && (l = 0), r === 0 && (u = 0), r === Infinity && (u = o.children.length), l === -1 || u === -1) for (let e = 0; e < o.children.length; e++) c += O(o.children[e]), l === -1 && c.length === n && (l = e + 1), u === -1 && c.length === r && (u = e + 1);
				if (l === -1) throw new e(`Failed to find start index for decoration ${JSON.stringify(a.start)}`);
				if (u === -1) throw new e(`Failed to find end index for decoration ${JSON.stringify(a.end)}`);
				let d = o.children.slice(l, u);
				if (!a.alwaysWrap && d.length === o.children.length) s(o, a, "line");
				else if (!a.alwaysWrap && d.length === 1 && d[0].type === "element") s(d[0], a, "token");
				else {
					let e = {
						type: "element",
						tagName: "span",
						properties: {},
						children: d
					};
					s(e, a, "wrapper"), o.children.splice(l, d.length, e);
				}
			}
			function o(e, t) {
				i[e] = s(i[e], t, "line");
			}
			function s(e, t, n) {
				let r = t.properties || {}, i = t.transform || ((e) => e);
				return e.tagName = t.tagName || "span", e.properties = {
					...e.properties,
					...r,
					class: e.properties.class
				}, t.properties?.class && g(e, t.properties.class), e = i(e, n) || e, e;
			}
			let c = [], l = r.decorations.sort((e, t) => t.start.offset - e.start.offset || e.end.offset - t.end.offset);
			for (let e of l) {
				let { start: t, end: n } = e;
				if (t.line === n.line) a(t.line, t.character, n.character, e);
				else if (t.line < n.line) {
					a(t.line, t.character, Infinity, e);
					for (let r = t.line + 1; r < n.line; r++) c.unshift(() => o(r, e));
					a(n.line, 0, n.character, e);
				}
			}
			c.forEach((e) => e());
		}
	};
}
function D(t) {
	for (let n = 0; n < t.length; n++) {
		let r = t[n];
		if (r.start.offset > r.end.offset) throw new e(`Invalid decoration range: ${JSON.stringify(r.start)} - ${JSON.stringify(r.end)}`);
		for (let i = n + 1; i < t.length; i++) {
			let n = t[i], a = r.start.offset <= n.start.offset && n.start.offset < r.end.offset, o = r.start.offset < n.end.offset && n.end.offset <= r.end.offset, s = n.start.offset <= r.start.offset && r.start.offset < n.end.offset, c = n.start.offset < r.end.offset && r.end.offset <= n.end.offset;
			if (a || o || s || c) {
				if (a && o || s && c || s && r.start.offset === r.end.offset || o && n.start.offset === n.end.offset) continue;
				throw new e(`Decorations ${JSON.stringify(r.start)} and ${JSON.stringify(n.start)} intersect.`);
			}
		}
	}
}
function O(e) {
	return e.type === "text" ? e.value : e.type === "element" ? e.children.map(O).join("") : "";
}
var k = [/* @__PURE__ */ E()];
function A(e) {
	let t = j(e.transformers || []);
	return [
		...t.pre,
		...t.normal,
		...t.post,
		...k
	];
}
function j(e) {
	let t = [], n = [], r = [];
	for (let i of e) switch (i.enforce) {
		case "pre":
			t.push(i);
			break;
		case "post":
			n.push(i);
			break;
		default: r.push(i);
	}
	return {
		pre: t,
		post: n,
		normal: r
	};
}
var M = [
	"black",
	"red",
	"green",
	"yellow",
	"blue",
	"magenta",
	"cyan",
	"white",
	"brightBlack",
	"brightRed",
	"brightGreen",
	"brightYellow",
	"brightBlue",
	"brightMagenta",
	"brightCyan",
	"brightWhite"
], N = {
	1: "bold",
	2: "dim",
	3: "italic",
	4: "underline",
	7: "reverse",
	8: "hidden",
	9: "strikethrough"
};
function P(e, t) {
	let n = e.indexOf("\x1B", t);
	if (n !== -1 && e[n + 1] === "[") {
		let t = e.indexOf("m", n);
		if (t !== -1) return {
			sequence: e.substring(n + 2, t).split(";"),
			startPosition: n,
			position: t + 1
		};
	}
	return { position: e.length };
}
function F(e) {
	let t = e.shift();
	if (t === "2") {
		let t = e.splice(0, 3).map((e) => Number.parseInt(e));
		return t.length !== 3 || t.some((e) => Number.isNaN(e)) ? void 0 : {
			type: "rgb",
			rgb: t
		};
	} else if (t === "5") {
		let t = e.shift();
		if (t) return {
			type: "table",
			index: Number(t)
		};
	}
}
function I(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) N[r] && t.push({
			type: "setDecoration",
			value: N[r]
		});
		else if (r <= 29) {
			let e = N[r - 20];
			e && (t.push({
				type: "resetDecoration",
				value: e
			}), e === "dim" && t.push({
				type: "resetDecoration",
				value: "bold"
			}));
		} else if (r <= 37) t.push({
			type: "setForegroundColor",
			value: {
				type: "named",
				name: M[r - 30]
			}
		});
		else if (r === 38) {
			let n = F(e);
			n && t.push({
				type: "setForegroundColor",
				value: n
			});
		} else if (r === 39) t.push({ type: "resetForegroundColor" });
		else if (r <= 47) t.push({
			type: "setBackgroundColor",
			value: {
				type: "named",
				name: M[r - 40]
			}
		});
		else if (r === 48) {
			let n = F(e);
			n && t.push({
				type: "setBackgroundColor",
				value: n
			});
		} 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: M[r - 90 + 8]
			}
		}) : r >= 100 && r <= 107 && t.push({
			type: "setBackgroundColor",
			value: {
				type: "named",
				name: M[r - 100 + 8]
			}
		});
	}
	return t;
}
function L() {
	let e = null, t = null, n = /* @__PURE__ */ new Set();
	return { parse(r) {
		let i = [], a = 0;
		do {
			let o = P(r, a), s = o.sequence ? r.substring(a, o.startPosition) : r.substring(a);
			if (s.length > 0 && i.push({
				value: s,
				foreground: e,
				background: t,
				decorations: new Set(n)
			}), o.sequence) {
				let r = I(o.sequence);
				for (let i of r) i.type === "resetAll" ? (e = null, t = null, n.clear()) : i.type === "resetForegroundColor" ? e = null : i.type === "resetBackgroundColor" ? t = null : i.type === "resetDecoration" && n.delete(i.value);
				for (let i of r) i.type === "setForegroundColor" ? e = i.value : i.type === "setBackgroundColor" ? t = i.value : i.type === "setDecoration" && n.add(i.value);
			}
			a = o.position;
		} while (a < r.length);
		return i;
	} };
}
var R = {
	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 z(e = R) {
	function t(t) {
		return e[t];
	}
	function n(e) {
		return `#${e.map((e) => Math.max(0, Math.min(e, 255)).toString(16).padStart(2, "0")).join("")}`;
	}
	let r;
	function i() {
		if (r) return r;
		r = [];
		for (let e = 0; e < M.length; e++) r.push(t(M[e]));
		let e = [
			0,
			95,
			135,
			175,
			215,
			255
		];
		for (let t = 0; t < 6; t++) for (let i = 0; i < 6; i++) for (let a = 0; a < 6; a++) r.push(n([
			e[t],
			e[i],
			e[a]
		]));
		let i = 8;
		for (let e = 0; e < 24; e++, i += 10) r.push(n([
			i,
			i,
			i
		]));
		return r;
	}
	function a(e) {
		return i()[e];
	}
	function o(e) {
		switch (e.type) {
			case "named": return t(e.name);
			case "rgb": return n(e.rgb);
			case "table": return a(e.index);
		}
	}
	return { value: o };
}
var B = {
	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 V(e, r, i) {
	let a = f(e, i), o = m(r), s = z(Object.fromEntries(M.map((t) => {
		let n = `terminal.ansi${t[0].toUpperCase()}${t.substring(1)}`;
		return [t, e.colors?.[n] || B[t]];
	}))), c = L();
	return o.map((r) => c.parse(r[0]).map((i) => {
		let o, c;
		i.decorations.has("reverse") ? (o = i.background ? s.value(i.background) : e.bg, c = i.foreground ? s.value(i.foreground) : e.fg) : (o = i.foreground ? s.value(i.foreground) : e.fg, c = i.background ? s.value(i.background) : void 0), o = n(o, a), c = n(c, a), i.decorations.has("dim") && (o = H(o));
		let l = t.None;
		return i.decorations.has("bold") && (l |= t.Bold), i.decorations.has("italic") && (l |= t.Italic), i.decorations.has("underline") && (l |= t.Underline), i.decorations.has("strikethrough") && (l |= t.Strikethrough), {
			content: i.value,
			offset: r[1],
			color: o,
			bgColor: c,
			fontStyle: l
		};
	}));
}
function H(e) {
	let t = e.match(/#([0-9a-f]{3,8})/i);
	if (t) {
		let e = t[1];
		if (e.length === 8) {
			let t = Math.round(Number.parseInt(e.slice(6, 8), 16) / 2).toString(16).padStart(2, "0");
			return `#${e.slice(0, 6)}${t}`;
		} else if (e.length === 6) return `#${e}80`;
		else if (e.length === 4) {
			let t = e[0], n = e[1], r = e[2], i = e[3];
			return `#${t}${t}${n}${n}${r}${r}${Math.round(Number.parseInt(`${i}${i}`, 16) / 2).toString(16).padStart(2, "0")}`;
		} else if (e.length === 3) {
			let t = e[0], n = e[1], r = e[2];
			return `#${t}${t}${n}${n}${r}${r}80`;
		}
	}
	let n = e.match(/var\((--[\w-]+-ansi-[\w-]+)\)/);
	return n ? `var(${n[1]}-dim)` : e;
}
function U(e, t, n = {}) {
	let i = e.resolveLangAlias(n.lang || "text"), { theme: a = e.getLoadedThemes()[0] } = n;
	if (!l(i) && !c(a) && i === "ansi") {
		let { theme: r } = e.setTheme(a);
		return V(r, t, n);
	}
	return r(e, t, n);
}
function W(t, r, a) {
	let o, c, l, u, d, m;
	if ("themes" in a) {
		let { defaultColor: n = "light", cssVariablePrefix: h = "--shiki-", colorsRendering: g = "css-vars" } = a, _ = Object.entries(a.themes).filter((e) => e[1]).map((e) => ({
			color: e[0],
			theme: e[1]
		})).sort((e, t) => e.color === n ? -1 : +(t.color === n));
		if (_.length === 0) throw new e("`themes` option must not be empty");
		let v = i(t, r, a, U);
		if (m = s(v), n && y !== n && !_.find((e) => e.color === n)) throw new e(`\`themes\` option must contain the defaultColor key \`${n}\``);
		let b = _.map((e) => t.getTheme(e.theme)), x = _.map((e) => e.color);
		l = v.map((e) => e.map((e) => C(e, x, h, n, g))), m && p(l, m);
		let S = _.map((e) => f(e.theme, a));
		c = G(_, b, S, h, n, "fg", g), o = G(_, b, S, h, n, "bg", g), u = `shiki-themes ${b.map((e) => e.name).join(" ")}`, d = n ? void 0 : [c, o].join(";");
	} else if ("theme" in a) {
		let e = f(a.theme, a);
		l = U(t, r, a);
		let i = t.getTheme(a.theme);
		o = n(i.bg, e), c = n(i.fg, e), u = i.name, m = s(l);
	} else throw new e("Invalid options, either `theme` or `themes` must be provided");
	return {
		tokens: l,
		fg: c,
		bg: o,
		themeName: u,
		rootStyle: d,
		grammarState: m
	};
}
function G(t, r, i, a, o, s, c) {
	return t.map((l, u) => {
		let d = n(r[u][s], i[u]) || "inherit", f = `${a + l.color}${s === "bg" ? "-bg" : ""}:${d}`;
		if (u === 0 && o) {
			if (o === y && t.length > 1) {
				let a = t.findIndex((e) => e.color === "light"), o = t.findIndex((e) => e.color === "dark");
				if (a === -1 || o === -1) throw new e("When using `defaultColor: \"light-dark()\"`, you must provide both `light` and `dark` themes");
				return `light-dark(${n(r[a][s], i[a]) || "inherit"}, ${n(r[o][s], i[o]) || "inherit"});${f}`;
			}
			return d;
		}
		return c === "css-vars" ? f : null;
	}).filter((e) => !!e).join(";");
}
function K(e, t, n, r = {
	meta: {},
	options: n,
	codeToHast: (t, n) => K(e, t, n),
	codeToTokens: (t, n) => W(e, t, n)
}) {
	let i = t;
	for (let e of A(n)) i = e.preprocess?.call(r, i, n) || i;
	let { tokens: a, fg: o, bg: s, themeName: c, rootStyle: l, grammarState: u } = W(e, i, n), { mergeWhitespaces: d = !0, mergeSameStyleTokens: f = !1 } = n;
	d === !0 ? a = J(a) : d === "never" && (a = Y(a)), f && (a = X(a));
	let p = {
		...r,
		get source() {
			return i;
		}
	};
	for (let e of A(n)) a = e.tokens?.call(p, a) || a;
	return q(a, {
		...n,
		fg: o,
		bg: s,
		themeName: c,
		rootStyle: n.rootStyle === !1 ? !1 : n.rootStyle ?? l
	}, p, u);
}
function q(e, t, n, r = s(e)) {
	let i = A(t), a = [], o = {
		type: "root",
		children: []
	}, { structure: c = "classic", tabindex: l = "0" } = t, u = { class: `shiki ${t.themeName || ""}` };
	t.rootStyle !== !1 && (t.rootStyle == null ? u.style = `background-color:${t.bg};color:${t.fg}` : u.style = t.rootStyle), l !== !1 && l != null && (u.tabindex = l.toString());
	for (let [e, n] of Object.entries(t.meta || {})) e.startsWith("_") || (u[e] = n);
	let d = {
		type: "element",
		tagName: "pre",
		properties: u,
		children: [],
		data: t.data
	}, f = {
		type: "element",
		tagName: "code",
		properties: {},
		children: a
	}, m = [], h = {
		...n,
		structure: c,
		addClassToHast: g,
		get source() {
			return n.source;
		},
		get tokens() {
			return e;
		},
		get options() {
			return t;
		},
		get root() {
			return o;
		},
		get pre() {
			return d;
		},
		get code() {
			return f;
		},
		get lines() {
			return m;
		}
	};
	if (e.forEach((e, t) => {
		t && (c === "inline" ? o.children.push({
			type: "element",
			tagName: "br",
			properties: {},
			children: []
		}) : c === "classic" && a.push({
			type: "text",
			value: "\n"
		}));
		let n = {
			type: "element",
			tagName: "span",
			properties: { class: "line" },
			children: []
		}, r = 0;
		for (let a of e) {
			let e = {
				type: "element",
				tagName: "span",
				properties: { ...a.htmlAttrs },
				children: [{
					type: "text",
					value: a.content
				}]
			}, s = T(a.htmlStyle || w(a));
			s && (e.properties.style = s);
			for (let o of i) e = o?.span?.call(h, e, t + 1, r, n, a) || e;
			c === "inline" ? o.children.push(e) : c === "classic" && n.children.push(e), r += a.content.length;
		}
		if (c === "classic") {
			for (let e of i) n = e?.line?.call(h, n, t + 1) || n;
			m.push(n), a.push(n);
		} else c === "inline" && m.push(n);
	}), c === "classic") {
		for (let e of i) f = e?.code?.call(h, f) || f;
		d.children.push(f);
		for (let e of i) d = e?.pre?.call(h, d) || d;
		o.children.push(d);
	} else if (c === "inline") {
		let e = [], t = {
			type: "element",
			tagName: "span",
			properties: { class: "line" },
			children: []
		};
		for (let n of o.children) n.type === "element" && n.tagName === "br" ? (e.push(t), t = {
			type: "element",
			tagName: "span",
			properties: { class: "line" },
			children: []
		}) : (n.type === "element" || n.type === "text") && t.children.push(n);
		e.push(t);
		let n = {
			type: "element",
			tagName: "code",
			properties: {},
			children: e
		};
		for (let e of i) n = e?.code?.call(h, n) || n;
		o.children = [];
		for (let e = 0; e < n.children.length; e++) {
			e > 0 && o.children.push({
				type: "element",
				tagName: "br",
				properties: {},
				children: []
			});
			let t = n.children[e];
			t.type === "element" && o.children.push(...t.children);
		}
	}
	let _ = o;
	for (let e of i) _ = e?.root?.call(h, _) || _;
	return r && p(_, r), _;
}
function J(e) {
	return e.map((e) => {
		let n = [], r = "", i;
		return e.forEach((a, o) => {
			let s = !(a.fontStyle && (a.fontStyle & t.Underline || a.fontStyle & t.Strikethrough));
			s && a.content.match(/^\s+$/) && e[o + 1] ? (i === void 0 && (i = a.offset), r += a.content) : r ? (s ? n.push({
				...a,
				offset: i,
				content: r + a.content
			}) : n.push({
				content: r,
				offset: i
			}, a), i = void 0, r = "") : n.push(a);
		}), n;
	});
}
function Y(e) {
	return e.map((e) => e.flatMap((e) => {
		if (e.content.match(/^\s+$/)) return e;
		let t = e.content.match(/^(\s*)(.*?)(\s*)$/);
		if (!t) return e;
		let [, n, r, i] = t;
		if (!n && !i) return e;
		let a = [{
			...e,
			offset: e.offset + n.length,
			content: r
		}];
		return n && a.unshift({
			content: n,
			offset: e.offset
		}), i && a.push({
			content: i,
			offset: e.offset + n.length + r.length
		}), a;
	}));
}
function X(e) {
	return e.map((e) => {
		let n = [];
		for (let r of e) {
			if (n.length === 0) {
				n.push({ ...r });
				continue;
			}
			let e = n[n.length - 1], i = T(e.htmlStyle || w(e)), a = T(r.htmlStyle || w(r)), o = e.fontStyle && (e.fontStyle & t.Underline || e.fontStyle & t.Strikethrough), s = r.fontStyle && (r.fontStyle & t.Underline || r.fontStyle & t.Strikethrough);
			!o && !s && i === a ? e.content += r.content : n.push({ ...r });
		}
		return n;
	});
}
var Z = h;
function ee(e, t, n) {
	let r = {
		meta: {},
		options: n,
		codeToHast: (t, n) => K(e, t, n),
		codeToTokens: (t, n) => W(e, t, n)
	}, i = Z(K(e, t, n, r));
	for (let e of A(n)) i = e.postprocess?.call(r, i, n) || i;
	return i;
}
async function Q(e) {
	let t = await a(e);
	return {
		getLastGrammarState: (...e) => o(t, ...e),
		codeToTokensBase: (e, n) => U(t, e, n),
		codeToTokensWithThemes: (e, n) => i(t, e, n),
		codeToTokens: (e, n) => W(t, e, n),
		codeToHast: (e, n) => K(t, e, n),
		codeToHtml: (e, n) => ee(t, e, n),
		getBundledLanguages: () => ({}),
		getBundledThemes: () => ({}),
		...t,
		getInternalContext: () => t
	};
}
function te(t) {
	let n = t.langs, r = t.themes, i = t.engine;
	async function a(t) {
		function a(r) {
			if (typeof r == "string") {
				if (r = t.langAlias?.[r] || r, u(r)) return [];
				let i = n[r];
				if (!i) throw new e(`Language \`${r}\` is not included in this bundle. You may want to load it from external source.`);
				return i;
			}
			return r;
		}
		function o(t) {
			if (d(t)) return "none";
			if (typeof t == "string") {
				let n = r[t];
				if (!n) throw new e(`Theme \`${t}\` is not included in this bundle. You may want to load it from external source.`);
				return n;
			}
			return t;
		}
		let s = (t.themes ?? []).map((e) => o(e)), c = (t.langs ?? []).map((e) => a(e)), l = await Q({
			engine: t.engine ?? i(),
			...t,
			themes: s,
			langs: c
		});
		return {
			...l,
			loadLanguage(...e) {
				return l.loadLanguage(...e.map(a));
			},
			loadTheme(...e) {
				return l.loadTheme(...e.map(o));
			},
			getBundledLanguages() {
				return n;
			},
			getBundledThemes() {
				return r;
			}
		};
	}
	return a;
}
function $(e) {
	let t;
	async function n(n = {}) {
		if (t) {
			let e = await t;
			return await Promise.all([e.loadTheme(...n.themes || []), e.loadLanguage(...n.langs || [])]), e;
		} else {
			t = e({
				...n,
				themes: [],
				langs: []
			});
			let r = await t;
			return await Promise.all([r.loadTheme(...n.themes || []), r.loadLanguage(...n.langs || [])]), r;
		}
	}
	return n;
}
function ne(e, t) {
	let n = $(e);
	async function r(e, r) {
		let i = await n({
			langs: [r.lang],
			themes: "theme" in r ? [r.theme] : Object.values(r.themes)
		}), a = await t?.guessEmbeddedLanguages?.(e, r.lang, i);
		return a && await i.loadLanguage(...a), i;
	}
	return {
		getSingletonHighlighter(e) {
			return n(e);
		},
		async codeToHtml(e, t) {
			return (await r(e, t)).codeToHtml(e, t);
		},
		async codeToHast(e, t) {
			return (await r(e, t)).codeToHast(e, t);
		},
		async codeToTokens(e, t) {
			return (await r(e, t)).codeToTokens(e, t);
		},
		async codeToTokensBase(e, t) {
			return (await r(e, t)).codeToTokensBase(e, t);
		},
		async codeToTokensWithThemes(e, t) {
			return (await r(e, t)).codeToTokensWithThemes(e, t);
		},
		async getLastGrammarState(e, t) {
			return (await n({
				langs: [t.lang],
				themes: [t.theme]
			})).getLastGrammarState(e, t);
		}
	};
}
//#endregion
export { g as addClassToHast, te as createBundledHighlighter, Q as createHighlighterCore, _ as createPositionConverter, ne as createSingletonShorthands, C as flatTokenVariants, w as getTokenStyleObject, v as guessEmbeddedLanguages, Z as hastToHtml, $ as makeSingletonHighlighter, x as splitToken, S as splitTokens, T as stringifyTokenStyle, V as tokenizeAnsiWithTheme, q as tokensToHast, E as transformerDecorations };
