react-native-nitro-sse 3.0.0 → 3.2.0-beta.1

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 (49) hide show
  1. package/NitroSse.podspec +0 -1
  2. package/README.md +16 -5
  3. package/android/build.gradle +0 -1
  4. package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +33 -10
  5. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +366 -78
  6. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +417 -94
  7. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +20 -0
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +9 -0
  9. package/ios/NitroSse.swift +302 -49
  10. package/ios/SseConnectionHandler.swift +647 -97
  11. package/ios/SseEventBuffer.swift +19 -1
  12. package/ios/SseReconnectStrategy.swift +26 -7
  13. package/lib/module/FetchSseDriver.js +845 -0
  14. package/lib/module/MockSseEngine.js +72 -3
  15. package/lib/module/NitroSseClient.js +43 -18
  16. package/lib/module/SseDriver.js +31 -15
  17. package/lib/module/SseEventParser.js +238 -0
  18. package/lib/module/createNitroSse.js +12 -5
  19. package/lib/module/createNitroSse.native.js +24 -0
  20. package/lib/module/createNitroSse.web.js +13 -0
  21. package/lib/module/index.js +2 -1
  22. package/lib/module/index.native.js +8 -0
  23. package/lib/module/index.web.js +9 -0
  24. package/lib/module/useNitroSse.js +1 -1
  25. package/lib/typescript/src/FetchSseDriver.d.ts +92 -0
  26. package/lib/typescript/src/MockSseEngine.d.ts +16 -0
  27. package/lib/typescript/src/NitroSseClient.d.ts +4 -1
  28. package/lib/typescript/src/SseDriver.d.ts +8 -4
  29. package/lib/typescript/src/SseEventParser.d.ts +42 -0
  30. package/lib/typescript/src/SseInterface.d.ts +46 -3
  31. package/lib/typescript/src/createNitroSse.d.ts +2 -2
  32. package/lib/typescript/src/createNitroSse.native.d.ts +9 -0
  33. package/lib/typescript/src/createNitroSse.web.d.ts +8 -0
  34. package/lib/typescript/src/index.d.ts +1 -0
  35. package/lib/typescript/src/index.native.d.ts +6 -0
  36. package/lib/typescript/src/index.web.d.ts +7 -0
  37. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +4 -0
  38. package/nitrogen/generated/android/c++/JSseDisconnectReason.hpp +67 -0
  39. package/nitrogen/generated/android/c++/JSseStats.hpp +87 -1
  40. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseDisconnectReason.kt +26 -0
  41. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +108 -3
  42. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +18 -0
  43. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +3 -0
  44. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +3 -0
  45. package/nitrogen/generated/ios/swift/SseDisconnectReason.swift +52 -0
  46. package/nitrogen/generated/ios/swift/SseStats.swift +217 -2
  47. package/nitrogen/generated/shared/c++/SseDisconnectReason.hpp +88 -0
  48. package/nitrogen/generated/shared/c++/SseStats.hpp +88 -2
  49. package/package.json +13 -2
package/NitroSse.podspec CHANGED
@@ -28,7 +28,6 @@ Pod::Spec.new do |s|
28
28
 
29
29
  s.dependency 'React-jsi'
30
30
  s.dependency 'React-callinvoker'
31
- s.dependency 'LDSwiftEventSource'
32
31
 
33
32
  load 'nitrogen/generated/ios/NitroSse+autolinking.rb'
34
33
  add_nitrogen_files(s)
package/README.md CHANGED
@@ -1,12 +1,13 @@
1
1
  # react-native-nitro-sse
2
2
 
3
- Server-Sent Events (SSE) client for React Native built on Nitro Modules (JSI).
3
+ Server-Sent Events (SSE) client for React Native built on Nitro Modules (JSI) with seamless Web support.
4
4
 
5
5
  ---
6
6
 
7
7
  ## Features
8
8
 
9
- - **JSI Execution**: Direct synchronous JS-to-native calls via Nitro Modules.
9
+ - **JSI Execution (Native)**: Direct synchronous JS-to-native calls via Nitro Modules on iOS and Android.
10
+ - **Universal Web Support**: Pure JS driver powered by the Fetch & ReadableStream API for React Native Web and Web browsers.
10
11
  - **Reconnection**: Exponential backoff with jitter and HTTP 429 (`Retry-After`) handling.
11
12
  - **Event Batching**: Configurable batch interval and buffer size limits.
12
13
  - **Lifecycle & Network**: Automatic pause and resume on app state or network transitions.
@@ -15,6 +16,16 @@ Server-Sent Events (SSE) client for React Native built on Nitro Modules (JSI).
15
16
 
16
17
  ---
17
18
 
19
+ ## Platform Support
20
+
21
+ | Platform | Implementation |
22
+ | :------- | :------------- |
23
+ | **iOS** | Nitro Modules (JSI) + URLSession |
24
+ | **Android** | Nitro Modules (JSI) + OkHttp |
25
+ | **Web** | Pure JS `FetchSseDriver` (Fetch Streams) |
26
+
27
+ ---
28
+
18
29
  ## Installation
19
30
 
20
31
  ```sh
@@ -23,7 +34,7 @@ npm install react-native-nitro-sse react-native-nitro-modules
23
34
  yarn add react-native-nitro-sse react-native-nitro-modules
24
35
  ```
25
36
 
26
- > **Note**: `react-native-nitro-modules` is a peer dependency.
37
+ > **Note**: `react-native-nitro-modules` is a peer dependency required for iOS and Android native compilation. On Web, the library uses the pure JS Fetch driver and does not invoke native binaries.
27
38
 
28
39
  <details>
29
40
  <summary><b>Compatibility Matrix</b></summary>
@@ -209,7 +220,7 @@ sse.start();
209
220
  - **`flush()`**: Flushes pending events in the buffer immediately.
210
221
  - **`isConnected()`**: Returns boolean indicating if connection is active (`connecting`, `open`, `reconnecting`).
211
222
  - **`getState()`**: Returns current `SseState`.
212
- - **`getStats()`**: Returns connection metrics (`totalBytesReceived`, `reconnectCount`, `lastErrorTime`, `lastErrorCode`).
223
+ - **`getStats()`**: Returns comprehensive connection metrics across transport (`rawBytesReceived`, `decompressedBytesReceived`, `totalBytesReceived`, `chunksReceived`, `lastStatusCode`), parser (`totalEventsReceived`, `commentsReceived`, `linesParsed`, `parseErrors`, `serverRetryDelayMs`), latency (`connectedAt`, `timeToFirstByteMs`, `lastEventTime`, `lastHeartbeatTime`, `maxEventGapMs`), buffer (`eventsBuffered`, `peakBufferedEvents`, `bufferFlushCount`, `bufferOverflowCount`), and diagnostics/lifecycle (`connectionAttempts`, `reconnectCount`, `lastReconnectDelayMs`, `disconnectReason`, `lastErrorTime`, `lastErrorCode`).
213
224
  - **`updateHeaders(headers)`**: Merges new headers into current configuration without closing the connection.
214
225
  - **`setLastProcessedId(id)`**: Sets the event ID to send in `Last-Event-ID` on subsequent reconnections.
215
226
  - **`addEventListener(type, listener)`**: Subscribes to an event type (`'message'`, `'open'`, `'close'`, `'error'`, `'heartbeat'`, `'state'`, or custom event name).
@@ -238,7 +249,7 @@ try {
238
249
 
239
250
  | Error Class | Error Code | Description |
240
251
  | :---------------------------- | :------------------------------------- | :-------------------------------------------------------------------- |
241
- | `NitroSseModuleNotFoundError` | `NATIVE_MODULE_NOT_FOUND` | Native Nitro module binary is missing. |
252
+ | `NitroSseModuleNotFoundError` | `NATIVE_MODULE_NOT_FOUND` | Native Nitro module binary is missing (iOS/Android only). |
242
253
  | `NitroSseValidationError` | `INVALID_CONFIG` \| `INVALID_ARGUMENT` | Invalid argument or configuration parameter. |
243
254
  | `NitroSseStateError` | `INVALID_STATE` | Method invoked in an invalid state (e.g. `start()` before `setup()`). |
244
255
  | `NitroSseDisposedError` | `CLIENT_DISPOSED` | Method invoked on an already disposed client instance. |
@@ -126,7 +126,6 @@ dependencies {
126
126
  implementation "com.facebook.react:react-android"
127
127
  implementation project(":react-native-nitro-modules")
128
128
  implementation "com.squareup.okhttp3:okhttp:4.12.0"
129
- implementation "com.squareup.okhttp3:okhttp-sse:4.12.0"
130
129
  implementation "androidx.lifecycle:lifecycle-process:2.8.7"
131
130
 
132
131
  testImplementation "junit:junit:4.13.2"
@@ -25,7 +25,7 @@ object JsonUtils {
25
25
  if (depth > MAX_DEPTH) {
26
26
  throw IllegalArgumentException("JSON nesting depth limit ($MAX_DEPTH) exceeded")
27
27
  }
28
- val map = mutableMapOf<String, Any?>()
28
+ val map = HashMap<String, Any?>(jsonObject.length())
29
29
  val keys = jsonObject.keys()
30
30
  while (keys.hasNext()) {
31
31
  val key = keys.next()
@@ -38,27 +38,50 @@ object JsonUtils {
38
38
  if (depth > MAX_DEPTH) {
39
39
  throw IllegalArgumentException("JSON nesting depth limit ($MAX_DEPTH) exceeded")
40
40
  }
41
- val list = mutableListOf<Any?>()
41
+ val list = ArrayList<Any?>(jsonArray.length())
42
42
  for (i in 0 until jsonArray.length()) {
43
43
  list.add(convertJsonValue(jsonArray.get(i), depth))
44
44
  }
45
45
  return list
46
46
  }
47
47
 
48
+ /**
49
+ * Parses a raw JSON string into a [Map]. Returns null on non-object roots.
50
+ * Throws [org.json.JSONException] on malformed JSON objects.
51
+ */
52
+ fun parseJsonToMap(data: String): Map<String, Any?>? {
53
+ val len = data.length
54
+ var firstChar = ' '
55
+ var idx = 0
56
+ var needsSubstring = false
57
+ while (idx < len) {
58
+ val c = data[idx]
59
+ if (c > ' ') {
60
+ if (c.isWhitespace()) {
61
+ needsSubstring = true
62
+ } else {
63
+ firstChar = c
64
+ break
65
+ }
66
+ }
67
+ idx++
68
+ }
69
+ if (firstChar != '{') {
70
+ return null
71
+ }
72
+ val jsonStr = if (needsSubstring) data.substring(idx) else data
73
+ val jsonObject = JSONObject(jsonStr)
74
+ return jsonObjectToMap(jsonObject)
75
+ }
76
+
48
77
  /**
49
78
  * Parses a raw JSON string into [AnyMap]. Returns null on malformed JSON or non-object roots
50
79
  * to prevent invalid SSE payloads from interrupting stream processing.
51
80
  */
52
81
  fun parseJsonToAnyMap(data: String): AnyMap? {
53
82
  return try {
54
- val trimmed = data.trim()
55
- if (trimmed.startsWith("{")) {
56
- val jsonObject = JSONObject(trimmed)
57
- val map = jsonObjectToMap(jsonObject)
58
- AnyMap.fromMap(map, true)
59
- } else {
60
- null
61
- }
83
+ val map = parseJsonToMap(data) ?: return null
84
+ AnyMap.fromMap(map, true)
62
85
  } catch (t: Throwable) {
63
86
  try {
64
87
  Log.w("JsonUtils", "Failed to parse JSON: ${t.message}")