import { ShikiError as e } from "../node_modules/@shikijs/types/dist/index.js";
import { EncodedTokenMetadata as t, INITIAL as n, Registry as r, Theme as i } from "../../vscode-textmate/dist/index.js";
//#region ../../node_modules/@shikijs/primitive/dist/index.mjs
function a(e, t) {
	let n = typeof e == "string" ? {} : { ...e.colorReplacements }, r = typeof e == "string" ? e : e.name;
	for (let [e, i] of Object.entries(t?.colorReplacements || {})) typeof i == "string" ? n[e] = i : e === r && Object.assign(n, i);
	return n;
}
function o(e, t) {
	return e && (t?.[e?.toLowerCase()] || e);
}
function s(e) {
	return Array.isArray(e) ? e : [e];
}
async function c(e) {
	return Promise.resolve(typeof e == "function" ? e() : e).then((e) => e.default || e);
}
function l(e) {
	return !e || [
		"plaintext",
		"txt",
		"text",
		"plain"
	].includes(e);
}
function u(e) {
	return e === "ansi" || l(e);
}
function d(e) {
	return e === "none";
}
function f(e) {
	return d(e);
}
var p = /(\r?\n)/g;
function m(e, t = !1) {
	if (e.length === 0) return [["", 0]];
	let n = e.split(p), r = 0, i = [];
	for (let e = 0; e < n.length; e += 2) {
		let a = t ? n[e] + (n[e + 1] || "") : n[e];
		i.push([a, r]), r += n[e].length, r += n[e + 1]?.length || 0;
	}
	return i;
}
var h = {
	light: "#333333",
	dark: "#bbbbbb"
}, g = {
	light: "#fffffe",
	dark: "#1e1e1e"
}, _ = "__shiki_resolved";
function v(e) {
	if (e?.[_]) 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 e = t.settings ? t.settings.find((e) => !e.name && !e.scope) : void 0;
		e?.settings?.foreground && (r = e.settings.foreground), e?.settings?.background && (n = e.settings.background), !r && t?.colors?.["editor.foreground"] && (r = t.colors["editor.foreground"]), !n && t?.colors?.["editor.background"] && (n = t.colors["editor.background"]), r ||= t.type === "light" ? h.light : h.dark, n ||= t.type === "light" ? g.light : g.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 i = 0, a = /* @__PURE__ */ new Map();
	function o(e) {
		if (a.has(e)) return a.get(e);
		i += 1;
		let n = `#${i.toString(16).padStart(8, "0").toLowerCase()}`;
		return t.colorReplacements?.[`#${n}`] ? o(e) : (a.set(e, n), n);
	}
	t.settings = t.settings.map((e) => {
		let n = e.settings?.foreground && !e.settings.foreground.startsWith("#"), r = e.settings?.background && !e.settings.background.startsWith("#");
		if (!n && !r) return e;
		let i = {
			...e,
			settings: { ...e.settings }
		};
		if (n) {
			let n = o(e.settings.foreground);
			t.colorReplacements[n] = e.settings.foreground, i.settings.foreground = n;
		}
		if (r) {
			let n = o(e.settings.background);
			t.colorReplacements[n] = e.settings.background, i.settings.background = n;
		}
		return i;
	});
	for (let e of Object.keys(t.colors || {})) if ((e === "editor.foreground" || e === "editor.background" || e.startsWith("terminal.ansi")) && !t.colors[e]?.startsWith("#")) {
		let n = o(t.colors[e]);
		t.colorReplacements[n] = t.colors[e], t.colors[e] = n;
	}
	return Object.defineProperty(t, _, {
		enumerable: !1,
		writable: !1,
		value: !0
	}), t;
}
async function y(e) {
	return [...new Set((await Promise.all(e.filter((e) => !u(e)).map(async (e) => await c(e).then((e) => Array.isArray(e) ? e : [e])))).flat())];
}
async function b(e) {
	return (await Promise.all(e.map(async (e) => f(e) ? null : v(await c(e))))).filter((e) => !!e);
}
function x(t, n) {
	if (!n) return t;
	if (n[t]) {
		let r = new Set([t]);
		for (; n[t];) {
			if (t = n[t], r.has(t)) throw new e(`Circular alias \`${[...r].join(" -> ")} -> ${t}\``);
			r.add(t);
		}
	}
	return t;
}
var S = class extends r {
	_resolver;
	_themes;
	_langs;
	_alias;
	_resolvedThemes = /* @__PURE__ */ new Map();
	_resolvedGrammars = /* @__PURE__ */ new Map();
	_langMap = /* @__PURE__ */ new Map();
	_langGraph = /* @__PURE__ */ new Map();
	_textmateThemeCache = /* @__PURE__ */ new WeakMap();
	_loadedThemesCache = null;
	_loadedLanguagesCache = null;
	constructor(e, t, n, r = {}) {
		super(e), this._resolver = e, this._themes = t, this._langs = n, this._alias = r, this._themes.map((e) => this.loadTheme(e)), this.loadLanguages(this._langs);
	}
	getTheme(e) {
		return typeof e == "string" ? this._resolvedThemes.get(e) : this.loadTheme(e);
	}
	loadTheme(e) {
		let t = v(e);
		return t.name && (this._resolvedThemes.set(t.name, t), this._loadedThemesCache = null), t;
	}
	getLoadedThemes() {
		return this._loadedThemesCache ||= [...this._resolvedThemes.keys()], this._loadedThemesCache;
	}
	setTheme(e) {
		let t = this._textmateThemeCache.get(e);
		t || (t = i.createFromRawTheme(e), this._textmateThemeCache.set(e, t)), this._syncRegistry.setTheme(t);
	}
	getGrammar(e) {
		return e = x(e, this._alias), this._resolvedGrammars.get(e);
	}
	loadLanguage(e) {
		if (this.getGrammar(e.name)) return;
		let t = new Set([...this._langMap.values()].filter((t) => t.embeddedLangsLazy?.includes(e.name)));
		this._resolver.addLanguage(e);
		let n = {
			balancedBracketSelectors: e.balancedBracketSelectors || ["*"],
			unbalancedBracketSelectors: e.unbalancedBracketSelectors || []
		};
		this._syncRegistry._rawGrammars.set(e.scopeName, e);
		let r = this.loadGrammarWithConfiguration(e.scopeName, 1, n);
		if (r.name = e.name, this._resolvedGrammars.set(e.name, r), e.aliases && e.aliases.forEach((t) => {
			this._alias[t] = e.name;
		}), this._loadedLanguagesCache = null, t.size) for (let e of t) this._resolvedGrammars.delete(e.name), this._loadedLanguagesCache = null, this._syncRegistry?._injectionGrammars?.delete(e.scopeName), this._syncRegistry?._grammars?.delete(e.scopeName), this.loadLanguage(this._langMap.get(e.name));
	}
	dispose() {
		super.dispose(), this._resolvedThemes.clear(), this._resolvedGrammars.clear(), this._langMap.clear(), this._langGraph.clear(), this._loadedThemesCache = null;
	}
	loadLanguages(t) {
		for (let e of t) this.resolveEmbeddedLanguages(e);
		let n = [...this._langGraph.entries()], r = n.filter(([e, t]) => !t);
		if (r.length) {
			let t = n.filter(([e, t]) => t ? (t.embeddedLanguages || t.embeddedLangs)?.some((e) => r.map(([e]) => e).includes(e)) : !1).filter((e) => !r.includes(e));
			throw new e(`Missing languages ${r.map(([e]) => `\`${e}\``).join(", ")}, required by ${t.map(([e]) => `\`${e}\``).join(", ")}`);
		}
		for (let [e, t] of n) this._resolver.addLanguage(t);
		for (let [e, t] of n) this.loadLanguage(t);
	}
	getLoadedLanguages() {
		return this._loadedLanguagesCache ||= [...new Set([...this._resolvedGrammars.keys(), ...Object.keys(this._alias)])], this._loadedLanguagesCache;
	}
	resolveEmbeddedLanguages(e) {
		this._langMap.set(e.name, e), this._langGraph.set(e.name, e);
		let t = e.embeddedLanguages ?? e.embeddedLangs;
		if (t) for (let e of t) this._langGraph.set(e, this._langMap.get(e));
	}
}, C = class {
	_langs = /* @__PURE__ */ new Map();
	_scopeToLang = /* @__PURE__ */ new Map();
	_injections = /* @__PURE__ */ new Map();
	_onigLib;
	constructor(e, t) {
		this._onigLib = {
			createOnigScanner: (t) => e.createScanner(t),
			createOnigString: (t) => e.createString(t)
		}, t.forEach((e) => this.addLanguage(e));
	}
	get onigLib() {
		return this._onigLib;
	}
	getLangRegistration(e) {
		return this._langs.get(e);
	}
	loadGrammar(e) {
		return this._scopeToLang.get(e);
	}
	addLanguage(e) {
		this._langs.set(e.name, e), e.aliases && e.aliases.forEach((t) => {
			this._langs.set(t, e);
		}), this._scopeToLang.set(e.scopeName, e), e.injectTo && e.injectTo.forEach((t) => {
			this._injections.get(t) || this._injections.set(t, []), this._injections.get(t).push(e.scopeName);
		});
	}
	getInjections(e) {
		let t = e.split("."), n = [];
		for (let e = 1; e <= t.length; e++) {
			let r = t.slice(0, e).join(".");
			n = [...n, ...this._injections.get(r) || []];
		}
		return n;
	}
}, w = 0;
function T(t) {
	w += 1, t.warnings !== !1 && w >= 10 && w % 10 == 0 && console.warn(`[Shiki] ${w} 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 n = !1;
	if (!t.engine) throw new e("`engine` option is required for synchronous mode");
	let r = (t.langs || []).flat(1), i = (t.themes || []).flat(1).map(v), a = new S(new C(t.engine, r), i, r, t.langAlias), o;
	function s(e) {
		return x(e, t.langAlias);
	}
	function c(t) {
		_();
		let n = a.getGrammar(typeof t == "string" ? t : t.name);
		if (!n) throw new e(`Language \`${t}\` not found, you may need to load it first`);
		return n;
	}
	function l(t) {
		if (t === "none") return {
			bg: "",
			fg: "",
			name: "none",
			settings: [],
			type: "dark"
		};
		_();
		let n = a.getTheme(t);
		if (!n) throw new e(`Theme \`${t}\` not found, you may need to load it first`);
		return n;
	}
	function u(e) {
		_();
		let t = l(e);
		return o !== e && (a.setTheme(t), o = e), {
			theme: t,
			colorMap: a.getColorMap()
		};
	}
	function d() {
		return _(), a.getLoadedThemes();
	}
	function f() {
		return _(), a.getLoadedLanguages();
	}
	function p(...e) {
		_(), a.loadLanguages(e.flat(1));
	}
	async function m(...e) {
		return p(await y(e));
	}
	function h(...e) {
		_();
		for (let t of e.flat(1)) a.loadTheme(t);
	}
	async function g(...e) {
		return _(), h(await b(e));
	}
	function _() {
		if (n) throw new e("Shiki instance has been disposed");
	}
	function T() {
		n || (n = !0, a.dispose(), --w);
	}
	return {
		setTheme: u,
		getTheme: l,
		getLanguage: c,
		getLoadedThemes: d,
		getLoadedLanguages: f,
		resolveLangAlias: s,
		loadLanguage: m,
		loadLanguageSync: p,
		loadTheme: g,
		loadThemeSync: h,
		dispose: T,
		[Symbol.dispose]: T
	};
}
async function E(e) {
	e.engine || console.warn("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");
	let [t, n, r] = await Promise.all([
		b(e.themes || []),
		y(e.langs || []),
		e.engine
	]);
	return T({
		...e,
		themes: t,
		langs: n,
		engine: r
	});
}
var D = /* @__PURE__ */ new WeakMap();
function O(e, t) {
	D.set(e, t);
}
function k(e) {
	return D.get(e);
}
var A = 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, r) {
		return new e(Object.fromEntries(s(r).map((e) => [e, n])), t);
	}
	constructor(...e) {
		if (e.length === 2) {
			let [t, n] = e;
			this.lang = n, this._stacks = t;
		} else {
			let [t, n, r] = e;
			this.lang = n, this._stacks = { [r]: t };
		}
	}
	getInternalStack(e = this.theme) {
		return this._stacks[e];
	}
	getScopes(e = this.theme) {
		return j(this._stacks[e]);
	}
	toJSON() {
		return {
			lang: this.lang,
			theme: this.theme,
			themes: this.themes,
			scopes: this.getScopes()
		};
	}
};
function j(e) {
	let t = [], n = /* @__PURE__ */ new Set();
	function r(e) {
		if (n.has(e)) return;
		n.add(e);
		let i = e?.nameScopesList?.scopeName;
		i && t.push(i), e.parent && r(e.parent);
	}
	return r(e), t;
}
function M(t, n) {
	if (!(t instanceof A)) throw new e("Invalid grammar state");
	return t.getInternalStack(n);
}
var N = /,/, P = / /;
function F(t, n, r = {}) {
	let { theme: i = t.getLoadedThemes()[0] } = r;
	if (l(t.resolveLangAlias(r.lang || "text")) || d(i)) return m(n).map((e) => [{
		content: e[0],
		offset: e[1]
	}]);
	let { theme: a, colorMap: o } = t.setTheme(i), s = t.getLanguage(r.lang || "text");
	if (r.grammarState) {
		if (r.grammarState.lang !== s.name) throw new e(`Grammar state language "${r.grammarState.lang}" does not match highlight language "${s.name}"`);
		if (!r.grammarState.themes.includes(a.name)) throw new e(`Grammar state themes "${r.grammarState.themes}" do not contain highlight theme "${a.name}"`);
	}
	return L(n, s, a, o, r);
}
function I(...t) {
	if (t.length === 2) return k(t[1]);
	let [n, r, i = {}] = t, { lang: a = "text", theme: o = n.getLoadedThemes()[0] } = i;
	if (l(a) || d(o)) throw new e("Plain language does not have grammar state");
	if (a === "ansi") throw new e("ANSI language does not have grammar state");
	let { theme: s, colorMap: c } = n.setTheme(o), u = n.getLanguage(a);
	return new A(R(r, u, s, c, i).stateStack, u.name, s.name);
}
function L(e, t, n, r, i) {
	let a = R(e, t, n, r, i), o = new A(a.stateStack, t.name, n.name);
	return O(a.tokens, o), a.tokens;
}
function R(e, r, i, s, c) {
	let l = a(i, c), { tokenizeMaxLineLength: u = 0, tokenizeTimeLimit: d = 500 } = c, f = m(e), p = c.grammarState ? M(c.grammarState, i.name) ?? n : c.grammarContextCode == null ? n : R(c.grammarContextCode, r, i, s, {
		...c,
		grammarState: void 0,
		grammarContextCode: void 0
	}).stateStack, h = [], g = [];
	for (let e = 0, n = f.length; e < n; e++) {
		let [n, a] = f[e];
		if (n === "") {
			h = [], g.push([]);
			continue;
		}
		if (u > 0 && n.length >= u) {
			h = [], g.push([{
				content: n,
				offset: a,
				color: "",
				fontStyle: 0
			}]);
			continue;
		}
		let m, _, v;
		c.includeExplanation && (m = r.tokenizeLine(n, p, d), _ = m.tokens, v = 0);
		let y = r.tokenizeLine2(n, p, d), b = y.tokens.length / 2;
		for (let e = 0; e < b; e++) {
			let r = y.tokens[2 * e], u = e + 1 < b ? y.tokens[2 * e + 2] : n.length;
			if (r === u) continue;
			let d = y.tokens[2 * e + 1], f = o(s[t.getForeground(d)], l), p = t.getFontStyle(d), m = {
				content: n.substring(r, u),
				offset: a + r,
				color: f,
				fontStyle: p
			};
			if (c.includeExplanation) {
				let e = [];
				if (c.includeExplanation !== "scopeName") for (let t of i.settings) {
					let n;
					switch (typeof t.scope) {
						case "string":
							n = t.scope.split(N).map((e) => e.trim());
							break;
						case "object":
							n = t.scope;
							break;
						default: continue;
					}
					e.push({
						settings: t,
						selectors: n.map((e) => e.split(P))
					});
				}
				m.explanation = [];
				let t = 0;
				for (; r + t < u;) {
					let r = _[v], i = n.substring(r.startIndex, r.endIndex);
					t += i.length, m.explanation.push({
						content: i,
						scopes: c.includeExplanation === "scopeName" ? z(r.scopes) : B(e, r.scopes)
					}), v += 1;
				}
			}
			h.push(m);
		}
		g.push(h), h = [], p = y.ruleStack;
	}
	return {
		tokens: g,
		stateStack: p
	};
}
function z(e) {
	return e.map((e) => ({ scopeName: e }));
}
function B(e, t) {
	let n = [];
	for (let r = 0, i = t.length; r < i; r++) {
		let i = t[r];
		n[r] = {
			scopeName: i,
			themeMatches: U(e, i, t.slice(0, r))
		};
	}
	return n;
}
function V(e, t) {
	return e === t || t.substring(0, e.length) === e && t[e.length] === ".";
}
function H(e, t, n) {
	if (!V(e.at(-1), t)) return !1;
	let r = e.length - 2, i = n.length - 1;
	for (; r >= 0 && i >= 0;) V(e[r], n[i]) && --r, --i;
	return r === -1;
}
function U(e, t, n) {
	let r = [];
	for (let { selectors: i, settings: a } of e) for (let e of i) if (H(e, t, n)) {
		r.push(a);
		break;
	}
	return r;
}
function W(e, t, n, r = F) {
	let i = Object.entries(n.themes).filter((e) => e[1]).map((e) => ({
		color: e[0],
		theme: e[1]
	})), a = i.map((i) => {
		let a = r(e, t, {
			...n,
			theme: i.theme
		});
		return {
			tokens: a,
			state: k(a),
			theme: typeof i.theme == "string" ? i.theme : i.theme.name
		};
	}), o = G(...a.map((e) => e.tokens)), s = o[0].map((e, t) => e.map((e, r) => {
		let a = {
			content: e.content,
			variants: {},
			offset: e.offset
		};
		return "includeExplanation" in n && n.includeExplanation && (a.explanation = e.explanation), o.forEach((e, n) => {
			let { content: o, explanation: s, offset: c, ...l } = e[t][r];
			a.variants[i[n].color] = l;
		}), a;
	})), c = a[0].state ? new A(Object.fromEntries(a.map((e) => [e.theme, e.state?.getInternalStack(e.theme)])), a[0].state.lang) : void 0;
	return c && O(s, c), s;
}
function G(...e) {
	let t = e.map(() => []), n = e.length;
	for (let r = 0; r < e[0].length; r++) {
		let i = e.map((e) => e[r]), a = t.map(() => []);
		t.forEach((e, t) => e.push(a[t]));
		let o = i.map(() => 0), s = i.map((e) => e[0]);
		for (; s.every((e) => e);) {
			let e = Math.min(...s.map((e) => e.content.length));
			for (let t = 0; t < n; t++) {
				let n = s[t];
				n.content.length === e ? (a[t].push(n), o[t] += 1, s[t] = i[t][o[t]]) : (a[t].push({
					...n,
					content: n.content.slice(0, e)
				}), s[t] = {
					...n,
					content: n.content.slice(e),
					offset: n.offset + e
				});
			}
		}
	}
	return t;
}
//#endregion
export { o as applyColorReplacements, F as codeToTokensBase, W as codeToTokensWithThemes, T as createShikiPrimitive, E as createShikiPrimitiveAsync, I as getLastGrammarState, k as getLastGrammarStateFromMap, d as isNoneTheme, l as isPlainLang, u as isSpecialLang, f as isSpecialTheme, c as normalizeGetter, v as normalizeTheme, a as resolveColorReplacements, O as setLastGrammarStateToMap, m as splitLines, s as toArray, L as tokenizeWithTheme };

//# sourceMappingURL=index.js.map