Repository Public License
1import Foundation23/// One server-sent event.4public struct SSEEvent: Sendable, Hashable {5 /// The `event:` field, when present.6 public var event: String?7 /// The `data:` lines joined with a newline.8 public var data: String910 public init(event: String? = nil, data: String) {11 self.event = event; self.data = data12 }1314 /// The OpenAI-style end-of-stream marker.15 public var isDone: Bool { data.trimmingCharacters(in: .whitespaces) == "[DONE]" }16}1718/// Incremental parser for `text/event-stream` (WHATWG HTML, "Server-sent events").19///20/// It takes raw bytes in chunks of any size and splits lines at the byte level, so a multi-byte UTF-8 character or a21/// CRLF pair cut in two by a chunk boundary is reassembled before decoding. Handles LF, CRLF and bare CR line ends,22/// multi-line `data`, comments (`:` keep-alives), a leading byte-order mark and fields without a value.23public struct SSEParser: Sendable {24 /// A single line larger than this is a protocol violation, not an event.25 public static let maxLineBytes = 8_000_0002627 private var line: [UInt8] = []28 private var lastWasCR = false29 private var atStreamStart = true30 private var event: String?31 private var data: [String] = []32 private var hasData = false33 /// Comment lines seen so far (keep-alives).34 public private(set) var commentCount = 03536 public init() { line.reserveCapacity(1_024) }3738 /// Feeds a chunk of the response body and returns the events it completes.39 public mutating func feed(_ chunk: Data) throws -> [SSEEvent] {40 var out: [SSEEvent] = []41 for byte in chunk {42 if lastWasCR {43 lastWasCR = false44 if byte == 0x0A { continue } // the LF of a CRLF whose CR already ended the line45 }46 switch byte {47 case 0x0A:48 if let done = endLine() { out.append(done) }49 case 0x0D:50 lastWasCR = true51 if let done = endLine() { out.append(done) }52 default:53 line.append(byte)54 if line.count > Self.maxLineBytes { throw ProviderError.malformedResponse("a single stream line exceeded 8 MB.") }55 }56 }57 return out58 }5960 public mutating func feed(_ text: String) throws -> [SSEEvent] { try feed(Data(text.utf8)) }6162 /// Call when the body ends. A final event that was not followed by a blank line is still delivered: several63 /// servers close the connection right after their last `data:` line.64 public mutating func finish() -> SSEEvent? {65 var last: SSEEvent?66 if !line.isEmpty { last = endLine() }67 return last ?? dispatch()68 }6970 private mutating func endLine() -> SSEEvent? {71 defer { line.removeAll(keepingCapacity: true) }72 var bytes = line[...]73 if atStreamStart {74 atStreamStart = false75 if bytes.starts(with: [0xEF, 0xBB, 0xBF]) { bytes = bytes.dropFirst(3) }76 }77 if bytes.isEmpty { return dispatch() }78 if bytes.first == 0x3A { commentCount += 1; return nil } // ":" comment79 let field: String, value: String80 if let colon = bytes.firstIndex(of: 0x3A) {81 field = String(decoding: bytes[..<colon], as: UTF8.self)82 var rest = bytes[bytes.index(after: colon)...]83 if rest.first == 0x20 { rest = rest.dropFirst() }84 value = String(decoding: rest, as: UTF8.self)85 } else {86 field = String(decoding: bytes, as: UTF8.self)87 value = ""88 }89 switch field {90 case "event": event = value91 case "data": data.append(value); hasData = true92 default: break // "id", "retry" and unknown fields are not used93 }94 return nil95 }9697 private mutating func dispatch() -> SSEEvent? {98 defer { event = nil; data.removeAll(keepingCapacity: true); hasData = false }99 return hasData ? SSEEvent(event: event, data: data.joined(separator: "\n")) : nil100 }101}102