(
res: http.ServerResponse,
events: Array<{ eventType: string; payload: object }>,
options?: {
latency?: number;
streamingProfile?: StreamingProfile;
recordedTimings?: RecordedTimings;
replaySpeed?: number;
signal?: AbortSignal;
onChunkSent?: () => void;
},
)
| 116 | * the provided abort signal. |
| 117 | */ |
| 118 | export async function writeEventStream( |
| 119 | res: http.ServerResponse, |
| 120 | events: Array<{ eventType: string; payload: object }>, |
| 121 | options?: { |
| 122 | latency?: number; |
| 123 | streamingProfile?: StreamingProfile; |
| 124 | recordedTimings?: RecordedTimings; |
| 125 | replaySpeed?: number; |
| 126 | signal?: AbortSignal; |
| 127 | onChunkSent?: () => void; |
| 128 | }, |
| 129 | ): Promise<boolean> { |
| 130 | const opts = options ?? {}; |
| 131 | const latency = opts.latency ?? 0; |
| 132 | const profile = opts.streamingProfile; |
| 133 | const { recordedTimings, replaySpeed } = opts; |
| 134 | const signal = opts.signal; |
| 135 | const onChunkSent = opts.onChunkSent; |
| 136 | |
| 137 | if (res.writableEnded) return true; |
| 138 | res.setHeader("Content-Type", "application/vnd.amazon.eventstream"); |
| 139 | res.setHeader("Transfer-Encoding", "chunked"); |
| 140 | |
| 141 | let chunkIndex = 0; |
| 142 | for (const event of events) { |
| 143 | const chunkDelay = calculateDelay(chunkIndex, profile, latency, recordedTimings, replaySpeed); |
| 144 | if (chunkDelay > 0) { |
| 145 | await delay(chunkDelay, signal); |
| 146 | } |
| 147 | if (signal?.aborted) return false; |
| 148 | if (res.writableEnded) return true; |
| 149 | |
| 150 | const frame = encodeEventStreamMessage(event.eventType, event.payload); |
| 151 | res.write(frame); |
| 152 | onChunkSent?.(); |
| 153 | if (signal?.aborted) return false; |
| 154 | chunkIndex++; |
| 155 | } |
| 156 | |
| 157 | if (!res.writableEnded) { |
| 158 | res.end(); |
| 159 | } |
| 160 | return true; |
| 161 | } |
no test coverage detected
searching dependent graphs…