deno.land / x / packup@v0.1.12 / livereload_server.ts

livereload_server.ts
View Documentation
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
import { logger } from "./logger_util.ts";
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;}
async function serve( httpConn: Deno.HttpConn, eventtarget: EventTarget, port: number,): Promise<void> { const requestEvent = await httpConn.nextRequest(); if (requestEvent == null) { return; }
const { request, respondWith } = requestEvent; const url = new URL(request.url); switch (url.pathname) { case "/livereload.js": respondWith( new Response(` window.onload = () => { new WebSocket("ws://localhost:${port}/livereload").onmessage = () => location.reload(); }; `), ).then( () => httpConn.close(), logger.error, ); break; case "/livereload": { const { response, socket } = Deno.upgradeWebSocket(request); handleWs(socket, eventtarget); respondWith(response); break; } default: httpConn.close(); break; }}
interface LivereloadServer { close(): Promise<void>;}
export function livereloadServer( port = 35729, eventtarget: EventTarget,): LivereloadServer { logger.debug(`livereload websocket server is running on port=${port}`); const listener = Deno.listen({ port }); const done = (async () => { for await (const conn of listener) { const httpConn = Deno.serveHttp(conn); serve(httpConn, eventtarget, port).catch(logger.error); } })();
return { async close() { listener.close(); await done; }, };}
packup
📦 Zero-config web application packager in Deno
GitHub Repositorykt3k/packup
GitHub Stars
260

Version Info

Tagged at
4 months ago