-
Notifications
You must be signed in to change notification settings - Fork 18
/
livereload_server.ts
84 lines (76 loc) · 2.12 KB
/
livereload_server.ts
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
import { logger } from "./logger_util.ts";
function livereloadScript(port: number) {
return `window.onload = () => {
new WebSocket("ws://localhost:${port}/livereload").onmessage = () => location.reload();
};`;
}
function handleWs(sock: WebSocket, eventtarget: EventTarget): void {
logger.debug("socket connected!");
sock.onmessage = (ev) => {
logger.debug("ws:Message", ev.data);
sock.send(ev.data);
};
sock.onopen = () => logger.debug("ws:Open");
sock.onclose = (ev) => {
const { code, reason } = ev;
logger.debug("ws:Close", code, reason);
};
sock.onerror = (ev) => {
logger.error("failed to receive frame:", ev);
if (canCloseSocket(sock)) {
sock.close(1000);
}
};
eventtarget.addEventListener("built", () => {
logger.debug("got reload event!");
if (canCloseSocket(sock)) {
sock.send(JSON.stringify({ type: "reload" }));
sock.close(1000);
}
}, { once: true });
}
function canCloseSocket(socket: WebSocket): boolean {
return socket.readyState === socket.OPEN;
}
function handleHttp(
request: Request,
eventtarget: EventTarget,
port: number,
): Response {
const url = new URL(request.url);
switch (url.pathname) {
case "/livereload.js":
return new Response(livereloadScript(port), {
headers: { "content-type": "text/javascript" },
});
case "/livereload": {
if (request.headers.get("upgrade") !== "websocket") {
return new Response(null, { status: 404 });
}
const { response, socket } = Deno.upgradeWebSocket(request);
handleWs(socket, eventtarget);
return response;
}
default:
return new Response(null, { status: 404 });
}
}
interface LivereloadServer {
close(): Promise<void>;
}
export function livereloadServer(
port = 35729,
eventtarget: EventTarget,
): LivereloadServer {
logger.debug(`livereload websocket server is running on port=${port}`);
const server = Deno.serve({
port,
// suppress unnecessary log
onListen: () => {},
}, (request) => handleHttp(request, eventtarget, port));
return {
async close() {
await server.shutdown();
},
};
}