react-native-nitro-sse 2.1.1 → 2.2.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.
- package/NitroSse.podspec +1 -1
- package/README.md +3 -1
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +152 -20
- package/ios/NitroSse.swift +105 -1
- package/lib/typescript/src/SseInterface.d.ts +7 -0
- package/lib/typescript/src/SseInterface.d.ts.map +1 -1
- package/nitrogen/generated/android/c++/JSseConfig.hpp +5 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +7 -4
- package/nitrogen/generated/ios/NitroSse+autolinking.rb +2 -0
- package/nitrogen/generated/ios/swift/SseConfig.swift +19 -1
- package/nitrogen/generated/shared/c++/SseConfig.hpp +5 -1
- package/package.json +3 -3
- package/src/SseInterface.ts +7 -0
package/NitroSse.podspec
CHANGED
|
@@ -10,7 +10,7 @@ Pod::Spec.new do |s|
|
|
|
10
10
|
s.license = package["license"]
|
|
11
11
|
s.authors = package["author"]
|
|
12
12
|
|
|
13
|
-
s.platforms = { :ios => min_ios_version_supported }
|
|
13
|
+
s.platforms = { :ios => min_ios_version_supported, :osx => "10.15" }
|
|
14
14
|
s.source = { :git => "https://github.com/IAmTester35/react-native-nitro-sse.git", :tag => "#{s.version}" }
|
|
15
15
|
|
|
16
16
|
s.source_files = [
|
package/README.md
CHANGED
|
@@ -33,7 +33,8 @@ npm install react-native-nitro-sse react-native-nitro-modules
|
|
|
33
33
|
|
|
34
34
|
| react-native-nitro-sse | react-native-nitro-modules |
|
|
35
35
|
| :--------------------- | :------------------------- |
|
|
36
|
-
| **2.
|
|
36
|
+
| **2.2.0 - latest** | **0.35.4** |
|
|
37
|
+
| **2.0.0 - 2.1.1** | **0.35.2** |
|
|
37
38
|
| **1.6.2** | **0.35.2** |
|
|
38
39
|
| **1.4.0 - 1.6.1** | **0.35.0** |
|
|
39
40
|
| **1.2.2 - 1.3.1** | **0.34.1** |
|
|
@@ -110,6 +111,7 @@ console.log(`Reconnections: ${stats.reconnectCount}`);
|
|
|
110
111
|
| `readTimeoutMs` | `number` | `300000`| Max idle time between data packets before reconnecting. |
|
|
111
112
|
| `backgroundExecution` | `boolean` | `false` | (iOS) Attempt to maintain connection via background tasks. |
|
|
112
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. |
|
|
113
115
|
| `onBeforeRequest` | `function`| - | Async hook to refresh headers/tokens before every attempt. |
|
|
114
116
|
|
|
115
117
|
---
|
|
@@ -23,6 +23,12 @@ import java.util.concurrent.atomic.AtomicLong
|
|
|
23
23
|
import java.util.concurrent.atomic.AtomicInteger
|
|
24
24
|
import java.util.UUID
|
|
25
25
|
import kotlin.random.Random
|
|
26
|
+
import android.content.Context
|
|
27
|
+
import android.net.ConnectivityManager
|
|
28
|
+
import android.net.Network
|
|
29
|
+
import android.net.NetworkCapabilities
|
|
30
|
+
import android.net.NetworkRequest
|
|
31
|
+
import com.margelo.nitro.NitroModules
|
|
26
32
|
|
|
27
33
|
/**
|
|
28
34
|
* NitroSse implements a high-performance SSE client using OkHttp.
|
|
@@ -56,8 +62,10 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
56
62
|
|
|
57
63
|
private val eventBuffer = mutableListOf<SseEvent>()
|
|
58
64
|
private var isFlushPending = AtomicBoolean(false)
|
|
65
|
+
private val flushRunnable = java.lang.Runnable { flushBufferToJs() }
|
|
59
66
|
|
|
60
67
|
private var backoffCounter = 0
|
|
68
|
+
private val isAppInBackground = AtomicBoolean(false)
|
|
61
69
|
private var currentReconnectAttempts = 0
|
|
62
70
|
@Volatile private var lastProcessedId: String? = null
|
|
63
71
|
|
|
@@ -69,6 +77,10 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
69
77
|
|
|
70
78
|
private var hasSubscribedToLifecycle = false
|
|
71
79
|
|
|
80
|
+
private var networkCallback: ConnectivityManager.NetworkCallback? = null
|
|
81
|
+
private var wasRunningBeforeNetworkLoss = false
|
|
82
|
+
private var lastNetworkCapabilities: NetworkCapabilities? = null
|
|
83
|
+
|
|
72
84
|
companion object {
|
|
73
85
|
private const val TAG = "NitroSse"
|
|
74
86
|
|
|
@@ -139,6 +151,100 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
139
151
|
hasSubscribedToLifecycle = true
|
|
140
152
|
}
|
|
141
153
|
}
|
|
154
|
+
|
|
155
|
+
if (config.monitorNetwork != false) {
|
|
156
|
+
sseHandler?.post {
|
|
157
|
+
startNetworkMonitoring()
|
|
158
|
+
}
|
|
159
|
+
} else {
|
|
160
|
+
sseHandler?.post {
|
|
161
|
+
stopNetworkMonitoring()
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
private fun startNetworkMonitoring() {
|
|
167
|
+
if (networkCallback != null) return
|
|
168
|
+
|
|
169
|
+
val context = NitroModules.applicationContext ?: return
|
|
170
|
+
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return
|
|
171
|
+
|
|
172
|
+
networkCallback = object : ConnectivityManager.NetworkCallback() {
|
|
173
|
+
override fun onAvailable(network: Network) {
|
|
174
|
+
val capabilities = connectivityManager.getNetworkCapabilities(network)
|
|
175
|
+
handleNetworkChange(true, capabilities)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
override fun onLost(network: Network) {
|
|
179
|
+
handleNetworkChange(false, null)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
|
|
183
|
+
handleNetworkChange(true, capabilities)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
|
|
188
|
+
connectivityManager.registerDefaultNetworkCallback(networkCallback!!)
|
|
189
|
+
} else {
|
|
190
|
+
val request = NetworkRequest.Builder()
|
|
191
|
+
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
|
192
|
+
.build()
|
|
193
|
+
connectivityManager.registerNetworkCallback(request, networkCallback!!)
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private fun handleNetworkChange(isAvailable: Boolean, capabilities: NetworkCapabilities?) {
|
|
198
|
+
sseHandler?.post {
|
|
199
|
+
Log.d(TAG, "Network change: available=$isAvailable")
|
|
200
|
+
|
|
201
|
+
if (isAvailable && capabilities != null) {
|
|
202
|
+
if (wasRunningBeforeNetworkLoss) {
|
|
203
|
+
Log.d(TAG, "Network restored. Resuming stream.")
|
|
204
|
+
wasRunningBeforeNetworkLoss = false
|
|
205
|
+
if (isAppInBackground.get() && config?.backgroundExecution != true) {
|
|
206
|
+
wasRunningBeforePaused = true
|
|
207
|
+
} else {
|
|
208
|
+
start()
|
|
209
|
+
}
|
|
210
|
+
} else if (isRunning.get()) {
|
|
211
|
+
// Check if interface changed (e.g. WiFi -> Cellular)
|
|
212
|
+
val isWifi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
|
|
213
|
+
val isCellular = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
|
|
214
|
+
|
|
215
|
+
val lastWifi = lastNetworkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ?: false
|
|
216
|
+
val lastCellular = lastNetworkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ?: false
|
|
217
|
+
|
|
218
|
+
if ((isWifi && !lastWifi) || (isCellular && !lastCellular)) {
|
|
219
|
+
Log.d(TAG, "Network interface changed. Restarting stream.")
|
|
220
|
+
restart()
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
lastNetworkCapabilities = capabilities
|
|
224
|
+
} else if (!isAvailable) {
|
|
225
|
+
if (isRunning.get()) {
|
|
226
|
+
Log.d(TAG, "Network lost. Hibernating.")
|
|
227
|
+
wasRunningBeforeNetworkLoss = true
|
|
228
|
+
isRunning.set(false)
|
|
229
|
+
connectionAttemptVersion.incrementAndGet()
|
|
230
|
+
performInternalCleanup()
|
|
231
|
+
}
|
|
232
|
+
lastNetworkCapabilities = null
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
private fun stopNetworkMonitoring() {
|
|
238
|
+
val callback = networkCallback ?: return
|
|
239
|
+
try {
|
|
240
|
+
val context = NitroModules.applicationContext
|
|
241
|
+
val connectivityManager = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
|
|
242
|
+
connectivityManager?.unregisterNetworkCallback(callback)
|
|
243
|
+
} catch (e: Exception) {
|
|
244
|
+
Log.w(TAG, "Failed to unregister network callback: ${e.message}")
|
|
245
|
+
}
|
|
246
|
+
networkCallback = null
|
|
247
|
+
lastNetworkCapabilities = null
|
|
142
248
|
}
|
|
143
249
|
|
|
144
250
|
/**
|
|
@@ -146,6 +252,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
146
252
|
* Automatically resumes the stream if it was hibernated.
|
|
147
253
|
*/
|
|
148
254
|
override fun onStart(owner: LifecycleOwner) {
|
|
255
|
+
isAppInBackground.set(false)
|
|
149
256
|
if (wasRunningBeforePaused) {
|
|
150
257
|
Log.d(TAG, "App foregrounded. Resuming NitroSse stream.")
|
|
151
258
|
wasRunningBeforePaused = false
|
|
@@ -158,6 +265,7 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
158
265
|
* Hibernates the connection to save battery and resources.
|
|
159
266
|
*/
|
|
160
267
|
override fun onStop(owner: LifecycleOwner) {
|
|
268
|
+
isAppInBackground.set(true)
|
|
161
269
|
if (isRunning.get()) {
|
|
162
270
|
if (config?.backgroundExecution == true) {
|
|
163
271
|
Log.d(TAG, "App backgrounded. backgroundExecution is true, keeping NitroSse connection alive.")
|
|
@@ -165,7 +273,11 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
165
273
|
}
|
|
166
274
|
Log.d(TAG, "App backgrounded. Hibernating NitroSse connection.")
|
|
167
275
|
wasRunningBeforePaused = true
|
|
168
|
-
|
|
276
|
+
isRunning.set(false)
|
|
277
|
+
connectionAttemptVersion.incrementAndGet()
|
|
278
|
+
sseHandler?.post {
|
|
279
|
+
performInternalCleanup()
|
|
280
|
+
}
|
|
169
281
|
}
|
|
170
282
|
}
|
|
171
283
|
|
|
@@ -182,11 +294,10 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
182
294
|
}
|
|
183
295
|
|
|
184
296
|
if (batchInterval <= 0 || shouldFlush) {
|
|
297
|
+
sseHandler?.removeCallbacks(flushRunnable)
|
|
185
298
|
flushBufferToJs()
|
|
186
299
|
} else if (!isFlushPending.getAndSet(true)) {
|
|
187
|
-
sseHandler?.postDelayed(
|
|
188
|
-
flushBufferToJs()
|
|
189
|
-
}, batchInterval.toLong())
|
|
300
|
+
sseHandler?.postDelayed(flushRunnable, batchInterval.toLong())
|
|
190
301
|
}
|
|
191
302
|
}
|
|
192
303
|
|
|
@@ -492,14 +603,18 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
492
603
|
val currentConfig = synchronized(this@NitroSse) { config }
|
|
493
604
|
if (currentConfig?.onBeforeRequest == null) {
|
|
494
605
|
pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - No interceptor provided. Stopping.", statusCode.toDouble(), null))
|
|
495
|
-
|
|
606
|
+
isRunning.set(false)
|
|
607
|
+
connectionAttemptVersion.incrementAndGet()
|
|
608
|
+
performInternalCleanup()
|
|
496
609
|
return@post
|
|
497
610
|
}
|
|
498
611
|
|
|
499
612
|
val retries = consecutiveAuthErrors.incrementAndGet()
|
|
500
613
|
if (retries >= maxAuthRetries) {
|
|
501
614
|
pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Auth Error ($statusCode) - Retry limit reached ($maxAuthRetries). Stopping.", statusCode.toDouble(), null))
|
|
502
|
-
|
|
615
|
+
isRunning.set(false)
|
|
616
|
+
connectionAttemptVersion.incrementAndGet()
|
|
617
|
+
performInternalCleanup()
|
|
503
618
|
return@post
|
|
504
619
|
}
|
|
505
620
|
|
|
@@ -510,7 +625,9 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
510
625
|
|
|
511
626
|
if (statusCode == 400) {
|
|
512
627
|
pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Fatal Error ($statusCode). Stopping.", statusCode.toDouble(), null))
|
|
513
|
-
|
|
628
|
+
isRunning.set(false)
|
|
629
|
+
connectionAttemptVersion.incrementAndGet()
|
|
630
|
+
performInternalCleanup()
|
|
514
631
|
return@post
|
|
515
632
|
}
|
|
516
633
|
|
|
@@ -527,13 +644,17 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
527
644
|
|
|
528
645
|
if (statusCode == 429) {
|
|
529
646
|
pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Rate Limited (429) without Retry-After. Stopping.", 429.0, null))
|
|
530
|
-
|
|
647
|
+
isRunning.set(false)
|
|
648
|
+
connectionAttemptVersion.incrementAndGet()
|
|
649
|
+
performInternalCleanup()
|
|
531
650
|
return@post
|
|
532
651
|
}
|
|
533
652
|
|
|
534
653
|
if (statusCode == 204) {
|
|
535
654
|
pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "No Content (204). Stopping.", 204.0, null))
|
|
536
|
-
|
|
655
|
+
isRunning.set(false)
|
|
656
|
+
connectionAttemptVersion.incrementAndGet()
|
|
657
|
+
performInternalCleanup()
|
|
537
658
|
return@post
|
|
538
659
|
}
|
|
539
660
|
|
|
@@ -584,7 +705,9 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
584
705
|
if (maxAttempts != -1 && currentReconnectAttempts >= maxAttempts) {
|
|
585
706
|
Log.d(TAG, "Max reconnection attempts reached ($maxAttempts). Stopping.")
|
|
586
707
|
pushEventToBuffer(SseEvent(SseEventType.ERROR, null, null, null, null, "Max reconnection attempts reached ($maxAttempts).", null, null))
|
|
587
|
-
|
|
708
|
+
isRunning.set(false)
|
|
709
|
+
connectionAttemptVersion.incrementAndGet()
|
|
710
|
+
performInternalCleanup()
|
|
588
711
|
return
|
|
589
712
|
}
|
|
590
713
|
|
|
@@ -631,21 +754,28 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
631
754
|
*/
|
|
632
755
|
override fun stop() {
|
|
633
756
|
isRunning.set(false)
|
|
757
|
+
wasRunningBeforeNetworkLoss = false
|
|
758
|
+
wasRunningBeforePaused = false
|
|
634
759
|
val version = connectionAttemptVersion.incrementAndGet()
|
|
635
760
|
sseHandler?.post {
|
|
636
|
-
|
|
637
|
-
backoffCounter = 0
|
|
638
|
-
sseHandler?.removeCallbacksAndMessages(null)
|
|
639
|
-
eventSource?.cancel()
|
|
640
|
-
eventSource = null
|
|
641
|
-
requestId?.let {
|
|
642
|
-
NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
|
|
643
|
-
requestId = null
|
|
644
|
-
}
|
|
645
|
-
isFlushPending.set(false)
|
|
761
|
+
performInternalCleanup()
|
|
646
762
|
}
|
|
647
763
|
}
|
|
648
764
|
|
|
765
|
+
private fun performInternalCleanup() {
|
|
766
|
+
// Runs on sseHandler thread
|
|
767
|
+
flushBufferToJs()
|
|
768
|
+
backoffCounter = 0
|
|
769
|
+
sseHandler?.removeCallbacksAndMessages(null)
|
|
770
|
+
eventSource?.cancel()
|
|
771
|
+
eventSource = null
|
|
772
|
+
requestId?.let {
|
|
773
|
+
NetworkInspector.reportResponseEnd(it, totalBytesReceived.get())
|
|
774
|
+
requestId = null
|
|
775
|
+
}
|
|
776
|
+
isFlushPending.set(false)
|
|
777
|
+
}
|
|
778
|
+
|
|
649
779
|
/**
|
|
650
780
|
* Clean up all resources, including background threads and lifecycle observers.
|
|
651
781
|
* This is called by Nitro when the HybridObject is being garbage collected or JS reloads.
|
|
@@ -656,6 +786,8 @@ class NitroSse : HybridNitroSseSpec(), DefaultLifecycleObserver {
|
|
|
656
786
|
isRunning.set(false)
|
|
657
787
|
connectionAttemptVersion.incrementAndGet()
|
|
658
788
|
|
|
789
|
+
stopNetworkMonitoring()
|
|
790
|
+
|
|
659
791
|
try {
|
|
660
792
|
eventSource?.cancel()
|
|
661
793
|
eventSource = null
|
package/ios/NitroSse.swift
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import Foundation
|
|
2
2
|
import NitroModules
|
|
3
3
|
import LDSwiftEventSource
|
|
4
|
+
import Network
|
|
5
|
+
#if os(iOS)
|
|
6
|
+
import UIKit
|
|
7
|
+
#endif
|
|
4
8
|
|
|
5
9
|
/**
|
|
6
10
|
* NitroSse implements a high-performance SSE client for iOS using LDSwiftEventSource.
|
|
@@ -20,11 +24,14 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
20
24
|
deinit {
|
|
21
25
|
if DispatchQueue.getSpecific(key: NitroSse.sseQueueKey) != nil {
|
|
22
26
|
self.stopInternal()
|
|
27
|
+
self.stopNetworkMonitoring()
|
|
23
28
|
} else {
|
|
24
29
|
sseQueue.sync {
|
|
25
30
|
self.stopInternal()
|
|
31
|
+
self.stopNetworkMonitoring()
|
|
26
32
|
}
|
|
27
33
|
}
|
|
34
|
+
NotificationCenter.default.removeObserver(self)
|
|
28
35
|
}
|
|
29
36
|
private var eventSource: EventSource?
|
|
30
37
|
private var config: SseConfig?
|
|
@@ -51,8 +58,15 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
51
58
|
return queue
|
|
52
59
|
}()
|
|
53
60
|
private var connectionAttemptVersion: Int = 0
|
|
61
|
+
#if os(iOS)
|
|
54
62
|
private var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = .invalid
|
|
63
|
+
#endif
|
|
55
64
|
private var wasRunningBeforeHibernation: Bool = false
|
|
65
|
+
private var isAppInBackground: Bool = false
|
|
66
|
+
|
|
67
|
+
private var pathMonitor: NWPathMonitor?
|
|
68
|
+
private var lastPathInterface: NWInterface.InterfaceType?
|
|
69
|
+
private var wasRunningBeforeNetworkLoss: Bool = false
|
|
56
70
|
|
|
57
71
|
/**
|
|
58
72
|
* Set up the NitroSse instance with configuration and an event callback.
|
|
@@ -68,24 +82,107 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
68
82
|
self.onEventsCallback = onEvent
|
|
69
83
|
|
|
70
84
|
NotificationCenter.default.removeObserver(self)
|
|
85
|
+
#if os(iOS)
|
|
71
86
|
NotificationCenter.default.addObserver(self, selector: #selector(self.handleAppDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
|
|
72
87
|
NotificationCenter.default.addObserver(self, selector: #selector(self.handleAppWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
|
|
88
|
+
#endif
|
|
89
|
+
|
|
90
|
+
if config.monitorNetwork != false {
|
|
91
|
+
self.startNetworkMonitoring()
|
|
92
|
+
} else {
|
|
93
|
+
self.stopNetworkMonitoring()
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private func stopNetworkMonitoring() {
|
|
99
|
+
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
100
|
+
pathMonitor?.cancel()
|
|
101
|
+
pathMonitor = nil
|
|
102
|
+
lastPathInterface = nil
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private func startNetworkMonitoring() {
|
|
106
|
+
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
107
|
+
guard pathMonitor == nil else { return }
|
|
108
|
+
|
|
109
|
+
let monitor = NWPathMonitor()
|
|
110
|
+
monitor.pathUpdateHandler = { [weak self] path in
|
|
111
|
+
self?.sseQueue.async {
|
|
112
|
+
self?.handleNetworkChange(path: path)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
self.pathMonitor = monitor
|
|
116
|
+
monitor.start(queue: sseQueue)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
private func handleNetworkChange(path: NWPath) {
|
|
120
|
+
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
121
|
+
let isSatisfied = path.status == .satisfied
|
|
122
|
+
|
|
123
|
+
var interfaceType: NWInterface.InterfaceType? = nil
|
|
124
|
+
if path.usesInterfaceType(.wifi) {
|
|
125
|
+
interfaceType = .wifi
|
|
126
|
+
} else if path.usesInterfaceType(.cellular) {
|
|
127
|
+
interfaceType = .cellular
|
|
128
|
+
} else if path.usesInterfaceType(.wiredEthernet) {
|
|
129
|
+
interfaceType = .wiredEthernet
|
|
130
|
+
} else {
|
|
131
|
+
interfaceType = path.availableInterfaces.first?.type
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
print("[NitroSse] Network path changed: status=\(path.status), interface=\(String(describing: interfaceType))")
|
|
135
|
+
|
|
136
|
+
if isSatisfied {
|
|
137
|
+
if wasRunningBeforeNetworkLoss {
|
|
138
|
+
print("[NitroSse] Network restored. Resuming stream.")
|
|
139
|
+
wasRunningBeforeNetworkLoss = false
|
|
140
|
+
if self.isAppInBackground && self.config?.backgroundExecution != true {
|
|
141
|
+
self.wasRunningBeforeHibernation = true
|
|
142
|
+
} else if isRunning {
|
|
143
|
+
self.restart()
|
|
144
|
+
} else {
|
|
145
|
+
try? self.start()
|
|
146
|
+
}
|
|
147
|
+
} else if isRunning {
|
|
148
|
+
if let lastInterface = lastPathInterface, let currentInterface = interfaceType, lastInterface != currentInterface {
|
|
149
|
+
print("[NitroSse] Network interface changed (\(lastInterface) -> \(currentInterface)). Restarting stream.")
|
|
150
|
+
self.restart()
|
|
151
|
+
} else if lastPathInterface == nil {
|
|
152
|
+
print("[NitroSse] Network interface acquired. Restarting stream.")
|
|
153
|
+
self.restart()
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
} else {
|
|
157
|
+
if isRunning {
|
|
158
|
+
print("[NitroSse] Network lost. Hibernating.")
|
|
159
|
+
wasRunningBeforeNetworkLoss = true
|
|
160
|
+
self.hibernateConnection()
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if isSatisfied {
|
|
165
|
+
self.lastPathInterface = interfaceType
|
|
73
166
|
}
|
|
74
167
|
}
|
|
75
168
|
|
|
76
169
|
@objc private func handleAppDidEnterBackground() {
|
|
77
170
|
sseQueue.async {
|
|
171
|
+
self.isAppInBackground = true
|
|
78
172
|
guard self.isRunning, let config = self.config else { return }
|
|
79
173
|
|
|
80
174
|
if config.backgroundExecution == true {
|
|
81
175
|
print("[NitroSse] App backgrounded. backgroundExecution is true, keeping connection alive.")
|
|
176
|
+
#if os(iOS)
|
|
82
177
|
// Start a background task to tell the OS we want to keep running
|
|
178
|
+
self.cleanupBackgroundTask()
|
|
83
179
|
self.backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(withName: "NitroSse-KeepAlive") { [weak self] in
|
|
84
180
|
self?.sseQueue.async {
|
|
85
181
|
print("[NitroSse] Background task expired. Hibernating now.")
|
|
86
182
|
self?.hibernateConnection()
|
|
87
183
|
}
|
|
88
184
|
}
|
|
185
|
+
#endif
|
|
89
186
|
return
|
|
90
187
|
}
|
|
91
188
|
|
|
@@ -115,6 +212,7 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
115
212
|
|
|
116
213
|
@objc private func handleAppWillEnterForeground() {
|
|
117
214
|
sseQueue.async {
|
|
215
|
+
self.isAppInBackground = false
|
|
118
216
|
self.cleanupBackgroundTask()
|
|
119
217
|
if self.wasRunningBeforeHibernation {
|
|
120
218
|
print("[NitroSse] App foregrounded. Resuming stream.")
|
|
@@ -126,10 +224,12 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
126
224
|
|
|
127
225
|
private func cleanupBackgroundTask() {
|
|
128
226
|
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
227
|
+
#if os(iOS)
|
|
129
228
|
if self.backgroundTaskIdentifier != .invalid {
|
|
130
229
|
UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier)
|
|
131
230
|
self.backgroundTaskIdentifier = .invalid
|
|
132
231
|
}
|
|
232
|
+
#endif
|
|
133
233
|
}
|
|
134
234
|
|
|
135
235
|
private func pushEventToBuffer(_ event: SseEvent) {
|
|
@@ -207,6 +307,7 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
207
307
|
jitterFactor: config.jitterFactor,
|
|
208
308
|
maxReconnectAttempts: config.maxReconnectAttempts,
|
|
209
309
|
autoParseJSON: config.autoParseJSON,
|
|
310
|
+
monitorNetwork: config.monitorNetwork,
|
|
210
311
|
onBeforeRequest: config.onBeforeRequest
|
|
211
312
|
)
|
|
212
313
|
print("[NitroSse] Headers updated for subsequent connections.")
|
|
@@ -237,7 +338,7 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
237
338
|
|
|
238
339
|
// Critical check: Ensure config is available before starting
|
|
239
340
|
guard self.config != nil else {
|
|
240
|
-
throw
|
|
341
|
+
throw RuntimeError("NitroSse not configured. Call setup() first.")
|
|
241
342
|
}
|
|
242
343
|
|
|
243
344
|
self.isRunning = true
|
|
@@ -312,6 +413,7 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
312
413
|
jitterFactor: currentConfig.jitterFactor,
|
|
313
414
|
maxReconnectAttempts: currentConfig.maxReconnectAttempts,
|
|
314
415
|
autoParseJSON: currentConfig.autoParseJSON,
|
|
416
|
+
monitorNetwork: currentConfig.monitorNetwork,
|
|
315
417
|
onBeforeRequest: currentConfig.onBeforeRequest
|
|
316
418
|
)
|
|
317
419
|
self.performEstablishConnection(attemptVersion: attemptVersion)
|
|
@@ -399,6 +501,8 @@ class NitroSse: HybridNitroSseSpec {
|
|
|
399
501
|
private func stopInternal() {
|
|
400
502
|
dispatchPrecondition(condition: .onQueue(sseQueue))
|
|
401
503
|
self.isRunning = false
|
|
504
|
+
self.wasRunningBeforeNetworkLoss = false
|
|
505
|
+
self.wasRunningBeforeHibernation = false
|
|
402
506
|
self.eventSource?.stop()
|
|
403
507
|
self.eventSource = nil
|
|
404
508
|
if let rid = self.requestId {
|
|
@@ -85,6 +85,13 @@ export interface SseConfig {
|
|
|
85
85
|
* @default false
|
|
86
86
|
*/
|
|
87
87
|
autoParseJSON?: boolean;
|
|
88
|
+
/**
|
|
89
|
+
* Whether to automatically monitor network connectivity changes.
|
|
90
|
+
* If true, the client will proactively reconnect when switching networks (WiFi <-> Cellular)
|
|
91
|
+
* and pause/resume based on internet availability.
|
|
92
|
+
* @default true
|
|
93
|
+
*/
|
|
94
|
+
monitorNetwork?: boolean;
|
|
88
95
|
/**
|
|
89
96
|
* Async interceptor called before every connection attempt (including auto-reconnects).
|
|
90
97
|
* Use this to refresh tokens or calculate dynamic headers.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SseInterface.d.ts","sourceRoot":"","sources":["../../../src/SseInterface.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AACzD;;GAEG;AACH,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,MAAM,CAAC;AAExC;;;;;;;GAOG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,GAAG,WAAW,CAAC;AAEhF;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,mCAAmC;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,oCAAoC;IACpC,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,qDAAqD;IACrD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,8BAA8B;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC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D,yBAAyB;IACzB,kBAAkB,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAAC;CACtC"}
|
|
@@ -68,6 +68,8 @@ namespace margelo::nitro::nitrosse {
|
|
|
68
68
|
jni::local_ref<jni::JDouble> maxReconnectAttempts = this->getFieldValue(fieldMaxReconnectAttempts);
|
|
69
69
|
static const auto fieldAutoParseJSON = clazz->getField<jni::JBoolean>("autoParseJSON");
|
|
70
70
|
jni::local_ref<jni::JBoolean> autoParseJSON = this->getFieldValue(fieldAutoParseJSON);
|
|
71
|
+
static const auto fieldMonitorNetwork = clazz->getField<jni::JBoolean>("monitorNetwork");
|
|
72
|
+
jni::local_ref<jni::JBoolean> monitorNetwork = this->getFieldValue(fieldMonitorNetwork);
|
|
71
73
|
static const auto fieldOnBeforeRequest = clazz->getField<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____::javaobject>("onBeforeRequest");
|
|
72
74
|
jni::local_ref<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____::javaobject> onBeforeRequest = this->getFieldValue(fieldOnBeforeRequest);
|
|
73
75
|
return SseConfig(
|
|
@@ -92,6 +94,7 @@ namespace margelo::nitro::nitrosse {
|
|
|
92
94
|
jitterFactor != nullptr ? std::make_optional(jitterFactor->value()) : std::nullopt,
|
|
93
95
|
maxReconnectAttempts != nullptr ? std::make_optional(maxReconnectAttempts->value()) : std::nullopt,
|
|
94
96
|
autoParseJSON != nullptr ? std::make_optional(static_cast<bool>(autoParseJSON->value())) : std::nullopt,
|
|
97
|
+
monitorNetwork != nullptr ? std::make_optional(static_cast<bool>(monitorNetwork->value())) : std::nullopt,
|
|
95
98
|
onBeforeRequest != nullptr ? std::make_optional([&]() -> std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()> {
|
|
96
99
|
if (onBeforeRequest->isInstanceOf(JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx::javaClassStatic())) [[likely]] {
|
|
97
100
|
auto downcast = jni::static_ref_cast<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx::javaobject>(onBeforeRequest);
|
|
@@ -110,7 +113,7 @@ namespace margelo::nitro::nitrosse {
|
|
|
110
113
|
*/
|
|
111
114
|
[[maybe_unused]]
|
|
112
115
|
static jni::local_ref<JSseConfig::javaobject> fromCpp(const SseConfig& value) {
|
|
113
|
-
using JSignature = JSseConfig(jni::alias_ref<jni::JString>, jni::alias_ref<JHttpMethod>, jni::alias_ref<jni::JMap<jni::JString, jni::JString>>, jni::alias_ref<jni::JString>, jni::alias_ref<jni::JBoolean>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JBoolean>, jni::alias_ref<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____::javaobject>);
|
|
116
|
+
using JSignature = JSseConfig(jni::alias_ref<jni::JString>, jni::alias_ref<JHttpMethod>, jni::alias_ref<jni::JMap<jni::JString, jni::JString>>, jni::alias_ref<jni::JString>, jni::alias_ref<jni::JBoolean>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JDouble>, jni::alias_ref<jni::JBoolean>, jni::alias_ref<jni::JBoolean>, jni::alias_ref<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____::javaobject>);
|
|
114
117
|
static const auto clazz = javaClassStatic();
|
|
115
118
|
static const auto create = clazz->getStaticMethod<JSignature>("fromCpp");
|
|
116
119
|
return create(
|
|
@@ -135,6 +138,7 @@ namespace margelo::nitro::nitrosse {
|
|
|
135
138
|
value.jitterFactor.has_value() ? jni::JDouble::valueOf(value.jitterFactor.value()) : nullptr,
|
|
136
139
|
value.maxReconnectAttempts.has_value() ? jni::JDouble::valueOf(value.maxReconnectAttempts.value()) : nullptr,
|
|
137
140
|
value.autoParseJSON.has_value() ? jni::JBoolean::valueOf(value.autoParseJSON.value()) : nullptr,
|
|
141
|
+
value.monitorNetwork.has_value() ? jni::JBoolean::valueOf(value.monitorNetwork.value()) : nullptr,
|
|
138
142
|
value.onBeforeRequest.has_value() ? JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx::fromCpp(value.onBeforeRequest.value()) : nullptr
|
|
139
143
|
);
|
|
140
144
|
}
|
|
@@ -61,13 +61,16 @@ data class SseConfig(
|
|
|
61
61
|
val autoParseJSON: Boolean?,
|
|
62
62
|
@DoNotStrip
|
|
63
63
|
@Keep
|
|
64
|
+
val monitorNetwork: Boolean?,
|
|
65
|
+
@DoNotStrip
|
|
66
|
+
@Keep
|
|
64
67
|
val onBeforeRequest: Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____?
|
|
65
68
|
) {
|
|
66
69
|
/**
|
|
67
70
|
* Create a new instance of SseConfig from Kotlin
|
|
68
71
|
*/
|
|
69
|
-
constructor(url: String, method: HttpMethod?, headers: Map<String, String>?, body: String?, backgroundExecution: Boolean?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, autoParseJSON: Boolean?, onBeforeRequest: (() -> Promise<Promise<Map<String, String>>>)?):
|
|
70
|
-
this(url, method, headers, body, backgroundExecution, batchingIntervalMs, maxBufferSize, connectionTimeoutMs, readTimeoutMs, retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts, autoParseJSON, onBeforeRequest?.let { Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______java(it) })
|
|
72
|
+
constructor(url: String, method: HttpMethod?, headers: Map<String, String>?, body: String?, backgroundExecution: Boolean?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, autoParseJSON: Boolean?, monitorNetwork: Boolean?, onBeforeRequest: (() -> Promise<Promise<Map<String, String>>>)?):
|
|
73
|
+
this(url, method, headers, body, backgroundExecution, batchingIntervalMs, maxBufferSize, connectionTimeoutMs, readTimeoutMs, retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts, autoParseJSON, monitorNetwork, onBeforeRequest?.let { Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______java(it) })
|
|
71
74
|
|
|
72
75
|
companion object {
|
|
73
76
|
/**
|
|
@@ -77,8 +80,8 @@ data class SseConfig(
|
|
|
77
80
|
@Keep
|
|
78
81
|
@Suppress("unused")
|
|
79
82
|
@JvmStatic
|
|
80
|
-
private fun fromCpp(url: String, method: HttpMethod?, headers: Map<String, String>?, body: String?, backgroundExecution: Boolean?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, autoParseJSON: Boolean?, onBeforeRequest: Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____?): SseConfig {
|
|
81
|
-
return SseConfig(url, method, headers, body, backgroundExecution, batchingIntervalMs, maxBufferSize, connectionTimeoutMs, readTimeoutMs, retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts, autoParseJSON, onBeforeRequest)
|
|
83
|
+
private fun fromCpp(url: String, method: HttpMethod?, headers: Map<String, String>?, body: String?, backgroundExecution: Boolean?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, autoParseJSON: Boolean?, monitorNetwork: Boolean?, onBeforeRequest: Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____?): SseConfig {
|
|
84
|
+
return SseConfig(url, method, headers, body, backgroundExecution, batchingIntervalMs, maxBufferSize, connectionTimeoutMs, readTimeoutMs, retryIntervalMs, maxRetryIntervalMs, jitterFactor, maxReconnectAttempts, autoParseJSON, monitorNetwork, onBeforeRequest)
|
|
82
85
|
}
|
|
83
86
|
}
|
|
84
87
|
}
|
|
@@ -56,5 +56,7 @@ def add_nitrogen_files(spec)
|
|
|
56
56
|
"SWIFT_OBJC_INTEROP_MODE" => "objcxx",
|
|
57
57
|
# Enables stricter modular headers
|
|
58
58
|
"DEFINES_MODULE" => "YES",
|
|
59
|
+
# Disable auto-generated ObjC header for Swift (Static linkage on Xcode 26.4 breaks here)
|
|
60
|
+
"SWIFT_INSTALL_OBJC_HEADER" => "NO",
|
|
59
61
|
})
|
|
60
62
|
end
|
|
@@ -18,7 +18,7 @@ public extension SseConfig {
|
|
|
18
18
|
/**
|
|
19
19
|
* Create a new instance of `SseConfig`.
|
|
20
20
|
*/
|
|
21
|
-
init(url: String, method: HttpMethod?, headers: Dictionary<String, String>?, body: String?, backgroundExecution: Bool?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, autoParseJSON: Bool?, onBeforeRequest: (() -> Promise<Promise<Dictionary<String, String>>>)?) {
|
|
21
|
+
init(url: String, method: HttpMethod?, headers: Dictionary<String, String>?, body: String?, backgroundExecution: Bool?, batchingIntervalMs: Double?, maxBufferSize: Double?, connectionTimeoutMs: Double?, readTimeoutMs: Double?, retryIntervalMs: Double?, maxRetryIntervalMs: Double?, jitterFactor: Double?, maxReconnectAttempts: Double?, autoParseJSON: Bool?, monitorNetwork: Bool?, onBeforeRequest: (() -> Promise<Promise<Dictionary<String, String>>>)?) {
|
|
22
22
|
self.init(std.string(url), { () -> bridge.std__optional_HttpMethod_ in
|
|
23
23
|
if let __unwrappedValue = method {
|
|
24
24
|
return bridge.create_std__optional_HttpMethod_(__unwrappedValue)
|
|
@@ -103,6 +103,12 @@ public extension SseConfig {
|
|
|
103
103
|
} else {
|
|
104
104
|
return .init()
|
|
105
105
|
}
|
|
106
|
+
}(), { () -> bridge.std__optional_bool_ in
|
|
107
|
+
if let __unwrappedValue = monitorNetwork {
|
|
108
|
+
return bridge.create_std__optional_bool_(__unwrappedValue)
|
|
109
|
+
} else {
|
|
110
|
+
return .init()
|
|
111
|
+
}
|
|
106
112
|
}(), { () -> bridge.std__optional_std__function_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_________ in
|
|
107
113
|
if let __unwrappedValue = onBeforeRequest {
|
|
108
114
|
return bridge.create_std__optional_std__function_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_________({ () -> bridge.Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____ in
|
|
@@ -277,6 +283,18 @@ public extension SseConfig {
|
|
|
277
283
|
}()
|
|
278
284
|
}
|
|
279
285
|
|
|
286
|
+
@inline(__always)
|
|
287
|
+
var monitorNetwork: Bool? {
|
|
288
|
+
return { () -> Bool? in
|
|
289
|
+
if bridge.has_value_std__optional_bool_(self.__monitorNetwork) {
|
|
290
|
+
let __unwrapped = bridge.get_std__optional_bool_(self.__monitorNetwork)
|
|
291
|
+
return __unwrapped
|
|
292
|
+
} else {
|
|
293
|
+
return nil
|
|
294
|
+
}
|
|
295
|
+
}()
|
|
296
|
+
}
|
|
297
|
+
|
|
280
298
|
@inline(__always)
|
|
281
299
|
var onBeforeRequest: (() -> Promise<Promise<Dictionary<String, String>>>)? {
|
|
282
300
|
return { () -> (() -> Promise<Promise<Dictionary<String, String>>>)? in
|
|
@@ -59,11 +59,12 @@ namespace margelo::nitro::nitrosse {
|
|
|
59
59
|
std::optional<double> jitterFactor SWIFT_PRIVATE;
|
|
60
60
|
std::optional<double> maxReconnectAttempts SWIFT_PRIVATE;
|
|
61
61
|
std::optional<bool> autoParseJSON SWIFT_PRIVATE;
|
|
62
|
+
std::optional<bool> monitorNetwork SWIFT_PRIVATE;
|
|
62
63
|
std::optional<std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>> onBeforeRequest SWIFT_PRIVATE;
|
|
63
64
|
|
|
64
65
|
public:
|
|
65
66
|
SseConfig() = default;
|
|
66
|
-
explicit SseConfig(std::string url, std::optional<HttpMethod> method, std::optional<std::unordered_map<std::string, std::string>> headers, std::optional<std::string> body, std::optional<bool> backgroundExecution, std::optional<double> batchingIntervalMs, std::optional<double> maxBufferSize, std::optional<double> connectionTimeoutMs, std::optional<double> readTimeoutMs, std::optional<double> retryIntervalMs, std::optional<double> maxRetryIntervalMs, std::optional<double> jitterFactor, std::optional<double> maxReconnectAttempts, std::optional<bool> autoParseJSON, std::optional<std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>> onBeforeRequest): url(url), method(method), headers(headers), body(body), backgroundExecution(backgroundExecution), batchingIntervalMs(batchingIntervalMs), maxBufferSize(maxBufferSize), connectionTimeoutMs(connectionTimeoutMs), readTimeoutMs(readTimeoutMs), retryIntervalMs(retryIntervalMs), maxRetryIntervalMs(maxRetryIntervalMs), jitterFactor(jitterFactor), maxReconnectAttempts(maxReconnectAttempts), autoParseJSON(autoParseJSON), onBeforeRequest(onBeforeRequest) {}
|
|
67
|
+
explicit SseConfig(std::string url, std::optional<HttpMethod> method, std::optional<std::unordered_map<std::string, std::string>> headers, std::optional<std::string> body, std::optional<bool> backgroundExecution, std::optional<double> batchingIntervalMs, std::optional<double> maxBufferSize, std::optional<double> connectionTimeoutMs, std::optional<double> readTimeoutMs, std::optional<double> retryIntervalMs, std::optional<double> maxRetryIntervalMs, std::optional<double> jitterFactor, std::optional<double> maxReconnectAttempts, std::optional<bool> autoParseJSON, std::optional<bool> monitorNetwork, std::optional<std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>> onBeforeRequest): url(url), method(method), headers(headers), body(body), backgroundExecution(backgroundExecution), batchingIntervalMs(batchingIntervalMs), maxBufferSize(maxBufferSize), connectionTimeoutMs(connectionTimeoutMs), readTimeoutMs(readTimeoutMs), retryIntervalMs(retryIntervalMs), maxRetryIntervalMs(maxRetryIntervalMs), jitterFactor(jitterFactor), maxReconnectAttempts(maxReconnectAttempts), autoParseJSON(autoParseJSON), monitorNetwork(monitorNetwork), onBeforeRequest(onBeforeRequest) {}
|
|
67
68
|
|
|
68
69
|
public:
|
|
69
70
|
// SseConfig is not equatable because these properties are not equatable: onBeforeRequest
|
|
@@ -93,6 +94,7 @@ namespace margelo::nitro {
|
|
|
93
94
|
JSIConverter<std::optional<double>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "jitterFactor"))),
|
|
94
95
|
JSIConverter<std::optional<double>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "maxReconnectAttempts"))),
|
|
95
96
|
JSIConverter<std::optional<bool>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "autoParseJSON"))),
|
|
97
|
+
JSIConverter<std::optional<bool>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "monitorNetwork"))),
|
|
96
98
|
JSIConverter<std::optional<std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "onBeforeRequest")))
|
|
97
99
|
);
|
|
98
100
|
}
|
|
@@ -112,6 +114,7 @@ namespace margelo::nitro {
|
|
|
112
114
|
obj.setProperty(runtime, PropNameIDCache::get(runtime, "jitterFactor"), JSIConverter<std::optional<double>>::toJSI(runtime, arg.jitterFactor));
|
|
113
115
|
obj.setProperty(runtime, PropNameIDCache::get(runtime, "maxReconnectAttempts"), JSIConverter<std::optional<double>>::toJSI(runtime, arg.maxReconnectAttempts));
|
|
114
116
|
obj.setProperty(runtime, PropNameIDCache::get(runtime, "autoParseJSON"), JSIConverter<std::optional<bool>>::toJSI(runtime, arg.autoParseJSON));
|
|
117
|
+
obj.setProperty(runtime, PropNameIDCache::get(runtime, "monitorNetwork"), JSIConverter<std::optional<bool>>::toJSI(runtime, arg.monitorNetwork));
|
|
115
118
|
obj.setProperty(runtime, PropNameIDCache::get(runtime, "onBeforeRequest"), JSIConverter<std::optional<std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>>>::toJSI(runtime, arg.onBeforeRequest));
|
|
116
119
|
return obj;
|
|
117
120
|
}
|
|
@@ -137,6 +140,7 @@ namespace margelo::nitro {
|
|
|
137
140
|
if (!JSIConverter<std::optional<double>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "jitterFactor")))) return false;
|
|
138
141
|
if (!JSIConverter<std::optional<double>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "maxReconnectAttempts")))) return false;
|
|
139
142
|
if (!JSIConverter<std::optional<bool>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "autoParseJSON")))) return false;
|
|
143
|
+
if (!JSIConverter<std::optional<bool>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "monitorNetwork")))) return false;
|
|
140
144
|
if (!JSIConverter<std::optional<std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "onBeforeRequest")))) return false;
|
|
141
145
|
return true;
|
|
142
146
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-native-nitro-sse",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
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",
|
|
@@ -89,12 +89,12 @@
|
|
|
89
89
|
"eslint-plugin-prettier": "^5.5.4",
|
|
90
90
|
"jest": "^29.7.0",
|
|
91
91
|
"lefthook": "^2.0.3",
|
|
92
|
-
"nitrogen": "0.35.
|
|
92
|
+
"nitrogen": "^0.35.4",
|
|
93
93
|
"prettier": "^2.8.8",
|
|
94
94
|
"react": "19.2.0",
|
|
95
95
|
"react-native": "0.83.4",
|
|
96
96
|
"react-native-builder-bob": "^0.40.17",
|
|
97
|
-
"react-native-nitro-modules": "0.35.
|
|
97
|
+
"react-native-nitro-modules": "^0.35.4",
|
|
98
98
|
"release-it": "^19.0.4",
|
|
99
99
|
"turbo": "^2.5.6",
|
|
100
100
|
"typescript": "^5.9.2"
|
package/src/SseInterface.ts
CHANGED
|
@@ -87,6 +87,13 @@ export interface SseConfig {
|
|
|
87
87
|
* @default false
|
|
88
88
|
*/
|
|
89
89
|
autoParseJSON?: boolean;
|
|
90
|
+
/**
|
|
91
|
+
* Whether to automatically monitor network connectivity changes.
|
|
92
|
+
* If true, the client will proactively reconnect when switching networks (WiFi <-> Cellular)
|
|
93
|
+
* and pause/resume based on internet availability.
|
|
94
|
+
* @default true
|
|
95
|
+
*/
|
|
96
|
+
monitorNetwork?: boolean;
|
|
90
97
|
/**
|
|
91
98
|
* Async interceptor called before every connection attempt (including auto-reconnects).
|
|
92
99
|
* Use this to refresh tokens or calculate dynamic headers.
|