react-native-nitro-sse 2.3.0 → 2.3.2

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.
package/README.md CHANGED
@@ -1,23 +1,24 @@
1
- # 🚀 react-native-nitro-sse
1
+ # react-native-nitro-sse
2
2
 
3
- High-performance Server-Sent Events (SSE) client for React Native, built on top of **Nitro Modules (JSI)**. Designed for mission-critical systems requiring extreme stability, high-throughput data streaming, and absolute battery optimization.
3
+ High-performance Server-Sent Events (SSE) client for React Native, built on top of **Nitro Modules (JSI)**. Designed for mission-critical apps requiring high-throughput streaming, battery optimization, and extreme stability.
4
4
 
5
- ## 🌟 Why NitroSSE?
5
+ ---
6
+
7
+ ## Why NitroSSE?
6
8
 
7
- Unlike traditional EventSource libraries that run on the JS thread or use the legacy Bridge, NitroSSE moves the entire control logic down to the deepest Native layer:
9
+ Traditional EventSource libraries run on the JS thread or use the legacy React Native Bridge. NitroSSE moves the entire control logic down to the native layer:
8
10
 
9
- - **🚀 Zero-Latency JSI**: Communication between JS and Native is instantaneous, bypassing the asynchronous bridge.
10
- - **🧠 Smart Reconnect**: Automatic reconnection strategy using **Exponential Backoff** and **Jitter** to prevent thundering herd problems.
11
- - **🛡️ DoS Protection**: Respects RFC `Retry-After` headers and enforces strict connection frequency limits.
12
- - **🌊 Backpressure Handling**: Advanced **Batching** mechanism aggregates messages and employs **Tail Drop** strategies to protect the UI thread from freezing during data surges.
13
- - **🔋 Mobile-First Architecture**: Automatically hibernates when the app enters the background and seamlessly reconnects upon foregrounding to conserve battery.
14
- - **💓 Heartbeat Detection**: Native-side detection of keep-alive signals (comments) to maintain a reliable connection watchdog.
15
- - **🔍 DevTools Integration**: Plug-and-play support for **React Native 0.83+ DevTools Network Tab**. Monitor connection status, request/response headers, and timing directly in the official desktop debugger.
16
- - **🛠️ Full Protocol Support**: Comprehensive support for GET/POST methods and dynamic header updates.
11
+ * **Zero-Latency JSI**: Instantaneous JS-Native communication bypassing the async bridge.
12
+ * **Advanced Backpressure**: Batches high-frequency events and employs tail-drop strategies to keep UI thread fluid under extreme load.
13
+ * **Intelligent Reconnect**: Automatic recovery using **Exponential Backoff** and **Jitter** to prevent server stampedes.
14
+ * **Lifecycles**: Auto-hibernates connections in background and resumes on foreground to preserve battery.
15
+ * **Heartbeat Watchdog**: Native detection of keep-alive/ping comments to auto-reconnect dead sockets.
16
+ * **RN DevTools Integration**: Plug-and-play network tracing in **React Native 0.83+ DevTools** (monitor streams directly).
17
+ * **Local Mocking Engine**: Simulates streams, connection drops, and delays entirely in JS without backend setup.
17
18
 
18
19
  ---
19
20
 
20
- ## 📦 Installation
21
+ ## Installation
21
22
 
22
23
  ```sh
23
24
  yarn add react-native-nitro-sse react-native-nitro-modules
@@ -25,15 +26,18 @@ yarn add react-native-nitro-sse react-native-nitro-modules
25
26
  npm install react-native-nitro-sse react-native-nitro-modules
26
27
  ```
27
28
 
28
- > **Note**: `react-native-nitro-modules` is required as the core foundation for JSI performance.
29
+ > [!NOTE]
30
+ > `react-native-nitro-modules` is a peer dependency and must be installed in the host project.
29
31
 
30
32
  ---
31
33
 
32
- ## 📊 Compatibility
34
+ ## Compatibility
33
35
 
34
36
  | react-native-nitro-sse | react-native-nitro-modules |
35
37
  | :--------------------- | :------------------------- |
36
- | **2.2.0 - latest** | **0.35.4** |
38
+ | **2.3.1 - latest** | **0.35.9** |
39
+ | **2.3.0** | **0.35.6** |
40
+ | **2.2.0 - 2.2.3** | **0.35.4** |
37
41
  | **2.0.0 - 2.1.1** | **0.35.2** |
38
42
  | **1.6.2** | **0.35.2** |
39
43
  | **1.4.0 - 1.6.1** | **0.35.0** |
@@ -42,103 +46,107 @@ npm install react-native-nitro-sse react-native-nitro-modules
42
46
  | **1.1.0** | **0.33.9** |
43
47
  | **1.0.0** | **0.33.8** |
44
48
 
45
-
46
49
  ---
47
50
 
48
- ## 🚀 Usage
49
-
50
- ### 1. Basic Initialization
51
-
52
- Initialize the module with your endpoint configuration and an event listener.
51
+ ## Usage
53
52
 
54
53
  ```tsx
55
54
  import { createNitroSse } from 'react-native-nitro-sse';
56
55
 
57
- const nitroSse = createNitroSse();
58
-
59
- nitroSse.setup(
60
- {
61
- url: 'https://api.yourserver.com/stream',
62
- method: 'get',
63
- headers: {
64
- 'Authorization': 'Bearer active-token',
65
- },
66
- // Batch messages every 100ms to optimize UI rendering
67
- batchingIntervalMs: 100,
68
- // Maximum of 1000 messages in the native queue before forced flush
69
- maxBufferSize: 1000,
70
- // Optional: Auto-refresh tokens or dynamic headers
71
- onBeforeRequest: async () => {
72
- const token = await fetchNewToken();
73
- return { 'Authorization': `Bearer ${token}` };
74
- }
75
- },
76
- (events) => {
77
- // events is an array of SseEvent objects
78
- events.forEach((event) => {
79
- console.log('Received:', event);
80
- });
81
- }
82
- );
56
+ const sse = createNitroSse();
83
57
 
84
- // Start the connection
85
- nitroSse.start();
86
- ```
58
+ sse.setup({
59
+ url: 'https://api.example.com/stream',
60
+ headers: { 'Authorization': 'Bearer TOKEN' }
61
+ });
87
62
 
88
- ### 2. Monitoring & Statistics
63
+ // Listen to events
64
+ sse.addEventListener('message', (e) => console.log('Received:', e.data));
65
+ sse.addEventListener('error', (e) => console.error('Error:', e.message));
89
66
 
90
- NitroSSE provides synchronous access to connection health and throughput data.
67
+ // Start streaming
68
+ sse.start();
91
69
 
92
- ```tsx
93
- const stats = nitroSse.getStats();
94
- console.log(`Downloaded: ${stats.totalBytesReceived / 1024} KB`);
95
- console.log(`Reconnections: ${stats.reconnectCount}`);
70
+ // Cleanup when done
71
+ // sse.stop();
96
72
  ```
97
73
 
98
74
  ---
99
75
 
100
- ## ⚙️ Configuration (SseConfig)
76
+ ## Configuration Reference (`SseConfig`)
101
77
 
102
78
  | Parameter | Type | Default | Description |
103
79
  | :--- | :--- | :--- | :--- |
104
- | `url` | `string` | - | **Required**. The URL of the SSE endpoint. |
105
- | `method` | `'get' \| 'post'` | `get` | HTTP method. |
106
- | `headers` | `Record<string, string>` | `{}` | Custom HTTP headers. |
107
- | `body` | `string` | - | Request body (payload) for POST requests. |
108
- | `batchingIntervalMs` | `number` | `0` | Time window (ms) to group events. `0` = real-time. |
109
- | `maxBufferSize` | `number` | `1000` | Native queue limit to prevent memory overflow. |
110
- | `connectionTimeoutMs`| `number` | `15000` | Max time for initial handshake / connect. |
111
- | `readTimeoutMs` | `number` | `300000`| Max idle time between data packets before reconnecting. |
112
- | `backgroundExecution` | `boolean` | `false` | (iOS) Attempt to maintain connection via background tasks. |
113
- | `autoParseJSON` | `boolean` | `false` | Automatically parse message data as JSON in a background native thread. Result is in `parsedData`. |
114
- | `monitorNetwork` | `boolean` | `true` | Automatically hibernate connection on system network loss to save battery. |
115
- | `onBeforeRequest` | `function`| - | Async hook to refresh headers/tokens before every attempt. |
80
+ | `url` | `string` | — | **Required**. SSE endpoint target. |
81
+ | `method` | `'get' \| 'post'` | `'get'` | HTTP method. |
82
+ | `headers` | `Record<string, string>` | `{}` | Custom request headers. |
83
+ | `body` | `string` | — | Payload sent during POST requests. |
84
+ | `backgroundExecution` | `boolean` | `false` | (iOS) Keep background execution active when app is minimized. |
85
+ | `batchingIntervalMs` | `number` | `0` | Batch window (ms). `0` sends events instantly. |
86
+ | `maxBufferSize` | `number` | `1000` | Native memory safety threshold. |
87
+ | `connectionTimeoutMs`| `number` | `15000` | Handshake connect timeout threshold. |
88
+ | `readTimeoutMs` | `number` | `300000`| Socket inactivity limit triggers reconnect. |
89
+ | `retryIntervalMs` | `number` | `1000` | Backoff base delay (ms) for reconnect. |
90
+ | `maxRetryIntervalMs` | `number` | `30000` | Cap on backoff reconnect delay (ms). |
91
+ | `jitterFactor` | `number` | `0.5` | Randomization spread ratio (`0.0` to `1.0`). |
92
+ | `maxReconnectAttempts`| `number` | `-1` | Limit reconnections. `-1` = infinite. `0` = disabled. |
93
+ | `autoParseJSON` | `boolean` | `false` | Parses event `data` on native thread; outputs to `parsedData`. |
94
+ | `monitorNetwork` | `boolean` | `true` | Pauses/resumes connection on WiFi <-> Cell or link changes. |
95
+ | `onBeforeRequest` | `() => Promise<Record<string, string>>` | — | Async hook running immediately before every request. |
96
+ | `mock` | `SseMockConfig` | — | Injected mock stream settings (Dev environment only). |
116
97
 
117
98
  ---
118
99
 
119
- ## 🛡️ Reliability Features (v1.5.1+)
100
+ ## Mocking & Testing System (`v2.3.0+`)
120
101
 
121
- - **Atomic State Management**: Calling `.start()` or `.stop()` updates the instance status immediately on the JSI thread, ensuring the UI (e.g., `isConnected()`) never feels laggy or stuck.
122
- - **Promise Safety**: The `onBeforeRequest` interceptor is wrapped in a native fallback timeout. Even if your JS token refresh hangs indefinitely, the native state machine will recover and retry safely.
123
- - **Zero-Ghost Reloads**: Seamlessly handles React Native Hot Reloads. The native layer detects when the JS environment is being destroyed and synchronously kills active sockets to prevent duplicate connections.
124
- - **Cumulative Logic**: Statistics (`totalBytesReceived`) are preserved across reconnections, giving you a true 360-degree view of the session's data usage.
102
+ NitroSSE includes a built-in mock streaming engine to test application responses without running live endpoints. Mocks are automatically disabled in production configurations.
125
103
 
126
- ---
104
+ ### Configuration (`SseMockConfig`)
127
105
 
128
- ## 🏗️ System Architecture
106
+ ```tsx
107
+ sse.setup({
108
+ url: 'https://api.mocked-endpoint.com/stream',
109
+ mock: {
110
+ mode: 'replace', // 'replace' = Pure JS local simulation; 'inject' = Server + injected events
111
+ eventsPerSecond: 2,
112
+ loop: true,
113
+ errorRate: 0.1, // 10% chance to simulate connection drops and trigger reconnects
114
+ data: [
115
+ { type: 'open', statusCode: 200 },
116
+ { type: 'message', data: 'Initial greeting' },
117
+ { event: 'user-updated', data: '{"id":123,"status":"online"}', delayMs: 1500 },
118
+ { type: 'message', data: 'Periodic heartbeat comments' },
119
+ ]
120
+ }
121
+ });
122
+ ```
123
+
124
+ ### Manual Injector
125
+ Inject custom testing events programmatically at runtime to mock specific app situations:
126
+
127
+ ```tsx
128
+ sse.injectMockEvent({
129
+ type: 'message',
130
+ event: 'alert',
131
+ data: 'System maintenance warning!'
132
+ });
133
+ ```
134
+
135
+ ---
129
136
 
130
- This project employs a robust **Producer-Consumer** model:
137
+ ## Advanced Operations
131
138
 
132
- 1. **Native (Producer)**: Collects data from the socket on a dedicated Background Thread, handling all backpressure logic.
133
- 2. **Nitro (Bridge)**: Snapshots data and securely transports it via the JSI CallInvoker.
134
- 3. **JavaScript (Consumer)**: Consumes data in batches, ensuring the UI Loop remains buttery smooth even under heavy load.
139
+ * **`updateHeaders(headers)`**: Change request headers (e.g., updating expired authentication tokens) without closing and opening the connection manually.
140
+ * **`setLastProcessedId(id)`**: Update the native parser's last processed event ID. Native uses this ID as the `Last-Event-ID` header on next reconnection.
141
+ * **`restart()`**: Immediately tears down the current network socket and initializes fresh handshake sequence.
142
+ * **`flush()`**: Explicitly forces dispatch of currently buffered events, ignoring `batchingIntervalMs`.
135
143
 
136
144
  ---
137
145
 
138
- ## 📄 License
146
+ ## License
139
147
 
140
148
  MIT
141
149
 
142
150
  ---
143
151
 
144
- Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
152
+ *Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)*
@@ -4,13 +4,19 @@ import android.os.Handler
4
4
  import android.os.Looper
5
5
  import android.util.Log
6
6
  import com.facebook.proguard.annotations.DoNotStrip
7
- import okhttp3.*
7
+ import okhttp3.OkHttpClient
8
+ import okhttp3.Request
9
+ import okhttp3.Response
10
+ import okhttp3.Interceptor
11
+ import okhttp3.ResponseBody
8
12
  import okhttp3.MediaType.Companion.toMediaType
9
13
  import okhttp3.RequestBody.Companion.toRequestBody
10
14
  import okhttp3.sse.EventSource
11
15
  import okhttp3.sse.EventSources
12
16
  import okhttp3.sse.EventSourceListener
13
- import okio.*
17
+ import okio.Buffer
18
+ import okio.ForwardingSource
19
+ import okio.buffer
14
20
  import com.margelo.nitro.core.AnyMap
15
21
  import org.json.JSONObject
16
22
  import org.json.JSONArray
@@ -54,6 +60,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
54
60
  @Volatile private var onEventsCallback: ((events: Array<SseEvent>) -> Unit)? = null
55
61
 
56
62
  private val isRunning = AtomicBoolean(false)
63
+ @Volatile private var isDispatcherDestroyed = false
57
64
  private var wasRunningBeforePaused = false
58
65
  private val consecutiveAuthErrors = AtomicInteger(0)
59
66
  private val maxAuthRetries = 3
@@ -89,7 +96,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
89
96
  val keys = jsonObject.keys()
90
97
  while (keys.hasNext()) {
91
98
  val key = keys.next()
92
- var value = jsonObject.get(key)
99
+ var value: Any? = jsonObject.get(key)
93
100
  if (value is JSONObject) {
94
101
  value = jsonObjectToMap(value)
95
102
  } else if (value is JSONArray) {
@@ -105,7 +112,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
105
112
  internal fun jsonArrayToList(jsonArray: JSONArray): List<Any?> {
106
113
  val list = mutableListOf<Any?>()
107
114
  for (i in 0 until jsonArray.length()) {
108
- var value = jsonArray.get(i)
115
+ var value: Any? = jsonArray.get(i)
109
116
  if (value is JSONObject) {
110
117
  value = jsonObjectToMap(value)
111
118
  } else if (value is JSONArray) {
@@ -131,13 +138,15 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
131
138
  this.onEventsCallback = onEvent
132
139
 
133
140
  if (this.client == null) {
134
- this.client = OkHttpClient.Builder()
141
+ val builder = OkHttpClient.Builder()
135
142
  .connectTimeout((config.connectionTimeoutMs ?: 15000.0).toLong(), TimeUnit.MILLISECONDS)
136
143
  .readTimeout((config.readTimeoutMs ?: 300000.0).toLong(), TimeUnit.MILLISECONDS)
137
144
  .addNetworkInterceptor(HeartbeatNetworkInterceptor(totalBytesReceived) {
138
145
  pushEventToBuffer(SseEvent(SseEventType.HEARTBEAT, null, null, null, null, "keep-alive", null, null))
139
146
  })
140
- .build()
147
+
148
+
149
+ this.client = builder.build()
141
150
  }
142
151
 
143
152
  if (sseHandlerThread == null) {
@@ -405,6 +414,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
405
414
  if (!isRunning.compareAndSet(false, true)) return
406
415
 
407
416
  consecutiveAuthErrors.set(0)
417
+ isDispatcherDestroyed = false
408
418
  val version = connectionAttemptVersion.incrementAndGet()
409
419
  sseHandler?.post {
410
420
  backoffCounter = 0
@@ -414,6 +424,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
414
424
  }
415
425
 
416
426
  private fun performConnection(version: Int) {
427
+ // Guard: connection attempt is discarded if client is stopped or a newer attempt is in progress
417
428
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return
418
429
 
419
430
  val currentConfig = synchronized(this) { config } ?: return
@@ -423,23 +434,31 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
423
434
  val interceptorCompleted = AtomicBoolean(false)
424
435
  val timeoutMs = (currentConfig.connectionTimeoutMs ?: 15000.0).toLong()
425
436
 
437
+ // Concurrency Safeguard: Prevents JS from hanging the native state machine indefinitely.
438
+ // If the JS interceptor promise does not resolve within connectionTimeoutMs, we fail safely.
426
439
  sseHandler?.postDelayed({
427
440
  if (interceptorCompleted.compareAndSet(false, true)) {
428
441
  handleInterceptorError(Exception("onBeforeRequest interceptor timed out after $timeoutMs ms"), version)
429
442
  }
430
443
  }, timeoutMs)
431
444
 
432
- interceptor.invoke().then { promise2 ->
433
- promise2.then { newHeaders ->
434
- sseHandler?.post {
435
- if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
436
- if (interceptorCompleted.compareAndSet(false, true)) {
437
- synchronized(this) {
438
- val mergedHeaders = (config?.headers ?: emptyMap()).toMutableMap()
439
- newHeaders.forEach { (k, v) -> mergedHeaders[k] = v }
440
- config = config?.copy(headers = mergedHeaders)
445
+ try {
446
+ interceptor.invoke().then { promise2 ->
447
+ promise2.then { newHeaders ->
448
+ sseHandler?.post {
449
+ if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
450
+ if (interceptorCompleted.compareAndSet(false, true)) {
451
+ synchronized(this) {
452
+ val mergedHeaders = (config?.headers ?: emptyMap()).toMutableMap()
453
+ newHeaders.forEach { (k, v) -> mergedHeaders[k] = v }
454
+ config = config?.copy(headers = mergedHeaders)
455
+ }
456
+ executeConnection(version)
441
457
  }
442
- executeConnection(version)
458
+ }
459
+ }.catch { error ->
460
+ if (interceptorCompleted.compareAndSet(false, true)) {
461
+ handleInterceptorError(error, version)
443
462
  }
444
463
  }
445
464
  }.catch { error ->
@@ -447,9 +466,9 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
447
466
  handleInterceptorError(error, version)
448
467
  }
449
468
  }
450
- }.catch { error ->
469
+ } catch (e: Throwable) {
451
470
  if (interceptorCompleted.compareAndSet(false, true)) {
452
- handleInterceptorError(error, version)
471
+ handleInterceptorError(e, version)
453
472
  }
454
473
  }
455
474
  } else {
@@ -471,8 +490,23 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
471
490
  sseHandler?.post {
472
491
  if (!isRunning.get() || version != connectionAttemptVersion.get()) return@post
473
492
  Log.e(TAG, "Request Interceptor Error: ${t?.message}")
493
+
494
+ // Note: We use string matching here because react-native-nitro-modules (as of 0.36.1)
495
+ // throws a generic std::runtime_error from C++ when the Dispatcher is destroyed.
496
+ // It does not provide a specific Exception class (like DispatcherDestroyedException)
497
+ // that we can catch, so checking the message is currently the only workaround.
498
+ val isDispatcherDestroyedMsg = t?.message?.contains("Dispatcher has already been destroyed", ignoreCase = true) == true
499
+ if (isDispatcherDestroyedMsg) {
500
+ Log.w(TAG, "JS Dispatcher destroyed. Stopping SSE stream.")
501
+ this@NitroSse.isDispatcherDestroyed = true
502
+ isRunning.set(false)
503
+ connectionAttemptVersion.incrementAndGet()
504
+ performInternalCleanup()
505
+ return@post
506
+ }
507
+
474
508
  pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Interceptor Error: ${t?.message}", -1.0, null))
475
-
509
+
476
510
  // Reconnect with delay
477
511
  val currentJitterFactor = config?.jitterFactor ?: 0.5
478
512
  val currentRetryInterval = (config?.retryIntervalMs ?: 1000.0).toLong()
@@ -496,7 +530,6 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
496
530
  this.requestId = null
497
531
  }
498
532
 
499
- // Cancel existing event source if any before starting new one
500
533
  eventSource?.cancel()
501
534
  eventSource = null
502
535
 
@@ -782,8 +815,12 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
782
815
  }
783
816
 
784
817
  private fun performInternalCleanup() {
785
- // Runs on sseHandler thread
786
- flushBufferToJs()
818
+ if (!isDispatcherDestroyed) {
819
+ flushBufferToJs()
820
+ } else {
821
+ synchronized(eventBuffer) { eventBuffer.clear() }
822
+ isFlushPending.set(false)
823
+ }
787
824
  sseHandler?.removeCallbacks(flushRunnable)
788
825
  backoffCounter = 0
789
826
  eventSource?.cancel()
@@ -867,6 +904,8 @@ internal class HeartbeatNetworkInterceptor(
867
904
  if (bytesRead != -1L) {
868
905
  totalBytesReceived.addAndGet(bytesRead)
869
906
  try {
907
+ // Raw stream sniffing: SSE comments/heartbeats (lines starting with ':') are discarded
908
+ // by OkHttp SSE parser. We scan raw bytes before parsing to trigger keep-alive watchdogs.
870
909
  for (i in 0 until bytesRead) {
871
910
  val b = sink.get(bufferOffset + i)
872
911
  if (isAtStartOfLine && b == ':'.code.toByte()) {
@@ -875,7 +914,7 @@ internal class HeartbeatNetworkInterceptor(
875
914
  isAtStartOfLine = (b == '\n'.code.toByte() || b == '\r'.code.toByte())
876
915
  }
877
916
  } catch (e: Exception) {
878
- // Silent
917
+ // Silent fallback to prevent crashing the stream reader on random parse bugs
879
918
  }
880
919
  }
881
920
  return bytesRead
@@ -1,4 +1,5 @@
1
1
  import Foundation
2
+ import ObjectiveC
2
3
  import NitroModules
3
4
  import LDSwiftEventSource
4
5
  import Network
@@ -37,6 +38,7 @@ class NitroSse: HybridNitroSseSpec {
37
38
  private var config: SseConfig?
38
39
  private var onEventsCallback: ((_ events: [SseEvent]) -> Void)?
39
40
  private var isRunning: Bool = false
41
+ private var isDispatcherDestroyed: Bool = false
40
42
  private var consecutiveAuthErrors: Int = 0
41
43
  private let maxAuthRetries: Int = 3
42
44
  private var requestId: String? = nil
@@ -60,6 +62,7 @@ class NitroSse: HybridNitroSseSpec {
60
62
  private var connectionAttemptVersion: Int = 0
61
63
  #if os(iOS)
62
64
  private var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = .invalid
65
+ private var isBackgroundTaskActive: Bool = false
63
66
  #endif
64
67
  private var wasRunningBeforeHibernation: Bool = false
65
68
  private var isAppInBackground: Bool = false
@@ -68,6 +71,8 @@ class NitroSse: HybridNitroSseSpec {
68
71
  private var lastPathInterface: NWInterface.InterfaceType?
69
72
  private var wasRunningBeforeNetworkLoss: Bool = false
70
73
 
74
+
75
+
71
76
  /**
72
77
  * Set up the NitroSse instance with configuration and an event callback.
73
78
  * This prepares the lifecycle observers and internal dispatch queue.
@@ -174,12 +179,29 @@ class NitroSse: HybridNitroSseSpec {
174
179
  if config.backgroundExecution == true {
175
180
  print("[NitroSse] App backgrounded. backgroundExecution is true, keeping connection alive.")
176
181
  #if os(iOS)
177
- // Start a background task to tell the OS we want to keep running
178
182
  self.cleanupBackgroundTask()
179
- self.backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(withName: "NitroSse-KeepAlive") { [weak self] in
183
+ self.isBackgroundTaskActive = true
184
+
185
+ DispatchQueue.main.async { [weak self] in
186
+ let taskId = UIApplication.shared.beginBackgroundTask(withName: "NitroSse-KeepAlive") {
187
+ self?.sseQueue.async {
188
+ print("[NitroSse] Background task expired. Hibernating now.")
189
+ self?.hibernateConnection()
190
+ }
191
+ }
180
192
  self?.sseQueue.async {
181
- print("[NitroSse] Background task expired. Hibernating now.")
182
- self?.hibernateConnection()
193
+ if self?.isBackgroundTaskActive == true {
194
+ if let oldTaskId = self?.backgroundTaskIdentifier, oldTaskId != .invalid {
195
+ DispatchQueue.main.async {
196
+ UIApplication.shared.endBackgroundTask(oldTaskId)
197
+ }
198
+ }
199
+ self?.backgroundTaskIdentifier = taskId
200
+ } else {
201
+ DispatchQueue.main.async {
202
+ UIApplication.shared.endBackgroundTask(taskId)
203
+ }
204
+ }
183
205
  }
184
206
  }
185
207
  #endif
@@ -225,9 +247,13 @@ class NitroSse: HybridNitroSseSpec {
225
247
  private func cleanupBackgroundTask() {
226
248
  dispatchPrecondition(condition: .onQueue(sseQueue))
227
249
  #if os(iOS)
228
- if self.backgroundTaskIdentifier != .invalid {
229
- UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier)
250
+ self.isBackgroundTaskActive = false
251
+ let taskId = self.backgroundTaskIdentifier
252
+ if taskId != .invalid {
230
253
  self.backgroundTaskIdentifier = .invalid
254
+ DispatchQueue.main.async {
255
+ UIApplication.shared.endBackgroundTask(taskId)
256
+ }
231
257
  }
232
258
  #endif
233
259
  }
@@ -337,12 +363,12 @@ class NitroSse: HybridNitroSseSpec {
337
363
  let startBody = {
338
364
  guard !self.isRunning else { return }
339
365
 
340
- // Critical check: Ensure config is available before starting
341
366
  guard self.config != nil else {
342
367
  throw RuntimeError("NitroSse not configured. Call setup() first.")
343
368
  }
344
369
 
345
370
  self.isRunning = true
371
+ self.isDispatcherDestroyed = false
346
372
  self.consecutiveAuthErrors = 0
347
373
  self.backoffCounter = 0
348
374
  self.connectionAttemptVersion += 1
@@ -376,6 +402,8 @@ class NitroSse: HybridNitroSseSpec {
376
402
  let flag = CompletionFlag()
377
403
  let timeoutMs = capturedConfig.connectionTimeoutMs ?? 15000.0
378
404
 
405
+ // Concurrency Safeguard: If the JS async interceptor does not resolve
406
+ // within connectionTimeoutMs, throw a timeout error and recover.
379
407
  sseQueue.asyncAfter(deadline: .now() + (timeoutMs / 1000.0)) { [weak self] in
380
408
  guard let self = self else { return }
381
409
  self.sseQueue.async { [weak self] in
@@ -388,37 +416,47 @@ class NitroSse: HybridNitroSseSpec {
388
416
  }
389
417
  }
390
418
 
391
- interceptor().then { [weak self] promise2 in
392
- promise2.then { [weak self] newHeaders in
393
- self?.sseQueue.async { [weak self] in
394
- guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
395
- if !flag.isCompleted {
396
- flag.isCompleted = true
397
- let currentConfig = self.config ?? capturedConfig
398
- var mergedHeaders = currentConfig.headers ?? [:]
399
- for (k, v) in newHeaders {
400
- mergedHeaders[k] = v
419
+ do {
420
+ try interceptor().then { [weak self] promise2 in
421
+ promise2.then { [weak self] newHeaders in
422
+ self?.sseQueue.async { [weak self] in
423
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
424
+ if !flag.isCompleted {
425
+ flag.isCompleted = true
426
+ let currentConfig = self.config ?? capturedConfig
427
+ var mergedHeaders = currentConfig.headers ?? [:]
428
+ for (k, v) in newHeaders {
429
+ mergedHeaders[k] = v
430
+ }
431
+ self.config = SseConfig(
432
+ url: currentConfig.url,
433
+ method: currentConfig.method,
434
+ headers: mergedHeaders,
435
+ body: currentConfig.body,
436
+ backgroundExecution: currentConfig.backgroundExecution,
437
+ batchingIntervalMs: currentConfig.batchingIntervalMs,
438
+ maxBufferSize: currentConfig.maxBufferSize,
439
+ connectionTimeoutMs: currentConfig.connectionTimeoutMs,
440
+ readTimeoutMs: currentConfig.readTimeoutMs,
441
+ retryIntervalMs: currentConfig.retryIntervalMs,
442
+ maxRetryIntervalMs: currentConfig.maxRetryIntervalMs,
443
+ jitterFactor: currentConfig.jitterFactor,
444
+ maxReconnectAttempts: currentConfig.maxReconnectAttempts,
445
+ autoParseJSON: currentConfig.autoParseJSON,
446
+ monitorNetwork: currentConfig.monitorNetwork,
447
+ onBeforeRequest: currentConfig.onBeforeRequest,
448
+ mock: currentConfig.mock
449
+ )
450
+ self.performEstablishConnection(attemptVersion: attemptVersion)
451
+ }
452
+ }
453
+ }.catch { [weak self] error in
454
+ self?.sseQueue.async { [weak self] in
455
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
456
+ if !flag.isCompleted {
457
+ flag.isCompleted = true
458
+ self.handleInterceptorError(error, attemptVersion: attemptVersion)
401
459
  }
402
- self.config = SseConfig(
403
- url: currentConfig.url,
404
- method: currentConfig.method,
405
- headers: mergedHeaders,
406
- body: currentConfig.body,
407
- backgroundExecution: currentConfig.backgroundExecution,
408
- batchingIntervalMs: currentConfig.batchingIntervalMs,
409
- maxBufferSize: currentConfig.maxBufferSize,
410
- connectionTimeoutMs: currentConfig.connectionTimeoutMs,
411
- readTimeoutMs: currentConfig.readTimeoutMs,
412
- retryIntervalMs: currentConfig.retryIntervalMs,
413
- maxRetryIntervalMs: currentConfig.maxRetryIntervalMs,
414
- jitterFactor: currentConfig.jitterFactor,
415
- maxReconnectAttempts: currentConfig.maxReconnectAttempts,
416
- autoParseJSON: currentConfig.autoParseJSON,
417
- monitorNetwork: currentConfig.monitorNetwork,
418
- onBeforeRequest: currentConfig.onBeforeRequest,
419
- mock: currentConfig.mock
420
- )
421
- self.performEstablishConnection(attemptVersion: attemptVersion)
422
460
  }
423
461
  }
424
462
  }.catch { [weak self] error in
@@ -430,13 +468,10 @@ class NitroSse: HybridNitroSseSpec {
430
468
  }
431
469
  }
432
470
  }
433
- }.catch { [weak self] error in
434
- self?.sseQueue.async { [weak self] in
435
- guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
436
- if !flag.isCompleted {
437
- flag.isCompleted = true
438
- self.handleInterceptorError(error, attemptVersion: attemptVersion)
439
- }
471
+ } catch {
472
+ if !flag.isCompleted {
473
+ flag.isCompleted = true
474
+ self.handleInterceptorError(error, attemptVersion: attemptVersion)
440
475
  }
441
476
  }
442
477
  } else {
@@ -447,9 +482,18 @@ class NitroSse: HybridNitroSseSpec {
447
482
  private func handleInterceptorError(_ error: Error, attemptVersion: Int) {
448
483
  dispatchPrecondition(condition: .onQueue(sseQueue))
449
484
  guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
450
- print("[NitroSse] Interceptor failed: \(error.localizedDescription)")
485
+ let desc = error.localizedDescription
486
+ // Note: We use string matching here because react-native-nitro-modules (as of 0.36.1)
487
+ // throws a generic std::runtime_error from C++ when the Dispatcher is destroyed.
488
+ // It does not provide a specific Exception class (like DispatcherDestroyedException)
489
+ // that we can catch, so checking the message is currently the only workaround.
490
+ if desc.contains("Dispatcher has already been destroyed") {
491
+ print("[NitroSse] JS Dispatcher destroyed. Stopping SSE stream.")
492
+ self.isDispatcherDestroyed = true
493
+ self.stopInternal()
494
+ return
495
+ }
451
496
  self.pushEventToBuffer(SseEvent(type: .error, data: nil, parsedData: nil, id: nil, event: nil, message: "Interceptor Error: \(error.localizedDescription)", statusCode: -1, retry: nil))
452
- // Reconnect after delay
453
497
  self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
454
498
  }
455
499
 
@@ -466,6 +510,8 @@ class NitroSse: HybridNitroSseSpec {
466
510
  let readTimeout = (config.readTimeoutMs ?? 300000.0) / 1000.0
467
511
  sessionConfig.timeoutIntervalForRequest = readTimeout
468
512
  sessionConfig.timeoutIntervalForResource = readTimeout
513
+
514
+
469
515
 
470
516
  let handler = SseHandler(parent: self, attemptVersion: attemptVersion)
471
517
  var esConfig = EventSource.Config(handler: handler, url: url)
@@ -503,6 +549,10 @@ class NitroSse: HybridNitroSseSpec {
503
549
  private func stopInternal() {
504
550
  dispatchPrecondition(condition: .onQueue(sseQueue))
505
551
  self.isRunning = false
552
+ if isDispatcherDestroyed {
553
+ eventBuffer.removeAll()
554
+ isFlushPending = false
555
+ }
506
556
  self.wasRunningBeforeNetworkLoss = false
507
557
  self.wasRunningBeforeHibernation = false
508
558
  self.eventSource?.stop()
@@ -646,6 +696,15 @@ class NitroSse: HybridNitroSseSpec {
646
696
  parent.backoffCounter = 0
647
697
  parent.currentReconnectAttempts = 0
648
698
  parent.consecutiveAuthErrors = 0
699
+
700
+ NitroSseNetworkInspector.reportResponseStart(
701
+ parent.requestId,
702
+ url: parent.config?.url,
703
+ response: nil,
704
+ statusCode: 200,
705
+ headers: parent.config?.headers ?? [:]
706
+ )
707
+
649
708
  parent.pushEventToBuffer(SseEvent(type: .open, data: nil, parsedData: nil, id: nil, event: nil, message: nil, statusCode: 200, retry: nil))
650
709
  }
651
710
  }
@@ -682,6 +741,9 @@ class NitroSse: HybridNitroSseSpec {
682
741
  }
683
742
  }
684
743
 
744
+ // LDSwiftEventSource natively parses SSE stream comments (lines beginning with ':')
745
+ // and triggers onComment. Unlike Android (which requires manual byte scanning),
746
+ // on iOS we simply convert comment packets directly into heartbeat events.
685
747
  func onComment(comment: String) {
686
748
  guard let parent = self.parent, source === parent.eventSource else { return }
687
749
  parent.sseQueue.async { [weak parent] in
@@ -695,13 +757,26 @@ class NitroSse: HybridNitroSseSpec {
695
757
  guard let parent = self.parent, source === parent.eventSource else { return }
696
758
  parent.sseQueue.async { [weak parent] in
697
759
  guard let parent = parent, parent.isRunning, self.attemptVersion == parent.connectionAttemptVersion else { return }
760
+
698
761
  let nsError = error as NSError
699
- let statusCode = nsError.code
762
+ var statusCode = nsError.code
763
+ if let responseError = error as? UnsuccessfulResponseError {
764
+ statusCode = responseError.responseCode
765
+ }
700
766
 
701
767
  parent.reconnectCount += 1
702
768
  parent.lastErrorTime = Date().timeIntervalSince1970 * 1000
703
769
  parent.lastErrorCode = "\(nsError.domain)(\(statusCode))"
704
770
 
771
+ if statusCode >= 100 && statusCode < 600 {
772
+ NitroSseNetworkInspector.reportResponseStart(
773
+ parent.requestId,
774
+ url: parent.config?.url,
775
+ response: nil,
776
+ statusCode: statusCode,
777
+ headers: [:]
778
+ )
779
+ }
705
780
  NitroSseNetworkInspector.reportRequestFailed(parent.requestId, cancelled: false)
706
781
  parent.requestId = nil
707
782
 
@@ -15,7 +15,7 @@ namespace margelo::nitro::nitrosse {
15
15
  using namespace facebook;
16
16
 
17
17
  /**
18
- * The C++ JNI bridge between the C++ enum "HttpMethod" and the the Kotlin enum "HttpMethod".
18
+ * The C++ JNI bridge between the C++ enum "HttpMethod" and the Kotlin enum "HttpMethod".
19
19
  */
20
20
  struct JHttpMethod final: public jni::JavaClass<JHttpMethod> {
21
21
  public:
@@ -37,7 +37,7 @@ namespace margelo::nitro::nitrosse {
37
37
  using namespace facebook;
38
38
 
39
39
  /**
40
- * The C++ JNI bridge between the C++ struct "SseConfig" and the the Kotlin data class "SseConfig".
40
+ * The C++ JNI bridge between the C++ struct "SseConfig" and the Kotlin data class "SseConfig".
41
41
  */
42
42
  struct JSseConfig final: public jni::JavaClass<JSseConfig> {
43
43
  public:
@@ -22,7 +22,7 @@ namespace margelo::nitro::nitrosse {
22
22
  using namespace facebook;
23
23
 
24
24
  /**
25
- * The C++ JNI bridge between the C++ struct "SseEvent" and the the Kotlin data class "SseEvent".
25
+ * The C++ JNI bridge between the C++ struct "SseEvent" and the Kotlin data class "SseEvent".
26
26
  */
27
27
  struct JSseEvent final: public jni::JavaClass<JSseEvent> {
28
28
  public:
@@ -15,7 +15,7 @@ namespace margelo::nitro::nitrosse {
15
15
  using namespace facebook;
16
16
 
17
17
  /**
18
- * The C++ JNI bridge between the C++ enum "SseEventType" and the the Kotlin enum "SseEventType".
18
+ * The C++ JNI bridge between the C++ enum "SseEventType" and the Kotlin enum "SseEventType".
19
19
  */
20
20
  struct JSseEventType final: public jni::JavaClass<JSseEventType> {
21
21
  public:
@@ -27,7 +27,7 @@ namespace margelo::nitro::nitrosse {
27
27
  using namespace facebook;
28
28
 
29
29
  /**
30
- * The C++ JNI bridge between the C++ struct "SseMockConfig" and the the Kotlin data class "SseMockConfig".
30
+ * The C++ JNI bridge between the C++ struct "SseMockConfig" and the Kotlin data class "SseMockConfig".
31
31
  */
32
32
  struct JSseMockConfig final: public jni::JavaClass<JSseMockConfig> {
33
33
  public:
@@ -22,7 +22,7 @@ namespace margelo::nitro::nitrosse {
22
22
  using namespace facebook;
23
23
 
24
24
  /**
25
- * The C++ JNI bridge between the C++ struct "SseMockEvent" and the the Kotlin data class "SseMockEvent".
25
+ * The C++ JNI bridge between the C++ struct "SseMockEvent" and the Kotlin data class "SseMockEvent".
26
26
  */
27
27
  struct JSseMockEvent final: public jni::JavaClass<JSseMockEvent> {
28
28
  public:
@@ -15,7 +15,7 @@ namespace margelo::nitro::nitrosse {
15
15
  using namespace facebook;
16
16
 
17
17
  /**
18
- * The C++ JNI bridge between the C++ enum "SseMockMode" and the the Kotlin enum "SseMockMode".
18
+ * The C++ JNI bridge between the C++ enum "SseMockMode" and the Kotlin enum "SseMockMode".
19
19
  */
20
20
  struct JSseMockMode final: public jni::JavaClass<JSseMockMode> {
21
21
  public:
@@ -18,7 +18,7 @@ namespace margelo::nitro::nitrosse {
18
18
  using namespace facebook;
19
19
 
20
20
  /**
21
- * The C++ JNI bridge between the C++ struct "SseStats" and the the Kotlin data class "SseStats".
21
+ * The C++ JNI bridge between the C++ struct "SseStats" and the Kotlin data class "SseStats".
22
22
  */
23
23
  struct JSseStats final: public jni::JavaClass<JSseStats> {
24
24
  public:
@@ -99,7 +99,7 @@ data class SseConfig(
99
99
  }
100
100
 
101
101
  override fun hashCode(): Int {
102
- return arrayOf(
102
+ return arrayOf<Any?>(
103
103
  url,
104
104
  method,
105
105
  headers,
@@ -59,7 +59,7 @@ data class SseEvent(
59
59
  }
60
60
 
61
61
  override fun hashCode(): Int {
62
- return arrayOf(
62
+ return arrayOf<Any?>(
63
63
  type,
64
64
  data,
65
65
  parsedData,
@@ -47,7 +47,7 @@ data class SseMockConfig(
47
47
  }
48
48
 
49
49
  override fun hashCode(): Int {
50
- return arrayOf(
50
+ return arrayOf<Any?>(
51
51
  mode,
52
52
  data,
53
53
  eventsPerSecond,
@@ -63,7 +63,7 @@ data class SseMockEvent(
63
63
  }
64
64
 
65
65
  override fun hashCode(): Int {
66
- return arrayOf(
66
+ return arrayOf<Any?>(
67
67
  type,
68
68
  data,
69
69
  parsedData,
@@ -43,7 +43,7 @@ data class SseStats(
43
43
  }
44
44
 
45
45
  override fun hashCode(): Int {
46
- return arrayOf(
46
+ return arrayOf<Any?>(
47
47
  totalBytesReceived,
48
48
  reconnectCount,
49
49
  lastErrorTime,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-nitro-sse",
3
- "version": "2.3.0",
3
+ "version": "2.3.2",
4
4
  "description": "High-performance Server-Sent Events (SSE) for React Native, powered by Nitro Modules.",
5
5
  "main": "./lib/module/index.js",
6
6
  "types": "./lib/typescript/src/index.d.ts",
@@ -43,8 +43,9 @@
43
43
  "typecheck": "tsc",
44
44
  "test": "jest",
45
45
  "test:android": "cd example/android && ./gradlew :react-native-nitro-sse:testDebugUnitTest",
46
- "test:ios": "cd example/ios && xcodebuild test -workspace NitroSseExample.xcworkspace -scheme NitroSse -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 16'",
46
+ "test:ios": "cd example/ios && xcodebuild test -workspace NitroSseExample.xcworkspace -scheme NitroSse -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 16e'",
47
47
  "test:native": "yarn test:android && yarn test:ios",
48
+ "ci": "yarn lint && yarn typecheck && yarn test && yarn prepare && yarn test:native && yarn turbo run build:android build:ios",
48
49
  "release": "release-it --only-version",
49
50
  "server": "node example/sse-server.js",
50
51
  "lint": "eslint \"**/*.{js,ts,tsx}\""
@@ -77,8 +78,9 @@
77
78
  "@eslint/compat": "^1.3.2",
78
79
  "@eslint/eslintrc": "^3.3.1",
79
80
  "@eslint/js": "^9.35.0",
80
- "@react-native/babel-preset": "0.83.4",
81
- "@react-native/eslint-config": "0.83.4",
81
+ "@react-native/babel-preset": "0.85.3",
82
+ "@react-native/eslint-config": "0.85.3",
83
+ "@react-native/jest-preset": "0.85.3",
82
84
  "@release-it/conventional-changelog": "^10.0.1",
83
85
  "@types/jest": "^29.5.14",
84
86
  "@types/react": "^19.2.0",
@@ -89,12 +91,12 @@
89
91
  "eslint-plugin-prettier": "^5.5.4",
90
92
  "jest": "^29.7.0",
91
93
  "lefthook": "^2.0.3",
92
- "nitrogen": "0.35.6",
94
+ "nitrogen": "0.36.1",
93
95
  "prettier": "^2.8.8",
94
- "react": "19.2.0",
95
- "react-native": "0.83.4",
96
+ "react": "19.2.3",
97
+ "react-native": "0.85.3",
96
98
  "react-native-builder-bob": "^0.40.17",
97
- "react-native-nitro-modules": "0.35.6",
99
+ "react-native-nitro-modules": "0.36.1",
98
100
  "release-it": "^19.0.4",
99
101
  "turbo": "^2.5.6",
100
102
  "typescript": "^5.9.2"
@@ -102,7 +104,7 @@
102
104
  "peerDependencies": {
103
105
  "react": "*",
104
106
  "react-native": "*",
105
- "react-native-nitro-modules": ">= 0.35.6"
107
+ "react-native-nitro-modules": ">= 0.36.1"
106
108
  },
107
109
  "workspaces": [
108
110
  "example"
@@ -134,7 +136,7 @@
134
136
  ]
135
137
  },
136
138
  "jest": {
137
- "preset": "react-native",
139
+ "preset": "@react-native/jest-preset",
138
140
  "modulePathIgnorePatterns": [
139
141
  "<rootDir>/example/node_modules",
140
142
  "<rootDir>/lib/"