-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
192 lines (166 loc) · 6.35 KB
/
server.ts
File metadata and controls
192 lines (166 loc) · 6.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import { Subprocess } from "bun";
import { readFileSync, writeFileSync, readdirSync, statSync } from "fs";
import { join, dirname } from "path";
interface ProjectConfig {
name: string;
path: string;
}
interface Config {
port: number;
projects: ProjectConfig[];
}
interface RunningProject {
name: string;
path: string;
port: number;
process: Subprocess;
}
const configPath = join(import.meta.dir, "config.json");
const config: Config = JSON.parse(readFileSync(configPath, "utf-8"));
const dashboardPort = config.port || 6420;
const running: RunningProject[] = [];
const configuredProjects: ProjectConfig[] = [...config.projects];
function nextPort(): number {
if (running.length === 0) return dashboardPort + 1;
return Math.max(...running.map((r) => r.port)) + 1;
}
function spawnProject(name: string, path: string): RunningProject {
const port = nextPort();
console.log(`Starting backlog for "${name}" on port ${port} (cwd: ${path})`);
const proc = Bun.spawn(["backlog", "browser", "--port", String(port), "--no-open"], {
cwd: path,
stdout: "ignore",
stderr: "pipe",
});
const entry: RunningProject = { name, path, port, process: proc };
running.push(entry);
return entry;
}
function saveConfig() {
const data: Config = {
port: dashboardPort,
projects: configuredProjects,
};
writeFileSync(configPath, JSON.stringify(data, null, 2) + "\n");
}
// Spawn backlog browser for each project
for (const project of config.projects) {
spawnProject(project.name, project.path);
}
// Wait for instances to start
await Bun.sleep(1500);
// Serve dashboard
const indexPath = join(import.meta.dir, "index.html");
const server = Bun.serve({
port: dashboardPort,
async fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/" || url.pathname === "/index.html") {
return new Response(readFileSync(indexPath, "utf-8"), {
headers: { "Content-Type": "text/html" },
});
}
if (url.pathname === "/api/projects" && req.method === "GET") {
// Return in config order
const projects = configuredProjects.map((cfg) => {
const r = running.find((r) => r.name === cfg.name && r.path === cfg.path);
return { name: cfg.name, port: r?.port ?? 0, path: cfg.path };
});
return Response.json(projects);
}
if (url.pathname === "/api/projects" && req.method === "POST") {
const body = await req.json() as { name?: string; path?: string };
if (!body.name || !body.path) {
return Response.json({ error: "name and path are required" }, { status: 400 });
}
const entry = spawnProject(body.name, body.path);
configuredProjects.push({ name: body.name, path: body.path });
saveConfig();
await Bun.sleep(1500);
return Response.json({ name: entry.name, port: entry.port, path: entry.path });
}
if (url.pathname.startsWith("/api/projects/") && req.method === "DELETE") {
const port = Number(url.pathname.split("/").pop());
const idx = running.findIndex((r) => r.port === port);
if (idx === -1) {
return Response.json({ error: "project not found" }, { status: 404 });
}
const removed = running[idx];
console.log(`Removing project "${removed.name}" (port ${port})`);
removed.process.kill();
running.splice(idx, 1);
const cfgIdx = configuredProjects.findIndex((p) => p.name === removed.name && p.path === removed.path);
if (cfgIdx !== -1) configuredProjects.splice(cfgIdx, 1);
saveConfig();
return Response.json({ ok: true });
}
if (url.pathname.match(/^\/api\/projects\/\d+\/restart$/) && req.method === "POST") {
const port = Number(url.pathname.split("/")[3]);
const idx = running.findIndex((r) => r.port === port);
if (idx === -1) {
return Response.json({ error: "project not found" }, { status: 404 });
}
const old = running[idx];
console.log(`Restarting backlog for "${old.name}" (port ${port})`);
old.process.kill();
running.splice(idx, 1);
const entry = spawnProject(old.name, old.path);
await Bun.sleep(1500);
return Response.json({ name: entry.name, port: entry.port, path: entry.path });
}
if (url.pathname === "/api/projects/reorder" && req.method === "PUT") {
const body = await req.json() as { order: number[] };
if (!body.order || !Array.isArray(body.order)) {
return Response.json({ error: "order array is required" }, { status: 400 });
}
const reordered = body.order.map((port) => {
const r = running.find((r) => r.port === port);
return r ? { name: r.name, path: r.path } : null;
}).filter(Boolean) as ProjectConfig[];
if (reordered.length !== configuredProjects.length) {
return Response.json({ error: "order must include all projects" }, { status: 400 });
}
configuredProjects.splice(0, configuredProjects.length, ...reordered);
saveConfig();
return Response.json({ ok: true });
}
if (url.pathname === "/api/browse") {
const dir = url.searchParams.get("dir") || "C:/";
try {
const entries = readdirSync(dir, { withFileTypes: true });
const dirs = entries
.filter((e) => e.isDirectory() && !e.name.startsWith("."))
.map((e) => e.name)
.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
const parent = dirname(dir) !== dir ? dirname(dir) : null;
return Response.json({ dir, parent, dirs });
} catch {
return Response.json({ dir, parent: dirname(dir), dirs: [], error: "Cannot read directory" });
}
}
if (url.pathname.startsWith("/api/health/")) {
const port = url.pathname.split("/").pop();
try {
const res = await fetch(`http://localhost:${port}/`);
return Response.json({ ok: res.ok });
} catch {
return Response.json({ ok: false });
}
}
return new Response("Not found", { status: 404 });
},
});
console.log(`\nBacklog Hub running at http://localhost:${dashboardPort}`);
console.log(`Managing ${running.length} project(s)\n`);
// Graceful shutdown
function shutdown() {
console.log("\nShutting down...");
for (const r of running) {
console.log(` Killing backlog for "${r.name}" (port ${r.port})`);
r.process.kill();
}
server.stop();
process.exit(0);
}
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);