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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +209 -95
  2. package/android/src/main/java/com/margelo/nitro/nitrosse/AndroidSseDispatcher.kt +5 -0
  3. package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +11 -18
  4. package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +79 -38
  5. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +194 -100
  6. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +40 -15
  7. package/android/src/main/java/com/margelo/nitro/nitrosse/SseDispatcher.kt +1 -0
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +34 -28
  9. package/android/src/main/java/com/margelo/nitro/nitrosse/SseLifecycleManager.kt +8 -1
  10. package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +7 -4
  11. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +6 -4
  12. package/ios/NitroSse.swift +244 -190
  13. package/ios/SseConfig+CopyWith.swift +2 -1
  14. package/ios/SseConnectionHandler.swift +59 -29
  15. package/ios/SseDispatchQueueDispatcher.swift +15 -2
  16. package/ios/SseDispatcher.swift +7 -1
  17. package/ios/SseEventBuffer.swift +23 -7
  18. package/ios/SseLifecycleManager.swift +10 -1
  19. package/ios/SseNetworkMonitor.swift +8 -2
  20. package/ios/SseReconnectStrategy.swift +9 -3
  21. package/lib/module/MockSseEngine.js +203 -0
  22. package/lib/module/NitroSseClient.js +411 -214
  23. package/lib/module/NitroSseError.js +61 -0
  24. package/lib/module/SseDriver.js +156 -0
  25. package/lib/module/index.js +6 -3
  26. package/lib/module/useNitroSse.js +359 -0
  27. package/lib/typescript/src/MockSseEngine.d.ts +31 -0
  28. package/lib/typescript/src/NitroSse.nitro.d.ts +25 -2
  29. package/lib/typescript/src/NitroSseClient.d.ts +25 -7
  30. package/lib/typescript/src/NitroSseError.d.ts +38 -0
  31. package/lib/typescript/src/SseDriver.d.ts +80 -0
  32. package/lib/typescript/src/SseInterface.d.ts +25 -7
  33. package/lib/typescript/src/index.d.ts +4 -2
  34. package/lib/typescript/src/useNitroSse.d.ts +69 -0
  35. package/nitrogen/generated/android/c++/JSseConfig.hpp +7 -1
  36. package/nitrogen/generated/android/c++/JSseMockConfig.hpp +2 -0
  37. package/nitrogen/generated/android/c++/JSseMockEvent.hpp +9 -3
  38. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +9 -4
  39. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockEvent.kt +9 -4
  40. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +15 -15
  41. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +3 -3
  42. package/nitrogen/generated/ios/swift/SseConfig.swift +19 -1
  43. package/nitrogen/generated/ios/swift/SseMockEvent.swift +12 -1
  44. package/nitrogen/generated/shared/c++/SseConfig.hpp +5 -1
  45. package/nitrogen/generated/shared/c++/SseMockEvent.hpp +9 -2
  46. package/package.json +10 -11
  47. package/android/jacoco.gradle +0 -33
  48. package/lib/module/NitroSse.nitro.js.map +0 -1
  49. package/lib/module/NitroSseClient.js.map +0 -1
  50. package/lib/module/SseInterface.js.map +0 -1
  51. package/lib/module/index.js.map +0 -1
  52. package/lib/typescript/src/NitroSse.nitro.d.ts.map +0 -1
  53. package/lib/typescript/src/NitroSseClient.d.ts.map +0 -1
  54. package/lib/typescript/src/SseInterface.d.ts.map +0 -1
  55. package/lib/typescript/src/index.d.ts.map +0 -1
  56. package/src/NitroSse.nitro.ts +0 -58
  57. package/src/NitroSseClient.ts +0 -337
  58. package/src/SseInterface.ts +0 -272
  59. package/src/index.ts +0 -31
package/README.md CHANGED
@@ -1,152 +1,266 @@
1
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 apps requiring high-throughput streaming, battery optimization, and extreme stability.
3
+ Server-Sent Events (SSE) client for React Native built on Nitro Modules (JSI).
4
4
 
5
5
  ---
6
6
 
7
- ## Why NitroSSE?
7
+ ## Features
8
8
 
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:
10
-
11
- * **Zero-Latency JSI**: Instantaneous JS-Native communication bypassing the async bridge.
12
- * **Advanced Backpressure**: Batches high-frequency events and automatically flushes when the buffer is full to prevent memory pressure, keeping the 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.
9
+ - **JSI Execution**: Direct synchronous JS-to-native calls via Nitro Modules.
10
+ - **Reconnection**: Exponential backoff with jitter and HTTP 429 (`Retry-After`) handling.
11
+ - **Event Batching**: Configurable batch interval and buffer size limits.
12
+ - **Lifecycle & Network**: Automatic pause and resume on app state or network transitions.
13
+ - **Heartbeat Detection**: Inactive connection detection via SSE comment pings (`:`).
14
+ - **Diagnostics**: Network inspection via DevTools and local stream simulation in development.
18
15
 
19
16
  ---
20
17
 
21
18
  ## Installation
22
19
 
23
20
  ```sh
24
- yarn add react-native-nitro-sse react-native-nitro-modules
25
- # or
26
21
  npm install react-native-nitro-sse react-native-nitro-modules
22
+ # or
23
+ yarn add react-native-nitro-sse react-native-nitro-modules
27
24
  ```
28
25
 
29
- > [!NOTE]
30
- > `react-native-nitro-modules` is a peer dependency and must be installed in the host project.
26
+ > **Note**: `react-native-nitro-modules` is a peer dependency.
31
27
 
32
- ---
33
-
34
- ## Compatibility
28
+ <details>
29
+ <summary><b>Compatibility Matrix</b></summary>
35
30
 
36
31
  | react-native-nitro-sse | react-native-nitro-modules |
37
32
  | :--------------------- | :------------------------- |
38
- | **2.3.1 - latest** | **0.35.9** |
39
- | **2.3.0** | **0.35.6** |
33
+ | **3.0.0+** | **0.37.1** |
34
+ | **2.3.0 - 2.4.2** | **0.35.9** |
40
35
  | **2.2.0 - 2.2.3** | **0.35.4** |
41
36
  | **2.0.0 - 2.1.1** | **0.35.2** |
42
- | **1.6.2** | **0.35.2** |
43
- | **1.4.0 - 1.6.1** | **0.35.0** |
44
- | **1.2.2 - 1.3.1** | **0.34.1** |
45
- | **1.2.0 - 1.2.1** | **0.34.0** |
46
- | **1.1.0** | **0.33.9** |
47
- | **1.0.0** | **0.33.8** |
37
+ | **1.0.0 - 1.6.2** | **0.34.1 - 0.35.2** |
38
+
39
+ </details>
48
40
 
49
41
  ---
50
42
 
51
43
  ## Usage
52
44
 
45
+ | Approach | Primary Use Case | Lifecycle |
46
+ | :------------------- | :--------------------------------------------------- | :--------------------------------------------- |
47
+ | **`useNitroSse`** | React components & UI views | Automatic (bound to component mount/unmount) |
48
+ | **`createNitroSse`** | Stores (Zustand/Redux), background tasks, singletons | Explicit (`setup`, `start`, `stop`, `dispose`) |
49
+
50
+ ---
51
+
52
+ ### 1. Declarative Hook (`useNitroSse`)
53
+
54
+ Used inside React functional components. Binds the stream to the component lifecycle.
55
+
53
56
  ```tsx
57
+ import { Text } from 'react-native';
58
+ import { useNitroSse } from 'react-native-nitro-sse';
59
+
60
+ interface StreamEvents {
61
+ user_joined: { userId: string; username: string };
62
+ price_update: { symbol: string; price: number };
63
+ }
64
+
65
+ export function EventStream() {
66
+ const { state, isConnected } = useNitroSse<StreamEvents>({
67
+ url: 'https://api.example.com/events',
68
+ headers: { Authorization: 'Bearer TOKEN' },
69
+ autoParseJSON: true,
70
+ onMessage: (e) => console.log(e.parsedData ?? e.data),
71
+ onError: (e) => console.error(e.message),
72
+ // Strongly-typed named event types ('event: <name>')
73
+ events: {
74
+ user_joined: (e) => console.log('User joined:', e.parsedData?.username),
75
+ price_update: (e) => console.log('Price update:', e.parsedData?.price),
76
+ },
77
+ });
78
+
79
+ return (
80
+ <Text>
81
+ Status: {state} ({isConnected ? 'Connected' : 'Disconnected'})
82
+ </Text>
83
+ );
84
+ }
85
+ ```
86
+
87
+ <details>
88
+ <summary><b><code>useNitroSse</code> Options & Return Values</b></summary>
89
+
90
+ #### `UseNitroSseOptions`
91
+
92
+ Inherits all [`SseConfig`](#configuration-reference-sseconfig) options plus:
93
+
94
+ | Option | Type | Default | Description |
95
+ | :-------------- | :----------------------------------------------------------------- | :------ | :------------------------------------------------------- |
96
+ | `autoStart` | `boolean` | `true` | Starts streaming on mount or when URL changes. |
97
+ | `events` | `{ [K in keyof TEvents]?: (event: SseEvent<TEvents[K]>) => void }` | — | Strongly-typed handlers for specific custom event types. |
98
+ | `onMessage` | `(event: SseEvent) => void` | — | Handler for message events. |
99
+ | `onError` | `(event: SseEvent) => void` | — | Handler for transport or connection errors. |
100
+ | `onOpen` | `(event: SseEvent) => void` | — | Handler for stream open events. |
101
+ | `onClose` | `(event: SseEvent) => void` | — | Handler for stream close events. |
102
+ | `onHeartbeat` | `(event: SseEvent) => void` | — | Handler for heartbeat ping comments (`:`). |
103
+ | `onStateChange` | `(state: SseState) => void` | — | Handler for connection state transitions. |
104
+
105
+ #### `UseNitroSseReturn`
106
+
107
+ | Property | Type | Description |
108
+ | :----------------------- | :------------------------------------------ | :-------------------------------------------------------------------------------------------------- |
109
+ | `client` | `SseClient \| null` | Native client instance (`null` before initialization). |
110
+ | `isReady` | `boolean` | True after initial mount and client initialization. |
111
+ | `state` | `SseState` | `'idle' \| 'connecting' \| 'open' \| 'reconnecting' \| 'paused' \| 'stale' \| 'closed' \| 'failed'` |
112
+ | `isConnected` | `boolean` | True when connection is active. |
113
+ | `start()` | `() => void` | Starts the stream. |
114
+ | `stop()` | `() => void` | Stops the stream. |
115
+ | `restart()` | `() => void` | Restarts connection handshake. |
116
+ | `flush()` | `() => void` | Immediately flushes buffered events. |
117
+ | `updateHeaders(headers)` | `(headers: Record<string, string>) => void` | Updates headers without reconnecting. |
118
+ | `setLastProcessedId(id)` | `(id: string) => void` | Updates event ID used for `Last-Event-ID` on reconnect. |
119
+ | `getStats()` | `() => SseStats \| undefined` | Returns connection metrics. |
120
+ | `injectMockEvent(event)` | `(event: Partial<SseEvent>) => void` | Injects a mock event (development only). |
121
+
122
+ </details>
123
+
124
+ ---
125
+
126
+ ### 2. Imperative Client (`createNitroSse`)
127
+
128
+ Used outside React component lifecycles:
129
+
130
+ - State management stores (Zustand, Redux, ...).
131
+ - Persistent connections spanning across screen navigation.
132
+ - Background and headless tasks (React Native Headless JS, background sync).
133
+ - Dedicated service classes or singleton modules.
134
+
135
+ ```ts
54
136
  import { createNitroSse } from 'react-native-nitro-sse';
55
137
 
56
138
  const sse = createNitroSse();
57
139
 
58
140
  sse.setup({
59
- url: 'https://api.example.com/stream',
60
- headers: { 'Authorization': 'Bearer TOKEN' }
141
+ url: 'https://api.example.com/events',
142
+ headers: { Authorization: 'Bearer TOKEN' },
143
+ autoParseJSON: true,
61
144
  });
62
145
 
63
- // Listen to events
64
- sse.addEventListener('message', (e) => console.log('Received:', e.data));
65
- sse.addEventListener('error', (e) => console.error('Error:', e.message));
146
+ // Event listeners
147
+ sse.addEventListener('message', (e) => console.log(e.parsedData ?? e.data));
148
+ sse.addEventListener('user_joined', (e) => console.log('Joined:', e.data));
149
+ sse.addEventListener('error', (e) => console.error(e.message));
66
150
 
67
- // Start streaming
151
+ // Connection controls
68
152
  sse.start();
69
153
 
70
- // Cleanup when done
71
- // sse.stop();
154
+ // Disposal
155
+ // sse.dispose();
72
156
  ```
73
157
 
74
158
  ---
75
159
 
76
- ## Configuration Reference (`SseConfig`)
77
-
78
- | Parameter | Type | Default | Description |
79
- | :--- | :--- | :--- | :--- |
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). |
160
+ ## API & Configuration
161
+
162
+ <details>
163
+ <summary><b>Configuration Reference (<code>SseConfig</code>)</b></summary>
164
+
165
+ <a id="configuration-reference-sseconfig"></a>
166
+
167
+ | Parameter | Type | Default | Description |
168
+ | :--------------------- | :-------------------------------------- | :------- | :-------------------------------------------------------------------- |
169
+ | `url` | `string` | — | **Required**. Target SSE endpoint URL. |
170
+ | `method` | `'get' \| 'post'` | `'get'` | HTTP method. |
171
+ | `headers` | `Record<string, string>` | `{}` | Request headers. |
172
+ | `body` | `string` | — | Body for POST requests. |
173
+ | `backgroundExecution` | `boolean` | `false` | (iOS) Continues streaming while app is in background. |
174
+ | `batchingIntervalMs` | `number` | `0` | Batching delay in ms (`0` dispatches immediately). |
175
+ | `maxBufferSize` | `number` | `1000` | Max buffer size before forcing event dispatch. |
176
+ | `connectionTimeoutMs` | `number` | `15000` | Socket connection timeout in ms. |
177
+ | `readTimeoutMs` | `number` | `300000` | Inactivity timeout in ms before reconnecting. |
178
+ | `retryIntervalMs` | `number` | `1000` | Base reconnect delay in ms. |
179
+ | `maxRetryIntervalMs` | `number` | `30000` | Maximum exponential backoff delay in ms. |
180
+ | `jitterFactor` | `number` | `0.5` | Jitter factor applied to reconnect delay (`0.0` to `1.0`). |
181
+ | `maxReconnectAttempts` | `number` | `-1` | Max reconnect retries (`-1` = infinite, `0` = disabled). |
182
+ | `maxAuthRetries` | `number` | `3` | Max retry attempts for 401/403 responses using `onBeforeRequest`. |
183
+ | `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). |
187
+
188
+ </details>
189
+
190
+ <details>
191
+ <summary><b>Client Methods Reference (<code>SseClient</code>)</b></summary>
192
+
193
+ - **`start()`**: Initiates the connection. If called during reconnection backoff, immediately retries.
194
+ - **`stop()`**: Disconnects the stream without disposing the instance.
195
+ - **`restart()`**: Reconnects with a fresh connection handshake.
196
+ - **`flush()`**: Flushes pending events in the buffer immediately.
197
+ - **`isConnected()`**: Returns boolean indicating if connection is active (`connecting`, `open`, `reconnecting`).
198
+ - **`getState()`**: Returns current `SseState`.
199
+ - **`getStats()`**: Returns connection metrics (`totalBytesReceived`, `reconnectCount`, `lastErrorTime`, `lastErrorCode`).
200
+ - **`updateHeaders(headers)`**: Merges new headers into current configuration without closing the connection.
201
+ - **`setLastProcessedId(id)`**: Sets the event ID to send in `Last-Event-ID` on subsequent reconnections.
202
+ - **`addEventListener(type, listener)`**: Subscribes to an event type (`'message'`, `'open'`, `'close'`, `'error'`, `'heartbeat'`, `'state'`, or custom event name).
203
+ - **`removeEventListener(type, listener)`**: Unsubscribes a specific listener.
204
+ - **`removeAllEventListeners(type?)`**: Unregisters all listeners (or listeners for a given event type).
205
+ - **`dispose()`**: Closes connection and releases native resources. Subsequent calls throw `NitroSseDisposedError`.
206
+
207
+ </details>
208
+
209
+ <details>
210
+ <summary><b>Error Handling (<code>NitroSseError</code>)</b></summary>
211
+
212
+ Errors thrown by the library inherit from `NitroSseError`:
213
+
214
+ ```ts
215
+ import { NitroSseError } from 'react-native-nitro-sse';
216
+
217
+ try {
218
+ // ...
219
+ } catch (err) {
220
+ if (err instanceof NitroSseError) {
221
+ console.error(`[${err.code}] ${err.message}`, err.details);
222
+ }
223
+ }
224
+ ```
97
225
 
98
- ---
226
+ | Error Class | Error Code | Description |
227
+ | :---------------------------- | :------------------------------------- | :-------------------------------------------------------------------- |
228
+ | `NitroSseModuleNotFoundError` | `NATIVE_MODULE_NOT_FOUND` | Native Nitro module binary is missing. |
229
+ | `NitroSseValidationError` | `INVALID_CONFIG` \| `INVALID_ARGUMENT` | Invalid argument or configuration parameter. |
230
+ | `NitroSseStateError` | `INVALID_STATE` | Method invoked in an invalid state (e.g. `start()` before `setup()`). |
231
+ | `NitroSseDisposedError` | `CLIENT_DISPOSED` | Method invoked on an already disposed client instance. |
99
232
 
100
- ## Mocking & Testing System (`v2.3.0+`)
233
+ </details>
101
234
 
102
- NitroSSE includes a built-in mock streaming engine to test application responses without running live endpoints. Mocks are automatically disabled in production configurations.
235
+ <details>
236
+ <summary><b>Mocking & Testing (Development Only)</b></summary>
103
237
 
104
- ### Configuration (`SseMockConfig`)
238
+ Development-only mock stream simulation:
105
239
 
106
- ```tsx
240
+ ```ts
107
241
  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
- }
242
+ url: 'https://api.example.com/events',
243
+ mock: __DEV__
244
+ ? {
245
+ mode: 'replace', // 'replace' = local mock, 'inject' = server + mocks
246
+ loop: true,
247
+ data: [
248
+ { type: 'open', statusCode: 200 },
249
+ { type: 'message', data: 'Hello' },
250
+ { event: 'status', data: '{"ok":true}', delayMs: 500 },
251
+ ],
252
+ }
253
+ : undefined,
121
254
  });
122
- ```
123
255
 
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
- });
256
+ // Programmatic event injection
257
+ sse.injectMockEvent({ type: 'message', data: 'Test' });
133
258
  ```
134
259
 
135
- ---
136
-
137
- ## Advanced Operations
138
-
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`.
260
+ </details>
143
261
 
144
262
  ---
145
263
 
146
264
  ## License
147
265
 
148
266
  MIT
149
-
150
- ---
151
-
152
- *Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)*
@@ -1,6 +1,7 @@
1
1
  package com.margelo.nitro.nitrosse
2
2
 
3
3
  import android.os.Handler
4
+ import android.os.Looper
4
5
 
5
6
  /**
6
7
  * Android implementation of [SseDispatcher] delegating execution to an [android.os.Handler].
@@ -24,4 +25,8 @@ class AndroidSseDispatcher(private val handler: Handler) : SseDispatcher {
24
25
  override fun removeCallbacksAndMessages(token: Any?) {
25
26
  handler.removeCallbacksAndMessages(token)
26
27
  }
28
+
29
+ override fun isCurrentDispatcher(): Boolean {
30
+ return Looper.myLooper() == handler.looper
31
+ }
27
32
  }
@@ -12,6 +12,15 @@ import org.json.JSONObject
12
12
  object JsonUtils {
13
13
  private const val MAX_DEPTH = 500
14
14
 
15
+ private fun convertJsonValue(value: Any?, depth: Int): Any? {
16
+ return when (value) {
17
+ is JSONObject -> jsonObjectToMap(value, depth + 1)
18
+ is JSONArray -> jsonArrayToList(value, depth + 1)
19
+ JSONObject.NULL -> null
20
+ else -> value
21
+ }
22
+ }
23
+
15
24
  fun jsonObjectToMap(jsonObject: JSONObject, depth: Int = 0): Map<String, Any?> {
16
25
  if (depth > MAX_DEPTH) {
17
26
  throw IllegalArgumentException("JSON nesting depth limit ($MAX_DEPTH) exceeded")
@@ -20,15 +29,7 @@ object JsonUtils {
20
29
  val keys = jsonObject.keys()
21
30
  while (keys.hasNext()) {
22
31
  val key = keys.next()
23
- var value: Any? = jsonObject.get(key)
24
- if (value is JSONObject) {
25
- value = jsonObjectToMap(value, depth + 1)
26
- } else if (value is JSONArray) {
27
- value = jsonArrayToList(value, depth + 1)
28
- } else if (value == JSONObject.NULL) {
29
- value = null
30
- }
31
- map[key] = value
32
+ map[key] = convertJsonValue(jsonObject.get(key), depth)
32
33
  }
33
34
  return map
34
35
  }
@@ -39,15 +40,7 @@ object JsonUtils {
39
40
  }
40
41
  val list = mutableListOf<Any?>()
41
42
  for (i in 0 until jsonArray.length()) {
42
- var value: Any? = jsonArray.get(i)
43
- if (value is JSONObject) {
44
- value = jsonObjectToMap(value, depth + 1)
45
- } else if (value is JSONArray) {
46
- value = jsonArrayToList(value, depth + 1)
47
- } else if (value == JSONObject.NULL) {
48
- value = null
49
- }
50
- list.add(value)
43
+ list.add(convertJsonValue(jsonArray.get(i), depth))
51
44
  }
52
45
  return list
53
46
  }
@@ -3,7 +3,8 @@ package com.margelo.nitro.nitrosse
3
3
  import android.util.Log
4
4
  import okhttp3.Request
5
5
  import okhttp3.Response
6
- import java.util.UUID
6
+ import okio.Buffer
7
+ import java.lang.reflect.Method
7
8
 
8
9
  /**
9
10
  * Reports SSE connection events to the React Native DevTools Network inspector.
@@ -14,82 +15,122 @@ import java.util.UUID
14
15
  */
15
16
  object NetworkInspector {
16
17
  private const val TAG = "NitroSseNetworkInspector"
17
- private var reporterClass: Class<*>? = null
18
- private var isEnabledCached: Boolean = false
18
+
19
+ private val isDebuggingEnabledMethod: Method?
20
+ private val reportRequestStartMethod: Method?
21
+ private val reportResponseStartMethod: Method?
22
+ private val reportResponseEndMethod: Method?
23
+ private val reportRequestFailedMethod: Method?
19
24
 
20
25
  init {
26
+ var isDebugging: Method? = null
27
+ var reqStart: Method? = null
28
+ var resStart: Method? = null
29
+ var resEnd: Method? = null
30
+ var reqFailed: Method? = null
31
+
21
32
  try {
22
- reporterClass = Class.forName("com.facebook.react.modules.network.InspectorNetworkReporter")
33
+ val clazz = Class.forName("com.facebook.react.modules.network.InspectorNetworkReporter")
34
+ isDebugging = clazz.getDeclaredMethod("isDebuggingEnabled")
35
+ reqStart = clazz.getDeclaredMethod(
36
+ "reportRequestStart",
37
+ String::class.java,
38
+ String::class.java,
39
+ String::class.java,
40
+ Map::class.java,
41
+ String::class.java,
42
+ Long::class.javaPrimitiveType
43
+ )
44
+ resStart = clazz.getDeclaredMethod(
45
+ "reportResponseStart",
46
+ String::class.java,
47
+ String::class.java,
48
+ Int::class.javaPrimitiveType,
49
+ Map::class.java,
50
+ Long::class.javaPrimitiveType
51
+ )
52
+ resEnd = clazz.getDeclaredMethod(
53
+ "reportResponseEnd",
54
+ String::class.java,
55
+ Long::class.javaPrimitiveType
56
+ )
57
+ reqFailed = clazz.getDeclaredMethod(
58
+ "reportRequestFailed",
59
+ String::class.java,
60
+ Boolean::class.javaPrimitiveType
61
+ )
23
62
  Log.d(TAG, "InspectorNetworkReporter found. Network tracing is available.")
24
- } catch (e: Exception) {
63
+ } catch (_: Throwable) {
25
64
  Log.d(TAG, "InspectorNetworkReporter not found. Network tracing is disabled.")
26
65
  }
66
+
67
+ isDebuggingEnabledMethod = isDebugging
68
+ reportRequestStartMethod = reqStart
69
+ reportResponseStartMethod = resStart
70
+ reportResponseEndMethod = resEnd
71
+ reportRequestFailedMethod = reqFailed
27
72
  }
28
73
 
29
74
  private fun isEnabled(): Boolean {
30
- if (reporterClass == null) return false
31
75
  return try {
32
- val method = reporterClass?.getDeclaredMethod("isDebuggingEnabled")
33
- method?.invoke(null) as? Boolean ?: false
34
- } catch (e: Exception) {
76
+ isDebuggingEnabledMethod?.invoke(null) as? Boolean == true
77
+ } catch (_: Throwable) {
35
78
  false
36
79
  }
37
80
  }
38
81
 
39
82
  fun reportRequestStart(requestId: String, request: Request) {
40
- if (reporterClass == null || !isEnabled()) return
83
+ if (!isEnabled()) return
41
84
  try {
42
- val method = reporterClass?.getDeclaredMethod(
43
- "reportRequestStart",
44
- String::class.java,
45
- String::class.java,
46
- String::class.java,
47
- Map::class.java,
48
- String::class.java,
49
- Long::class.javaPrimitiveType
85
+ val body = request.body?.let {
86
+ val buffer = Buffer()
87
+ it.writeTo(buffer)
88
+ buffer.readUtf8()
89
+ } ?: ""
90
+
91
+ reportRequestStartMethod?.invoke(
92
+ null,
93
+ requestId,
94
+ request.url.toString(),
95
+ request.method,
96
+ request.headers.toMap(),
97
+ body,
98
+ 0L
50
99
  )
51
- val headers = request.headers.toMap()
52
- // SSE connection requests do not send request bodies; passing empty body minimizes DevTools memory overhead
53
- val body = ""
54
- method?.invoke(null, requestId, request.url.toString(), request.method, headers, body, 0L)
55
100
  } catch (e: Exception) {
56
101
  Log.e(TAG, "Error reporting request start", e)
57
102
  }
58
103
  }
59
104
 
60
105
  fun reportResponseStart(requestId: String, request: Request, response: Response) {
61
- if (reporterClass == null || !isEnabled()) return
106
+ if (!isEnabled()) return
62
107
  try {
63
- val method = reporterClass?.getDeclaredMethod(
64
- "reportResponseStart",
65
- String::class.java,
66
- String::class.java,
67
- Int::class.javaPrimitiveType,
68
- Map::class.java,
69
- Long::class.javaPrimitiveType
108
+ reportResponseStartMethod?.invoke(
109
+ null,
110
+ requestId,
111
+ request.url.toString(),
112
+ response.code,
113
+ response.headers.toMap(),
114
+ -1L
70
115
  )
71
- val headers = response.headers.toMap()
72
- method?.invoke(null, requestId, request.url.toString(), response.code, headers, -1L)
73
116
  } catch (e: Exception) {
74
117
  Log.e(TAG, "Error reporting response start", e)
75
118
  }
76
119
  }
77
120
 
78
121
  fun reportResponseEnd(requestId: String, totalBytes: Long) {
79
- if (reporterClass == null || !isEnabled()) return
122
+ if (!isEnabled()) return
80
123
  try {
81
- val method = reporterClass?.getDeclaredMethod("reportResponseEnd", String::class.java, Long::class.javaPrimitiveType)
82
- method?.invoke(null, requestId, totalBytes)
124
+ reportResponseEndMethod?.invoke(null, requestId, totalBytes)
83
125
  } catch (e: Exception) {
84
126
  Log.e(TAG, "Error reporting response end", e)
85
127
  }
86
128
  }
87
129
 
88
130
  fun reportRequestFailed(requestId: String, cancelled: Boolean) {
89
- if (reporterClass == null || !isEnabled()) return
131
+ if (!isEnabled()) return
90
132
  try {
91
- val method = reporterClass?.getDeclaredMethod("reportRequestFailed", String::class.java, Boolean::class.javaPrimitiveType)
92
- method?.invoke(null, requestId, cancelled)
133
+ reportRequestFailedMethod?.invoke(null, requestId, cancelled)
93
134
  } catch (e: Exception) {
94
135
  Log.e(TAG, "Error reporting request failure", e)
95
136
  }