The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import * as Duration from "effect/Duration"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import type * as Schema from "effect/Schema"; |
| 4 | import * as Stream from "effect/Stream"; |
| 5 | import { HttpServerResponse } from "effect/http"; |
| 6 | |
| 7 | // Cloudflare closes idle streams after about 100 seconds. |
| 8 | const HEARTBEAT_INTERVAL = Duration.seconds(20); |
| 9 | |
| 10 | /** Server-sent events with a heartbeat, never cached or buffered on the way. */ |
| 11 | export const eventStreamResponse = <A>( |
| 12 | events: Stream.Stream<A>, |
| 13 | encode: (event: A) => Effect.Effect<string, Schema.SchemaError>, |
| 14 | ) => { |
| 15 | const data = events.pipe( |
| 16 | Stream.mapEffect((event) => |
| 17 | encode(event).pipe( |
| 18 | Effect.map((json) => [`data: ${json}\n\n`]), |
| 19 | // The reader misses one update instead of the whole stream. |
| 20 | Effect.catch(() => |
| 21 | Effect.logWarning("Dropped a stream event that failed to encode.").pipe(Effect.as([])), |
| 22 | ), |
| 23 | ), |
| 24 | ), |
| 25 | Stream.flattenIterable, |
| 26 | ); |
| 27 | const heartbeat = Stream.tick(HEARTBEAT_INTERVAL).pipe(Stream.map(() => ": ping\n\n")); |
| 28 | return HttpServerResponse.stream( |
| 29 | data.pipe(Stream.merge(heartbeat, { haltStrategy: "left" }), Stream.encodeText), |
| 30 | { |
| 31 | contentType: "text/event-stream", |
| 32 | // no-transform keeps the compression middleware from buffering the stream. |
| 33 | headers: { "cache-control": "no-store, no-transform", "x-accel-buffering": "no" }, |
| 34 | }, |
| 35 | ); |
| 36 | }; |