* Given an async iterable iterator, iterates over it and yields full * SSE chunks, i.e. yields when a double new-line is encountered.
( iterator: AsyncIterableIterator<Bytes> )
| 244 | * SSE chunks, i.e. yields when a double new-line is encountered. |
| 245 | */ |
| 246 | async function* iterSSEChunks( |
| 247 | iterator: AsyncIterableIterator<Bytes> |
| 248 | ): AsyncGenerator<Uint8Array> { |
| 249 | let data = new Uint8Array(); |
| 250 | |
| 251 | for await (const chunk of iterator) { |
| 252 | if (chunk == null) { |
| 253 | continue; |
| 254 | } |
| 255 | |
| 256 | const binaryChunk = |
| 257 | chunk instanceof ArrayBuffer |
| 258 | ? new Uint8Array(chunk) |
| 259 | : typeof chunk === 'string' |
| 260 | ? new TextEncoder().encode(chunk) |
| 261 | : chunk; |
| 262 | |
| 263 | let newData = new Uint8Array(data.length + binaryChunk.length); |
| 264 | newData.set(data); |
| 265 | newData.set(binaryChunk, data.length); |
| 266 | data = newData; |
| 267 | |
| 268 | let patternIndex; |
| 269 | while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { |
| 270 | yield data.slice(0, patternIndex); |
| 271 | data = data.slice(patternIndex); |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | if (data.length > 0) { |
| 276 | yield data; |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | function findDoubleNewlineIndex(buffer: Uint8Array): number { |
| 281 | // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) |
no test coverage detected