react-native-nitro-sse 1.6.2 → 2.1.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 (35) hide show
  1. package/README.md +2 -0
  2. package/android/build.gradle +1 -0
  3. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +256 -95
  4. package/ios/NitroSse.swift +90 -39
  5. package/lib/module/NitroSseClient.js +75 -0
  6. package/lib/module/NitroSseClient.js.map +1 -0
  7. package/lib/module/SseInterface.js +2 -0
  8. package/lib/module/index.js +9 -1
  9. package/lib/module/index.js.map +1 -1
  10. package/lib/typescript/src/NitroSseClient.d.ts +21 -0
  11. package/lib/typescript/src/NitroSseClient.d.ts.map +1 -0
  12. package/lib/typescript/src/SseInterface.d.ts +74 -2
  13. package/lib/typescript/src/SseInterface.d.ts.map +1 -1
  14. package/lib/typescript/src/index.d.ts +8 -2
  15. package/lib/typescript/src/index.d.ts.map +1 -1
  16. package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +2 -0
  17. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +2 -0
  18. package/nitrogen/generated/android/c++/JSseConfig.hpp +21 -1
  19. package/nitrogen/generated/android/c++/JSseEvent.hpp +7 -1
  20. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +19 -4
  21. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +6 -3
  22. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +16 -0
  23. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +1 -0
  24. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +1 -0
  25. package/nitrogen/generated/ios/swift/SseConfig.swift +91 -1
  26. package/nitrogen/generated/ios/swift/SseEvent.swift +19 -1
  27. package/nitrogen/generated/shared/c++/SseConfig.hpp +21 -1
  28. package/nitrogen/generated/shared/c++/SseEvent.hpp +6 -1
  29. package/package.json +9 -4
  30. package/src/NitroSseClient.ts +96 -0
  31. package/src/SseInterface.ts +79 -2
  32. package/src/index.ts +10 -2
  33. package/android/src/test/java/com/margelo/nitro/nitrosse/HeartbeatScannerTest.kt +0 -98
  34. package/android/src/test/java/com/margelo/nitro/nitrosse/NitroSseLogicTest.kt +0 -157
  35. package/ios/Tests/NitroSseTests.swift +0 -122
@@ -1,3 +1,4 @@
1
+ import type { AnyMap } from 'react-native-nitro-modules';
1
2
  /**
2
3
  * HTTP method to use for the SSE connection.
3
4
  */
@@ -46,7 +47,7 @@ export interface SseConfig {
46
47
  maxBufferSize?: number;
47
48
  /**
48
49
  * Maximum time (in ms) to wait for the initial server connection and handshake to complete.
49
- * Effectively the "Connect Timeout".
50
+ * Effectively the \"Connect Timeout\".
50
51
  * @default 15000
51
52
  */
52
53
  connectionTimeoutMs?: number;
@@ -57,6 +58,35 @@ export interface SseConfig {
57
58
  * @default 300000
58
59
  */
59
60
  readTimeoutMs?: number;
61
+ /**
62
+ * Initial delay (in ms) for reconnection attempts.
63
+ * Subsequent attempts use exponential backoff.
64
+ * @default 1000
65
+ */
66
+ retryIntervalMs?: number;
67
+ /**
68
+ * Maximum delay (in ms) for reconnection attempts.
69
+ * @default 30000
70
+ */
71
+ maxRetryIntervalMs?: number;
72
+ /**
73
+ * Factor to randomize reconnection attempts (0.0 to 1.0).
74
+ * 0 means no jitter, 1.0 means up to 100% randomization.
75
+ * @default 0.5
76
+ */
77
+ jitterFactor?: number;
78
+ /**
79
+ * Maximum number of reconnection attempts before giving up.
80
+ * Use -1 for infinite (default), 0 to disable auto-reconnection.
81
+ * @default -1
82
+ */
83
+ maxReconnectAttempts?: number;
84
+ /**
85
+ * Whether to automatically parse message data as JSON in a background native thread.
86
+ * If true, and parsing succeeds, the result will be available in the 'parsedData' field.
87
+ * @default false
88
+ */
89
+ autoParseJSON?: boolean;
60
90
  /**
61
91
  * Async interceptor called before every connection attempt (including auto-reconnects).
62
92
  * Use this to refresh tokens or calculate dynamic headers.
@@ -71,8 +101,10 @@ export interface SseConfig {
71
101
  export interface SseEvent {
72
102
  /** The type of the event. */
73
103
  type: SseEventType;
74
- /** The data payload of the event. */
104
+ /** The data payload of the event as a raw string. */
75
105
  data?: string;
106
+ /** The parsed JSON data, if autoParseJSON is enabled and parsing succeeds. */
107
+ parsedData?: AnyMap;
76
108
  /** The event ID, if provided. */
77
109
  id?: string;
78
110
  /** The event name, if provided (internal 'event' field in SSE). */
@@ -98,3 +130,48 @@ export interface SseStats {
98
130
  /** Error code of the last error. */
99
131
  lastErrorCode?: string;
100
132
  }
133
+
134
+ /**
135
+ * Listener for a specific SSE event.
136
+ */
137
+ export type SseListener = (event: SseEvent) => void;
138
+
139
+ /**
140
+ * Public interface for the NitroSse client, supporting typed event listeners.
141
+ */
142
+ export interface SseClient {
143
+ /**
144
+ * Configure SSE and setup event callback.
145
+ * @param config The SSE configuration.
146
+ * @param onEvent Optional legacy batch callback for all events.
147
+ */
148
+ setup(config: SseConfig, onEvent?: (events: SseEvent[]) => void): void;
149
+
150
+ /**
151
+ * Register a listener for a specific event type ('message', 'open', etc.)
152
+ * or a custom SSE event name (from the 'event:' field).
153
+ */
154
+ addEventListener(type: string, listener: SseListener): void;
155
+
156
+ /**
157
+ * Unregister a listener.
158
+ */
159
+ removeEventListener(type: string, listener: SseListener): void;
160
+
161
+ /** Start the connection. */
162
+ start(): void;
163
+ /** Stop the connection. */
164
+ stop(): void;
165
+ /** Restart the connection (stop + start). */
166
+ restart(): void;
167
+ /** Force flush buffered events to JS. */
168
+ flush(): void;
169
+ /** Check if active. */
170
+ isConnected(): boolean;
171
+ /** Get stats. */
172
+ getStats(): SseStats;
173
+ /** Manually update headers. */
174
+ updateHeaders(headers: Record<string, string>): void;
175
+ /** Set last event ID. */
176
+ setLastProcessedId(id: string): void;
177
+ }
package/src/index.ts CHANGED
@@ -1,10 +1,18 @@
1
1
  import { NitroModules } from 'react-native-nitro-modules';
2
2
  import type { NitroSse } from './NitroSse.nitro';
3
+ import { NitroSseClient } from './NitroSseClient';
4
+ import type { SseClient } from './SseInterface';
3
5
 
4
6
  export * from './SseInterface';
5
7
  export * from './NitroSse.nitro';
6
8
 
7
- export function createNitroSse(): NitroSse {
9
+ /**
10
+ * Creates a high-performance SSE client that supports typed event listeners (`addEventListener`) and legacy batching.
11
+ *
12
+ * @returns An SseClient instance wrapping the native NitroSse implementation.
13
+ * @throws If the native NitroSse module cannot be found. Ensure the library is linked and the app is built for iOS/Android.
14
+ */
15
+ export function createNitroSse(): SseClient {
8
16
  let nativeSse: NitroSse | undefined;
9
17
  try {
10
18
  nativeSse = NitroModules.createHybridObject<NitroSse>('NitroSse');
@@ -19,5 +27,5 @@ export function createNitroSse(): NitroSse {
19
27
  'NitroSse: Native module not found. Ensure you have linked the library and built the app for iOS/Android.'
20
28
  );
21
29
  }
22
- return nativeSse;
30
+ return new NitroSseClient(nativeSse);
23
31
  }
@@ -1,98 +0,0 @@
1
- package com.margelo.nitro.nitrosse
2
-
3
- import org.junit.Assert.assertEquals
4
- import org.junit.Test
5
-
6
- class HeartbeatScanner {
7
- private var isAtStartOfLine = true
8
- var heartbeatCount = 0
9
- private set
10
-
11
- fun scan(bytes: ByteArray, length: Int) {
12
- for (i in 0 until length) {
13
- val b = bytes[i]
14
- if (isAtStartOfLine && b == ':'.toByte()) {
15
- heartbeatCount++
16
- }
17
- isAtStartOfLine = (b == '\n'.toByte() || b == '\r'.toByte())
18
- }
19
- }
20
- }
21
-
22
- class HeartbeatScannerTest {
23
-
24
- @Test
25
- fun testNormalHeartbeat() {
26
- val scanner = HeartbeatScanner()
27
- val data = ":heartbeat\n".toByteArray()
28
- scanner.scan(data, data.size)
29
- assertEquals(1, scanner.heartbeatCount)
30
- }
31
-
32
- @Test
33
- fun testHeartbeatAfterNewline() {
34
- val scanner = HeartbeatScanner()
35
- val data = "data: hello\n:heartbeat\n".toByteArray()
36
- scanner.scan(data, data.size)
37
- assertEquals(1, scanner.heartbeatCount)
38
- }
39
-
40
- @Test
41
- fun testSplitPacketHeartbeat() {
42
- val scanner = HeartbeatScanner()
43
-
44
- // Packet 1 ends right before heartbeat
45
- val p1 = "data: hello\n".toByteArray()
46
- scanner.scan(p1, p1.size)
47
-
48
- // Packet 2 starts with heartbeat
49
- val p2 = ":heartbeat\n".toByteArray()
50
- scanner.scan(p2, p2.size)
51
-
52
- assertEquals(1, scanner.heartbeatCount)
53
- }
54
-
55
- @Test
56
- fun testHeartbeatSplitAcrossPackets() {
57
- val scanner = HeartbeatScanner()
58
-
59
- // Packet 1 ends with newline
60
- val p1 = "data: hello\n".toByteArray()
61
- scanner.scan(p1, p1.size)
62
-
63
- // Packet 2 starts with ':' but no more
64
- val p2 = ":".toByteArray()
65
- scanner.scan(p2, p2.size)
66
- assertEquals(1, scanner.heartbeatCount)
67
-
68
- // Packet 3 contains the rest of comment
69
- val p3 = "heartbeat\n".toByteArray()
70
- scanner.scan(p3, p3.size)
71
-
72
- assertEquals(1, scanner.heartbeatCount)
73
- }
74
-
75
- @Test
76
- fun testColonsInDataAreNotHeartbeats() {
77
- val scanner = HeartbeatScanner()
78
- val data = "data: something:with:colons\n".toByteArray()
79
- scanner.scan(data, data.size)
80
- assertEquals(0, scanner.heartbeatCount)
81
- }
82
-
83
- @Test
84
- fun testMultipleHeartbeats() {
85
- val scanner = HeartbeatScanner()
86
- val data = ":h1\n:h2\n\n:h3\n".toByteArray()
87
- scanner.scan(data, data.size)
88
- assertEquals(3, scanner.heartbeatCount)
89
- }
90
-
91
- @Test
92
- fun testCRLFHeartbeat() {
93
- val scanner = HeartbeatScanner()
94
- val data = "data: ok\r\n:heartbeat\r\n".toByteArray()
95
- scanner.scan(data, data.size)
96
- assertEquals(1, scanner.heartbeatCount)
97
- }
98
- }
@@ -1,157 +0,0 @@
1
- package com.margelo.nitro.nitrosse
2
-
3
- import org.junit.Assert.*
4
- import org.junit.Before
5
- import org.junit.Test
6
- import java.util.concurrent.atomic.AtomicInteger
7
-
8
- class NitroSseLogicTest {
9
-
10
- private lateinit var eventBuffer: MutableList<SseEvent>
11
- private var bufferCapacity = 100
12
- private var batchInterval = 0.0
13
-
14
- @Before
15
- fun setup() {
16
- eventBuffer = mutableListOf()
17
- }
18
-
19
- private fun pushEventToBuffer(event: SseEvent, onFlush: () -> Unit) {
20
- synchronized(eventBuffer) {
21
- while (eventBuffer.size >= bufferCapacity) {
22
- eventBuffer.removeAt(0)
23
- }
24
- eventBuffer.add(event)
25
- }
26
-
27
- if (batchInterval <= 0) {
28
- onFlush()
29
- }
30
- }
31
-
32
- @Test
33
- fun testBufferCapacityLimit() {
34
- bufferCapacity = 5
35
- batchInterval = 100.0 // Enable batching so we don't flush immediately
36
-
37
- for (i in 1..10) {
38
- pushEventToBuffer(SseEvent(SseEventType.MESSAGE, "data $i", "$i", null, null, null, null)) {}
39
- }
40
-
41
- assertEquals(5, eventBuffer.size)
42
- assertEquals("6", eventBuffer[0].id)
43
- assertEquals("10", eventBuffer[4].id)
44
- }
45
-
46
- @Test
47
- fun testImmediateFlushWhenNoBatching() {
48
- batchInterval = 0.0
49
- val flushCount = AtomicInteger(0)
50
-
51
- pushEventToBuffer(SseEvent(SseEventType.OPEN, null, null, null, null, null, null)) {
52
- flushCount.incrementAndGet()
53
- }
54
-
55
- assertEquals(1, flushCount.get())
56
- }
57
-
58
- @Test
59
- fun testRetryAfterExtraction() {
60
- // Mock non-standard retry after logic (conceptual check of the method)
61
- fun extractMillis(headerValue: String?): Long? {
62
- if (headerValue == null) return null
63
- return try {
64
- headerValue.toLong() * 1000L
65
- } catch (e: Exception) {
66
- null // Simplifying for the logic test
67
- }
68
- }
69
-
70
- assertEquals(5000L, extractMillis("5"))
71
- assertEquals(60000L, extractMillis("60"))
72
- assertNull(extractMillis(null))
73
- assertNull(extractMillis("invalid"))
74
- }
75
-
76
- @Test
77
- fun testBackoffCalculation() {
78
- val baseBackoffDelayMs = 2000L
79
- val maxBackoffDelayMs = 30000L
80
-
81
- fun calculateDelay(counter: Int): Long {
82
- return Math.min(baseBackoffDelayMs * (1 shl counter), maxBackoffDelayMs)
83
- }
84
-
85
- assertEquals(2000L, calculateDelay(0))
86
- assertEquals(4000L, calculateDelay(1))
87
- assertEquals(8000L, calculateDelay(2))
88
- assertEquals(16000L, calculateDelay(3))
89
- assertEquals(30000L, calculateDelay(4)) // Capped at max
90
- assertEquals(30000L, calculateDelay(10)) // Still capped
91
- }
92
-
93
- @Test
94
- fun testAuthenticationErrorsReset() {
95
- var consecutiveAuthErrors = 3
96
-
97
- fun onOpened() {
98
- consecutiveAuthErrors = 0
99
- }
100
-
101
- onOpened()
102
- assertEquals(0, consecutiveAuthErrors)
103
- }
104
-
105
- @Test
106
- fun testCumulativeStatsAcrossAttempts() {
107
- val totalBytesReceived = AtomicInteger(0)
108
-
109
- fun simulateDataReceived(bytes: Int) {
110
- totalBytesReceived.addAndGet(bytes)
111
- }
112
-
113
- fun stopConnection() {
114
- // New logic: We don't reset totalBytesReceived in stop/reportResponseEnd anymore
115
- // requestId?.let { NetworkInspector.reportResponseEnd(it, totalBytesReceived.get()) }
116
- }
117
-
118
- simulateDataReceived(100)
119
- stopConnection()
120
- simulateDataReceived(200)
121
-
122
- assertEquals(300, totalBytesReceived.get())
123
- }
124
-
125
- @Test
126
- fun testVersioningSafeguard() {
127
- val connectionAttemptVersion = AtomicInteger(0)
128
- var connectionExecutedCount = 0
129
-
130
- fun start() {
131
- val versionAtStart = connectionAttemptVersion.get()
132
-
133
- // Simulate async interceptor delay
134
- val delayResolvedWithVersion = versionAtStart
135
-
136
- // Before executing, check version
137
- if (delayResolvedWithVersion == connectionAttemptVersion.get()) {
138
- connectionExecutedCount++
139
- }
140
- }
141
-
142
- fun stop() {
143
- connectionAttemptVersion.incrementAndGet()
144
- }
145
-
146
- // Scenario: Start -> Stop -> Interceptor returns for OLD Start
147
- val version1 = connectionAttemptVersion.get()
148
- stop() // User cancels before start finishes
149
-
150
- // Old "start" logic tries to finish
151
- if (version1 == connectionAttemptVersion.get()) {
152
- connectionExecutedCount++
153
- }
154
-
155
- assertEquals(0, connectionExecutedCount)
156
- }
157
- }
@@ -1,122 +0,0 @@
1
- import XCTest
2
- @testable import NitroSse
3
-
4
- class NitroSseTests: XCTestCase {
5
-
6
- // Manual re-implementation of core logic for unit testing
7
- // since NitroSse is heavily tied to background queues and LDSwiftEventSource
8
- // but the algorithms are extracted for verify quality.
9
-
10
- func testBackoffDelayCalculation() {
11
- let baseBackoffDelay: TimeInterval = 2.0
12
- let maxBackoffDelay: TimeInterval = 30.0
13
-
14
- func calculateDelay(counter: Int) -> TimeInterval {
15
- let exponent = Double(counter)
16
- return min(baseBackoffDelay * pow(2.0, exponent), maxBackoffDelay)
17
- }
18
-
19
- XCTAssertEqual(calculateDelay(counter: 0), 2.0)
20
- XCTAssertEqual(calculateDelay(counter: 1), 4.0)
21
- XCTAssertEqual(calculateDelay(counter: 2), 8.0)
22
- XCTAssertEqual(calculateDelay(counter: 3), 16.0)
23
- XCTAssertEqual(calculateDelay(counter: 4), 30.0) // Capped
24
- XCTAssertEqual(calculateDelay(counter: 10), 30.0) // Still capped
25
- }
26
-
27
- func testRetryAfterExtraction() {
28
- // Mocked logic for testing since URLResponse and HTTPURLResponse initialization is complex
29
- func extractRetryAfter(headerValue: String?) -> TimeInterval? {
30
- guard let retryAfterHeader = headerValue else { return nil }
31
- if let seconds = Double(retryAfterHeader) {
32
- return seconds
33
- }
34
- // Date parsing (Simplified RFC1123 check)
35
- let formatter = DateFormatter()
36
- formatter.locale = Locale(identifier: "en_US_POSIX")
37
- formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
38
- if let date = formatter.date(from: retryAfterHeader) {
39
- let diff = date.timeIntervalSinceNow
40
- return diff > 0 ? diff : nil
41
- }
42
- return nil
43
- }
44
-
45
- XCTAssertEqual(extractRetryAfter(headerValue: "5"), 5.0)
46
- XCTAssertEqual(extractRetryAfter(headerValue: "60"), 60.0)
47
- XCTAssertNil(extractRetryAfter(headerValue: nil))
48
- XCTAssertNil(extractRetryAfter(headerValue: "invalid"))
49
-
50
- // Test date format (far in future)
51
- let futureDate = "Wed, 01 Jan 2030 00:00:00 GMT"
52
- XCTAssertNotNil(extractRetryAfter(headerValue: futureDate))
53
- }
54
-
55
- func testBufferManagement() {
56
- var buffer: [String] = []
57
- let capacity = 5
58
-
59
- func pushToBuffer(_ item: String) {
60
- while buffer.count >= capacity {
61
- buffer.removeFirst()
62
- }
63
- buffer.append(item)
64
- }
65
-
66
- for i in 1...10 {
67
- pushToBuffer("event-\(i)")
68
- }
69
-
70
- XCTAssertEqual(buffer.count, 5)
71
- XCTAssertEqual(buffer.first, "event-6")
72
- XCTAssertEqual(buffer.last, "event-10")
73
- }
74
-
75
- func testEventSizeCalculation() {
76
- // Total bytes count logic
77
- func calculateSize(eventType: String, data: String, lastId: String) -> Double {
78
- let encodedDataSize = Double(data.utf8.count)
79
- let metadataSize = Double(eventType.utf8.count) + Double(lastId.utf8.count)
80
- return encodedDataSize + metadataSize
81
- }
82
-
83
- let size = calculateSize(eventType: "message", data: "{\"id\":1}", lastId: "event-1")
84
- XCTAssertEqual(size, 22.0) // 8 (data) + 7 (type) + 7 (id) = 22 bytes
85
- }
86
-
87
- func testVersioningSafety() {
88
- var connectionAttemptVersion: Int32 = 0
89
- var executeCount = 0
90
-
91
- func stop() {
92
- connectionAttemptVersion += 1
93
- }
94
-
95
- // Start called, captures version 0
96
- let capturedVersion = connectionAttemptVersion
97
-
98
- // User stops immediately
99
- stop()
100
-
101
- // Connection logic tries to execute
102
- func establishConnection(version: Int32) {
103
- if version == connectionAttemptVersion {
104
- executeCount += 1
105
- }
106
- }
107
-
108
- establishConnection(version: capturedVersion)
109
- XCTAssertEqual(executeCount, 0, "Should not execute if version changed")
110
- }
111
-
112
- func testAuthErrorReset() {
113
- var consecutiveAuthErrors = 3
114
-
115
- func onOpened() {
116
- consecutiveAuthErrors = 0
117
- }
118
-
119
- onOpened()
120
- XCTAssertEqual(consecutiveAuthErrors, 0, "Errors should reset on success")
121
- }
122
- }