async function readJsonResponse(response) { const text = await response.text(); if (!text) { return {}; } try { return JSON.parse(text); } catch (error) { throw new Error(text); } } function loginRedirectPath() { return `/login?next=${encodeURIComponent(`${window.location.pathname}${window.location.search}`)}`; } window.addEventListener("DOMContentLoaded", async () => { const bootIndicator = document.getElementById("boot-indicator"); const root = document.getElementById("select-root"); const errorNode = document.getElementById("select-error"); const usernameNode = document.getElementById("select-username"); const logoutButton = document.getElementById("select-logout"); const showPage = () => { if (bootIndicator) { bootIndicator.hidden = true; } if (root) { root.hidden = false; } }; const setError = (message) => { if (!errorNode) { return; } errorNode.textContent = message || ""; errorNode.hidden = !message; }; try { const response = await fetch("/api/auth/session", { cache: "no-store", credentials: "same-origin", }); const payload = await readJsonResponse(response); if (response.status === 401) { window.location.replace(loginRedirectPath()); return; } if (!response.ok) { throw new Error(payload.error || `HTTP ${response.status}`); } if (usernameNode) { usernameNode.textContent = payload.username || ""; usernameNode.hidden = !payload.username; } } catch (error) { setError(error instanceof Error ? error.message : String(error)); } finally { showPage(); } if (!(logoutButton instanceof HTMLButtonElement)) { return; } logoutButton.addEventListener("click", async () => { logoutButton.disabled = true; try { await fetch("/api/auth/logout", { method: "POST", credentials: "same-origin", }); } finally { window.location.replace("/login"); } }); });