(server, path)
| 55 | } |
| 56 | |
| 57 | function attachToServer(server, path) { |
| 58 | const wss = new WebSocketServer({ |
| 59 | server: server, |
| 60 | path: path |
| 61 | }); |
| 62 | const clients = new Map(); |
| 63 | let nextClientId = 0; |
| 64 | |
| 65 | function getClientWs(clientId) { |
| 66 | const clientWs = clients.get(clientId); |
| 67 | if (clientWs === undefined) { |
| 68 | throw `could not find id "${clientId}" while forwarding request`; |
| 69 | } |
| 70 | return clientWs; |
| 71 | } |
| 72 | |
| 73 | function handleSendBroadcast(broadcasterId, message) { |
| 74 | const forwarded = { |
| 75 | version: PROTOCOL_VERSION, |
| 76 | method: message.method, |
| 77 | params: message.params, |
| 78 | }; |
| 79 | for (const [otherId, otherWs] of clients) { |
| 80 | if (otherId !== broadcasterId) { |
| 81 | try { |
| 82 | otherWs.send(JSON.stringify(forwarded)); |
| 83 | } catch (e) { |
| 84 | console.error(`Failed to send broadcast to client: '${otherId}' ` + |
| 85 | `due to:\n ${e.toString()}`); |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | wss.on('connection', function(clientWs) { |
| 92 | const clientId = `client#${nextClientId++}`; |
| 93 | |
| 94 | function handleCaughtError(message, error) { |
| 95 | const errorMessage = { |
| 96 | id: message.id, |
| 97 | method: message.method, |
| 98 | target: message.target, |
| 99 | error: message.error === undefined ? 'undefined' : 'defined', |
| 100 | params: message.params === undefined ? 'undefined' : 'defined', |
| 101 | result: message.result === undefined ? 'undefined' : 'defined', |
| 102 | }; |
| 103 | |
| 104 | if (message.id === undefined) { |
| 105 | console.error( |
| 106 | `Handling message from ${clientId} failed with:\n${error}\n` + |
| 107 | `message:\n${JSON.stringify(errorMessage)}`); |
| 108 | } else { |
| 109 | try { |
| 110 | clientWs.send(JSON.stringify({ |
| 111 | version: PROTOCOL_VERSION, |
| 112 | error: error, |
| 113 | id: message.id, |
| 114 | })); |
nothing calls this directly
no test coverage detected
searching dependent graphs…