react-native-nitro-sse 3.0.0-beta.2 → 3.1.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 +0 -1
- package/README.md +44 -24
- package/android/build.gradle +0 -1
- package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +33 -10
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +464 -130
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +420 -88
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +23 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +29 -2
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +9 -0
- package/ios/NitroSse.swift +353 -64
- package/ios/SseConfig+CopyWith.swift +35 -19
- package/ios/SseConnectionHandler.swift +647 -97
- package/ios/SseEventBuffer.swift +19 -1
- package/ios/SseReconnectStrategy.swift +26 -7
- package/lib/module/MockSseEngine.js +72 -8
- package/lib/module/NitroSseClient.js +79 -8
- package/lib/module/createNitroSse.js +24 -0
- package/lib/module/index.js +1 -22
- package/lib/module/useNitroSse.js +22 -5
- package/lib/typescript/src/MockSseEngine.d.ts +16 -0
- package/lib/typescript/src/NitroSse.nitro.d.ts +2 -2
- package/lib/typescript/src/NitroSseClient.d.ts +7 -3
- package/lib/typescript/src/SseInterface.d.ts +60 -10
- package/lib/typescript/src/createNitroSse.d.ts +9 -0
- package/lib/typescript/src/index.d.ts +1 -8
- package/lib/typescript/src/useNitroSse.d.ts +2 -2
- package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +12 -8
- package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseConfig.hpp +1 -18
- package/nitrogen/generated/android/c++/JSseDisconnectReason.hpp +67 -0
- package/nitrogen/generated/android/c++/JSseStats.hpp +87 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +4 -3
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +4 -13
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseDisconnectReason.kt +26 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +108 -3
- package/nitrogen/generated/android/nitrosseOnLoad.cpp +2 -2
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +8 -8
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +114 -96
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +3 -0
- package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +7 -4
- package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +1 -1
- package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +34 -1
- package/nitrogen/generated/ios/swift/SseConfig.swift +1 -48
- package/nitrogen/generated/ios/swift/SseDisconnectReason.swift +52 -0
- package/nitrogen/generated/ios/swift/SseStats.swift +217 -2
- package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +3 -1
- package/nitrogen/generated/shared/c++/SseConfig.hpp +2 -8
- package/nitrogen/generated/shared/c++/SseDisconnectReason.hpp +88 -0
- package/nitrogen/generated/shared/c++/SseStats.hpp +88 -2
- package/package.json +2 -2
package/NitroSse.podspec
CHANGED
package/README.md
CHANGED
|
@@ -67,6 +67,11 @@ export function EventStream() {
|
|
|
67
67
|
url: 'https://api.example.com/events',
|
|
68
68
|
headers: { Authorization: 'Bearer TOKEN' },
|
|
69
69
|
autoParseJSON: true,
|
|
70
|
+
// Async interceptor called before initial connection & auto-reconnects
|
|
71
|
+
onBeforeRequest: async () => {
|
|
72
|
+
const token = await getFreshAuthToken();
|
|
73
|
+
return { Authorization: `Bearer ${token}` };
|
|
74
|
+
},
|
|
70
75
|
onMessage: (e) => console.log(e.parsedData ?? e.data),
|
|
71
76
|
onError: (e) => console.error(e.message),
|
|
72
77
|
// Strongly-typed named event types ('event: <name>')
|
|
@@ -89,7 +94,7 @@ export function EventStream() {
|
|
|
89
94
|
|
|
90
95
|
#### `UseNitroSseOptions`
|
|
91
96
|
|
|
92
|
-
Inherits all [`
|
|
97
|
+
Inherits all [`SseClientOptions`](#configuration-reference-sseclientoptions) options plus:
|
|
93
98
|
|
|
94
99
|
| Option | Type | Default | Description |
|
|
95
100
|
| :-------------- | :----------------------------------------------------------------- | :------ | :------------------------------------------------------- |
|
|
@@ -141,6 +146,11 @@ sse.setup({
|
|
|
141
146
|
url: 'https://api.example.com/events',
|
|
142
147
|
headers: { Authorization: 'Bearer TOKEN' },
|
|
143
148
|
autoParseJSON: true,
|
|
149
|
+
// Dynamic header refresh for initial connection and auto-reconnects
|
|
150
|
+
onBeforeRequest: async () => {
|
|
151
|
+
const token = await getFreshAuthToken();
|
|
152
|
+
return { Authorization: `Bearer ${token}` };
|
|
153
|
+
},
|
|
144
154
|
});
|
|
145
155
|
|
|
146
156
|
// Event listeners
|
|
@@ -160,30 +170,33 @@ sse.start();
|
|
|
160
170
|
## API & Configuration
|
|
161
171
|
|
|
162
172
|
<details>
|
|
163
|
-
<summary><b>Configuration Reference (<code>
|
|
173
|
+
<summary><b>Configuration Reference (<code>SseClientOptions</code>)</b></summary>
|
|
164
174
|
|
|
175
|
+
<a id="configuration-reference-sseclientoptions"></a>
|
|
165
176
|
<a id="configuration-reference-sseconfig"></a>
|
|
166
177
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
|
170
|
-
|
|
|
171
|
-
| `
|
|
172
|
-
| `
|
|
173
|
-
| `
|
|
174
|
-
| `
|
|
175
|
-
| `
|
|
176
|
-
| `
|
|
177
|
-
| `
|
|
178
|
-
| `
|
|
179
|
-
| `
|
|
180
|
-
| `
|
|
181
|
-
| `
|
|
182
|
-
| `
|
|
178
|
+
`SseClientOptions` is the configuration object accepted by `setup()` and `useNitroSse()`. It extends the native data struct `SseConfig` with dynamic client interceptors:
|
|
179
|
+
|
|
180
|
+
| Parameter | Type | Default | Description |
|
|
181
|
+
| :--------------------- | :-------------------------------------- | :------- | :------------------------------------------------------------------------------------------------- |
|
|
182
|
+
| `url` | `string` | — | **Required**. Target SSE endpoint URL. |
|
|
183
|
+
| `method` | `'get' \| 'post'` | `'get'` | HTTP method. |
|
|
184
|
+
| `headers` | `Record<string, string>` | `{}` | Request headers. |
|
|
185
|
+
| `body` | `string` | — | Body for POST requests. |
|
|
186
|
+
| `backgroundExecution` | `boolean` | `false` | (iOS) Continues streaming while app is in background. |
|
|
187
|
+
| `batchingIntervalMs` | `number` | `0` | Batching delay in ms (`0` dispatches immediately). |
|
|
188
|
+
| `maxBufferSize` | `number` | `1000` | Max buffer size before forcing event dispatch. |
|
|
189
|
+
| `connectionTimeoutMs` | `number` | `15000` | Socket connection timeout in ms. |
|
|
190
|
+
| `readTimeoutMs` | `number` | `300000` | Inactivity timeout in ms before reconnecting. |
|
|
191
|
+
| `retryIntervalMs` | `number` | `1000` | Base reconnect delay in ms. |
|
|
192
|
+
| `maxRetryIntervalMs` | `number` | `30000` | Maximum exponential backoff delay in ms. |
|
|
193
|
+
| `jitterFactor` | `number` | `0.5` | Jitter factor applied to reconnect delay (`0.0` to `1.0`). |
|
|
194
|
+
| `maxReconnectAttempts` | `number` | `-1` | Max reconnect retries (`-1` = infinite, `0` = disabled). |
|
|
195
|
+
| `maxAuthRetries` | `number` | `3` | Max retry attempts for 401/403 responses using `onBeforeRequest`. |
|
|
183
196
|
| `autoParseJSON` | `boolean` | `false` | Parses JSON root objects (`'{...}'`) into `parsedData`. If `false`, use `data` and parse manually. |
|
|
184
|
-
| `monitorNetwork` | `boolean` | `true` | Automatically pauses/resumes on network changes.
|
|
185
|
-
| `onBeforeRequest` | `() => Promise<Record<string, string>>` | — | Async hook to refresh headers prior to connection attempts.
|
|
186
|
-
| `mock` | `SseMockConfig` | — | Mock stream configuration (development only).
|
|
197
|
+
| `monitorNetwork` | `boolean` | `true` | Automatically pauses/resumes on network changes. |
|
|
198
|
+
| `onBeforeRequest` | `() => Promise<Record<string, string>>` | — | Async hook to refresh headers prior to connection attempts. |
|
|
199
|
+
| `mock` | `SseMockConfig` | — | Mock stream configuration (development only). |
|
|
187
200
|
|
|
188
201
|
</details>
|
|
189
202
|
|
|
@@ -196,13 +209,13 @@ sse.start();
|
|
|
196
209
|
- **`flush()`**: Flushes pending events in the buffer immediately.
|
|
197
210
|
- **`isConnected()`**: Returns boolean indicating if connection is active (`connecting`, `open`, `reconnecting`).
|
|
198
211
|
- **`getState()`**: Returns current `SseState`.
|
|
199
|
-
- **`getStats()`**: Returns connection metrics (`totalBytesReceived`, `reconnectCount`, `lastErrorTime`, `lastErrorCode`).
|
|
212
|
+
- **`getStats()`**: Returns comprehensive connection metrics across transport (`rawBytesReceived`, `decompressedBytesReceived`, `totalBytesReceived`, `chunksReceived`, `lastStatusCode`), parser (`totalEventsReceived`, `commentsReceived`, `linesParsed`, `parseErrors`, `serverRetryDelayMs`), latency (`connectedAt`, `timeToFirstByteMs`, `lastEventTime`, `lastHeartbeatTime`, `maxEventGapMs`), buffer (`eventsBuffered`, `peakBufferedEvents`, `bufferFlushCount`, `bufferOverflowCount`), and diagnostics/lifecycle (`connectionAttempts`, `reconnectCount`, `lastReconnectDelayMs`, `disconnectReason`, `lastErrorTime`, `lastErrorCode`).
|
|
200
213
|
- **`updateHeaders(headers)`**: Merges new headers into current configuration without closing the connection.
|
|
201
214
|
- **`setLastProcessedId(id)`**: Sets the event ID to send in `Last-Event-ID` on subsequent reconnections.
|
|
202
215
|
- **`addEventListener(type, listener)`**: Subscribes to an event type (`'message'`, `'open'`, `'close'`, `'error'`, `'heartbeat'`, `'state'`, or custom event name).
|
|
203
216
|
- **`removeEventListener(type, listener)`**: Unsubscribes a specific listener.
|
|
204
217
|
- **`removeAllEventListeners(type?)`**: Unregisters all listeners (or listeners for a given event type).
|
|
205
|
-
- **`dispose()`**: Closes connection and releases native resources.
|
|
218
|
+
- **`dispose()`**: Closes connection and releases native resources. Idempotent and safe to call multiple times.
|
|
206
219
|
|
|
207
220
|
</details>
|
|
208
221
|
|
|
@@ -238,6 +251,10 @@ try {
|
|
|
238
251
|
Development-only mock stream simulation:
|
|
239
252
|
|
|
240
253
|
```ts
|
|
254
|
+
import { createNitroSse } from 'react-native-nitro-sse';
|
|
255
|
+
|
|
256
|
+
const sse = createNitroSse();
|
|
257
|
+
|
|
241
258
|
sse.setup({
|
|
242
259
|
url: 'https://api.example.com/events',
|
|
243
260
|
mock: __DEV__
|
|
@@ -253,7 +270,10 @@ sse.setup({
|
|
|
253
270
|
: undefined,
|
|
254
271
|
});
|
|
255
272
|
|
|
256
|
-
|
|
273
|
+
sse.addEventListener('message', (e) => console.log('Message:', e.data));
|
|
274
|
+
sse.start();
|
|
275
|
+
|
|
276
|
+
// Programmatic event injection (development only)
|
|
257
277
|
sse.injectMockEvent({ type: 'message', data: 'Test' });
|
|
258
278
|
```
|
|
259
279
|
|
package/android/build.gradle
CHANGED
|
@@ -126,7 +126,6 @@ dependencies {
|
|
|
126
126
|
implementation "com.facebook.react:react-android"
|
|
127
127
|
implementation project(":react-native-nitro-modules")
|
|
128
128
|
implementation "com.squareup.okhttp3:okhttp:4.12.0"
|
|
129
|
-
implementation "com.squareup.okhttp3:okhttp-sse:4.12.0"
|
|
130
129
|
implementation "androidx.lifecycle:lifecycle-process:2.8.7"
|
|
131
130
|
|
|
132
131
|
testImplementation "junit:junit:4.13.2"
|
|
@@ -25,7 +25,7 @@ object JsonUtils {
|
|
|
25
25
|
if (depth > MAX_DEPTH) {
|
|
26
26
|
throw IllegalArgumentException("JSON nesting depth limit ($MAX_DEPTH) exceeded")
|
|
27
27
|
}
|
|
28
|
-
val map =
|
|
28
|
+
val map = HashMap<String, Any?>(jsonObject.length())
|
|
29
29
|
val keys = jsonObject.keys()
|
|
30
30
|
while (keys.hasNext()) {
|
|
31
31
|
val key = keys.next()
|
|
@@ -38,27 +38,50 @@ object JsonUtils {
|
|
|
38
38
|
if (depth > MAX_DEPTH) {
|
|
39
39
|
throw IllegalArgumentException("JSON nesting depth limit ($MAX_DEPTH) exceeded")
|
|
40
40
|
}
|
|
41
|
-
val list =
|
|
41
|
+
val list = ArrayList<Any?>(jsonArray.length())
|
|
42
42
|
for (i in 0 until jsonArray.length()) {
|
|
43
43
|
list.add(convertJsonValue(jsonArray.get(i), depth))
|
|
44
44
|
}
|
|
45
45
|
return list
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
+
/**
|
|
49
|
+
* Parses a raw JSON string into a [Map]. Returns null on non-object roots.
|
|
50
|
+
* Throws [org.json.JSONException] on malformed JSON objects.
|
|
51
|
+
*/
|
|
52
|
+
fun parseJsonToMap(data: String): Map<String, Any?>? {
|
|
53
|
+
val len = data.length
|
|
54
|
+
var firstChar = ' '
|
|
55
|
+
var idx = 0
|
|
56
|
+
var needsSubstring = false
|
|
57
|
+
while (idx < len) {
|
|
58
|
+
val c = data[idx]
|
|
59
|
+
if (c > ' ') {
|
|
60
|
+
if (c.isWhitespace()) {
|
|
61
|
+
needsSubstring = true
|
|
62
|
+
} else {
|
|
63
|
+
firstChar = c
|
|
64
|
+
break
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
idx++
|
|
68
|
+
}
|
|
69
|
+
if (firstChar != '{') {
|
|
70
|
+
return null
|
|
71
|
+
}
|
|
72
|
+
val jsonStr = if (needsSubstring) data.substring(idx) else data
|
|
73
|
+
val jsonObject = JSONObject(jsonStr)
|
|
74
|
+
return jsonObjectToMap(jsonObject)
|
|
75
|
+
}
|
|
76
|
+
|
|
48
77
|
/**
|
|
49
78
|
* Parses a raw JSON string into [AnyMap]. Returns null on malformed JSON or non-object roots
|
|
50
79
|
* to prevent invalid SSE payloads from interrupting stream processing.
|
|
51
80
|
*/
|
|
52
81
|
fun parseJsonToAnyMap(data: String): AnyMap? {
|
|
53
82
|
return try {
|
|
54
|
-
val
|
|
55
|
-
|
|
56
|
-
val jsonObject = JSONObject(trimmed)
|
|
57
|
-
val map = jsonObjectToMap(jsonObject)
|
|
58
|
-
AnyMap.fromMap(map, true)
|
|
59
|
-
} else {
|
|
60
|
-
null
|
|
61
|
-
}
|
|
83
|
+
val map = parseJsonToMap(data) ?: return null
|
|
84
|
+
AnyMap.fromMap(map, true)
|
|
62
85
|
} catch (t: Throwable) {
|
|
63
86
|
try {
|
|
64
87
|
Log.w("JsonUtils", "Failed to parse JSON: ${t.message}")
|