"use strict"; (() => { const form = $("notfound-form"), dialog = $("notfound-dialog"), list = $("notfound-list"); if (!form || !dialog || !list) return; const sortColumns = ["id", "name", "hostname", "status", "mode", "listeners", "certificate"]; let notFoundAutoCertificate = null, editing = null, revision = null, dirty = false, readBindings = () => [], readHosts = () => [], listPrefs = { sort: "id", descending: false }; function normalizeListPrefs(preferences) { return { sort: sortColumns.includes(preferences?.notfound_list_sort) ? preferences.notfound_list_sort : "id", descending: preferences?.notfound_list_descending === true }; } function syncSortDirection() { const control = $("notfound-sort-direction"); if (!control) return; control.textContent = listPrefs.descending ? "↓" : "↑"; control.setAttribute("aria-label", t(listPrefs.descending ? "backendSortDescending" : "backendSortAscending")); } function applyPreferences(preferences) { listPrefs = normalizeListPrefs(preferences); if ($("notfound-sort")) $("notfound-sort").value = listPrefs.sort; syncSortDirection(); render(); } async function saveListPrefs() { if (!authenticated) return; try { listPrefs = normalizeListPrefs(await window.rustProxyPreferences.update({ notfound_list_sort: listPrefs.sort, notfound_list_descending: listPrefs.descending })); if ($("notfound-sort")) $("notfound-sort").value = listPrefs.sort; syncSortDirection(); } catch (error) { if (error.status !== 401) toast(error.message, true); } } const syncEnabledControl = window.rustProxyEnableControl($("notfound-enabled")); const ERROR_STATUSES = [400, 401, 403, 404, 408, 413, 429, 500, 502, 503, 504]; const BUILTIN_STATUSES = [401, 403, 404, 429, 503, 504]; const CLOUDFLARE_STATUSES = [400, 401, 403, 404, 408, 410, 413, 429, 500, 502, 503, 504]; const STATUS_NAMES = { 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 408: "Request Timeout", 410: "Gone", 413: "Payload Too Large", 429: "Too Many Requests", 500: "Internal Server Error", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout" }; function populateStatuses(selected = null) { const select = $("notfound-status"); if (!select) return; const kind = $("notfound-mode")?.value; const codes = kind === "builtin" ? BUILTIN_STATUSES : kind === "cloudflare" ? CLOUDFLARE_STATUSES : ERROR_STATUSES; const wanted = Number(selected ?? select.value ?? 404); select.replaceChildren(...codes.map(code => { const node = el("option", `${code} ${STATUS_NAMES[code]}`); node.value = String(code); return node; })); select.value = codes.includes(wanted) ? String(wanted) : "404"; } const value = id => $(id).value.trim(), yes = id => $(id).checked; const defaults = () => ({ id: "", name: "", enabled: true, http2_enabled: true, http3_enabled: true, frontend: { hosts: [], listener_ids: [] }, certificate_id: null, page: { kind: "welcome", status: 404, html: "" } }); const option = (value, text) => { const node = el("option", text); node.value = value; return node; }; const changed = () => { dirty = true; }; const allowDiscard = async () => !dirty || await appConfirm(t("notfoundUnsaved"), { danger: true, confirmLabel: t("discardAction") }); function certificateChoices(selected) { const select = $("notfound-certificate"); select.replaceChildren(option("", t("vhCertificateDefault"))); for (const cert of envelope?.config.tls?.certificates || []) select.append(option(cert.id, cert.id)); select.value = selected || ""; } function listenerChoices(selected = []) { const holder = $("notfound-listeners"); holder.replaceChildren(); const control = window.rustProxyIntegrations.bindings(holder, selected, !editing); readBindings = control.read; const h2 = $("notfound-http2"), h3 = $("notfound-http3"); control.onChange(() => { const caps = control.capabilities(); h2.disabled = !caps.http2; h3.disabled = !caps.http3; if (!caps.http2) h2.checked = false; if (!caps.http3) h3.checked = false; }); } function syncMode() { const mode = $("notfound-mode").value; populateStatuses(); $("notfound-html-field").hidden = mode !== "html"; } function load(item = defaults()) { editing = item.id || null; revision = envelope?.revision ?? null; dirty = false; $("notfound-editing").textContent = editing || t("notfoundNewLabel"); $("notfound-id").value = item.id || ""; $("notfound-id").disabled = Boolean(editing); $("notfound-name").value = item.name || ""; window.rustProxyAutoId.attach($("notfound-id"), { elements: [$("notfound-name")], taken: () => (envelope?.config.not_found_hosts || []).map(value => value.id) }); $("notfound-enabled").checked = item.enabled !== false; syncEnabledControl(); $("notfound-http2").checked = item.http2_enabled !== false; $("notfound-http3").checked = item.http3_enabled !== false; const hostHolder = $("notfound-hosts-editor"); hostHolder.replaceChildren(); readHosts = window.rustProxyIntegrations.hostnames(hostHolder, item.frontend?.hosts || [], { labelKey: "notfoundHosts", helpKey: "vhHostsHelp", requiredKey: "notfoundHostsRequired", onChange: () => { changed(); notFoundAutoCertificate?.refresh(); } }); listenerChoices(item.frontend?.listener_ids || []); certificateChoices(item.certificate_id); notFoundAutoCertificate = window.rustProxyAutoCertificate.attach($("notfound-certificate"), { auto: !editing, hosts: () => { try { return readHosts(); } catch { return []; } }, certificates: () => envelope?.config.tls?.certificates || [] }); notFoundAutoCertificate.refresh(); $("notfound-mode").value = item.page?.kind || "welcome"; populateStatuses(item.page?.status ?? 404); $("notfound-html").value = item.page?.html || ""; syncMode(); dialog.showModal(); } function suspendDraft() { const state = { editing, revision, label: $("notfound-editing").textContent, controls: window.rustProxyDrafts.captureControls(form), hosts: window.rustProxyDrafts.takeChildren($("notfound-hosts-editor")), listeners: window.rustProxyDrafts.takeChildren($("notfound-listeners")), readBindings, readHosts }; const title = value("notfound-id") || editing || t("draftUntitled"); editing = null; revision = null; dirty = false; dialog.close(); return { title, state }; } function restoreDraft(state) { window.rustProxyDrafts.restoreChildren($("notfound-hosts-editor"), state.hosts); window.rustProxyDrafts.restoreChildren($("notfound-listeners"), state.listeners); readBindings = state.readBindings; readHosts = state.readHosts; editing = state.editing; revision = state.revision; dirty = true; $("notfound-editing").textContent = state.label; window.rustProxyDrafts.restoreControls(form, state.controls); syncEnabledControl(); syncMode(); if (!dialog.open) dialog.showModal(); } function closeEditor() { if (dirty) return window.rustProxyDrafts.dock("notfound"); if (dialog.open) dialog.close(); return true; } function collect() { const id = value("notfound-id"), name = value("notfound-name") || id, hosts = readHosts(), listener_ids = readBindings(), kind = value("notfound-mode"), status = Number(value("notfound-status")), html = $("notfound-html").value; if (!listener_ids.length) throw new Error(t("notfoundListenersRequired")); const allowed = kind === "builtin" ? BUILTIN_STATUSES : kind === "cloudflare" ? CLOUDFLARE_STATUSES : ERROR_STATUSES; if (!Number.isInteger(status) || !allowed.includes(status)) throw new Error(t("notfoundStatusInvalid")); if (kind === "html" && !html.trim()) throw new Error(t("notfoundHtmlRequired")); return { id, name, enabled: yes("notfound-enabled"), http2_enabled: yes("notfound-http2"), http3_enabled: yes("notfound-http3"), frontend: { hosts, listener_ids }, certificate_id: value("notfound-certificate") || null, page: { kind, status, html: kind === "html" ? html : "" } }; } function render() { if (!envelope) return; const query = ($("notfound-search").value || "").trim().toLowerCase(); const entries = (envelope.config.not_found_hosts || []).filter(item => !query || [item.id, item.name, ...(item.frontend?.hosts || [])].join(" ").toLowerCase().includes(query)); const sortValue = item => ({ id: String(item.id || "").toLowerCase(), name: String(item.name || item.id || "").toLowerCase(), hostname: String(item.frontend?.hosts?.[0] || "").toLowerCase(), status: Number(item.page?.status ?? 404), mode: String(item.page?.kind || "welcome"), listeners: (item.frontend?.listener_ids || []).join(" ").toLowerCase(), certificate: String(item.certificate_id || "").toLowerCase() }[listPrefs.sort]); entries.sort((left, right) => { const a = sortValue(left), b = sortValue(right); const result = typeof a === "number" && typeof b === "number" ? a - b : compareText(a, b); return listPrefs.descending ? -result : result; }); list.replaceChildren(...entries.map(item => { const card = el("article", undefined, "vhost-card redirect-card"), head = el("div", undefined, "vhost-card-head"), identity = el("div", undefined, "vhost-card-identity"), title = el("div", undefined, "vhost-title-line"); title.append(el("strong", item.name || item.id, "entity-title")); if (item.enabled === false) title.append(el("span", t("vhDisabled"), "pill")); identity.append(title); head.append(identity); const actions = el("div", undefined, "entity-actions"); actions.append(action(t("edit"), () => { window.rustProxyDrafts.prepare(); load(structuredClone(item)); }), action(t("copyEntry"), () => { window.rustProxyDrafts.prepare(); const copy = structuredClone(item); copy.id = ""; copy.name = ""; copy.frontend = { ...(copy.frontend || {}), hosts: [] }; copy.certificate_id = null; load(copy); }), action(t("remove"), async () => { if (busy || !(await appConfirm(t("confirmDelete"), { danger: true }))) return; const next = (envelope.config.not_found_hosts || []).filter(value => value.id !== item.id); if (await saveSection("not-found-hosts", next)) { if (editing === item.id) dialog.close(); render(); } })); head.append(actions); card.append(head); const flow = el("div", undefined, "redirect-flow"), from = el("div", undefined, "redirect-flow-from"), to = el("div", undefined, "redirect-flow-to"); for (const host of item.frontend?.hosts || []) from.append(el("span", host, "redirect-host-chip")); to.append(el("span", `${item.page?.status ?? 404} ${STATUS_NAMES[item.page?.status ?? 404] || ""}`.trim(), "redirect-target"), el("span", t(`notfoundMode${(item.page?.kind || "welcome").replace(/^./, c => c.toUpperCase())}`), "redirect-target-more")); flow.append(from, el("span", "→", "redirect-flow-arrow"), to); card.append(flow); const meta = el("div", undefined, "redirect-meta"); for (const [k, v] of [["redirectListeners", (item.frontend?.listener_ids || []).join(", ") || "-"], ["vhCertificate", item.certificate_id || t("vhCertificateDefault")]]) { const node = el("span", undefined, "redirect-meta-item"); node.append(el("span", t(k)), el("b", v)); meta.append(node); } card.append(meta); return card; })); if (!entries.length) list.append(el("p", t(query ? "notfoundSearchEmpty" : "notfoundEmpty"), "fine")); } form.addEventListener("input", changed); form.addEventListener("change", changed); $("notfound-mode").addEventListener("change", syncMode); $("notfound-status").addEventListener("change", syncMode); form.addEventListener("submit", async event => { event.preventDefault(); if (!envelope || busy) return; const invalid = [...form.elements].find(input => input.willValidate && !input.checkValidity()); if (invalid) { invalid.reportValidity(); return; } if (revision !== envelope.revision) { toast(t("stale"), true); return; } try { const item = collect(), next = structuredClone(envelope.config.not_found_hosts || []); if (!editing && next.some(value => value.id === item.id)) throw new Error(t("notfoundDuplicate")); const index = next.findIndex(value => value.id === editing); if (index < 0) next.push(item); else next[index] = item; if (await saveSection("not-found-hosts", next)) { dirty = false; editing = item.id; dialog.close(); render(); } } catch (error) { toast(error.message, true); } }); $("notfound-new").addEventListener("click", () => { window.rustProxyDrafts.prepare(); load(); }); $("notfound-search").addEventListener("input", render); $("notfound-sort")?.addEventListener("change", event => { listPrefs.sort = event.target.value; void saveListPrefs(); render(); }); $("notfound-sort-direction")?.addEventListener("click", () => { listPrefs.descending = !listPrefs.descending; syncSortDirection(); void saveListPrefs(); render(); }); $("notfound-close").addEventListener("click", closeEditor); $("notfound-reset").addEventListener("click", async () => { if (await allowDiscard()) load(editing ? structuredClone((envelope?.config.not_found_hosts || []).find(item => item.id === editing) || defaults()) : defaults()); }); dialog.addEventListener("cancel", event => { event.preventDefault(); closeEditor(); }); window.rustProxyDrafts.register("notfound", { labelKey: "notfound", isOpen: () => dialog.open, isDirty: () => dirty, suspend: suspendDraft, restore: restoreDraft, close: () => { dirty = false; if (dialog.open) dialog.close(); } }); window.rustProxyNotFound = { render, applyPreferences, reset() { dialog.close(); editing = null; revision = null; dirty = false; listPrefs = { sort: "id", descending: false }; list.replaceChildren(); $("notfound-search").value = ""; if ($("notfound-sort")) $("notfound-sort").value = listPrefs.sort; syncSortDirection(); } }; if (envelope) render(); })();