* Asynchronously iterates over SSE (Server-Sent Events) chunks and yields the data as Uint8Array. * * Given an async iterable iterator, iterates over it and yields full * SSE chunks, i.e. yields when a double new-line is encountered. * * @param iterator - The async iterator that provides the SS
(iterator: AsyncIterableIterator<Bytes>)
| 249 | * @returns An async generator that yields Uint8Array chunks. |
| 250 | */ |
| 251 | async function* iterSSEChunks(iterator: AsyncIterableIterator<Bytes>): AsyncGenerator<Uint8Array> { |
| 252 | let data = new Uint8Array(); |
| 253 | |
| 254 | for await (const chunk of iterator) { |
| 255 | if (chunk == null) { |
| 256 | continue; |
| 257 | } |
| 258 | |
| 259 | const binaryChunk = |
| 260 | chunk instanceof ArrayBuffer |
| 261 | ? new Uint8Array(chunk) |
| 262 | : typeof chunk === 'string' |
| 263 | ? new TextEncoder().encode(chunk) |
| 264 | : chunk; |
| 265 | |
| 266 | let newData = new Uint8Array(data.length + binaryChunk.length); |
| 267 | newData.set(data); |
| 268 | newData.set(binaryChunk, data.length); |
| 269 | data = newData; |
| 270 | |
| 271 | let patternIndex; |
| 272 | while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { |
| 273 | yield data.slice(0, patternIndex); |
| 274 | data = data.slice(patternIndex); |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | if (data.length > 0) { |
| 279 | yield data; |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | /** |
| 284 | * Finds the index of the first occurrence of a double newline pattern (\r\r, \n\n, \r\n\r\n) in the given buffer. |
no test coverage detected