import { n as e } from "../sanitize-CDxuPfMB.js";
//#region src/services/router.ts
function t(e, t) {
	let n = [], r = t;
	r.startsWith(e) && (r = r.slice(e.length)), r.startsWith("/") || (r = "/" + r);
	let i = r.split("/").map((e) => e.startsWith(":") ? (n.push(e.slice(1)), "([^/]+)") : e.startsWith("*") ? (n.push(e.slice(1)), "(.*)") : e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")), a = e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + i.join("/");
	return {
		regex: RegExp("^" + a + "/?$"),
		paramNames: n
	};
}
var n = class {
	apps = /* @__PURE__ */ new Map();
	compiledRoutes = [];
	moduleLoaders = /* @__PURE__ */ new Map();
	loadedModules = /* @__PURE__ */ new Map();
	currentRoute = null;
	currentAppPrefix = null;
	config;
	listeners = /* @__PURE__ */ new Map();
	clickHandler = null;
	popstateHandler = null;
	started = !1;
	constructor(e) {
		this.config = {
			contentSelector: e?.contentSelector ?? "#app-content",
			interceptLinks: e?.interceptLinks ?? !0,
			onAuthError: e?.onAuthError ?? ((e) => {
				window.location.href = "/login";
			}),
			transitionClass: e?.transitionClass ?? "page__content--transitioning",
			sanitizeFetchedHtml: e?.sanitizeFetchedHtml ?? !1,
			onAfterSwap: e?.onAfterSwap ?? (() => {})
		};
	}
	registerApp(e) {
		this.apps.set(e.prefix, e);
		let n = e.routes.map((n) => {
			let { regex: r, paramNames: i } = t(e.prefix, n.pattern);
			return {
				definition: n,
				regex: r,
				paramNames: i,
				appPrefix: e.prefix
			};
		});
		n.sort((e, t) => {
			let n = e.definition.pattern.split("/").length;
			return t.definition.pattern.split("/").length - n;
		}), this.compiledRoutes.push(...n), this.compiledRoutes.sort((e, t) => t.appPrefix.length === e.appPrefix.length ? t.definition.pattern.split("/").length - e.definition.pattern.split("/").length : t.appPrefix.length - e.appPrefix.length);
	}
	registerModule(e, t) {
		this.moduleLoaders.set(e, t);
	}
	matchRoute(e) {
		for (let t of this.compiledRoutes) {
			let n = t.regex.exec(e);
			if (n) {
				let r = {};
				return t.paramNames.forEach((e, t) => {
					r[e] = decodeURIComponent(n[t + 1] ?? "");
				}), {
					pattern: t.definition.pattern,
					params: r,
					path: e,
					appPrefix: t.appPrefix,
					view: t.definition.view,
					navSection: t.definition.navSection
				};
			}
		}
		for (let [t, n] of this.apps) if (e === t || e === t + "/") return {
			pattern: t,
			params: {},
			path: e,
			appPrefix: t,
			view: n.defaultView ?? "dashboard",
			navSection: void 0
		};
		return null;
	}
	getCurrentRoute() {
		return this.currentRoute;
	}
	async navigate(e, t) {
		let n = t?.pushState ?? !0, r = t?.replace ?? !1, i = this.matchRoute(e);
		if (!i) {
			window.location.href = e;
			return;
		}
		let a = this.currentRoute;
		a !== null && a.appPrefix === i.appPrefix ? await this.navigateIntraApp(i, n, r) : await this.navigateCrossApp(i, n, r), this.setCurrentRoute(i), this.emit("navigate", {
			from: a,
			to: i,
			path: e
		});
	}
	async navigateIntraApp(e, t, n) {
		let r = this.apps.get(e.appPrefix);
		r && this.showAppView(r, e.view, e.navSection), t && this.pushOrReplace(e.path, n), this.setCurrentRoute(e);
		let i = this.loadedModules.get(e.appPrefix);
		i && await i.init(e.params), window.scrollTo(0, 0);
	}
	async navigateCrossApp(e, t, n) {
		let r = document.querySelector(this.config.contentSelector);
		if (!r) {
			window.location.href = e.path;
			return;
		}
		let i = this.currentAppPrefix ? this.loadedModules.get(this.currentAppPrefix) : null;
		if (i?.destroy && await i.destroy(), r.classList.add(this.config.transitionClass), !this.isSameOriginPath(e.path)) {
			r.classList.remove(this.config.transitionClass), window.location.href = e.path;
			return;
		}
		let a;
		try {
			let t = await fetch(e.path, { credentials: "same-origin" });
			if (t.status === 401 || t.status === 403) {
				r.classList.remove(this.config.transitionClass), this.config.onAuthError(t.status);
				return;
			}
			if (t.redirected) {
				r.classList.remove(this.config.transitionClass), window.location.href = t.url;
				return;
			}
			if (!t.ok) {
				r.classList.remove(this.config.transitionClass), window.location.href = e.path;
				return;
			}
			a = await t.text();
		} catch {
			r.classList.remove(this.config.transitionClass), window.location.href = e.path;
			return;
		}
		let o = new DOMParser().parseFromString(a, "text/html"), s = o.querySelector(this.config.contentSelector);
		if (!s) {
			r.classList.remove(this.config.transitionClass), window.location.href = e.path;
			return;
		}
		let c = document.querySelector(".page__shell");
		if (c) {
			let e = c.querySelector(":scope > aside[data-sidebar]"), t = c.querySelector(":scope > .sidebar__backdrop");
			e && e.remove(), t && t.remove();
			let n = o.querySelector(".page__shell");
			if (n) {
				let e = n.querySelector(":scope > aside[data-sidebar]"), t = n.querySelector(":scope > .sidebar__backdrop"), r = c.querySelector("main");
				if (e && r) {
					let t = this.prepareFetchedElement(e);
					t && c.insertBefore(t, r);
				}
				if (t && r) {
					let e = this.prepareFetchedElement(t);
					e && c.insertBefore(e, r);
				}
			}
		}
		r.innerHTML = this.prepareFetchedHtml(s.innerHTML), r.className = s.className, document.body.className = o.body.className, document.title = o.title;
		let l = document.getElementById("web-config"), u = o.getElementById("web-config");
		l && u && (l.textContent = u.textContent), t && this.pushOrReplace(e.path, n), this.setCurrentRoute(e), await this.loadAndInitModule(e), await this.config.onAfterSwap(), r.classList.remove(this.config.transitionClass), window.scrollTo(0, 0);
	}
	async loadAndInitModule(e) {
		let t = this.loadedModules.get(e.appPrefix);
		if (!t) {
			let n = this.moduleLoaders.get(e.appPrefix);
			n && (t = await n(), this.loadedModules.set(e.appPrefix, t));
		}
		if (t) {
			let n = this.apps.get(e.appPrefix);
			n && this.showAppView(n, e.view, e.navSection), await t.init(e.params);
		}
	}
	showAppView(e, t, n) {
		let r = e.viewAttribute, i = e.navAttribute, a = e.activeViewClass ?? `${e.prefix.slice(1)}-view--active`, o = e.activeNavClass ?? "sidebar__item--active";
		document.querySelectorAll(`[${r}]`).forEach((e) => {
			let n = e.getAttribute(r) === t;
			e.classList.toggle(a, n), n ? e.removeAttribute("hidden") : e.setAttribute("hidden", "true");
		});
		let s = n ?? t;
		document.querySelectorAll(`[${i}]`).forEach((e) => {
			e.classList.toggle(o, e.getAttribute(i) === s);
		});
	}
	start() {
		if (this.started) return;
		this.started = !0, this.config.interceptLinks && (this.clickHandler = (e) => {
			if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey || e.button !== 0) return;
			let t = e.target.closest("a[href]");
			if (!t || t.origin !== window.location.origin || t.target === "_blank" || t.target === "_parent" || t.target === "_top" || t.hasAttribute("data-no-router") || t.hasAttribute("download")) return;
			let n = t.pathname;
			this.matchRoute(n) && (e.preventDefault(), this.navigate(n, { pushState: !0 }));
		}, document.addEventListener("click", this.clickHandler)), this.popstateHandler = () => {
			this.navigate(window.location.pathname, { pushState: !1 });
		}, window.addEventListener("popstate", this.popstateHandler);
		let e = this.matchRoute(window.location.pathname);
		e && (this.currentRoute = e, this.currentAppPrefix = e.appPrefix, this.loadAndInitModule(e));
	}
	destroy() {
		this.clickHandler &&= (document.removeEventListener("click", this.clickHandler), null), this.popstateHandler &&= (window.removeEventListener("popstate", this.popstateHandler), null), this.started = !1, this.listeners.clear();
	}
	on(e, t) {
		let n = this.listeners.get(e);
		return n || (n = /* @__PURE__ */ new Set(), this.listeners.set(e, n)), n.add(t), () => {
			n.delete(t);
		};
	}
	emit(e, t) {
		let n = this.listeners.get(e);
		if (n) for (let e of n) e(t);
	}
	pushOrReplace(e, t) {
		let n = {
			scrollX: window.scrollX,
			scrollY: window.scrollY
		};
		window.history.replaceState({
			...window.history.state,
			...n
		}, "", window.location.href), t ? window.history.replaceState({}, "", e) : window.history.pushState({}, "", e);
	}
	setCurrentRoute(e) {
		this.currentRoute = e, this.currentAppPrefix = e.appPrefix;
	}
	isSameOriginPath(e) {
		try {
			return new URL(e, window.location.origin).origin === window.location.origin;
		} catch {
			return !1;
		}
	}
	prepareFetchedHtml(t) {
		return this.config.sanitizeFetchedHtml ? e(t, { allowSvg: !0 }) : t;
	}
	prepareFetchedElement(e) {
		if (!this.config.sanitizeFetchedHtml) return e;
		let t = document.createElement("template");
		return t.innerHTML = this.prepareFetchedHtml(e.outerHTML), t.content.firstElementChild;
	}
	clearModuleCache() {
		this.loadedModules.clear();
	}
};
function r(e) {
	return new n(e);
}
//#endregion
export { n as Router, r as createRouter };

//# sourceMappingURL=router.js.map