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

Function toServerSentEventsStream

packages/ai/src/stream-to-response.ts:50–100  ·  view source on GitHub ↗
(
  stream: AsyncIterable<StreamChunk>,
  abortController?: AbortController,
)

Source from the content-addressed store, hash-verified

48 * @returns ReadableStream in Server-Sent Events format
49 */
50export function toServerSentEventsStream(
51 stream: AsyncIterable<StreamChunk>,
52 abortController?: AbortController,
53): ReadableStream<Uint8Array> {
54 const encoder = new TextEncoder()
55
56 return new ReadableStream({
57 async start(controller) {
58 try {
59 for await (const chunk of stream) {
60 // Check if stream was cancelled/aborted
61 if (abortController?.signal.aborted) {
62 break
63 }
64
65 // Send each chunk as Server-Sent Events format
66 controller.enqueue(
67 encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`),
68 )
69 }
70
71 controller.close()
72 } catch (error: unknown) {
73 // Don't send error if aborted
74 if (abortController?.signal.aborted) {
75 controller.close()
76 return
77 }
78
79 // Send error event (AG-UI RUN_ERROR)
80 controller.enqueue(
81 encoder.encode(
82 `data: ${JSON.stringify({
83 type: 'RUN_ERROR',
84 timestamp: Date.now(),
85 error: toRunErrorPayload(error),
86 })}\n\n`,
87 ),
88 )
89 controller.close()
90 }
91 },
92 cancel() {
93 // When the ReadableStream is cancelled (e.g., client disconnects),
94 // abort the underlying stream
95 if (abortController) {
96 abortController.abort()
97 }
98 },
99 })
100}
101
102/**
103 * Convert a StreamChunk async iterable to a Response in Server-Sent Events format

Callers 13

api.codemode.tsFile · 0.90
api.reports.tsFile · 0.90
api.run.tsFile · 0.90
configureServerFunction · 0.90
configureServerFunction · 0.90
api.run.tsFile · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected