import { createServer } from "node:http"; import process from "node:process"; import { WebSocketServer } from "ws"; const server = createServer(); const requests: string[] = []; const clients = new Set(); server.on("listening", () => { const address = server.address(); if (!address || typeof address !== "object") { throw new Error("[test server] Unexpected address assigned"); } const port = address.port; console.log(`[test server] Listening at port ${port}`); process.send?.(`ready:${port}`); }); server.on("upgrade", (req, socket) => { const url = new URL(`http://example.com${req.url}`); const clientId = url.searchParams.get("clientId"); let shouldDeny = url.searchParams.get("deny") === "always"; if (clientId) { const denyPattern = url.searchParams.get("deny"); requests.push(clientId); if (!shouldDeny && denyPattern) { const requestIndex = requests.reduce( (count, req) => (req === clientId ? count + 1 : count), -1, ); shouldDeny = denyPattern[requestIndex] === "1"; } } if (shouldDeny) { console.log("[test server] Upgrade request denied"); socket.destroy(); } }); server.on("close", () => { console.log("[test server] Server stopped"); clients.clear(); }); const wss = new WebSocketServer({ server }); wss.on("connection", (ws, req) => { const url = new URL(`http://example.com${req.url}`); const clientId = url.searchParams.get("clientId"); const greet = url.searchParams.get("hello"); console.log(`[test server] Incoming connection ${clientId ?? "(no id)"}`); if (clientId) { clients.add(clientId); } if (greet) { ws.send(`Hello, ${greet}`); } ws.on("message", (data) => { const message = data.toString("utf-8"); if (message === "close") { ws.close(1000, "client requested to close"); } else { ws.send(message); } }); ws.on("close", (code) => { if (clientId) { clients.delete(clientId); } console.log( `[test server] Connection ${clientId ?? "(no id)"} closed with code ${code}`, ); }); }); server.listen(0); process.on("message", (message) => { if (typeof message === "string") { const status = clients.has(message) ? "connected" : "disconnected"; const requestCount = requests.reduce( (count, req) => (req === message ? count + 1 : count), 0, ); process.send?.(`${message}:${status}:${requestCount}`); } }); process.on("SIGINT", () => { console.log("[test server] Gracefully stopping..."); wss.clients.forEach((ws) => ws.close(1001, "Test server stopped")); server.close(); process.exit(0); });