| 254 | yield "data: [DONE]\n\n"; |
| 255 | } |
| 256 | function streamResponse(gen: AsyncGenerator<string>, status = 200) { |
| 257 | const stream = new ReadableStream({ |
| 258 | async start(ctrl) { |
| 259 | try { |
| 260 | for await (const chunk of gen) { |
| 261 | ctrl.enqueue(new TextEncoder().encode(chunk)); |
| 262 | } |
| 263 | ctrl.close(); |
| 264 | } catch (e) { |
| 265 | ctrl.error(e); |
| 266 | } |
| 267 | }, |
| 268 | }); |
| 269 | return new Response(stream, { |
| 270 | status, |
| 271 | headers: { |
| 272 | "Content-Type": "text/event-stream", |
| 273 | "Cache-Control": "no-cache", |
| 274 | Connection: "keep-alive", |
| 275 | }, |
| 276 | }); |
| 277 | } |
| 278 | |
| 279 | /* ------------------------------------------------------------------------------------------------ |
| 280 | * Core request handler |