"use strict";
const REFRESH_INTERVAL_MS = 5_000;
const REQUEST_TIMEOUT_MS = 10_000;
const MAX_PORT = 65_535;
const MAX_PID = 4_294_967_295;
const DURATION_UNITS = new Map([["d", 86_400], ["h", 3_600], ["m", 60], ["s", 1]]);
const MAX_DURATION_SECONDS = 9_223_372_036_854_775_807n;
const WEB_PATH = /^\/[A-Za-z0-9._~/-]{0,127}$/;
const LABEL_PATTERN = "(?!\\.{1,2}$)[a-z0-9._\\-]{1,64}";
const ZONE_LABEL_PATTERN = "(?!\\.{1,2}$)[A-Za-z0-9._\\-]{1,64}";
const COMPONENT_PATTERN = "[a-z0-9\\-]{1,32}";
const CONTAINER_PATTERN = "[a-zA-Z0-9][a-zA-Z0-9_.\\-]{0,127}";
const ACCESS_MESSAGE = "Page access token unavailable. Reload the console.";
const API_ROOT = "/api/v1";
const PORTS_URL = "/api/v1/ports";
const DRIFT_URL = "/api/v1/drift";
const DRIFT_INK = { leases_expiring: "expire-ink", zone_conflicts: "conflict-ink" };
const APPS_URL = "/api/v1/apps";
const ZONES_URL = "/api/v1/zones";
const SWEEP_URL = "/api/v1/sweep";
const HISTORY_URL = "/api/v1/history";
const THEME_KEY = "troll.console.theme";
const THEMES = new Set(["slate", "graphite", "harbor", "daylight", "meridian", "parchment"]);
function applyTheme(value) {
const theme = THEMES.has(value) ? value : "system";
if (theme === "system") document.documentElement.removeAttribute("data-theme");
else document.documentElement.dataset.theme = theme;
return theme;
}
function readTheme() {
try {
return applyTheme(localStorage.getItem(THEME_KEY));
} catch (_) {
return applyTheme("system");
}
}
function saveTheme(value) {
const theme = applyTheme(value);
try {
if (theme === "system") localStorage.removeItem(THEME_KEY);
else localStorage.setItem(THEME_KEY, theme);
} catch (_) {
}
return theme;
}
const byId = id => document.getElementById(id);
const token = document.querySelector('meta[name="troll-token"]')?.content;
const refreshToggle = byId("refresh-toggle");
const searchInput = byId("search-filter");
const kindSelect = byId("kind-filter");
const listenerSelect = byId("listener-filter");
const protocolSelect = byId("protocol-filter");
const driftButtons = document.querySelectorAll("#drift-filters [data-drift]");
const registryRows = byId("registry-rows");
const dialog = byId("action-dialog");
const form = byId("action-form");
const fields = byId("dialog-fields");
const dialogCancel = byId("dialog-cancel");
const dialogSubmit = byId("dialog-submit");
const dialogReview = byId("dialog-review");
const dialogRecover = byId("dialog-recover");
const dialogUseCurrent = byId("dialog-use-current");
const relativeTime = new Intl.RelativeTimeFormat(undefined, { numeric: "always" });
const localTime = new Intl.DateTimeFormat(undefined, { timeStyle: "medium" });
let snapshot = null;
let historySnapshot = null;
let historyRequest = null;
let refreshRequest = null;
let stale = false;
let paused = false;
let driftFilter = null;
let tokenRejected = null;
let active = null;
let screen = "console";
let pendingTarget = null;
let locationDeferred = false;
function element(tag, content, className) {
const node = document.createElement(tag);
setContent(node, content);
if (className) node.className = className;
return node;
}
function setContent(node, content) {
if (Array.isArray(content)) node.replaceChildren(...content);
else if (content !== undefined) node.textContent = content;
}
function isolatedText(value) {
const node = element("bdi", value, "isolated-text");
node.dir = "auto";
return node;
}
function isolatedNames(names) {
return names.flatMap((name, index) => index ? [", ", isolatedText(name)] : [isolatedText(name)]);
}
function setText(node, message) {
if (node.textContent !== message) node.textContent = message;
}
function showMessage(id, message) {
const node = byId(id);
setText(node, message);
node.hidden = !message;
}
function button(label, handle, { className = "button", name, key } = {}) {
const node = element("button", label, className);
node.type = "button";
if (name) node.ariaLabel = name;
if (key) node.dataset.focusKey = key;
node.addEventListener("click", handle);
return node;
}
function endpoint(collection, ...segments) {
const encoded = segments.map(segment => encodeURIComponent(segment));
if (encoded.some(segment => segment === "." || segment === "..")) {
throw new Error("The entry name is a reserved URL path segment.");
}
return [API_ROOT, collection, ...encoded].join("/");
}
function withQuery(path, values) {
return path + "?" + new URLSearchParams(values);
}
class ApiError extends Error {
constructor(status, problem) {
super(typeof problem?.message === "string" ? problem.message : `HTTP ${status}`);
this.status = status;
this.kind = problem?.kind;
}
}
async function requestJson(path, { method = "GET", tag, body, signal } = {}) {
const controller = new AbortController();
const abort = () => controller.abort(signal.reason);
if (signal?.aborted) abort();
else signal?.addEventListener("abort", abort, { once: true });
const timeout = setTimeout(() => {
controller.abort(new DOMException("Request timed out.", "TimeoutError"));
}, REQUEST_TIMEOUT_MS);
const headers = {};
if (method !== "GET") {
if (!canWrite()) {
clearTimeout(timeout);
signal?.removeEventListener("abort", abort);
throw new Error(ACCESS_MESSAGE);
}
headers["X-Troll-Token"] = token;
}
if (tag !== undefined) headers["If-Match"] = tag;
if (body !== undefined) headers["Content-Type"] = "application/json";
try {
const response = await fetch(path, {
method, headers, signal: controller.signal,
body: body === undefined ? undefined : JSON.stringify(body),
mode: "same-origin", redirect: "error", cache: "no-store",
referrer: "", referrerPolicy: "same-origin",
});
if (!response.ok) {
const json = await response.json().catch(() => null);
const error = new ApiError(response.status, json?.error);
if (response.status === 401 && method !== "GET") {
tokenRejected = error.message;
renderAccess();
}
throw error;
}
return await response.json();
} finally {
signal?.removeEventListener("abort", abort);
clearTimeout(timeout);
}
}
function canWrite() {
return Boolean(token) && tokenRejected === null;
}
function renderAccess() {
byId("access-warning").hidden = canWrite();
setText(byId("access-message"), canWrite() ? "" : ACCESS_MESSAGE);
setText(byId("rejected-token-message"), active ? "" : (tokenRejected ?? ""));
byId("dialog-access").hidden = canWrite();
for (const node of document.querySelectorAll("[data-write]")) {
node.disabled = !canWrite() || !snapshot;
}
updateDialogControls();
}
function refresh({ fresh = false, automatic = false, forAction = false } = {}) {
if (refreshRequest && (!fresh || refreshRequest.forAction)) {
if (forAction) refreshRequest.forAction = true;
return refreshRequest.promise;
}
refreshRequest?.controller.abort();
const controller = new AbortController();
const request = { controller, automatic, forAction };
refreshRequest = request;
request.promise = loadRegistry(request);
return request.promise;
}
async function loadRegistry(request) {
const { controller } = request;
const options = { signal: controller.signal };
byId("retry-refresh").disabled = true;
try {
const [ports, drift, apps, zones] = await Promise.all([
requestJson(PORTS_URL, options), requestJson(DRIFT_URL, options),
requestJson(APPS_URL, options), requestJson(ZONES_URL, options),
]);
if (request !== refreshRequest) return null;
snapshot = registrySnapshot(ports, drift, apps, zones);
stale = false;
registryRows.classList.remove("stale");
byId("fetch-error").hidden = true;
setText(byId("fetch-error-message"), "");
const skipped = Math.max(ports.skipped_rows, drift.skipped_rows);
showMessage("scan-warning", ports.complete && drift.complete ? "" :
`Listener scan incomplete: up to ${skipped} ${skipped === 1 ? "row" : "rows"} per scan could not be read. Ports or owners may be missing.`);
const now = new Date();
const lastRefresh = byId("last-refresh");
lastRefresh.dateTime = now.toISOString();
lastRefresh.textContent = localTime.format(now);
renderRegistry(now.getTime());
if (screen === "history") void loadHistory();
updateOpenScope();
return true;
} catch (error) {
if (request !== refreshRequest) return null;
stale = true;
registryRows.classList.add("stale");
byId("fetch-error").hidden = false;
let message = "Could not refresh the registry.";
const detail = error.message.trim();
if (detail) message += ` ${detail}${/[\p{Sentence_Terminal}โฆ]$/u.test(detail) ? "" : "."}`;
if (snapshot) message += " Showing stale data from the last successful refresh.";
setText(byId("fetch-error-message"), message);
return false;
} finally {
controller.abort();
if (request === refreshRequest) {
refreshRequest = null;
byId("loading-status").hidden = true;
byId("retry-refresh").disabled = false;
}
}
}
function refreshIfRunning() {
if (!paused && !document.hidden) void refresh({ automatic: true });
}
async function loadHistory() {
if (historyRequest) return historyRequest;
historyRequest = requestJson(HISTORY_URL)
.then(data => {
historySnapshot = data;
if (screen === "history") renderRegistry();
return data;
})
.catch(() => null)
.finally(() => {
historyRequest = null;
});
return historyRequest;
}
function rowProtocol(row) {
return row?.protocol === "udp" ? "udp" : "tcp";
}
function portDisplay(row) {
return rowProtocol(row) === "udp" ? `${row.port}/udp` : String(row.port);
}
function rowKey(tier, row) {
if (tier === "unregistered") return JSON.stringify([tier, row.id]);
return JSON.stringify([tier, row.port, rowProtocol(row), row.bind, row.leased_at ?? null]);
}
function driftKey(tier, row) {
if (tier === "unregistered") return JSON.stringify([tier, row.port, rowProtocol(row), row.bind]);
return rowKey(tier, row);
}
function rowId(tier, row) {
if (tier === "unregistered") return `unregistered-socket-${row.id}`;
const bind = String(row.bind).replaceAll(":", "_").replaceAll(".", "-");
const proto = rowProtocol(row) === "udp" ? "-udp" : "";
const suffix = tier === "lease" ? `-${row.leased_at}` : "";
return `${tier}-port-${row.port}${proto}-${bind}${suffix}`;
}
function zoneKey(label) {
return String(label ?? "").toLowerCase();
}
function zoneId(zone) {
return `zone-row-${zoneKey(zone.label)}`;
}
function groupBy(rows, field) {
const groups = new Map();
for (const row of rows) {
const key = row[field];
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(row);
}
return groups;
}
function sortPorts(rows) {
return rows.sort((a, b) => a.port - b.port || rowProtocol(a).localeCompare(rowProtocol(b)) || a.bind.localeCompare(b.bind));
}
function projectMembership(permanent, apps) {
const unmatched = new Map(permanent.map(row => [rowKey("permanent", row), row]));
const projects = new Map();
for (const { app, entries } of apps) {
const members = [];
for (const entry of entries) {
const key = rowKey("permanent", entry);
const observed = unmatched.get(key);
if (observed?.project !== app) continue;
members.push(observed);
unmatched.delete(key);
}
if (members.length) projects.set(app, sortPorts(members));
}
for (const [project, rows] of groupBy(unmatched.values(), "project")) {
projects.set(project, sortPorts([...(projects.get(project) ?? []), ...rows]));
}
return projects;
}
function allocationKey(tier, row) {
return JSON.stringify([tier, row.port, rowProtocol(row), row.project]);
}
function zoneConflicts(zones, permanent, leases) {
const enabled = new Map(zones.zones.filter(zone => zone.enabled).map(zone => [zoneKey(zone.label), zone]));
const labelsByAllocation = new Map();
for (const conflict of zones.conflicts) {
const zkey = zoneKey(conflict.label);
if (!enabled.has(zkey)) continue;
const key = allocationKey(conflict.tier, conflict);
if (!labelsByAllocation.has(key)) labelsByAllocation.set(key, new Set());
labelsByAllocation.get(key).add(zkey);
}
const conflictsByZone = new Map();
const zonesByRow = new Map();
for (const [tier, rows] of [["permanent", permanent], ["lease", leases]]) {
for (const row of rows) {
const labels = labelsByAllocation.get(allocationKey(tier, row));
if (!labels) continue;
zonesByRow.set(rowKey(tier, row), [...labels].map(label => enabled.get(label)));
for (const label of labels) {
if (!conflictsByZone.has(label)) conflictsByZone.set(label, []);
conflictsByZone.get(label).push({ tier, row });
}
}
}
return { conflictsByZone, zonesByRow };
}
function registrySnapshot(ports, drift, apps, zones) {
const permanent = sortPorts([...ports.apps, ...ports.services]);
const projects = projectMembership(permanent, apps.apps);
const appGroups = [...projects.values()].filter(rows => rows.length > 1 || rows[0].component);
const singles = permanent.filter(row => projects.get(row.project).length === 1 && !row.component);
const stacks = groupBy(ports.leases.filter(row => row.group), "group");
const conflicts = zoneConflicts(zones, permanent, ports.leases);
const appDetails = new Map(apps.apps.map(app => [app.app, app]));
const portCounts = new Map();
for (const row of [...permanent, ...ports.leases, ...ports.unregistered]) {
portCounts.set(row.port, (portCounts.get(row.port) ?? 0) + 1);
}
const sharedPorts = new Set([...portCounts].filter(([, count]) => count > 1).map(([port]) => port));
return {
ports, drift, zones: zones.zones, permanent, projects, appGroups, appDetails, singles, stacks, sharedPorts,
...conflicts,
};
}
function searchFields(tier, row) {
const listeners = tier === "unregistered" ? [row] : row.listeners;
const processes = listeners.flatMap(listener => [
listener.container?.name, listener.container?.image,
...listener.owners.flatMap(owner => [owner.name, owner.exe, owner.cwd, owner.unit, owner.package_name]),
]);
const own = tier === "unregistered" ? [] : tier === "permanent" ?
[row.project, row.component, row.service, row.claimed_by, row.container] :
[row.project, row.component, row.purpose, row.group, row.holder];
const detected = row.service_info ? [row.service_info.name, row.service_info.category] : [];
return [String(row.port), rowProtocol(row), ...own, ...detected, ...processes]
.filter(field => typeof field === "string" && field)
.map(field => field.toLowerCase());
}
function searchTerms() {
return searchInput.value.toLowerCase().split(/\s+/).filter(Boolean);
}
function matchingRows(now) {
const { drift, permanent, ports } = snapshot;
const kind = kindSelect.value;
const listener = listenerSelect.value;
const protocol = protocolSelect.value;
const terms = searchTerms();
let keys;
if (driftFilter === "listening_unclaimed") {
keys = drift.listening_unclaimed.map(row => driftKey("unregistered", row));
} else if (driftFilter === "claimed_silent") {
keys = drift.claimed_silent.map(row => driftKey(row.tier, row));
} else if (driftFilter === "leases_expiring") {
keys = drift.leases_expiring.map(row => driftKey("lease", row));
} else if (driftFilter === "zone_conflicts") {
const conflicted = new Set(drift.zone_conflicts.map(conflict =>
allocationKey(conflict.tier, conflict)));
keys = [
...permanent.filter(row => conflicted.has(allocationKey("permanent", row)))
.map(row => driftKey("permanent", row)),
...ports.leases.filter(row => conflicted.has(allocationKey("lease", row)))
.map(row => driftKey("lease", row)),
];
}
const driftKeys = keys && new Set(keys);
return {
now,
filtered: Boolean(driftKeys) || kind !== "all" || listener !== "all" || protocol !== "all" || terms.length > 0,
matches(tier, row) {
const state = tier === "unregistered" ? "listening" :
(row.status === "listening" || row.status === "silent" ? row.status : "unknown");
if (terms.length) {
const fields = searchFields(tier, row);
if (!terms.every(term => fields.some(field => field.includes(term)))) return false;
}
return (!driftKeys || driftKeys.has(driftKey(tier, row))) &&
(protocol === "all" || rowProtocol(row) === protocol) &&
(listener === "all" || listener === state) &&
(kind === "all" || listenerKinds(tier === "unregistered" ? [row] : row.listeners).includes(kind));
},
};
}
function listenerKinds(listeners) {
return listeners.length ? [...new Set(listeners.map(listener => listener.kind))] : ["unknown"];
}
const LABELLED_PART = 'section[aria-labelledby], [role="group"][aria-labelledby]';
function sectionHeadings(node) {
const headings = [];
for (let section = node.closest(LABELLED_PART); section;
section = section.parentElement?.closest(LABELLED_PART)) {
headings.push(section.getAttribute("aria-labelledby"));
}
return headings;
}
function captureRowFocus(node) {
if (!registryRows.contains(node)) return null;
return { node, key: node.dataset.focusKey, headings: sectionHeadings(node) };
}
function isShown(node) {
return node.isConnected && !node.closest("[hidden]");
}
function focusLeftScreen() {
const node = document.activeElement;
return !node || node === document.body || !isShown(node);
}
function restoreFocus(target) {
if (!target) return;
const replacement = target.key && [...registryRows.querySelectorAll("[data-focus-key]")]
.find(node => node.dataset.focusKey === target.key && isShown(node));
const next = isShown(target.node) ? target.node : replacement;
if (next && !next.disabled) {
next.focus({ preventScroll: true });
return;
}
const heading = target.headings.map(byId).find(node => node && isShown(node));
heading?.focus({ preventScroll: true });
}
function renderRegistry(now = Date.now()) {
for (const node of driftButtons) {
const key = node.dataset.drift;
node.setAttribute("aria-pressed", String(driftFilter === key));
const count = node.querySelector("[data-count]");
setText(count, snapshot ? String(snapshot.drift.counts[key]) : "โ");
const ink = DRIFT_INK[key];
if (ink) count.classList.toggle(ink, Boolean(snapshot && snapshot.drift.counts[key] > 0));
node.disabled = !snapshot;
}
renderSummary(now);
if (!snapshot) return;
const focused = captureRowFocus(document.activeElement);
const match = matchingRows(now);
if (screen === "apps") renderApps(match);
else if (screen === "history") renderHistory(match);
else renderConsole(match);
renderMatchSummary(match);
renderAccess();
if (!active) restoreFocus(focused);
revealPendingTarget();
}
function renderSummary(now) {
const urgent = snapshot ? snapshot.ports.leases.filter(row => leaseTiming(row, now).warm).length : null;
const sockets = snapshot ? new Set([
...snapshot.permanent.flatMap(row => row.listeners), ...snapshot.ports.leases.flatMap(row => row.listeners),
...snapshot.ports.unregistered,
].map(socket => socket.id)).size : null;
setText(byId("claims-held"), snapshot ? String(snapshot.permanent.length) : "โ");
setText(byId("leases-held"), snapshot ? String(snapshot.ports.leases.length) : "โ");
setText(byId("listening-now"), snapshot ? String(sockets) : "โ");
const urgency = byId("leases-urgent");
setText(urgency, snapshot ? (urgent ? `${counted(urgent, "lease expires", "leases expire")} within five minutes` :
"No lease expires within five minutes") : "");
urgency.classList.toggle("urgent", urgent > 0);
}
function renderMatchSummary(match) {
const { permanent, ports } = snapshot;
const matched = permanent.filter(row => match.matches("permanent", row)).length +
ports.leases.filter(row => match.matches("lease", row)).length +
ports.unregistered.filter(row => match.matches("unregistered", row)).length;
const context = registryRows.querySelectorAll(".entry").length - matched;
setText(byId("match-summary"), !match.filtered ? "" :
`${matched} matched` + (context > 0 ? ` ยท ${counted(context, "context row", "context rows")} shown` : ""));
}
const CONSOLE_PANELS = ["app-groups", "single-claim-rows", "lease-rows", "unregistered-rows", "zone-rows"];
const APPS_PANELS = ["project-rows", "no-claim-rows"];
const HISTORY_PANELS = ["history-rows"];
function renderConsole(match) {
for (const id of [...APPS_PANELS, ...HISTORY_PANELS]) byId(id).replaceChildren();
const { appGroups, singles, stacks, ports, zones } = snapshot;
const apps = appGroups.filter(rows => rows.some(row => match.matches("permanent", row)))
.map(rows => appPanel(rows, match));
const singleEntries = singles.filter(row => match.matches("permanent", row))
.map(row => permanentEntry(row, false, match));
const leasePanels = [...stacks.values()]
.filter(rows => rows.some(row => match.matches("lease", row)))
.map(rows => stackPanel(rows, match));
const soloLeases = ports.leases.filter(row => !row.group && match.matches("lease", row))
.map(row => leaseEntry(row, false, match));
if (soloLeases.length) leasePanels.push(standaloneLeases(soloLeases));
const unregistered = ports.unregistered.filter(row => match.matches("unregistered", row)).map(listenerEntry);
const zoneEntries = zones.filter(zone => !match.filtered || (snapshot.conflictsByZone.get(zoneKey(zone.label)) ?? [])
.some(({ tier, row }) => match.matches(tier, row))).map(zoneEntry);
panels("app-groups", apps, match, "No apps. Reserve an app to allocate its component ports.");
panels("single-claim-rows", singleEntries.length ? [entryList(singleEntries)] : [], match,
"No single claims. Claim a port to register it.");
panels("lease-rows", leasePanels, match, "No leases. Take a lease or stack to reserve temporary ports.");
panels("unregistered-rows", unregistered.length ? [entryList(unregistered)] : [], match,
"No unregistered listeners.");
panels("zone-rows", zoneEntries.length ? [entryList(zoneEntries)] : [], match,
"No red zones. Add a zone to block allocation in its ranges.");
}
function renderApps(match) {
for (const id of [...CONSOLE_PANELS, ...HISTORY_PANELS]) byId(id).replaceChildren();
const { projects, ports } = snapshot;
const leases = groupBy(ports.leases, "project");
const names = [...new Set([...projects.keys(), ...leases.keys()])].sort();
const sections = names.map(project =>
projectSection(project, projects.get(project) ?? [], leases.get(project) ?? [], match)).filter(Boolean);
panels("project-rows", sections, match, "No projects.");
const unregistered = ports.unregistered.filter(row => match.matches("unregistered", row)).map(listenerEntry);
panels("no-claim-rows", unregistered.length ? [entryList(unregistered)] : [], match,
"No unregistered listeners.");
}
const HISTORY_KINDS = new Map([
["claim", "Claim"], ["component", "Component"], ["app", "App"],
["lease", "Lease"], ["lease_group", "Stack"],
]);
const HISTORY_REASONS = new Map([
["released", "Released"], ["component_removed", "Component removed"],
["app_released", "App released"], ["group_released", "Stack released"], ["swept", "Swept"],
]);
function renderHistory(match) {
for (const id of [...CONSOLE_PANELS, ...APPS_PANELS]) byId(id).replaceChildren();
const terms = searchTerms();
const items = (historySnapshot?.entries ?? []).filter(item => {
if (!terms.length) return true;
const ports = [...(item.permanent ?? []), ...(item.lease ?? [])].map(r => String(r.port));
const fields = [item.id, item.project, item.kind, item.reason, ...ports].map(v => String(v).toLowerCase());
return terms.every(term => fields.some(field => field.includes(term)));
}).map(item => historyEntry(item, match.now));
const empty = historySnapshot ? "No removed apps or ports in the last 30 days." : "Loading removal historyโฆ";
panels("history-rows", items.length ? [entryList(items)] : [], { filtered: terms.length > 0 }, empty);
}
function historyEntry(item, now) {
const id = `history-row-${item.id}`;
const allocations = [...(item.permanent ?? []), ...(item.lease ?? [])];
const portSummary = allocations.map(a => a.component ? `${a.port} (${a.component})` : String(a.port)).join(", ");
const firstPort = allocations[0]?.port ?? "โ";
const kindLabel = HISTORY_KINDS.get(item.kind) ?? item.kind;
const reasonLabel = HISTORY_REASONS.get(item.reason) ?? item.reason;
const daysLeft = Math.max(0, Math.ceil((instant(item.expires_at) - now) / (DURATION_UNITS.get("d") * 1_000)));
const notes = [
note(`${kindLabel} ยท ${reasonLabel}`),
note(`Ports: ${portSummary || "โ"}`),
note(`ID: ${item.id}`),
];
const facts = [
element("div", [pill(`${daysLeft}d left to restore`, daysLeft <= 3 ? "warning" : "quiet")], "state-line"),
note(`Removed ${item.removed_at}`),
];
const actions = [
writeButton("Restore", `Restore ${item.project} (${item.id})`, `restore-${id}`, openHistoryRestore, item,
{ icon: "restore", primary: true }),
];
return entry(id, {
label: `History ${item.project} ${item.id}`,
port: [element("span", allocations.length > 1 ? `${allocations.length} ports` : String(firstPort), "chip port"),
element("code", allocations[0]?.bind ?? "", "bind")],
name: [isolatedText(item.project)],
notes, facts, actions, kind: "entry-history",
});
}
function projectId(project) {
return `apps-project-${project}`;
}
function appActionKey(action, project) {
return JSON.stringify(["app", action, project]);
}
function counted(count, singular, plural) {
return `${count} ${count === 1 ? singular : plural}`;
}
function projectSection(project, permanent, leases, match) {
if (!permanent.some(row => match.matches("permanent", row)) &&
!leases.some(row => match.matches("lease", row))) return null;
const id = projectId(project);
const section = element("section", undefined, "group project");
section.setAttribute("aria-labelledby", id);
const heading = element("h3", [isolatedText(project)]);
heading.id = id;
heading.dataset.focusKey = id;
heading.tabIndex = -1;
const mark = element("span", [...project][0]?.toUpperCase() ?? "", "chip project-mark");
mark.ariaHidden = "true";
const listening = [...permanent, ...leases].filter(row => row.status === "listening").length;
const details = [];
if (permanent.length) details.push(counted(permanent.length, "claim", "claims"));
if (leases.length) details.push(counted(leases.length, "lease", "leases"));
details.push(`${listening} listening`);
const identity = element("div", undefined, "group-title");
identity.append(mark, heading, element("span", details.join(" ยท "), "small"));
const controls = element("div", undefined, "actions");
if (permanent.length) {
const envText = envTextForRows(permanent);
if (envText) controls.append(copyEnvButton(project, envText, appActionKey("copy-env", project)));
const webLinks = webLinksForRows(permanent);
if (webLinks.length >= 2) controls.append(openAllWebButton(project, webLinks, appActionKey("open-all", project)));
controls.append(writeButton("Add components", `Add components to ${project}`, appActionKey("add", project),
openAppAllocation, project, { icon: "add" }));
if (snapshot.appDetails.has(project)) {
controls.append(writeButton("Release app", `Release app ${project}`, appActionKey("release", project),
openAppRelease, project, { icon: "release", danger: true }));
}
}
const header = element("header", undefined, "group-head");
header.append(identity, controls);
section.append(header);
if (permanent.length) {
section.append(projectPart(`apps-claims-${project}`, "Claims",
[entryList(permanent.map(row => permanentEntry(row, true, match)))]));
}
if (leases.length) {
const parts = [...groupBy(leases.filter(row => row.group), "group").values()]
.map(rows => stackPanel(rows, match, true));
const solo = leases.filter(row => !row.group).map(row => leaseEntry(row, true, match));
if (solo.length) parts.push(standaloneLeases(solo, true));
section.append(projectPart(`apps-leases-${project}`, "Leases", parts));
}
return section;
}
function projectPart(id, label, children) {
const part = element("div", undefined, "project-part");
part.setAttribute("role", "group");
part.setAttribute("aria-labelledby", id);
const heading = element("h4", label);
heading.id = id;
heading.tabIndex = -1;
part.append(heading, element("div", children, "panels"));
return part;
}
function panels(id, children, match, empty) {
const message = match.filtered ? "No matching entries." : empty;
byId(id).replaceChildren(...(children.length ? children : [element("p", message, "panel empty")]));
}
function entryList(entries) {
return element("div", entries, "entries");
}
function standaloneLeases(entries, grouped = false) {
const part = element(grouped ? "div" : "section", [entryList(entries)]);
if (grouped) part.setAttribute("role", "group");
part.ariaLabel = "Standalone leases";
return part;
}
function entry(id, { label, port, name, notes, facts, actions, matched = false, kind }) {
const node = element("article", undefined, ["entry", kind, matched && "match"].filter(Boolean).join(" "));
node.id = id;
node.dataset.focusKey = id;
node.tabIndex = -1;
node.ariaLabel = label;
const title = element("div", undefined, "entry-title");
title.append(element("p", name, "entry-name"), element("p", notes, "entry-notes"));
node.append(element("div", port, "entry-port"), title, element("div", facts, "entry-facts"),
element("div", actions, "entry-actions"));
return node;
}
function note(content) {
return element("span", content, "row-note");
}
function groupPanel(title, details, actions, entries, id, level) {
const panel = element("article", undefined, "group");
const header = element("header", undefined, "group-head");
const heading = element(level, [isolatedText(title)]);
heading.id = id;
heading.dataset.focusKey = id;
heading.tabIndex = -1;
panel.ariaLabel = title;
const identity = element("div", undefined, "group-title");
identity.append(heading, element("span", details, "small"));
const controls = element("div", undefined, "actions");
controls.append(...actions);
header.append(identity, controls);
panel.append(header, entryList(entries));
return panel;
}
function appPanel(rows, match) {
const { project } = rows[0];
const id = `app-group-${project}`;
const listening = rows.filter(row => row.status === "listening").length;
const count = rows.length === 1 ? "1 port" : `${rows.length} ports`;
const actions = [
screenLink(project, "apps", projectId(project), id),
];
const envText = envTextForRows(rows);
if (envText) actions.push(copyEnvButton(project, envText, appActionKey("copy-env", project)));
const webLinks = webLinksForRows(rows);
if (webLinks.length >= 2) actions.push(openAllWebButton(project, webLinks, appActionKey("open-all", project)));
actions.push(
writeButton("Add components", `Add components to ${project}`, appActionKey("add", project), openAppAllocation,
project, { icon: "add" }),
);
if (snapshot.appDetails.has(project)) {
actions.push(writeButton("Release app", `Release app ${project}`, appActionKey("release", project),
openAppRelease, project, { icon: "release", danger: true }));
}
return groupPanel(project, `${count} ยท ${listening} listening`, actions,
rows.map(row => permanentEntry(row, true, match)), id, "h4");
}
function stackPanel(rows, match, inProject = false) {
const { project, group } = rows[0];
const id = `stack-group-${group}`;
const [title, details] = inProject ? [group, `Stack ยท ${counted(rows.length, "lease", "leases")}`] :
[project, [isolatedText(group)]];
return groupPanel(title, details, [
...(inProject ? [] : [screenLink(`stack ${group}`, "apps", id, id)]),
writeButton("Renew stack", `Renew stack ${group}`, `renew-${id}`, openStackRenew, group, { icon: "renew" }),
writeButton("Release stack", `Release stack ${group}`, `release-${id}`, openStackRelease, group,
{ icon: "release", danger: true }),
], rows.map(row => leaseEntry(row, true, match)), id, inProject ? "h5" : "h3");
}
function screenLink(name, target, id, originId) {
const link = jumpLink("Show in Apps", id, originId, "button", target);
link.ariaLabel = `Show in Apps: ${name}`;
return link;
}
const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
const CIRCLE = "M13.6 8A5.6 5.6 0 1 1 2.4 8A5.6 5.6 0 1 1 13.6 8";
const ICONS = new Map([
["open", ["M9.3 2.7h4v4", "M13.3 2.7 7.6 8.4",
"M11.4 9.8v2.9a1.1 1.1 0 0 1-1.1 1.1H3.4a1.1 1.1 0 0 1-1.1-1.1V5.8a1.1 1.1 0 0 1 1.1-1.1h2.9"]],
["edit", ["M10.6 2.9l2.5 2.5L6 12.5l-3.1.6.6-3.1z", "M9.2 4.3l2.5 2.5"]],
["renew", ["M8 4.6V8l2.6 1.6", "M2.6 8a5.4 5.4 0 1 0 1.7-3.9", "M2.4 2.6V5h2.4"]],
["release", [CIRCLE, "M5.4 8h5.2"]],
["add", ["M8 3.2v9.6", "M3.2 8h9.6"]],
["claim", ["M4 13.6V2.6", "M4 3h7.6L10 5.7l1.6 2.7H4"]],
["enable", [CIRCLE, "M5.4 8.2 7.2 10l3.4-3.6"]],
["disable", [CIRCLE, "M4 12 12 4"]],
["remove", ["M3 4.5h10", "M6.2 4.5V3h3.6v1.5", "M4.5 4.5l.7 8.5h5.6l.7-8.5"]],
["cards", ["M2.3 2.3h5v5h-5z", "M8.7 2.3h5v5h-5z", "M2.3 8.7h5v5h-5z", "M8.7 8.7h5v5h-5z"]],
["list", ["M2.6 4h10.8", "M2.6 8h10.8", "M2.6 12h10.8"]],
["globe", [CIRCLE, "M2.4 8h11.2", "M8 2.4c1.8 1.6 1.8 9.6 0 11.2", "M8 2.4c-1.8 1.6-1.8 9.6 0 11.2"]],
["layout", ["M2.4 3h11.2v10H2.4z", "M2.4 6.2h11.2", "M6.4 6.2V13"]],
["database", ["M3 4.5c0-1.1 2.2-2 5-2s5 .9 5 2-2.2 2-5 2-5-.9-5-2z", "M3 4.5v7c0 1.1 2.2 2 5 2s5-.9 5-2v-7", "M3 8c0 1.1 2.2 2 5 2s5-.9 5-2"]],
["bolt", ["M8.8 2.2L4.2 8.6h3.5L7.2 13.8l4.6-6.4H8.3z"]],
["api", ["M5.4 4.8L2.4 8l3 3.2", "M10.6 4.8L13.6 8l-3 3.2", "M9 3.6L7 12.4"]],
["server", ["M2.6 3.2h10.8v3.6H2.6z", "M2.6 9.2h10.8v3.6H2.6z", "M5 5h.1", "M5 11h.1"]],
["box", ["M8 2.4l5 2.8v5.6L8 13.6l-5-2.8V5.2z", "M3 5.2L8 8l5-2.8", "M8 8v5.6"]],
["info", [CIRCLE, "M8 7.2v3.6", "M8 5.2h.01"]],
["restore", ["M3.2 8a4.8 4.8 0 1 0 1.4-3.4", "M3.2 2.8v2.8H6"]],
["copy", ["M5.4 5.4h7.2v7.2H5.4z", "M3.4 10.6V3.4h7.2"]],
]);
function icon(name) {
const svg = document.createElementNS(SVG_NAMESPACE, "svg");
svg.setAttribute("viewBox", "0 0 16 16");
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("focusable", "false");
svg.setAttribute("class", "icon");
for (const geometry of ICONS.get(name)) {
const path = document.createElementNS(SVG_NAMESPACE, "path");
path.setAttribute("d", geometry);
svg.append(path);
}
return svg;
}
function iconLabel(glyph, label) {
return [icon(glyph), element("span", label, "action-label")];
}
function writeButton(label, name, key, open, target, { icon: glyph, danger = false, primary = false } = {}) {
const classes = ["button", "icon-action"];
if (danger) classes.push("danger");
if (primary) classes.push("primary");
const node = button(iconLabel(glyph, label), () => startAction(node, open, target), {
name, key, className: classes.join(" "),
});
node.dataset.write = "";
return node;
}
function bindNote(row) {
return snapshot.sharedPorts.has(row.port) ? ` on ${row.bind}` : "";
}
function portLabel(row) {
return `port ${portDisplay(row)}${bindNote(row)}`;
}
function onPort(row) {
return `on ${portLabel(row)}`;
}
function portBlock(row) {
return [
element("span", row.port, "chip port"),
...(rowProtocol(row) === "udp" ? [pill("UDP", "quiet")] : []),
element("code", row.bind, "bind"),
];
}
function pill(label, style) {
return element("span", label, `state ${style}`);
}
const SERVICE_ICONS = new Map([
["webui", "globe"],
["frontend", "layout"],
["database", "database"],
["cache", "bolt"],
["broker", "bolt"],
["api", "api"],
["proxy", "server"],
["container", "box"],
["system", "server"],
]);
const SERVICE_CATEGORY_LABELS = new Map([
["webui", "Web UI"],
["frontend", "Frontend"],
["database", "Database"],
["cache", "Cache"],
["broker", "Broker"],
["api", "API"],
["proxy", "Proxy"],
["container", "Container"],
["system", "System"],
]);
function serviceBadge(row) {
const info = row.service_info;
if (!info) return null;
const glyph = SERVICE_ICONS.get(info.category);
const categoryLabel = SERVICE_CATEGORY_LABELS.get(info.category);
const text = info.name && categoryLabel && info.name.toLowerCase() !== categoryLabel.toLowerCase()
? `${categoryLabel} ยท ${info.name}`
: (info.name || categoryLabel);
if (!text) return null;
const content = glyph ? [icon(glyph), element("span", text)] : [element("span", text)];
const cls = info.is_web ? "service-badge service-web" : "service-badge";
return element("span", content, cls);
}
function entryStateClass(tier, row, now) {
if (tier === "unregistered") return "entry-unregistered";
const zones = snapshot.zonesByRow.get(rowKey(tier, row)) ?? [];
if (zones.length) return "entry-danger";
if (tier === "lease") {
if (row.state === "reclaimable") return "entry-danger";
const { seconds, settled, warm } = leaseTiming(row, now);
if (row.state === "overdue" || warm || (!settled && seconds > 0 && seconds <= EXPIRING_WINDOW_SECONDS)) {
return "entry-warning";
}
}
if (row.status === "listening") return "entry-live";
return "entry-silent";
}
function loopbackHost(bind) {
if (bind === "127.0.0.1" || bind === "0.0.0.0") return "127.0.0.1";
if (bind === "::1" || bind === "::") return "[::1]";
return null;
}
function detectedWebLink(tier, row) {
if (tier === "permanent" && row.web) return null;
if (!row.service_info?.is_web) return null;
if (tier !== "unregistered" && row.status !== "listening") return null;
if (!Number.isInteger(row.port) || row.port < 1 || row.port > MAX_PORT) return null;
const host = loopbackHost(row.bind);
return host ? `http://${host}:${row.port}/` : null;
}
function componentEnvLine(component, port) {
return `PORT_${component.toUpperCase().replace(/-/g, "_")}=${port}`;
}
function envTextForRows(rows) {
const labeled = rows
.filter(row => row.component)
.slice()
.sort((a, b) => a.component.localeCompare(b.component));
return labeled.map(row => componentEnvLine(row.component, row.port)).join("\n");
}
function webLinksForRows(rows) {
const seen = new Set();
const links = [];
for (const row of rows) {
const href = claimLink(row) || detectedWebLink("permanent", row);
if (href && !seen.has(href)) {
seen.add(href);
links.push(href);
}
}
return links;
}
function copyEnvButton(project, envText, key) {
const node = button(iconLabel("copy", "Copy .env"), () => void copyText(envText, node, `${project} .env`), {
name: `Copy .env assignments for ${project}`,
key,
className: "button icon-action",
});
return node;
}
function openAllWebButton(project, links, key) {
return button(iconLabel("open", `Open ${links.length} web UIs`), () => openAllLinks(links, project), {
name: `Open ${links.length} web interfaces for ${project} (opens in new tabs)`,
key,
className: "button icon-action",
});
}
function infoButton(tier, row, target, id) {
const node = button(iconLabel("info", "Info"), () => openInfoDialog(tier, row, node), {
name: `Inspect details for ${target}`,
key: `info-${id}`,
className: "button icon-action",
});
return node;
}
function listenerFacts(tier, row, expiry) {
const status = element("div", undefined, "state-line");
if (row.status === "listening") status.append(pill("Listening", "live"));
else if (row.status === "silent") status.append(pill("Silent", "quiet"));
else status.append(pill("Listener unknown", "quiet"));
const badge = serviceBadge(row);
if (badge) status.append(badge);
const zones = snapshot.zonesByRow.get(rowKey(tier, row)) ?? [];
if (zones.length) status.append(pill("Zone conflict", "conflict"));
return [
...(expiry ? [expiry] : []), status, ...ownerNotes(row.listeners),
...zones.map(zone => jumpLink([isolatedText(zone.label)], zoneId(zone), rowId(tier, row), "row-note", "console")),
];
}
function ownerNotes(listeners) {
const containers = new Map();
const owners = new Map();
for (const listener of listeners) {
if (listener.container && !containers.has(listener.container.name)) {
containers.set(listener.container.name, listener.container);
}
for (const owner of listener.owners) {
if (owner.name || !owners.has(owner.pid)) owners.set(owner.pid, owner.name);
}
}
const nodes = [...containers.values()].map(c =>
note(["Container ", isolatedText(c.name), c.image ? ` ยท ${c.image}` : ""]));
nodes.push(...[...owners].map(([pid, name]) => note([isolatedText(name || "Unknown process"), ` ยท PID ${pid}`])));
return nodes;
}
function claimLink(entry) {
if (!entry.web || !Number.isInteger(entry.port) || entry.port < 1 || entry.port > MAX_PORT) return null;
const { scheme = "http", path = "/" } = entry.web;
if ((scheme !== "http" && scheme !== "https") || typeof path !== "string" ||
path.length > 128 || !WEB_PATH.test(path) || /\s/.test(path)) return null;
let host;
if (entry.bind === "127.0.0.1" || entry.bind === "0.0.0.0") host = "127.0.0.1";
else if (entry.bind === "::1" || entry.bind === "::") host = "[::1]";
else return null;
return scheme + "://" + host + ":" + entry.port + path;
}
function openLink(row, href, tier = "permanent") {
const name = row.component || row.project || `port ${row.port}`;
const link = element("a", iconLabel("open", "Open"), "button icon-action open-link");
link.href = href;
link.target = "_blank";
link.rel = "noopener noreferrer";
link.dataset.focusKey = `web-${rowId(tier, row)}`;
link.ariaLabel = `Open ${name} ${onPort(row)} (opens in a new tab)`;
return link;
}
function permanentDetails(row, href) {
const details = [];
if (href) details.push(element("code", href, "link-target"));
if (row.used_by?.length) details.push(note(["Used by ", ...isolatedNames(row.used_by)]));
if (row.container) details.push(note(["Container ", isolatedText(row.container)]));
return details;
}
function matchNotes(notes, matched) {
if (matched) notes.unshift(element("span", "Matches filter", "row-note match-note"));
return notes;
}
function permanentEntry(row, grouped, match) {
const id = rowId("permanent", row);
const role = row.role === "service" ? "Service" : "App";
const name = grouped ? (row.component || row.service) : row.project;
const description = !grouped || row.component ? [isolatedText(row.service), ` ยท ${role}`] : role;
const matched = grouped && match.filtered && match.matches("permanent", row);
const notes = matchNotes([note(description), note(["Claimed by ", isolatedText(row.claimed_by)])], matched);
const target = row.component ? `${row.project} component ${row.component} ${onPort(row)}` :
`${row.project} ${onPort(row)}`;
const configuredHref = claimLink(row);
const href = configuredHref || detectedWebLink("permanent", row);
const actions = href ? [openLink(row, href, "permanent")] : [];
actions.push(infoButton("permanent", row, target, id));
if (!grouped) {
actions.push(writeButton("Add components", `Add components to ${row.project}`, appActionKey("add", row.project),
openAppAllocation, row.project, { icon: "add" }));
}
actions.push(
writeButton("Edit", `Edit ${target}`, `edit-${id}`, openClaimEdit, row, { icon: "edit" }),
writeButton(row.component ? "Remove" : "Release", row.component ? `Remove component ${target}` : `Release ${target}`,
`release-${id}`, openClaimRelease, row, { icon: "release", danger: true }),
);
return entry(id, {
label: `${name} ${onPort(row)}`, port: portBlock(row), name: [isolatedText(name)], notes,
facts: [...listenerFacts("permanent", row), ...permanentDetails(row, configuredHref)], actions, matched,
kind: entryStateClass("permanent", row, match.now),
});
}
function leaseEntry(row, grouped, match) {
const id = rowId("lease", row);
const holder = [isolatedText(row.holder)];
if (row.holder_pid) holder.push(` ยท PID ${row.holder_pid}`);
const matched = grouped && match.filtered && match.matches("lease", row);
const named = grouped && !row.component;
const notes = matchNotes(named ? [note(holder)] : [note([isolatedText(row.purpose)]), note(holder)], matched);
const name = grouped ? (row.component || row.purpose) : row.project;
const target = `lease ${onPort(row)}`;
const href = detectedWebLink("lease", row);
const actions = href ? [openLink(row, href, "lease")] : [];
actions.push(
infoButton("lease", row, target, id),
writeButton("Edit", `Edit ${target}`, `edit-${id}`, openLeaseEdit, row, { icon: "edit" }),
writeButton("Renew", `Renew ${target}`, `renew-${id}`, openLeaseRenew, row, { icon: "renew" }),
writeButton("Release", `Release ${target}`, `release-${id}`, openLeaseRelease, row,
{ icon: "release", danger: true }),
);
return entry(id, {
label: `${name} lease ${onPort(row)}`, port: portBlock(row), name: [isolatedText(name)], notes,
facts: listenerFacts("lease", row, expiryFacts(row, match.now)),
actions,
matched,
kind: entryStateClass("lease", row, match.now),
});
}
const EXPIRING_WINDOW_SECONDS = 2 * DURATION_UNITS.get("h");
const WARM_WINDOW_SECONDS = 5 * DURATION_UNITS.get("m");
const RELATIVE_EXPIRY_UNITS = [
["day", DURATION_UNITS.get("d")], ["hour", DURATION_UNITS.get("h")],
["minute", DURATION_UNITS.get("m")], ["second", DURATION_UNITS.get("s")],
];
function instant(value) {
return typeof value === "string" ? Date.parse(value.replace(/(\.\d{3})\d+/, "$1")) : NaN;
}
function leaseTiming(row, now) {
const seconds = (instant(row.expires_at) - now) / 1_000;
const settled = row.state === "overdue" || row.state === "reclaimable";
return { seconds, settled, warm: !settled && seconds > 0 && seconds < WARM_WINDOW_SECONDS };
}
function expiryFacts(row, now) {
const block = element("div", undefined, "expiry");
const expires = instant(row.expires_at);
const { seconds, settled, warm } = leaseTiming(row, now);
const [unit, size] = RELATIVE_EXPIRY_UNITS.find(([, size]) => Math.abs(seconds) >= size) ??
RELATIVE_EXPIRY_UNITS.at(-1);
const relative = Number.isFinite(seconds) ? relativeTime.format(
seconds < 0 ? Math.floor(seconds / size) : Math.ceil(seconds / size), unit) : "";
const status = element("div", undefined, "state-line");
if (row.state === "overdue") status.append(pill("Overdue", "warning"));
else if (row.state === "reclaimable") status.append(pill("Reclaimable", "conflict"));
else if (row.state === "unknown") status.append(pill("Lease state unknown", "quiet"));
if (warm) status.append(pill("Expires within 5 minutes", "warning"));
else if (!settled && seconds > 0 && seconds <= EXPIRING_WINDOW_SECONDS) {
status.append(pill("Expiring soon", "warning"));
}
if (status.hasChildNodes()) block.append(status);
if (relative) block.append(element("span", relative, "relative-expiry"));
const total = (expires - instant(row.leased_at)) / 1_000;
if (Number.isFinite(total) && total > 0 && Number.isFinite(seconds)) {
const meter = element("meter", undefined, warm ? "lease-meter warm" : "lease-meter");
meter.min = 0;
meter.max = total;
meter.value = Math.min(Math.max(seconds, 0), total);
meter.ariaLabel = `Time remaining on lease ${onPort(row)}`;
meter.setAttribute("aria-valuetext", relative);
meter.textContent = `${Math.round(meter.value / total * 100)}% of the lease remains`;
block.append(meter);
} else {
block.append(note("Time remaining unavailable"));
}
const time = element("time", row.expires_at, "row-note");
time.dateTime = row.expires_at;
block.append(time);
return block;
}
const PROCESS_KINDS = new Map([["ours", "Ours"], ["system", "System"], ["third-party", "Third-party"]]);
function listenerEntry(row) {
const id = rowId("unregistered", row);
const owners = ownerNotes([row]);
const names = [...new Set(row.owners.map(owner => owner.name || "Unknown process"))];
const status = element("div", [pill("Listening", "live")], "state-line");
const badge = serviceBadge(row);
if (badge) status.append(badge);
const href = detectedWebLink("unregistered", row);
const actions = href ? [openLink(row, href, "unregistered")] : [];
actions.push(
infoButton("unregistered", row, `unregistered listener ${onPort(row)}`, id),
writeButton("Claim", `Claim unregistered port ${row.port} on ${row.bind}`,
`claim-${id}`, openClaimCreate, row, { icon: "claim", primary: true }),
);
return entry(id, {
label: `Unregistered listener ${onPort(row)}`, port: portBlock(row),
name: names.length ? isolatedNames(names) : "Unknown process",
notes: [note(`Process kind ยท ${PROCESS_KINDS.get(row.kind) ?? "Unknown"}`)],
facts: [status, ...owners],
actions,
kind: "entry-unregistered",
});
}
function jumpLink(label, id, originId, className, target = screen) {
const link = element("a", label, className);
link.href = screenHref(target, id);
link.dataset.focusKey = JSON.stringify(["jump", originId, id]);
link.addEventListener("click", event => {
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
event.preventDefault();
if (target === screen) revealTarget(id);
else navigate(link.getAttribute("href"));
});
return link;
}
const SCREENS = new Map([
["console", { href: "/", heading: "Port registry", title: "Troll console" }],
["apps", { href: "/?screen=apps", heading: "Apps and local ports", title: "Apps and local ports ยท Troll console" }],
["history", { href: "/?screen=history", heading: "Removal history", title: "History ยท Troll console" }],
]);
function screenHref(name, id) {
return SCREENS.get(name).href + (id ? "#" + encodeURIComponent(id) : "");
}
function locationScreen() {
const value = new URLSearchParams(window.location.search).get("screen");
return value === "apps" || value === "history" ? value : "console";
}
function locationTarget() {
try {
return decodeURIComponent(window.location.hash.slice(1)) || null;
} catch (_) {
return null;
}
}
function applyLocation() {
screen = locationScreen();
const { heading, title } = SCREENS.get(screen);
setText(byId("screen-title"), heading);
document.title = title;
for (const link of document.querySelectorAll("#screen-nav [data-screen]")) {
if (link.dataset.screen === screen) link.setAttribute("aria-current", "page");
else link.removeAttribute("aria-current");
}
byId("console-screen").hidden = screen !== "console";
byId("sweep").hidden = screen !== "console";
byId("apps-screen").hidden = screen !== "apps";
byId("history-screen").hidden = screen !== "history";
pendingTarget = locationTarget();
if (screen === "history") void loadHistory();
renderRegistry();
}
function navigate(href) {
const url = new URL(href, window.location.href);
if (url.href !== window.location.href) window.history.pushState(null, "", url);
applyLocation();
}
function revealPendingTarget() {
if (!pendingTarget) return;
const id = pendingTarget;
pendingTarget = null;
if (!active) revealTarget(id);
}
function revealTarget(id) {
const shown = node => registryRows.contains(node) && !node.closest("[hidden]");
if (!shown(byId(id))) {
const filters = [driftFilter, kindSelect.value, listenerSelect.value, protocolSelect.value, searchInput.value];
driftFilter = null;
kindSelect.value = "all";
listenerSelect.value = "all";
protocolSelect.value = "all";
searchInput.value = "";
renderRegistry();
if (!shown(byId(id))) {
[driftFilter, kindSelect.value, listenerSelect.value, protocolSelect.value, searchInput.value] = filters;
renderRegistry();
return;
}
}
const target = byId(id);
target.scrollIntoView({ block: "nearest" });
target.focus({ preventScroll: true });
}
function zoneEntry(zone) {
const id = zoneId(zone);
const status = element("div", undefined, "state-line");
status.append(zone.enabled ? pill("Enabled", "warning") : pill("Disabled", "quiet"));
if (zone.protocol) status.append(pill(zone.protocol.toUpperCase(), "quiet"));
const facts = [status];
const conflicts = snapshot.conflictsByZone.get(zoneKey(zone.label)) ?? [];
if (conflicts.length) {
const list = element("ul", undefined, "zone-conflicts");
for (const { tier, row: allocation } of conflicts) {
const type = tier === "permanent" ? "claim" : "lease";
const item = element("li");
const label = [`Port ${allocation.port}${bindNote(allocation)} ยท `, isolatedText(allocation.project), ` ${type}`];
item.append(jumpLink(label, rowId(tier, allocation), id, undefined, "console"));
list.append(item);
}
facts.push(list);
} else if (zone.enabled) {
facts.push(note("No conflicts"));
}
const verb = zone.enabled ? "Disable" : "Enable";
const actions = [
writeButton("Edit", `Edit zone ${zone.label}`, `edit-${id}`, openZoneEdit, zone, { icon: "edit" }),
writeButton(verb, `${verb} zone ${zone.label}`, `toggle-${id}`, openZoneToggle, zone,
{ icon: zone.enabled ? "disable" : "enable", danger: zone.enabled }),
writeButton("Remove", `Remove zone ${zone.label}`, `remove-${id}`, openZoneRemove, zone,
{ icon: "remove", danger: true }),
];
if (zone.label === "." || zone.label === "..") {
for (const action of actions) {
delete action.dataset.write;
action.disabled = true;
}
facts.push(note("Manage this zone with the command line."));
}
return entry(id, {
label: `zone ${zone.label}`, port: [element("code", zone.ports.join(", "), "zone-ranges")],
name: [isolatedText(zone.label)], notes: zone.reason ? [note([isolatedText(zone.reason)])] : [],
facts, actions, kind: "zone-entry",
});
}
const DENSITY_KEY = "troll.console.density";
const DENSITIES = new Set(["cards", "list"]);
const densityButtons = byId("density").querySelectorAll("[data-density]");
function applyDensity(value) {
const density = DENSITIES.has(value) ? value : "cards";
registryRows.classList.toggle("list-view", density === "list");
for (const node of densityButtons) node.setAttribute("aria-pressed", String(node.dataset.density === density));
return density;
}
function readDensity() {
try {
return applyDensity(localStorage.getItem(DENSITY_KEY));
} catch (_) {
return applyDensity("cards");
}
}
function saveDensity(value) {
const density = applyDensity(value);
try {
localStorage.setItem(DENSITY_KEY, density);
} catch (_) {
}
return density;
}