import { Observable } from 'rxjs'; export function createWebSocket( host: string, wsPort: number, deserialize: (input: string) => T, endpoint = '' ): Observable { return new Observable((observer) => { const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const ws = new WebSocket(`${protocol}//${host}:${wsPort}/${endpoint}`); ws.onmessage = (e) => { const reader = new FileReader(); reader.onload = () => { const data = deserialize(JSON.parse(reader.result as string)); observer.next(data); }; reader.readAsText(e.data); }; ws.onerror = () => { observer.error(); }; ws.onclose = () => { observer.complete(); }; return () => { // Removing listeners to avoid loop ws.onmessage = null; ws.onclose = null; ws.onerror = null; ws.close(); }; }); }