()
| 116 | } |
| 117 | |
| 118 | connect(): void { |
| 119 | if (this.closed) return; |
| 120 | |
| 121 | this.eventSource = new EventSource(this.url); |
| 122 | |
| 123 | this.eventSource.onopen = () => { |
| 124 | this.reconnectAttempts = 0; |
| 125 | this.opts.onConnect?.(); |
| 126 | }; |
| 127 | |
| 128 | this.eventSource.onmessage = (e: MessageEvent) => { |
| 129 | if (typeof e.data !== "string") return; |
| 130 | if (e.data === "[DONE]") return; |
| 131 | try { |
| 132 | const event = JSON.parse(e.data as string) as StreamEvent; |
| 133 | this.opts.onEvent(event); |
| 134 | } catch { |
| 135 | // skip malformed events |
| 136 | } |
| 137 | }; |
| 138 | |
| 139 | this.eventSource.onerror = () => { |
| 140 | this.eventSource?.close(); |
| 141 | this.eventSource = null; |
| 142 | this.opts.onDisconnect?.(); |
| 143 | this.scheduleReconnect(); |
| 144 | }; |
| 145 | } |
| 146 | |
| 147 | disconnect(): void { |
| 148 | this.closed = true; |
no test coverage detected