MCPcopy Create free account
hub / github.com/CommandCodeAI/BaseAI / iterSSEChunks

Function iterSSEChunks

packages/baseai/src/dev/utils/stream/stream.ts:246–278  ·  view source on GitHub ↗

* 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>
)

Source from the content-addressed store, hash-verified

244 * SSE chunks, i.e. yields when a double new-line is encountered.
245 */
246async 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
280function findDoubleNewlineIndex(buffer: Uint8Array): number {
281 // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)

Callers 1

_iterSSEMessagesFunction · 0.70

Calls 1

findDoubleNewlineIndexFunction · 0.70

Tested by

no test coverage detected