-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathserver.ts
More file actions
143 lines (123 loc) · 4.82 KB
/
server.ts
File metadata and controls
143 lines (123 loc) · 4.82 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
import { readFileSync, existsSync } from "fs";
import { join } from "path";
import { ensureDirectories, getSession } from "./lib/storage";
import { handleApi } from "./routes/api";
import { websocketHandlers, allClients } from "./routes/websocket";
import { initNetwork, registerSprite, updateHeartbeat, buildSpriteRegistration, isNetworkEnabled } from "./lib/network";
// Load .env file if present
const ENV_FILE = join(import.meta.dir, ".env");
if (existsSync(ENV_FILE)) {
const envContent = readFileSync(ENV_FILE, "utf-8");
for (const line of envContent.split("\n")) {
const [key, ...valueParts] = line.split("=");
if (key && valueParts.length > 0) {
process.env[key.trim()] = valueParts.join("=").trim();
}
}
}
// Configuration
const PORT = parseInt(process.env.PORT || "8081");
const PUBLIC_DIR = join(import.meta.dir, "public");
// Ensure data directories exist
ensureDirectories();
// CORS headers for cross-origin requests
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};
function addCorsHeaders(response: Response): Response {
const newHeaders = new Headers(response.headers);
for (const [key, value] of Object.entries(corsHeaders)) {
newHeaders.set(key, value);
}
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders,
});
}
function getContentType(path: string): string {
if (path.endsWith(".html")) return "text/html";
if (path.endsWith(".css")) return "text/css";
if (path.endsWith(".js")) return "text/javascript";
if (path.endsWith(".json")) return "application/json";
if (path.endsWith(".svg")) return "image/svg+xml";
if (path.endsWith(".png")) return "image/png";
return "text/plain";
}
// Start server
const server = Bun.serve({
port: PORT,
idleTimeout: 120, // seconds - needed for Claude summarization endpoints
async fetch(req, server) {
const url = new URL(req.url);
// Handle CORS preflight
if (req.method === "OPTIONS") {
return new Response(null, { headers: corsHeaders });
}
// API routes
if (url.pathname.startsWith("/api/")) {
const response = await handleApi(req, url);
if (response) return addCorsHeaders(response);
}
// Keepalive WebSocket
if (url.pathname === "/ws/keepalive") {
const upgraded = server.upgrade(req, { data: { type: "keepalive" } });
if (!upgraded) return new Response("WebSocket upgrade failed", { status: 400 });
return undefined;
}
// Chat WebSocket
if (url.pathname === "/ws") {
const sessionId = url.searchParams.get("session");
if (!sessionId) return new Response("Missing session ID", { status: 400 });
const session = getSession(sessionId);
if (!session) return new Response("Session not found", { status: 404 });
const upgraded = server.upgrade(req, {
data: { sessionId, cwd: session.cwd, claudeSessionId: session.claudeSessionId }
});
if (!upgraded) return new Response("WebSocket upgrade failed", { status: 400 });
return undefined;
}
// Static files
let filePath = url.pathname === "/" ? "/index.html" : url.pathname;
try {
const content = readFileSync(join(PUBLIC_DIR, filePath));
return new Response(content, {
headers: { "Content-Type": getContentType(filePath) },
});
} catch {
return new Response("Not found", { status: 404 });
}
},
websocket: websocketHandlers,
});
// Initialize sprite network for discovery
const networkEnabled = initNetwork();
if (networkEnabled) {
// Register this sprite on startup
const spriteInfo = buildSpriteRegistration();
registerSprite(spriteInfo)
.then(() => console.log(`Registered in sprite network as: ${spriteInfo.hostname}`))
.catch((err) => console.error("Failed to register in sprite network:", err));
// Heartbeat every 5 minutes to update lastSeen
setInterval(() => {
updateHeartbeat().catch((err) => console.error("Heartbeat failed:", err));
}, 5 * 60 * 1000);
}
// Hot-reloading disabled to prevent constant app refreshes during conversations
// If you need hot-reload during development, uncomment this block:
// let reloadDebounce: ReturnType<typeof setTimeout> | null = null;
// watch(PUBLIC_DIR, { recursive: true }, (event, filename) => {
// if (reloadDebounce) clearTimeout(reloadDebounce);
// reloadDebounce = setTimeout(() => {
// console.log(`File changed: ${filename}, notifying ${allClients.size} clients to reload`);
// const msg = JSON.stringify({ type: "reload" });
// for (const ws of allClients) {
// try {
// if (ws.readyState === 1) ws.send(msg);
// } catch {}
// }
// }, 300);
// });
console.log(`Claude Mobile server running on http://localhost:${PORT}`);