"use strict"; const sockets = {}; const isSocketOpen = (url) => { return sockets[url]?._ws?.readyState === WebSocket.OPEN; }; const initSocket = (url) => { if (sockets[url]) { if (isSocketOpen(url)) { return sockets[url]; } else { sockets[url]._ws.close(); } } const ws = new WebSocket(url); const socket = { send: (data) => { sockets[url]._ws.send(data); }, addMessageListener: (listener) => { socket._listeners.push(listener); }, _listeners: sockets[url]?._listeners ?? [], _ws: ws, }; ws.onerror = () => ws.close(); ws.onclose = () => initSocket(url); ws.onmessage = (event) => { console; sockets[url]._listeners.forEach((listener) => listener(event.data)); }; sockets[url] = socket; return sockets[url]; };