feat: initialize unidesk platform
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
FROM oven/bun:1-alpine
|
||||
WORKDIR /app/src/components/frontend
|
||||
COPY src/components/frontend/package.json ./package.json
|
||||
RUN bun install --production
|
||||
COPY src/components/frontend/src ./src
|
||||
COPY src/components/frontend/public ./public
|
||||
CMD ["bun", "run", "src/index.ts"]
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "@unidesk/frontend",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "bun run src/index.ts",
|
||||
"check": "tsc -p tsconfig.json --noEmit"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
const rawCfg = window.UNIDESK_CONFIG || { coreApiUrl: "http://127.0.0.1:18080", corePort: "18080" };
|
||||
const cfg = { ...rawCfg, coreApiUrl: resolveCoreApiUrl(rawCfg) };
|
||||
const state = { overview: null, nodes: [], events: [], tasks: [], activeModule: "ops", activeTab: "overview", lastRefresh: null };
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const fmtTime = (value) => value ? new Date(value).toLocaleTimeString() : "--";
|
||||
const compactJson = (value) => JSON.stringify(value ?? {}, null, 0);
|
||||
|
||||
function resolveCoreApiUrl(config) {
|
||||
const api = new URL(config.coreApiUrl, window.location.href);
|
||||
const pageHost = window.location.hostname;
|
||||
const apiIsLoopback = api.hostname === "127.0.0.1" || api.hostname === "localhost";
|
||||
const pageIsLoopback = pageHost === "127.0.0.1" || pageHost === "localhost";
|
||||
if (apiIsLoopback && !pageIsLoopback) {
|
||||
api.hostname = pageHost;
|
||||
api.port = String(config.corePort || api.port || "18080");
|
||||
}
|
||||
return api.origin;
|
||||
}
|
||||
|
||||
function setConnection(ok, text) {
|
||||
const dot = $("conn-dot");
|
||||
dot.className = `dot ${ok ? "ok" : "fail"}`;
|
||||
$("conn-text").textContent = text;
|
||||
}
|
||||
|
||||
async function api(path, options) {
|
||||
const res = await fetch(`${cfg.coreApiUrl}${path}`, options);
|
||||
const json = await res.json();
|
||||
if (!res.ok || json.ok === false) throw new Error(json.error?.message || json.error || `HTTP ${res.status}`);
|
||||
return json;
|
||||
}
|
||||
|
||||
function metric(label, value, hint) {
|
||||
return `<article class="metric"><div class="label">${label}</div><div class="value">${value}</div><div class="hint">${hint}</div></article>`;
|
||||
}
|
||||
|
||||
function renderMetrics() {
|
||||
const o = state.overview || {};
|
||||
$("metric-grid").innerHTML = [
|
||||
metric("DB Ready", o.dbReady ? "YES" : "NO", "PostgreSQL central state"),
|
||||
metric("Online Nodes", o.onlineNodeCount ?? 0, `${o.nodeCount ?? 0} registered`),
|
||||
metric("Active Sockets", o.activeSocketCount ?? 0, "Provider WebSocket"),
|
||||
metric("Pending Tasks", o.pendingTaskCount ?? 0, "queued / running"),
|
||||
].join("");
|
||||
$("refresh-age").textContent = state.lastRefresh ? `刷新 ${fmtTime(state.lastRefresh)}` : "--";
|
||||
}
|
||||
|
||||
function renderNodes() {
|
||||
$("node-count").textContent = `${state.nodes.length} nodes`;
|
||||
$("nodes-body").innerHTML = state.nodes.map((node) => `
|
||||
<tr>
|
||||
<td><span class="badge ${node.status}">${node.status}</span></td>
|
||||
<td><div>${node.name}</div><div class="code">${node.providerId}</div></td>
|
||||
<td class="code">${compactJson(node.labels)}</td>
|
||||
<td>${fmtTime(node.lastHeartbeat)}</td>
|
||||
</tr>
|
||||
`).join("") || `<tr><td colspan="4">暂无 Provider 节点</td></tr>`;
|
||||
if (state.nodes[0] && !$("dispatch-provider").value) $("dispatch-provider").value = state.nodes[0].providerId;
|
||||
}
|
||||
|
||||
function renderEvents() {
|
||||
$("events-body").innerHTML = state.events.map((event) => `
|
||||
<tr>
|
||||
<td class="code">${event.id}</td>
|
||||
<td>${event.type}</td>
|
||||
<td class="code">${event.source}</td>
|
||||
<td class="code">${compactJson(event.payload)}</td>
|
||||
<td>${fmtTime(event.createdAt)}</td>
|
||||
</tr>
|
||||
`).join("") || `<tr><td colspan="5">暂无事件</td></tr>`;
|
||||
}
|
||||
|
||||
function render() {
|
||||
renderMetrics();
|
||||
renderNodes();
|
||||
renderEvents();
|
||||
document.querySelectorAll("[data-panel]").forEach((panel) => {
|
||||
const key = panel.getAttribute("data-panel");
|
||||
panel.style.display = state.activeTab === "overview" ? "" : key === state.activeTab ? "" : key === "overview" && state.activeModule === "ops" ? "" : "none";
|
||||
});
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
const [overview, nodes, events] = await Promise.all([
|
||||
api("/api/overview"),
|
||||
api("/api/nodes"),
|
||||
api("/api/events?limit=100"),
|
||||
]);
|
||||
state.overview = overview;
|
||||
state.nodes = nodes.nodes || [];
|
||||
state.events = events.events || [];
|
||||
state.lastRefresh = new Date();
|
||||
setConnection(true, "核心在线");
|
||||
render();
|
||||
} catch (error) {
|
||||
setConnection(false, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function bindNav() {
|
||||
document.querySelectorAll(".module").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
document.querySelectorAll(".module").forEach((b) => b.classList.remove("active"));
|
||||
btn.classList.add("active");
|
||||
state.activeModule = btn.dataset.module;
|
||||
if (state.activeModule === "nodes") setTab("nodes");
|
||||
if (state.activeModule === "tasks") setTab("dispatch");
|
||||
if (state.activeModule === "config") setTab("events");
|
||||
if (state.activeModule === "ops") setTab("overview");
|
||||
});
|
||||
});
|
||||
document.querySelectorAll(".tab").forEach((btn) => btn.addEventListener("click", () => setTab(btn.dataset.tab)));
|
||||
}
|
||||
|
||||
function setTab(tab) {
|
||||
state.activeTab = tab;
|
||||
document.querySelectorAll(".tab").forEach((b) => b.classList.toggle("active", b.dataset.tab === tab));
|
||||
render();
|
||||
}
|
||||
|
||||
function bindDispatch() {
|
||||
$("dispatch-form").addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const providerId = $("dispatch-provider").value.trim();
|
||||
const command = $("dispatch-command").value;
|
||||
const payloadText = $("dispatch-payload").value.trim();
|
||||
try {
|
||||
const payload = payloadText ? JSON.parse(payloadText) : {};
|
||||
const result = await api("/api/dispatch", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ providerId, command, payload }),
|
||||
});
|
||||
$("dispatch-result").textContent = JSON.stringify(result, null, 2);
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
$("dispatch-result").textContent = `ERROR: ${error.message}`;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function tick() {
|
||||
$("clock").textContent = new Date().toLocaleTimeString();
|
||||
}
|
||||
|
||||
bindNav();
|
||||
bindDispatch();
|
||||
tick();
|
||||
setInterval(tick, 1000);
|
||||
refresh();
|
||||
setInterval(refresh, 5000);
|
||||
@@ -0,0 +1,68 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>UniDesk Control Plane</title>
|
||||
<link rel="stylesheet" href="/style.css" />
|
||||
<script>window.UNIDESK_CONFIG = __UNIDESK_CONFIG__;</script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="shell">
|
||||
<aside class="rail" aria-label="Main modules">
|
||||
<div class="brand">
|
||||
<span class="brand-mark">UD</span>
|
||||
<span class="brand-text">UniDesk</span>
|
||||
</div>
|
||||
<button class="module active" data-module="ops">运行总览</button>
|
||||
<button class="module" data-module="nodes">资源节点</button>
|
||||
<button class="module" data-module="tasks">任务调度</button>
|
||||
<button class="module" data-module="config">系统配置</button>
|
||||
</aside>
|
||||
<main class="workspace">
|
||||
<header class="topbar">
|
||||
<div>
|
||||
<p class="eyebrow">Distributed Work Platform</p>
|
||||
<h1>控制平面</h1>
|
||||
</div>
|
||||
<div class="status-strip">
|
||||
<span id="conn-dot" class="dot warn"></span>
|
||||
<span id="conn-text">连接中</span>
|
||||
<span id="clock">--:--:--</span>
|
||||
</div>
|
||||
</header>
|
||||
<nav class="tabs" aria-label="Sub modules">
|
||||
<button class="tab active" data-tab="overview">Overview</button>
|
||||
<button class="tab" data-tab="nodes">Live Nodes</button>
|
||||
<button class="tab" data-tab="events">Event Log</button>
|
||||
<button class="tab" data-tab="dispatch">Dispatch</button>
|
||||
</nav>
|
||||
<section class="content-grid">
|
||||
<section class="panel metrics-panel" data-panel="overview">
|
||||
<div class="panel-head"><h2>核心指标</h2><span id="refresh-age">--</span></div>
|
||||
<div class="metric-grid" id="metric-grid"></div>
|
||||
</section>
|
||||
<section class="panel table-panel" data-panel="nodes">
|
||||
<div class="panel-head"><h2>Provider 节点</h2><span id="node-count">0</span></div>
|
||||
<div class="table-wrap"><table><thead><tr><th>状态</th><th>Provider</th><th>标签</th><th>最后心跳</th></tr></thead><tbody id="nodes-body"></tbody></table></div>
|
||||
</section>
|
||||
<section class="panel table-panel" data-panel="events">
|
||||
<div class="panel-head"><h2>事件流</h2><span>最近 100 条</span></div>
|
||||
<div class="table-wrap"><table><thead><tr><th>ID</th><th>类型</th><th>来源</th><th>载荷</th><th>时间</th></tr></thead><tbody id="events-body"></tbody></table></div>
|
||||
</section>
|
||||
<section class="panel dispatch-panel" data-panel="dispatch">
|
||||
<div class="panel-head"><h2>调度试运行</h2><span>真实 WebSocket 下发</span></div>
|
||||
<form id="dispatch-form" class="dispatch-form">
|
||||
<label>Provider ID<input id="dispatch-provider" placeholder="main-server" /></label>
|
||||
<label>Command<select id="dispatch-command"><option value="docker.ps">docker.ps</option><option value="echo">echo</option></select></label>
|
||||
<label class="wide">Payload JSON<textarea id="dispatch-payload">{"source":"frontend"}</textarea></label>
|
||||
<button type="submit">下发任务</button>
|
||||
</form>
|
||||
<pre id="dispatch-result" class="result-block">等待操作</pre>
|
||||
</section>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
<script src="/app.js" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,329 @@
|
||||
:root {
|
||||
--bg: #111820;
|
||||
--panel: #17212b;
|
||||
--panel-2: #1d2a35;
|
||||
--line: #30404d;
|
||||
--line-soft: #24323e;
|
||||
--text: #dce7ec;
|
||||
--muted: #8496a3;
|
||||
--accent: #e2a329;
|
||||
--accent-2: #4bb7aa;
|
||||
--danger: #d86b55;
|
||||
--ok: #6fbe73;
|
||||
--rail: #0c1218;
|
||||
--shadow: 0 16px 40px rgba(0, 0, 0, 0.28);
|
||||
font-family: "DIN Condensed", "Aptos Narrow", "Liberation Sans Narrow", "Noto Sans", sans-serif;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body { min-height: 100%; }
|
||||
body {
|
||||
margin: 0;
|
||||
color: var(--text);
|
||||
background:
|
||||
linear-gradient(135deg, rgba(226, 163, 41, 0.08), transparent 28%),
|
||||
linear-gradient(315deg, rgba(75, 183, 170, 0.08), transparent 30%),
|
||||
repeating-linear-gradient(90deg, rgba(255,255,255,0.025) 0, rgba(255,255,255,0.025) 1px, transparent 1px, transparent 36px),
|
||||
var(--bg);
|
||||
font-size: 13px;
|
||||
letter-spacing: 0.01em;
|
||||
}
|
||||
|
||||
button, input, select, textarea {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.shell {
|
||||
display: grid;
|
||||
grid-template-columns: 176px minmax(0, 1fr);
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.rail {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
height: 100vh;
|
||||
padding: 12px 10px;
|
||||
border-right: 1px solid var(--line);
|
||||
background: linear-gradient(180deg, #0a1015, var(--rail));
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
height: 40px;
|
||||
padding: 0 5px 12px;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.brand-mark {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 32px;
|
||||
height: 26px;
|
||||
border: 1px solid var(--accent);
|
||||
color: var(--accent);
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.08em;
|
||||
}
|
||||
|
||||
.brand-text {
|
||||
font-size: 15px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.14em;
|
||||
}
|
||||
|
||||
.module, .tab, .dispatch-form button {
|
||||
border: 1px solid transparent;
|
||||
color: var(--muted);
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.module {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
margin: 4px 0;
|
||||
text-align: left;
|
||||
border-left: 3px solid transparent;
|
||||
}
|
||||
|
||||
.module:hover, .module.active {
|
||||
color: var(--text);
|
||||
background: rgba(255,255,255,0.045);
|
||||
border-left-color: var(--accent);
|
||||
}
|
||||
|
||||
.workspace {
|
||||
min-width: 0;
|
||||
padding: 12px 14px 16px;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
min-height: 54px;
|
||||
padding: 0 0 10px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
margin: 0 0 2px;
|
||||
color: var(--accent);
|
||||
font-size: 10px;
|
||||
letter-spacing: 0.22em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
h1, h2 { margin: 0; font-weight: 650; }
|
||||
h1 { font-size: 22px; letter-spacing: 0.08em; }
|
||||
h2 { font-size: 14px; text-transform: uppercase; letter-spacing: 0.09em; }
|
||||
|
||||
.status-strip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 7px 9px;
|
||||
border: 1px solid var(--line);
|
||||
background: rgba(0,0,0,0.14);
|
||||
color: var(--muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--muted);
|
||||
box-shadow: 0 0 0 2px rgba(255,255,255,0.06);
|
||||
}
|
||||
.dot.ok { background: var(--ok); }
|
||||
.dot.warn { background: var(--accent); }
|
||||
.dot.fail { background: var(--danger); }
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
padding: 10px 0;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.tab {
|
||||
padding: 7px 12px;
|
||||
border-color: var(--line);
|
||||
background: rgba(12, 18, 24, 0.58);
|
||||
color: var(--muted);
|
||||
min-width: 108px;
|
||||
}
|
||||
|
||||
.tab.active, .tab:hover {
|
||||
color: var(--text);
|
||||
border-color: var(--accent-2);
|
||||
background: rgba(75, 183, 170, 0.12);
|
||||
}
|
||||
|
||||
.content-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(320px, 0.9fr) minmax(520px, 1.6fr);
|
||||
gap: 10px;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.panel {
|
||||
border: 1px solid var(--line);
|
||||
background: linear-gradient(180deg, rgba(255,255,255,0.035), rgba(255,255,255,0.015)), var(--panel);
|
||||
box-shadow: var(--shadow);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.panel-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
height: 38px;
|
||||
padding: 0 10px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.metrics-panel { grid-column: 1 / 2; }
|
||||
.table-panel[data-panel="nodes"] { grid-column: 2 / 3; }
|
||||
.table-panel[data-panel="events"], .dispatch-panel { grid-column: 1 / -1; }
|
||||
|
||||
.metric-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.metric {
|
||||
padding: 10px;
|
||||
min-height: 74px;
|
||||
border: 1px solid var(--line-soft);
|
||||
background: var(--panel-2);
|
||||
}
|
||||
|
||||
.metric .label {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.12em;
|
||||
}
|
||||
.metric .value {
|
||||
margin-top: 8px;
|
||||
color: var(--text);
|
||||
font-size: 24px;
|
||||
font-weight: 720;
|
||||
}
|
||||
.metric .hint {
|
||||
margin-top: 3px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.table-wrap { overflow: auto; max-height: 46vh; }
|
||||
table { width: 100%; border-collapse: collapse; min-width: 680px; }
|
||||
th, td {
|
||||
padding: 7px 9px;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: #121b24;
|
||||
color: var(--accent);
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.11em;
|
||||
z-index: 1;
|
||||
}
|
||||
td { color: var(--text); }
|
||||
.code, code {
|
||||
font-family: "Cascadia Mono", "IBM Plex Mono", "Liberation Mono", monospace;
|
||||
font-size: 12px;
|
||||
color: #bfd7dc;
|
||||
}
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 2px 7px;
|
||||
border: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
background: rgba(0,0,0,0.18);
|
||||
}
|
||||
.badge.online { color: var(--ok); border-color: rgba(111, 190, 115, 0.45); }
|
||||
.badge.offline { color: var(--danger); border-color: rgba(216, 107, 85, 0.45); }
|
||||
|
||||
.dispatch-panel { min-height: 230px; }
|
||||
.dispatch-form {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 180px auto;
|
||||
gap: 8px;
|
||||
padding: 10px;
|
||||
align-items: end;
|
||||
}
|
||||
.dispatch-form label {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.12em;
|
||||
}
|
||||
.dispatch-form .wide { grid-column: 1 / -1; }
|
||||
input, select, textarea {
|
||||
width: 100%;
|
||||
border: 1px solid var(--line);
|
||||
color: var(--text);
|
||||
background: #0d151c;
|
||||
padding: 7px 8px;
|
||||
outline: none;
|
||||
}
|
||||
textarea { min-height: 76px; resize: vertical; font-family: "Cascadia Mono", "IBM Plex Mono", monospace; }
|
||||
.dispatch-form button {
|
||||
height: 33px;
|
||||
padding: 0 14px;
|
||||
border-color: var(--accent);
|
||||
color: #130f08;
|
||||
background: var(--accent);
|
||||
font-weight: 700;
|
||||
}
|
||||
.result-block {
|
||||
margin: 0 10px 10px;
|
||||
padding: 8px;
|
||||
max-height: 170px;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--line-soft);
|
||||
background: #0d151c;
|
||||
color: #bfd7dc;
|
||||
}
|
||||
|
||||
@media (max-width: 980px) {
|
||||
.shell { grid-template-columns: 1fr; }
|
||||
.rail {
|
||||
position: static;
|
||||
height: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
overflow-x: auto;
|
||||
border-right: 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.brand { border-bottom: 0; margin-bottom: 0; padding-bottom: 0; flex: 0 0 auto; }
|
||||
.module { width: auto; white-space: nowrap; border-left: 0; border-bottom: 2px solid transparent; }
|
||||
.module.active, .module:hover { border-bottom-color: var(--accent); }
|
||||
.content-grid { grid-template-columns: 1fr; }
|
||||
.metrics-panel, .table-panel[data-panel="nodes"], .table-panel[data-panel="events"], .dispatch-panel { grid-column: 1; }
|
||||
.dispatch-form { grid-template-columns: 1fr; }
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
interface RuntimeConfig {
|
||||
port: number;
|
||||
corePublicUrl: string;
|
||||
logFile: string;
|
||||
}
|
||||
|
||||
type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
|
||||
|
||||
const config = readConfig();
|
||||
const logger = createLogger("frontend", config.logFile);
|
||||
const publicDir = join(import.meta.dir, "..", "public");
|
||||
const indexHtml = readFileSync(join(publicDir, "index.html"), "utf8").replace(
|
||||
"__UNIDESK_CONFIG__",
|
||||
JSON.stringify({ coreApiUrl: config.corePublicUrl, corePort: new URL(config.corePublicUrl).port }),
|
||||
);
|
||||
|
||||
function requiredEnv(name: string): string {
|
||||
const value = process.env[name];
|
||||
if (value === undefined || value.length === 0) {
|
||||
throw new Error(`Missing required environment variable: ${name}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function readNumberEnv(name: string): number {
|
||||
const raw = requiredEnv(name);
|
||||
const parsed = Number(raw);
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) {
|
||||
throw new Error(`Environment variable ${name} must be a positive number, got ${raw}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function readConfig(): RuntimeConfig {
|
||||
return {
|
||||
port: readNumberEnv("PORT"),
|
||||
corePublicUrl: requiredEnv("CORE_PUBLIC_URL"),
|
||||
logFile: requiredEnv("LOG_FILE"),
|
||||
};
|
||||
}
|
||||
|
||||
function createLogger(service: string, logFile: string) {
|
||||
mkdirSync(dirname(logFile), { recursive: true });
|
||||
return (level: "debug" | "info" | "warn" | "error", message: string, data?: JsonValue): void => {
|
||||
const entry = { ts: new Date().toISOString(), service, level, message, data };
|
||||
const line = `${JSON.stringify(entry)}\n`;
|
||||
try {
|
||||
appendFileSync(logFile, line, "utf8");
|
||||
} catch (error) {
|
||||
console.error(JSON.stringify({ ts: new Date().toISOString(), service, level: "error", message: "log_write_failed", data: String(error) }));
|
||||
}
|
||||
const consoleMethod = level === "error" ? console.error : level === "warn" ? console.warn : console.log;
|
||||
consoleMethod(line.trimEnd());
|
||||
};
|
||||
}
|
||||
|
||||
function contentType(pathname: string): string {
|
||||
if (pathname.endsWith(".css")) return "text/css; charset=utf-8";
|
||||
if (pathname.endsWith(".js")) return "text/javascript; charset=utf-8";
|
||||
if (pathname.endsWith(".svg")) return "image/svg+xml";
|
||||
return "text/plain; charset=utf-8";
|
||||
}
|
||||
|
||||
function jsonResponse(body: JsonValue, status = 200): Response {
|
||||
return new Response(JSON.stringify(body, null, 2), {
|
||||
status,
|
||||
headers: { "content-type": "application/json; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
|
||||
const server = Bun.serve({
|
||||
port: config.port,
|
||||
hostname: "0.0.0.0",
|
||||
async fetch(req) {
|
||||
const url = new URL(req.url);
|
||||
logger("debug", "request", { path: url.pathname });
|
||||
if (url.pathname === "/health") {
|
||||
return jsonResponse({ ok: true, service: "unidesk-frontend", coreApiUrl: config.corePublicUrl });
|
||||
}
|
||||
if (url.pathname === "/" || url.pathname === "/index.html") {
|
||||
return new Response(indexHtml, { headers: { "content-type": "text/html; charset=utf-8" } });
|
||||
}
|
||||
const safePath = url.pathname.replace(/^\/+/, "");
|
||||
if (safePath.includes("..")) {
|
||||
return jsonResponse({ ok: false, error: "invalid path" }, 400);
|
||||
}
|
||||
const file = Bun.file(join(publicDir, safePath));
|
||||
if (!(await file.exists())) {
|
||||
return jsonResponse({ ok: false, error: "not found", path: url.pathname }, 404);
|
||||
}
|
||||
return new Response(file, { headers: { "content-type": contentType(url.pathname) } });
|
||||
},
|
||||
});
|
||||
|
||||
logger("info", "server_listening", { url: `http://0.0.0.0:${server.port}`, coreApiUrl: config.corePublicUrl, logFile: config.logFile });
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"types": ["bun", "node"],
|
||||
"strict": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"declaration": true,
|
||||
"emitDeclarationOnly": true,
|
||||
"outDir": "dist",
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user