react-native-nitro-sse 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +50 -27
  2. package/android/build.gradle +4 -2
  3. package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +8 -32
  4. package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +124 -6
  5. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +439 -510
  6. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +137 -316
  7. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +18 -8
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventReader.kt +231 -0
  9. package/android/src/main/java/com/margelo/nitro/nitrosse/SseFailureClassifier.kt +245 -0
  10. package/android/src/main/java/com/margelo/nitro/nitrosse/SseMetrics.kt +237 -0
  11. package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +13 -6
  12. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +48 -22
  13. package/ios/NitroSse.swift +402 -484
  14. package/ios/SseConfig+CopyWith.swift +0 -2
  15. package/ios/SseConnectionHandler.swift +238 -446
  16. package/ios/SseDispatchQueueDispatcher.swift +7 -7
  17. package/ios/SseDispatcher.swift +5 -4
  18. package/ios/SseEventBuffer.swift +24 -23
  19. package/ios/SseEventParser.swift +360 -0
  20. package/ios/SseFailureClassifier.swift +249 -0
  21. package/ios/SseLifecycleManager.swift +19 -14
  22. package/ios/SseMetrics.swift +188 -0
  23. package/ios/SseNetworkMonitor.swift +18 -14
  24. package/ios/SseReconnectStrategy.swift +28 -30
  25. package/lib/module/FetchSseDriver.js +385 -169
  26. package/lib/module/MockSseEngine.js +15 -17
  27. package/lib/module/NitroSseClient.js +70 -56
  28. package/lib/module/SseConsoleLogger.js +64 -0
  29. package/lib/module/SseEventParser.js +173 -115
  30. package/lib/module/createNitroSse.js +7 -14
  31. package/lib/module/createNitroSse.native.js +2 -1
  32. package/lib/module/useNitroSse.js +103 -90
  33. package/lib/typescript/src/FetchSseDriver.d.ts +11 -4
  34. package/lib/typescript/src/MockSseEngine.d.ts +2 -2
  35. package/lib/typescript/src/NitroSse.nitro.d.ts +9 -1
  36. package/lib/typescript/src/NitroSseClient.d.ts +4 -1
  37. package/lib/typescript/src/SseConsoleLogger.d.ts +28 -0
  38. package/lib/typescript/src/SseEventParser.d.ts +18 -2
  39. package/lib/typescript/src/SseInterface.d.ts +21 -4
  40. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.hpp +1 -1
  41. package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +1 -1
  42. package/nitrogen/generated/android/c++/JHttpMethod.hpp +1 -1
  43. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +1 -1
  44. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +1 -1
  45. package/nitrogen/generated/android/c++/JSseConfig.hpp +1 -1
  46. package/nitrogen/generated/android/c++/JSseDisconnectReason.hpp +1 -1
  47. package/nitrogen/generated/android/c++/JSseEvent.hpp +1 -1
  48. package/nitrogen/generated/android/c++/JSseEventType.hpp +1 -1
  49. package/nitrogen/generated/android/c++/JSseMockConfig.hpp +1 -1
  50. package/nitrogen/generated/android/c++/JSseMockEvent.hpp +1 -1
  51. package/nitrogen/generated/android/c++/JSseMockMode.hpp +1 -1
  52. package/nitrogen/generated/android/c++/JSseState.hpp +1 -1
  53. package/nitrogen/generated/android/c++/JSseStats.hpp +1 -1
  54. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.kt +1 -1
  55. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_void_std__vector_SseEvent_.kt +1 -1
  56. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HttpMethod.kt +1 -1
  57. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +1 -1
  58. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +1 -1
  59. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseDisconnectReason.kt +1 -1
  60. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +1 -1
  61. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEventType.kt +1 -1
  62. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockConfig.kt +1 -1
  63. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockEvent.kt +1 -1
  64. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockMode.kt +1 -1
  65. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseState.kt +1 -1
  66. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +1 -1
  67. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/nitrosseOnLoad.kt +1 -1
  68. package/nitrogen/generated/android/nitrosse+autolinking.cmake +1 -1
  69. package/nitrogen/generated/android/nitrosse+autolinking.gradle +1 -1
  70. package/nitrogen/generated/android/nitrosseOnLoad.cpp +1 -1
  71. package/nitrogen/generated/android/nitrosseOnLoad.hpp +1 -1
  72. package/nitrogen/generated/ios/NitroSse+autolinking.rb +1 -1
  73. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +1 -1
  74. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +1 -1
  75. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +1 -1
  76. package/nitrogen/generated/ios/NitroSseAutolinking.mm +1 -1
  77. package/nitrogen/generated/ios/NitroSseAutolinking.swift +1 -5
  78. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.cpp +1 -1
  79. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +1 -1
  80. package/nitrogen/generated/ios/swift/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.swift +1 -1
  81. package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +1 -1
  82. package/nitrogen/generated/ios/swift/Func_void_std__shared_ptr_Promise_std__unordered_map_std__string__std__string___.swift +1 -1
  83. package/nitrogen/generated/ios/swift/Func_void_std__unordered_map_std__string__std__string_.swift +1 -1
  84. package/nitrogen/generated/ios/swift/Func_void_std__vector_SseEvent_.swift +1 -1
  85. package/nitrogen/generated/ios/swift/HttpMethod.swift +1 -1
  86. package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +1 -1
  87. package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +3 -3
  88. package/nitrogen/generated/ios/swift/SseConfig.swift +1 -1
  89. package/nitrogen/generated/ios/swift/SseDisconnectReason.swift +1 -1
  90. package/nitrogen/generated/ios/swift/SseEvent.swift +1 -1
  91. package/nitrogen/generated/ios/swift/SseEventType.swift +1 -1
  92. package/nitrogen/generated/ios/swift/SseMockConfig.swift +1 -1
  93. package/nitrogen/generated/ios/swift/SseMockEvent.swift +1 -1
  94. package/nitrogen/generated/ios/swift/SseMockMode.swift +1 -1
  95. package/nitrogen/generated/ios/swift/SseState.swift +1 -1
  96. package/nitrogen/generated/ios/swift/SseStats.swift +1 -1
  97. package/nitrogen/generated/shared/c++/HttpMethod.hpp +1 -1
  98. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.cpp +1 -1
  99. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +1 -1
  100. package/nitrogen/generated/shared/c++/SseConfig.hpp +1 -1
  101. package/nitrogen/generated/shared/c++/SseDisconnectReason.hpp +1 -1
  102. package/nitrogen/generated/shared/c++/SseEvent.hpp +1 -1
  103. package/nitrogen/generated/shared/c++/SseEventType.hpp +1 -1
  104. package/nitrogen/generated/shared/c++/SseMockConfig.hpp +1 -1
  105. package/nitrogen/generated/shared/c++/SseMockEvent.hpp +1 -1
  106. package/nitrogen/generated/shared/c++/SseMockMode.hpp +1 -1
  107. package/nitrogen/generated/shared/c++/SseState.hpp +1 -1
  108. package/nitrogen/generated/shared/c++/SseStats.hpp +1 -1
  109. package/package.json +12 -4
@@ -5,16 +5,16 @@ class SseDispatchQueueDispatcher: SseDispatcher {
5
5
  let queue: DispatchQueue
6
6
  var underlyingQueue: DispatchQueue? { queue }
7
7
  private let queueKey: DispatchSpecificKey<Void>
8
-
8
+
9
9
  init(queue: DispatchQueue, queueKey: DispatchSpecificKey<Void>) {
10
10
  self.queue = queue
11
11
  self.queueKey = queueKey
12
12
  }
13
-
13
+
14
14
  func async(_ block: @escaping () -> Void) {
15
15
  queue.async(execute: block)
16
16
  }
17
-
17
+
18
18
  private class WorkItemCancellable: SseCancellable {
19
19
  private let item: DispatchWorkItem
20
20
  init(item: DispatchWorkItem) {
@@ -24,14 +24,14 @@ class SseDispatchQueueDispatcher: SseDispatcher {
24
24
  item.cancel()
25
25
  }
26
26
  }
27
-
27
+
28
28
  @discardableResult
29
29
  func asyncAfter(delay: TimeInterval, _ block: @escaping () -> Void) -> SseCancellable? {
30
30
  let workItem = DispatchWorkItem(block: block)
31
31
  queue.asyncAfter(deadline: .now() + delay, execute: workItem)
32
32
  return WorkItemCancellable(item: workItem)
33
33
  }
34
-
34
+
35
35
  /// Executes block inline if already running on queue to avoid re-entrant deadlocks.
36
36
  func sync<T>(_ block: () throws -> T) rethrows -> T {
37
37
  if isCurrentDispatcher() {
@@ -40,11 +40,11 @@ class SseDispatchQueueDispatcher: SseDispatcher {
40
40
  return try queue.sync(execute: block)
41
41
  }
42
42
  }
43
-
43
+
44
44
  func isCurrentDispatcher() -> Bool {
45
45
  return DispatchQueue.getSpecific(key: queueKey) != nil
46
46
  }
47
-
47
+
48
48
  func assertOnQueue() {
49
49
  dispatchPrecondition(condition: .onQueue(queue))
50
50
  }
@@ -12,13 +12,14 @@ protocol SseDispatcher: AnyObject {
12
12
  @discardableResult
13
13
  func asyncAfter(delay: TimeInterval, _ block: @escaping () -> Void) -> SseCancellable?
14
14
  func sync<T>(_ block: () throws -> T) rethrows -> T
15
-
16
- /// Checks whether the caller is running on the dispatcher's execution context to avoid re-entrant deadlocks on `sync`.
15
+
16
+ /// Checks whether the caller is running on the dispatcher's execution context
17
+ /// to avoid re-entrant deadlocks on `sync`.
17
18
  func isCurrentDispatcher() -> Bool
18
-
19
+
19
20
  /// Asserts execution context during debug builds to verify thread safety invariants.
20
21
  func assertOnQueue()
21
-
22
+
22
23
  /// Underlying `DispatchQueue` required by system frameworks (e.g. `NWPathMonitor`).
23
24
  var underlyingQueue: DispatchQueue? { get }
24
25
  }
@@ -7,20 +7,20 @@ class SseEventBuffer {
7
7
  private var eventBuffer: [SseEvent] = []
8
8
  private var pendingTimer: SseCancellable?
9
9
  private var onFlush: ((_ events: [SseEvent]) -> Void)?
10
-
10
+
11
11
  private var batchingIntervalMs: Double = 0
12
12
  private var maxBufferSize: Int = 1000
13
13
  private weak var dispatcher: SseDispatcher?
14
-
14
+
15
15
  // MARK: - Buffer Metrics
16
16
  private(set) var peakBufferedEvents: Int = 0
17
17
  private(set) var bufferFlushCount: Int = 0
18
18
  private(set) var bufferOverflowCount: Int = 0
19
-
19
+
20
20
  var eventsBuffered: Int {
21
21
  return eventBuffer.count
22
22
  }
23
-
23
+
24
24
  /// Initializes buffer batching thresholds and dispatch target.
25
25
  func configure(
26
26
  batchingIntervalMs: Double,
@@ -29,30 +29,31 @@ class SseEventBuffer {
29
29
  onFlush: @escaping (_ events: [SseEvent]) -> Void
30
30
  ) {
31
31
  self.batchingIntervalMs = batchingIntervalMs
32
- if maxBufferSize.isNaN || !maxBufferSize.isFinite || maxBufferSize <= 0 || maxBufferSize > Double(Int.max) {
32
+ if !maxBufferSize.isFinite || maxBufferSize <= 0 {
33
33
  self.maxBufferSize = 1000
34
34
  } else {
35
- self.maxBufferSize = Int(maxBufferSize)
35
+ self.maxBufferSize = Int(min(maxBufferSize, Double(Self.hardMaxBufferSize)))
36
36
  }
37
37
  self.dispatcher = dispatcher
38
38
  self.onFlush = onFlush
39
39
  }
40
-
41
- /// Appends an event to the queue. Triggers immediate flush if buffer capacity is reached or batching is disabled (interval <= 0).
40
+
41
+ private static let hardMaxBufferSize: Int = 10000
42
+
43
+ /// Appends an event to the queue. Triggers immediate flush if buffer capacity is reached
44
+ /// or batching is disabled (interval <= 0).
42
45
  func push(_ event: SseEvent) {
43
46
  dispatcher?.assertOnQueue()
44
47
  eventBuffer.append(event)
45
-
48
+
46
49
  if eventBuffer.count > peakBufferedEvents {
47
50
  peakBufferedEvents = eventBuffer.count
48
51
  }
49
-
50
- if eventBuffer.count >= maxBufferSize && batchingIntervalMs > 0 {
51
- bufferOverflowCount += 1
52
- cancelPendingTimer()
52
+
53
+ if batchingIntervalMs <= 0 {
53
54
  flush()
54
- } else if eventBuffer.count >= maxBufferSize || batchingIntervalMs <= 0 {
55
- cancelPendingTimer()
55
+ } else if eventBuffer.count >= maxBufferSize {
56
+ bufferOverflowCount += 1
56
57
  flush()
57
58
  } else if pendingTimer == nil, let dispatcher = dispatcher {
58
59
  pendingTimer = dispatcher.asyncAfter(delay: batchingIntervalMs / 1000.0) { [weak self] in
@@ -63,32 +64,32 @@ class SseEventBuffer {
63
64
  }
64
65
  }
65
66
  }
66
-
67
+
67
68
  /// Flushes all pending buffered events to JavaScript.
68
69
  func flush() {
69
70
  dispatcher?.assertOnQueue()
70
71
  cancelPendingTimer()
71
72
  guard !eventBuffer.isEmpty else { return }
72
-
73
+
73
74
  bufferFlushCount += 1
74
75
  let batch = eventBuffer
75
76
  eventBuffer.removeAll()
76
-
77
+
77
78
  onFlush?(batch)
78
79
  }
79
-
80
+
80
81
  private func cancelPendingTimer() {
81
82
  dispatcher?.assertOnQueue()
82
83
  pendingTimer?.cancel()
83
84
  pendingTimer = nil
84
85
  }
85
-
86
+
86
87
  /// Nullifies the flush callback to prevent invoking a destroyed JS runtime during teardown.
87
88
  func clearCallback() {
88
89
  dispatcher?.assertOnQueue()
89
90
  self.onFlush = nil
90
91
  }
91
-
92
+
92
93
  /// Clears buffered events without invoking the flush callback.
93
94
  /// Used during teardown to avoid executing JS callbacks after the bridge runtime is destroyed.
94
95
  func clear() {
@@ -96,7 +97,7 @@ class SseEventBuffer {
96
97
  cancelPendingTimer()
97
98
  eventBuffer.removeAll()
98
99
  }
99
-
100
+
100
101
  /// Converts a raw JSON payload string into a Nitro `AnyMap`.
101
102
  /// Returns `nil` if payload is not a valid JSON dictionary required by `AnyMap`.
102
103
  static func parseJsonToAnyMap(_ data: String) -> AnyMap? {
@@ -106,7 +107,7 @@ class SseEventBuffer {
106
107
  return AnyMap.fromDictionaryIgnoreIncompatible(dictionary)
107
108
  }
108
109
  } catch {
109
- print("[NitroSse] Failed to parse JSON: \(error.localizedDescription)")
110
+ // Silently return nil without blocking dispatcher on synchronous console logging
110
111
  }
111
112
  return nil
112
113
  }
@@ -0,0 +1,360 @@
1
+ import Foundation
2
+
3
+ /// Maximum bytes allowed for a single SSE line to prevent Out-Of-Memory errors.
4
+ private let maxSseLineLength: Int = 16 * 1024 * 1024
5
+
6
+ /// Maximum bytes allowed for accumulated event data to prevent Out-Of-Memory errors.
7
+ private let maxSseEventDataSize: Int = 16 * 1024 * 1024
8
+
9
+ protocol SseEventParserDelegate: AnyObject {
10
+ func parserDidReceiveEvent(id: String?, type: String?, data: String)
11
+ func parserDidReceiveComment(_ comment: String)
12
+ func parserDidReceiveRetry(retryMs: Int64)
13
+ func parserDidUpdateLastEventId(_ id: String?)
14
+ func parserDidFail(error: Error)
15
+ func parserDidParseLines(_ count: Int)
16
+ }
17
+
18
+ extension SseEventParserDelegate {
19
+ func parserDidUpdateLastEventId(_ id: String?) {}
20
+ func parserDidFail(error: Error) {}
21
+ func parserDidParseLines(_ count: Int) {}
22
+ }
23
+
24
+ /// Sequential streaming line-by-line SSE parser complying strictly with WHATWG Server-Sent Events specification.
25
+ /// Handles CR, LF, and CRLF line breaks, multi-line data concatenation, comments, IDs, and retry directives.
26
+ internal class SseEventParser {
27
+ weak var delegate: SseEventParserDelegate?
28
+
29
+ private var buffer = Data()
30
+ private var dataBuffer: String = ""
31
+ private var hasData: Bool = false
32
+ private var eventType: String?
33
+ private var lastEventId: String?
34
+ private var lastEventIdBuffer: String?
35
+ private var idUpdatedInCurrentEvent: Bool = false
36
+ private var isAtStreamStart: Bool = true
37
+ /// Set once a resource limit violation (-2002 / -2003) is reported; all further input is ignored
38
+ /// until `reset()`, mirroring `_aborted` in the TypeScript parser and `SseParserLimitException` on Android.
39
+ private var isAborted: Bool = false
40
+
41
+ init(initialLastEventId: String? = nil) {
42
+ self.lastEventId = initialLastEventId
43
+ self.lastEventIdBuffer = initialLastEventId
44
+ }
45
+
46
+ func reset(initialLastEventId: String? = nil) {
47
+ buffer.removeAll()
48
+ dataBuffer = ""
49
+ hasData = false
50
+ eventType = nil
51
+ lastEventId = initialLastEventId
52
+ lastEventIdBuffer = initialLastEventId
53
+ idUpdatedInCurrentEvent = false
54
+ isAtStreamStart = true
55
+ isAborted = false
56
+ }
57
+
58
+ /// Reports a fatal parser limit violation exactly once and stops all further parsing.
59
+ private func abort(code: Int, message: String) {
60
+ guard !isAborted else { return }
61
+ isAborted = true
62
+ buffer.removeAll()
63
+ dataBuffer = ""
64
+ hasData = false
65
+ eventType = nil
66
+ lastEventIdBuffer = lastEventId
67
+ idUpdatedInCurrentEvent = false
68
+ let error = NSError(domain: "NitroSse", code: code, userInfo: [NSLocalizedDescriptionKey: message])
69
+ delegate?.parserDidFail(error: error)
70
+ }
71
+
72
+ /// Signals end of stream (EOF).
73
+ /// Per WHATWG SSE spec: "Once the end of the file is reached, any pending data must be discarded.
74
+ /// (If the file ends in the middle of an event, before the final empty line,
75
+ /// the incomplete event is not dispatched.)"
76
+ func endOfStream() {
77
+ if !isAborted && buffer.last == 0x0D {
78
+ buffer.removeLast()
79
+ // WHATWG SSE Section 9.2.2: invalid UTF-8 bytes must be replaced with U+FFFD, not dropped.
80
+ // swiftlint:disable:next optional_data_string_conversion
81
+ let line = String(decoding: buffer, as: UTF8.self)
82
+ buffer.removeAll()
83
+ processLine(line)
84
+ delegate?.parserDidParseLines(1)
85
+ } else {
86
+ buffer.removeAll()
87
+ }
88
+ dataBuffer = ""
89
+ hasData = false
90
+ eventType = nil
91
+ lastEventIdBuffer = lastEventId
92
+ idUpdatedInCurrentEvent = false
93
+ }
94
+
95
+ func feed(data: Data) {
96
+ guard !data.isEmpty, !isAborted else { return }
97
+ var parsedLinesInChunk = 0
98
+ defer {
99
+ if parsedLinesInChunk > 0 {
100
+ delegate?.parserDidParseLines(parsedLinesInChunk)
101
+ }
102
+ }
103
+
104
+ guard let currentData = stripLeadingBomIfAtStart(data) else { return }
105
+ var readIndex = currentData.startIndex
106
+
107
+ guard processBufferedPrefix(
108
+ in: currentData,
109
+ readIndex: &readIndex,
110
+ parsedLines: &parsedLinesInChunk
111
+ ) else {
112
+ return
113
+ }
114
+
115
+ scanCompleteLines(in: currentData, readIndex: &readIndex, parsedLines: &parsedLinesInChunk)
116
+ if isAborted { return }
117
+
118
+ appendTrailingFragment(of: currentData, from: readIndex)
119
+ }
120
+ }
121
+
122
+ private extension SseEventParser {
123
+ struct LineRange {
124
+ let content: Range<Int>
125
+ let nextIndex: Int
126
+ }
127
+
128
+ func stripLeadingBomIfAtStart(_ data: Data) -> Data? {
129
+ guard isAtStreamStart else { return data }
130
+ if buffer.isEmpty && data.count >= 3 {
131
+ let sIdx = data.startIndex
132
+ let trimmed = (data[sIdx] == 0xEF && data[sIdx + 1] == 0xBB && data[sIdx + 2] == 0xBF)
133
+ ? data[(sIdx + 3)..<data.endIndex]
134
+ : data
135
+ isAtStreamStart = false
136
+ return trimmed
137
+ }
138
+ let bom: [UInt8] = [0xEF, 0xBB, 0xBF]
139
+ buffer.append(data)
140
+ if buffer.count >= 3 {
141
+ if buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF {
142
+ buffer.removeSubrange(0..<3)
143
+ }
144
+ isAtStreamStart = false
145
+ let combined = buffer
146
+ buffer.removeAll()
147
+ return combined
148
+ }
149
+ for index in 0..<buffer.count where buffer[index] != bom[index] {
150
+ isAtStreamStart = false
151
+ let combined = buffer
152
+ buffer.removeAll()
153
+ return combined
154
+ }
155
+ return nil
156
+ }
157
+
158
+ func processBufferedPrefix(
159
+ in currentData: Data,
160
+ readIndex: inout Data.Index,
161
+ parsedLines: inout Int
162
+ ) -> Bool {
163
+ guard !buffer.isEmpty else { return true }
164
+ if buffer.last == 0x0D {
165
+ buffer.removeLast()
166
+ // WHATWG SSE Section 9.2.2: invalid UTF-8 bytes must be replaced with U+FFFD, not dropped.
167
+ // swiftlint:disable:next optional_data_string_conversion
168
+ let line = String(decoding: buffer, as: UTF8.self)
169
+ buffer.removeAll()
170
+ processLine(line)
171
+ parsedLines += 1
172
+ if currentData.first == 0x0A {
173
+ readIndex = currentData.startIndex + 1
174
+ }
175
+ return true
176
+ }
177
+ if let firstLine = findNextLine(in: currentData, from: readIndex) {
178
+ if buffer.count + firstLine.content.count > maxSseLineLength {
179
+ abort(code: -2002, message: "SSE line exceeded maximum limit of \(maxSseLineLength) bytes")
180
+ return false
181
+ }
182
+ buffer.append(currentData[firstLine.content])
183
+ // WHATWG SSE Section 9.2.2: invalid UTF-8 bytes must be replaced with U+FFFD, not dropped.
184
+ // swiftlint:disable:next optional_data_string_conversion
185
+ let line = String(decoding: buffer, as: UTF8.self)
186
+ buffer.removeAll()
187
+ processLine(line)
188
+ parsedLines += 1
189
+ readIndex = firstLine.nextIndex
190
+ return true
191
+ }
192
+ // currentData has no line ending: append chunk to buffer if within limit
193
+ if buffer.count + currentData.count > maxSseLineLength {
194
+ abort(code: -2002, message: "SSE line exceeded maximum limit of \(maxSseLineLength) bytes")
195
+ return false
196
+ }
197
+ buffer.append(currentData)
198
+ return false
199
+ }
200
+
201
+ func scanCompleteLines(
202
+ in currentData: Data,
203
+ readIndex: inout Data.Index,
204
+ parsedLines: inout Int
205
+ ) {
206
+ let endIndex = currentData.endIndex
207
+ while readIndex < endIndex && !isAborted {
208
+ guard let lineRange = findNextLine(in: currentData, from: readIndex) else {
209
+ break
210
+ }
211
+ if lineRange.content.count > maxSseLineLength {
212
+ abort(code: -2002, message: "SSE line exceeded maximum limit of \(maxSseLineLength) bytes")
213
+ return
214
+ }
215
+ let lineSlice = currentData[lineRange.content]
216
+ readIndex = lineRange.nextIndex
217
+ // WHATWG SSE Section 9.2.2: invalid UTF-8 bytes must be replaced with U+FFFD, not dropped.
218
+ // swiftlint:disable:next optional_data_string_conversion
219
+ let line = String(decoding: lineSlice, as: UTF8.self)
220
+ processLine(line)
221
+ parsedLines += 1
222
+ }
223
+ }
224
+
225
+ func appendTrailingFragment(of currentData: Data, from readIndex: Data.Index) {
226
+ let endIndex = currentData.endIndex
227
+ guard readIndex < endIndex else { return }
228
+ let trailingSlice = currentData[readIndex..<endIndex]
229
+ if buffer.count + trailingSlice.count > maxSseLineLength {
230
+ abort(code: -2002, message: "SSE line exceeded maximum limit of \(maxSseLineLength) bytes")
231
+ return
232
+ }
233
+ buffer.append(trailingSlice)
234
+ }
235
+
236
+ /// Finds next line in data from startIndex handling \r\n, \r, and \n using UnsafeRawBufferPointer.
237
+ /// If data ends with \r at the very end, returns nil to defer until next chunk so \r\n can be resolved.
238
+ func findNextLine(in data: Data, from startIndex: Int) -> LineRange? {
239
+ let endIndex = data.endIndex
240
+ let baseIndex = data.startIndex
241
+
242
+ return data.withUnsafeBytes { (raw: UnsafeRawBufferPointer) -> LineRange? in
243
+ var offset = startIndex - baseIndex
244
+ let endOffset = endIndex - baseIndex
245
+ while offset < endOffset {
246
+ let byte = raw[offset]
247
+ if byte == 0x0A { // \n (LF)
248
+ let foundIndex = baseIndex + offset
249
+ return LineRange(content: startIndex..<foundIndex, nextIndex: foundIndex + 1)
250
+ } else if byte == 0x0D { // \r (CR)
251
+ let foundIndex = baseIndex + offset
252
+ if offset + 1 < endOffset {
253
+ if raw[offset + 1] == 0x0A { // \r\n (CRLF)
254
+ return LineRange(content: startIndex..<foundIndex, nextIndex: foundIndex + 2)
255
+ } else { // Single \r
256
+ return LineRange(content: startIndex..<foundIndex, nextIndex: foundIndex + 1)
257
+ }
258
+ } else {
259
+ // Buffer ends with \r; wait for next chunk to verify if it is \r\n
260
+ return nil
261
+ }
262
+ }
263
+ offset += 1
264
+ }
265
+ return nil
266
+ }
267
+ }
268
+
269
+ func handleEmptyLine() {
270
+ if idUpdatedInCurrentEvent {
271
+ lastEventId = lastEventIdBuffer
272
+ idUpdatedInCurrentEvent = false
273
+ delegate?.parserDidUpdateLastEventId(lastEventId)
274
+ }
275
+ // Empty line dispatches the current event per WHATWG specification
276
+ if hasData {
277
+ let eventData = dataBuffer
278
+ let id = lastEventId
279
+ let type = eventType
280
+
281
+ dataBuffer = ""
282
+ hasData = false
283
+ eventType = nil
284
+
285
+ delegate?.parserDidReceiveEvent(id: id, type: type, data: eventData)
286
+ } else {
287
+ // WHATWG SSE: Dispatching an empty event still resets the event type buffer
288
+ eventType = nil
289
+ }
290
+ }
291
+
292
+ func appendDataField(_ value: String) {
293
+ let separatorSize = hasData ? 1 : 0
294
+ if dataBuffer.utf8.count + separatorSize + value.utf8.count > maxSseEventDataSize {
295
+ abort(
296
+ code: -2003,
297
+ message: "SSE event data exceeded maximum limit of \(maxSseEventDataSize) bytes"
298
+ )
299
+ return
300
+ }
301
+ if hasData {
302
+ dataBuffer.append("\n")
303
+ dataBuffer.append(value)
304
+ } else {
305
+ dataBuffer = value
306
+ hasData = true
307
+ }
308
+ }
309
+
310
+ func handleField(_ field: String, value: String) {
311
+ switch field {
312
+ case "data":
313
+ appendDataField(value)
314
+ case "id":
315
+ // WHATWG: If field value contains a U+0000 NULL character, the field must be ignored.
316
+ if !value.contains("\0") {
317
+ lastEventIdBuffer = value.isEmpty ? nil : value
318
+ idUpdatedInCurrentEvent = true
319
+ }
320
+ case "event":
321
+ eventType = value.isEmpty ? nil : value
322
+ case "retry":
323
+ let isDigitsOnly = !value.isEmpty && value.allSatisfy { $0.isASCII && $0.isNumber }
324
+ if isDigitsOnly, let retryVal = Int64(value) {
325
+ delegate?.parserDidReceiveRetry(retryMs: retryVal)
326
+ }
327
+ default:
328
+ // Unrecognized fields are ignored per WHATWG specification
329
+ break
330
+ }
331
+ }
332
+
333
+ func processLine(_ line: String) {
334
+ if line.isEmpty {
335
+ handleEmptyLine()
336
+ return
337
+ }
338
+
339
+ if line.hasPrefix(":") {
340
+ // WHATWG SSE: Lines starting with ':' are comments (often used for keepalive/heartbeat).
341
+ // Normalizes comment by removing only a single leading space per WHATWG SSE specification.
342
+ let rawComment = String(line.dropFirst())
343
+ let comment = rawComment.hasPrefix(" ") ? String(rawComment.dropFirst()) : rawComment
344
+ delegate?.parserDidReceiveComment(comment)
345
+ return
346
+ }
347
+
348
+ let field: String
349
+ let value: String
350
+ if let colon = line.firstIndex(of: ":") {
351
+ field = String(line[..<colon])
352
+ let rawValue = String(line[line.index(after: colon)...])
353
+ value = rawValue.hasPrefix(" ") ? String(rawValue.dropFirst()) : rawValue
354
+ } else {
355
+ field = line
356
+ value = ""
357
+ }
358
+ handleField(field, value: value)
359
+ }
360
+ }