MCPcopy
hub / github.com/TanStack/ai / parseSSEStream

Function parseSSEStream

packages/ai/tests/stream-to-response.test.ts:483–517  ·  view source on GitHub ↗

* Helper to parse SSE stream back into chunks

(
    sseStream: ReadableStream<Uint8Array>,
  )

Source from the content-addressed store, hash-verified

481 * Helper to parse SSE stream back into chunks
482 */
483 async function parseSSEStream(
484 sseStream: ReadableStream<Uint8Array>,
485 ): Promise<Array<Record<string, unknown>>> {
486 const reader = sseStream.getReader()
487 const decoder = new TextDecoder()
488 const chunks: Array<Record<string, unknown>> = []
489 let buffer = ''
490
491 try {
492 while (true) {
493 const { done, value } = await reader.read()
494 if (done) break
495
496 buffer += decoder.decode(value, { stream: true })
497 const lines = buffer.split('\n\n')
498 buffer = lines.pop() || ''
499
500 for (const line of lines) {
501 if (line.startsWith('data: ')) {
502 const data = line.slice(6)
503 if (data === '[DONE]') continue
504 try {
505 chunks.push(JSON.parse(data))
506 } catch {
507 // Skip invalid JSON
508 }
509 }
510 }
511 }
512 } finally {
513 reader.releaseLock()
514 }
515
516 return chunks
517 }
518
519 it('should preserve TEXT_MESSAGE_CONTENT events', async () => {
520 const originalChunks: Array<Record<string, unknown>> = [

Callers 1

Calls 4

getReaderMethod · 0.80
parseMethod · 0.80
readMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected