-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
52 lines (44 loc) · 1.58 KB
/
server.ts
File metadata and controls
52 lines (44 loc) · 1.58 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
import { createServer } from "node:http";
import type { Duplex } from "node:stream";
import next from "next";
import { WebSocketServer } from "ws";
import { BROWSERBOX_WS_PATH } from "@/lib/ws-path";
import { attachBrowserboxWebSocketServer } from "@/lib/server/ws-http-server";
const dev = process.env.NODE_ENV !== "production";
const hostname = process.env.HOSTNAME ?? "localhost";
const port = Number.parseInt(process.env.PORT ?? "3000", 10);
const bindHost = process.env.HOST ?? "0.0.0.0";
const app = next({ dev, hostname, port });
/** `IncomingMessage.url` is path + query only; WHATWG URL needs a base. */
function pathnameFromRequestUrl(urlPath: string | undefined): string {
if (!urlPath) return "";
try {
return new URL(urlPath, "http://internal.invalid").pathname;
} catch {
return "";
}
}
const wss = new WebSocketServer({ noServer: true });
attachBrowserboxWebSocketServer(wss);
void app.prepare().then(() => {
const handle = app.getRequestHandler();
const upgradeHandler = app.getUpgradeHandler();
const server = createServer((req, res) => {
void handle(req, res);
});
server.on("upgrade", (request, socket, head) => {
const pathname = pathnameFromRequestUrl(request.url);
if (pathname === BROWSERBOX_WS_PATH) {
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit("connection", ws, request);
});
} else {
void upgradeHandler(request, socket as Duplex, head);
}
});
server.listen(port, bindHost, () => {
console.log(
`> Ready on http://${hostname}:${port} (WS ${BROWSERBOX_WS_PATH})`,
);
});
});