| 5 | import type * as d from '../declarations'; |
| 6 | |
| 7 | export function createWebSocket( |
| 8 | httpServer: Server, |
| 9 | onMessageFromClient: (msg: d.DevServerMessage) => void, |
| 10 | ): DevWebSocket { |
| 11 | const wsConfig: ServerOptions = { |
| 12 | server: httpServer, |
| 13 | }; |
| 14 | |
| 15 | const wsServer = new WebSocketServer(wsConfig); |
| 16 | |
| 17 | function heartbeat(this: WebSocket) { |
| 18 | // we need to coerce the `ws` type to our custom `DevWS` type here, since |
| 19 | // this function is going to be passed in to `ws.on('pong'` which expects |
| 20 | // to be passed a function where `this` is bound to `ws`. |
| 21 | (this as DevWS).isAlive = true; |
| 22 | } |
| 23 | |
| 24 | wsServer.on('connection', (ws: DevWS) => { |
| 25 | ws.on('message', (data) => { |
| 26 | // the server process has received a message from the browser |
| 27 | // pass the message received from the browser to the main cli process |
| 28 | try { |
| 29 | onMessageFromClient(JSON.parse(data.toString())); |
| 30 | } catch (e) { |
| 31 | console.error(e); |
| 32 | } |
| 33 | }); |
| 34 | |
| 35 | ws.isAlive = true; |
| 36 | |
| 37 | ws.on('pong', heartbeat); |
| 38 | |
| 39 | // ignore invalid close frames sent by Safari 15 |
| 40 | ws.on('error', console.error); |
| 41 | }); |
| 42 | |
| 43 | const pingInterval = setInterval(() => { |
| 44 | (wsServer.clients as Set<DevWS>).forEach((ws: DevWS) => { |
| 45 | if (!ws.isAlive) { |
| 46 | return ws.close(1000); |
| 47 | } |
| 48 | ws.isAlive = false; |
| 49 | ws.ping(noop); |
| 50 | }); |
| 51 | }, 10000); |
| 52 | |
| 53 | return { |
| 54 | sendToBrowser: (msg: d.DevServerMessage) => { |
| 55 | if (msg && wsServer && wsServer.clients) { |
| 56 | const data = JSON.stringify(msg); |
| 57 | wsServer.clients.forEach((ws) => { |
| 58 | if (ws.readyState === ws.OPEN) { |
| 59 | ws.send(data); |
| 60 | } |
| 61 | }); |
| 62 | } |
| 63 | }, |
| 64 | close: () => { |