| 255 | } |
| 256 | |
| 257 | function parseEventStreamLine( |
| 258 | lineBuffer: string, |
| 259 | index: number, |
| 260 | fieldLength: number, |
| 261 | lineLength: number |
| 262 | ) { |
| 263 | if (lineLength === 0) { |
| 264 | // We reached the last line of this event |
| 265 | if (data.length > 0) { |
| 266 | onParse({ |
| 267 | _tag: "Event", |
| 268 | id: eventId, |
| 269 | event: eventName ?? "message", |
| 270 | data: data.slice(0, -1) // remove trailing newline |
| 271 | }) |
| 272 | data = "" |
| 273 | eventId = undefined |
| 274 | } |
| 275 | eventName = undefined |
| 276 | return |
| 277 | } |
| 278 | |
| 279 | const noValue = fieldLength < 0 |
| 280 | const field = lineBuffer.slice(index, index + (noValue ? lineLength : fieldLength)) |
| 281 | let step = 0 |
| 282 | |
| 283 | if (noValue) { |
| 284 | step = lineLength |
| 285 | } else if (lineBuffer[index + fieldLength + 1] === " ") { |
| 286 | step = fieldLength + 2 |
| 287 | } else { |
| 288 | step = fieldLength + 1 |
| 289 | } |
| 290 | |
| 291 | const position = index + step |
| 292 | const valueLength = lineLength - step |
| 293 | const value = lineBuffer.slice(position, position + valueLength).toString() |
| 294 | |
| 295 | if (field === "data") { |
| 296 | data += value ? `${value}\n` : "\n" |
| 297 | } else if (field === "event") { |
| 298 | eventName = value |
| 299 | } else if (field === "id" && !value.includes("\u0000")) { |
| 300 | eventId = value |
| 301 | lastEventId = value |
| 302 | } else if (field === "retry") { |
| 303 | const retry = parseInt(value, 10) |
| 304 | if (!Number.isNaN(retry)) { |
| 305 | onParse(new Retry({ duration: Duration.millis(retry), lastEventId })) |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | const BOM = [239, 187, 191] |