import { signal } from "@preact/signals";
import { u } from "./base.js";
export const signedOut = signal(false);
const SIGNED_OUT_EVENT = "mobux:signed-out";
export function isSignedOutResponse(res) {
if (res.type === "opaqueredirect") return true;
return (
res.status === 401 &&
(res.headers.get("www-authenticate") || "").includes("cloudflare-access")
);
}
export function markSignedOut() {
signedOut.value = true;
}
export async function probeSession() {
if (signedOut.value) return true;
const res = await fetch(u("/api/build-info"), {
headers: { Accept: "application/json" },
credentials: "same-origin",
redirect: "manual",
}).catch(() => null);
if (!res) return false;
res.body?.cancel().catch(() => {});
if (isSignedOutResponse(res)) markSignedOut();
return signedOut.value;
}
if (typeof window !== "undefined") {
window.addEventListener(SIGNED_OUT_EVENT, markSignedOut);
}
const ROUTE_PARAM = "mobux_route";
export function signInUrl(location = window.location) {
const url = new URL(location.href);
if (url.hash) url.searchParams.set(ROUTE_PARAM, url.hash);
return url.href;
}
export function restoreSignInRoute(location = window.location) {
const url = new URL(location.href);
const route = url.searchParams.get(ROUTE_PARAM);
if (route === null) return;
url.searchParams.delete(ROUTE_PARAM);
if (route.startsWith("#")) url.hash = route;
window.history.replaceState(null, "", url.href);
}