react-native-nitro-sse 2.3.1 → 2.4.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.
- package/README.md +91 -83
- package/android/build.gradle +11 -0
- package/android/jacoco.gradle +33 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/AndroidSseDispatcher.kt +27 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +66 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +6 -3
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +334 -644
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSsePackage.kt +4 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +108 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseDispatcher.kt +14 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +99 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseLifecycleManager.kt +52 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +81 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +80 -0
- package/ios/NitroSse.swift +448 -617
- package/ios/SseConfig+CopyWith.swift +46 -0
- package/ios/SseConnectionHandler.swift +113 -0
- package/ios/SseDispatchQueueDispatcher.swift +38 -0
- package/ios/SseDispatcher.swift +18 -0
- package/ios/SseEventBuffer.swift +75 -0
- package/ios/SseLifecycleManager.swift +118 -0
- package/ios/SseNetworkMonitor.swift +79 -0
- package/ios/SseReconnectStrategy.swift +76 -0
- package/lib/module/NitroSseClient.js +8 -1
- package/lib/module/NitroSseClient.js.map +1 -1
- package/lib/typescript/src/NitroSse.nitro.d.ts +5 -1
- package/lib/typescript/src/NitroSse.nitro.d.ts.map +1 -1
- package/lib/typescript/src/NitroSseClient.d.ts +2 -1
- package/lib/typescript/src/NitroSseClient.d.ts.map +1 -1
- package/lib/typescript/src/SseInterface.d.ts +10 -1
- package/lib/typescript/src/SseInterface.d.ts.map +1 -1
- package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +2 -0
- package/nitrogen/generated/android/c++/JHttpMethod.hpp +1 -1
- package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +9 -0
- package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +1 -0
- package/nitrogen/generated/android/c++/JSseConfig.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseEvent.hpp +10 -4
- package/nitrogen/generated/android/c++/JSseEventType.hpp +4 -1
- package/nitrogen/generated/android/c++/JSseMockConfig.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseMockEvent.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseMockMode.hpp +1 -1
- package/nitrogen/generated/android/c++/JSseState.hpp +76 -0
- package/nitrogen/generated/android/c++/JSseStats.hpp +1 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.kt +0 -2
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_void_std__vector_SseEvent_.kt +0 -2
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +6 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +9 -4
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEventType.kt +2 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseState.kt +29 -0
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +27 -0
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +3 -0
- package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +11 -0
- package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +1 -0
- package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +12 -0
- package/nitrogen/generated/ios/swift/SseEvent.swift +12 -1
- package/nitrogen/generated/ios/swift/SseEventType.swift +4 -0
- package/nitrogen/generated/ios/swift/SseState.swift +64 -0
- package/nitrogen/generated/shared/c++/HybridNitroSseSpec.cpp +1 -0
- package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +4 -0
- package/nitrogen/generated/shared/c++/SseEvent.hpp +9 -2
- package/nitrogen/generated/shared/c++/SseEventType.hpp +4 -0
- package/nitrogen/generated/shared/c++/SseState.hpp +100 -0
- package/package.json +4 -4
- package/src/NitroSse.nitro.ts +6 -1
- package/src/NitroSseClient.ts +9 -0
- package/src/SseInterface.ts +25 -1
package/README.md
CHANGED
|
@@ -1,23 +1,24 @@
|
|
|
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
|
|
3
|
+
High-performance Server-Sent Events (SSE) client for React Native, built on top of **Nitro Modules (JSI)**. Designed for mission-critical apps requiring high-throughput streaming, battery optimization, and extreme stability.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Why NitroSSE?
|
|
6
8
|
|
|
7
|
-
|
|
9
|
+
Traditional EventSource libraries run on the JS thread or use the legacy React Native Bridge. NitroSSE moves the entire control logic down to the native layer:
|
|
8
10
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
- **🛠️ Full Protocol Support**: Comprehensive support for GET/POST methods and dynamic header updates.
|
|
11
|
+
* **Zero-Latency JSI**: Instantaneous JS-Native communication bypassing the async bridge.
|
|
12
|
+
* **Advanced Backpressure**: Batches high-frequency events and 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.
|
|
17
18
|
|
|
18
19
|
---
|
|
19
20
|
|
|
20
|
-
##
|
|
21
|
+
## Installation
|
|
21
22
|
|
|
22
23
|
```sh
|
|
23
24
|
yarn add react-native-nitro-sse react-native-nitro-modules
|
|
@@ -25,15 +26,18 @@ yarn add react-native-nitro-sse react-native-nitro-modules
|
|
|
25
26
|
npm install react-native-nitro-sse react-native-nitro-modules
|
|
26
27
|
```
|
|
27
28
|
|
|
28
|
-
>
|
|
29
|
+
> [!NOTE]
|
|
30
|
+
> `react-native-nitro-modules` is a peer dependency and must be installed in the host project.
|
|
29
31
|
|
|
30
32
|
---
|
|
31
33
|
|
|
32
|
-
##
|
|
34
|
+
## Compatibility
|
|
33
35
|
|
|
34
36
|
| react-native-nitro-sse | react-native-nitro-modules |
|
|
35
37
|
| :--------------------- | :------------------------- |
|
|
36
|
-
| **2.
|
|
38
|
+
| **2.3.1 - latest** | **0.35.9** |
|
|
39
|
+
| **2.3.0** | **0.35.6** |
|
|
40
|
+
| **2.2.0 - 2.2.3** | **0.35.4** |
|
|
37
41
|
| **2.0.0 - 2.1.1** | **0.35.2** |
|
|
38
42
|
| **1.6.2** | **0.35.2** |
|
|
39
43
|
| **1.4.0 - 1.6.1** | **0.35.0** |
|
|
@@ -42,103 +46,107 @@ npm install react-native-nitro-sse react-native-nitro-modules
|
|
|
42
46
|
| **1.1.0** | **0.33.9** |
|
|
43
47
|
| **1.0.0** | **0.33.8** |
|
|
44
48
|
|
|
45
|
-
|
|
46
49
|
---
|
|
47
50
|
|
|
48
|
-
##
|
|
49
|
-
|
|
50
|
-
### 1. Basic Initialization
|
|
51
|
-
|
|
52
|
-
Initialize the module with your endpoint configuration and an event listener.
|
|
51
|
+
## Usage
|
|
53
52
|
|
|
54
53
|
```tsx
|
|
55
54
|
import { createNitroSse } from 'react-native-nitro-sse';
|
|
56
55
|
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
nitroSse.setup(
|
|
60
|
-
{
|
|
61
|
-
url: 'https://api.yourserver.com/stream',
|
|
62
|
-
method: 'get',
|
|
63
|
-
headers: {
|
|
64
|
-
'Authorization': 'Bearer active-token',
|
|
65
|
-
},
|
|
66
|
-
// Batch messages every 100ms to optimize UI rendering
|
|
67
|
-
batchingIntervalMs: 100,
|
|
68
|
-
// Maximum of 1000 messages in the native queue before forced flush
|
|
69
|
-
maxBufferSize: 1000,
|
|
70
|
-
// Optional: Auto-refresh tokens or dynamic headers
|
|
71
|
-
onBeforeRequest: async () => {
|
|
72
|
-
const token = await fetchNewToken();
|
|
73
|
-
return { 'Authorization': `Bearer ${token}` };
|
|
74
|
-
}
|
|
75
|
-
},
|
|
76
|
-
(events) => {
|
|
77
|
-
// events is an array of SseEvent objects
|
|
78
|
-
events.forEach((event) => {
|
|
79
|
-
console.log('Received:', event);
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
);
|
|
56
|
+
const sse = createNitroSse();
|
|
83
57
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
58
|
+
sse.setup({
|
|
59
|
+
url: 'https://api.example.com/stream',
|
|
60
|
+
headers: { 'Authorization': 'Bearer TOKEN' }
|
|
61
|
+
});
|
|
87
62
|
|
|
88
|
-
|
|
63
|
+
// Listen to events
|
|
64
|
+
sse.addEventListener('message', (e) => console.log('Received:', e.data));
|
|
65
|
+
sse.addEventListener('error', (e) => console.error('Error:', e.message));
|
|
89
66
|
|
|
90
|
-
|
|
67
|
+
// Start streaming
|
|
68
|
+
sse.start();
|
|
91
69
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
console.log(`Downloaded: ${stats.totalBytesReceived / 1024} KB`);
|
|
95
|
-
console.log(`Reconnections: ${stats.reconnectCount}`);
|
|
70
|
+
// Cleanup when done
|
|
71
|
+
// sse.stop();
|
|
96
72
|
```
|
|
97
73
|
|
|
98
74
|
---
|
|
99
75
|
|
|
100
|
-
##
|
|
76
|
+
## Configuration Reference (`SseConfig`)
|
|
101
77
|
|
|
102
78
|
| Parameter | Type | Default | Description |
|
|
103
79
|
| :--- | :--- | :--- | :--- |
|
|
104
|
-
| `url` | `string` |
|
|
105
|
-
| `method` | `'get' \| 'post'` | `get` | HTTP method. |
|
|
106
|
-
| `headers` | `Record<string, string>` | `{}` | Custom
|
|
107
|
-
| `body` | `string` |
|
|
108
|
-
| `
|
|
109
|
-
| `
|
|
110
|
-
| `
|
|
111
|
-
| `
|
|
112
|
-
| `
|
|
113
|
-
| `
|
|
114
|
-
| `
|
|
115
|
-
| `
|
|
80
|
+
| `url` | `string` | — | **Required**. SSE endpoint target. |
|
|
81
|
+
| `method` | `'get' \| 'post'` | `'get'` | HTTP method. |
|
|
82
|
+
| `headers` | `Record<string, string>` | `{}` | Custom request headers. |
|
|
83
|
+
| `body` | `string` | — | Payload sent during POST requests. |
|
|
84
|
+
| `backgroundExecution` | `boolean` | `false` | (iOS) Keep background execution active when app is minimized. |
|
|
85
|
+
| `batchingIntervalMs` | `number` | `0` | Batch window (ms). `0` sends events instantly. |
|
|
86
|
+
| `maxBufferSize` | `number` | `1000` | Native memory safety threshold. |
|
|
87
|
+
| `connectionTimeoutMs`| `number` | `15000` | Handshake connect timeout threshold. |
|
|
88
|
+
| `readTimeoutMs` | `number` | `300000`| Socket inactivity limit triggers reconnect. |
|
|
89
|
+
| `retryIntervalMs` | `number` | `1000` | Backoff base delay (ms) for reconnect. |
|
|
90
|
+
| `maxRetryIntervalMs` | `number` | `30000` | Cap on backoff reconnect delay (ms). |
|
|
91
|
+
| `jitterFactor` | `number` | `0.5` | Randomization spread ratio (`0.0` to `1.0`). |
|
|
92
|
+
| `maxReconnectAttempts`| `number` | `-1` | Limit reconnections. `-1` = infinite. `0` = disabled. |
|
|
93
|
+
| `autoParseJSON` | `boolean` | `false` | Parses event `data` on native thread; outputs to `parsedData`. |
|
|
94
|
+
| `monitorNetwork` | `boolean` | `true` | Pauses/resumes connection on WiFi <-> Cell or link changes. |
|
|
95
|
+
| `onBeforeRequest` | `() => Promise<Record<string, string>>` | — | Async hook running immediately before every request. |
|
|
96
|
+
| `mock` | `SseMockConfig` | — | Injected mock stream settings (Dev environment only). |
|
|
116
97
|
|
|
117
98
|
---
|
|
118
99
|
|
|
119
|
-
##
|
|
100
|
+
## Mocking & Testing System (`v2.3.0+`)
|
|
120
101
|
|
|
121
|
-
|
|
122
|
-
- **Promise Safety**: The `onBeforeRequest` interceptor is wrapped in a native fallback timeout. Even if your JS token refresh hangs indefinitely, the native state machine will recover and retry safely.
|
|
123
|
-
- **Zero-Ghost Reloads**: Seamlessly handles React Native Hot Reloads. The native layer detects when the JS environment is being destroyed and synchronously kills active sockets to prevent duplicate connections.
|
|
124
|
-
- **Cumulative Logic**: Statistics (`totalBytesReceived`) are preserved across reconnections, giving you a true 360-degree view of the session's data usage.
|
|
102
|
+
NitroSSE includes a built-in mock streaming engine to test application responses without running live endpoints. Mocks are automatically disabled in production configurations.
|
|
125
103
|
|
|
126
|
-
|
|
104
|
+
### Configuration (`SseMockConfig`)
|
|
127
105
|
|
|
128
|
-
|
|
106
|
+
```tsx
|
|
107
|
+
sse.setup({
|
|
108
|
+
url: 'https://api.mocked-endpoint.com/stream',
|
|
109
|
+
mock: {
|
|
110
|
+
mode: 'replace', // 'replace' = Pure JS local simulation; 'inject' = Server + injected events
|
|
111
|
+
eventsPerSecond: 2,
|
|
112
|
+
loop: true,
|
|
113
|
+
errorRate: 0.1, // 10% chance to simulate connection drops and trigger reconnects
|
|
114
|
+
data: [
|
|
115
|
+
{ type: 'open', statusCode: 200 },
|
|
116
|
+
{ type: 'message', data: 'Initial greeting' },
|
|
117
|
+
{ event: 'user-updated', data: '{"id":123,"status":"online"}', delayMs: 1500 },
|
|
118
|
+
{ type: 'message', data: 'Periodic heartbeat comments' },
|
|
119
|
+
]
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### Manual Injector
|
|
125
|
+
Inject custom testing events programmatically at runtime to mock specific app situations:
|
|
126
|
+
|
|
127
|
+
```tsx
|
|
128
|
+
sse.injectMockEvent({
|
|
129
|
+
type: 'message',
|
|
130
|
+
event: 'alert',
|
|
131
|
+
data: 'System maintenance warning!'
|
|
132
|
+
});
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
---
|
|
129
136
|
|
|
130
|
-
|
|
137
|
+
## Advanced Operations
|
|
131
138
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
139
|
+
* **`updateHeaders(headers)`**: Change request headers (e.g., updating expired authentication tokens) without closing and opening the connection manually.
|
|
140
|
+
* **`setLastProcessedId(id)`**: Update the native parser's last processed event ID. Native uses this ID as the `Last-Event-ID` header on next reconnection.
|
|
141
|
+
* **`restart()`**: Immediately tears down the current network socket and initializes fresh handshake sequence.
|
|
142
|
+
* **`flush()`**: Explicitly forces dispatch of currently buffered events, ignoring `batchingIntervalMs`.
|
|
135
143
|
|
|
136
144
|
---
|
|
137
145
|
|
|
138
|
-
##
|
|
146
|
+
## License
|
|
139
147
|
|
|
140
148
|
MIT
|
|
141
149
|
|
|
142
150
|
---
|
|
143
151
|
|
|
144
|
-
Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
|
|
152
|
+
*Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)*
|
package/android/build.gradle
CHANGED
|
@@ -36,6 +36,7 @@ apply plugin: "kotlin-android"
|
|
|
36
36
|
apply from: '../nitrogen/generated/android/nitrosse+autolinking.gradle'
|
|
37
37
|
|
|
38
38
|
apply plugin: "com.facebook.react"
|
|
39
|
+
apply from: 'jacoco.gradle'
|
|
39
40
|
|
|
40
41
|
android {
|
|
41
42
|
namespace "com.margelo.nitro.nitrosse"
|
|
@@ -110,6 +111,12 @@ android {
|
|
|
110
111
|
sourceCompatibility JavaVersion.VERSION_1_8
|
|
111
112
|
targetCompatibility JavaVersion.VERSION_1_8
|
|
112
113
|
}
|
|
114
|
+
|
|
115
|
+
testOptions {
|
|
116
|
+
unitTests {
|
|
117
|
+
includeAndroidResources = true
|
|
118
|
+
}
|
|
119
|
+
}
|
|
113
120
|
}
|
|
114
121
|
|
|
115
122
|
dependencies {
|
|
@@ -121,4 +128,8 @@ dependencies {
|
|
|
121
128
|
|
|
122
129
|
testImplementation "junit:junit:4.13.2"
|
|
123
130
|
testImplementation "org.json:json:20240303"
|
|
131
|
+
testImplementation "org.robolectric:robolectric:4.14.1"
|
|
132
|
+
testImplementation "androidx.test:core:1.6.1"
|
|
133
|
+
testImplementation "org.mockito:mockito-core:5.5.0"
|
|
134
|
+
testImplementation "com.squareup.okhttp3:mockwebserver:4.12.0"
|
|
124
135
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
apply plugin: "jacoco"
|
|
2
|
+
|
|
3
|
+
jacoco {
|
|
4
|
+
toolVersion = "0.8.11"
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
tasks.withType(Test) {
|
|
8
|
+
jacoco.includeNoLocationClasses = true
|
|
9
|
+
jacoco.excludes = ['jdk.internal.*']
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest']) {
|
|
13
|
+
reports {
|
|
14
|
+
xml.required = true
|
|
15
|
+
html.required = true
|
|
16
|
+
html.outputLocation = layout.buildDirectory.dir('reports/jacoco')
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
def fileFilter = [
|
|
20
|
+
'**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*',
|
|
21
|
+
'**/*Test*.*', 'android/**/*.*', '**/NitroSsePackage.*', '**/NetworkInspector.*'
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
// For Kotlin projects in Android, classes are usually in build/tmp/kotlin-classes/debug
|
|
25
|
+
def debugTree = fileTree(dir: "${buildDir}/tmp/kotlin-classes/debug", excludes: fileFilter)
|
|
26
|
+
def mainSrc = "${projectDir}/src/main/java"
|
|
27
|
+
|
|
28
|
+
sourceDirectories.setFrom(files([mainSrc]))
|
|
29
|
+
classDirectories.setFrom(files([debugTree]))
|
|
30
|
+
executionData.setFrom(fileTree(dir: "${buildDir}", includes: [
|
|
31
|
+
'jacoco/testDebugUnitTest.exec'
|
|
32
|
+
]))
|
|
33
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
package com.margelo.nitro.nitrosse
|
|
2
|
+
|
|
3
|
+
import android.os.Handler
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Android implementation of [SseDispatcher] delegating execution to an [android.os.Handler].
|
|
7
|
+
*
|
|
8
|
+
* Decouples thread scheduling from Android OS dependencies, allowing unit tests
|
|
9
|
+
* to swap handler execution with deterministic in-memory dispatchers.
|
|
10
|
+
*/
|
|
11
|
+
class AndroidSseDispatcher(private val handler: Handler) : SseDispatcher {
|
|
12
|
+
override fun post(runnable: Runnable) {
|
|
13
|
+
handler.post(runnable)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
override fun postDelayed(runnable: Runnable, delayMillis: Long) {
|
|
17
|
+
handler.postDelayed(runnable, delayMillis)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
override fun removeCallbacks(runnable: Runnable) {
|
|
21
|
+
handler.removeCallbacks(runnable)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
override fun removeCallbacksAndMessages(token: Any?) {
|
|
25
|
+
handler.removeCallbacksAndMessages(token)
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
package com.margelo.nitro.nitrosse
|
|
2
|
+
|
|
3
|
+
import android.util.Log
|
|
4
|
+
import com.margelo.nitro.core.AnyMap
|
|
5
|
+
import org.json.JSONArray
|
|
6
|
+
import org.json.JSONObject
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Utility for recursive conversion of Android [JSONObject] and [JSONArray] structures
|
|
10
|
+
* into [AnyMap] representations required by the Nitro JavaScript bridge.
|
|
11
|
+
*/
|
|
12
|
+
object JsonUtils {
|
|
13
|
+
fun jsonObjectToMap(jsonObject: JSONObject): Map<String, Any?> {
|
|
14
|
+
val map = mutableMapOf<String, Any?>()
|
|
15
|
+
val keys = jsonObject.keys()
|
|
16
|
+
while (keys.hasNext()) {
|
|
17
|
+
val key = keys.next()
|
|
18
|
+
var value: Any? = jsonObject.get(key)
|
|
19
|
+
if (value is JSONObject) {
|
|
20
|
+
value = jsonObjectToMap(value)
|
|
21
|
+
} else if (value is JSONArray) {
|
|
22
|
+
value = jsonArrayToList(value)
|
|
23
|
+
} else if (value == JSONObject.NULL) {
|
|
24
|
+
value = null
|
|
25
|
+
}
|
|
26
|
+
map[key] = value
|
|
27
|
+
}
|
|
28
|
+
return map
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
fun jsonArrayToList(jsonArray: JSONArray): List<Any?> {
|
|
32
|
+
val list = mutableListOf<Any?>()
|
|
33
|
+
for (i in 0 until jsonArray.length()) {
|
|
34
|
+
var value: Any? = jsonArray.get(i)
|
|
35
|
+
if (value is JSONObject) {
|
|
36
|
+
value = jsonObjectToMap(value)
|
|
37
|
+
} else if (value is JSONArray) {
|
|
38
|
+
value = jsonArrayToList(value)
|
|
39
|
+
} else if (value == JSONObject.NULL) {
|
|
40
|
+
value = null
|
|
41
|
+
}
|
|
42
|
+
list.add(value)
|
|
43
|
+
}
|
|
44
|
+
return list
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Parses a raw JSON string into [AnyMap]. Returns null on malformed JSON or non-object roots
|
|
49
|
+
* to prevent invalid SSE payloads from interrupting stream processing.
|
|
50
|
+
*/
|
|
51
|
+
fun parseJsonToAnyMap(data: String): AnyMap? {
|
|
52
|
+
return try {
|
|
53
|
+
val trimmed = data.trim()
|
|
54
|
+
if (trimmed.startsWith("{")) {
|
|
55
|
+
val jsonObject = JSONObject(trimmed)
|
|
56
|
+
val map = jsonObjectToMap(jsonObject)
|
|
57
|
+
AnyMap.fromMap(map, true)
|
|
58
|
+
} else {
|
|
59
|
+
null
|
|
60
|
+
}
|
|
61
|
+
} catch (e: Exception) {
|
|
62
|
+
Log.w("JsonUtils", "Failed to parse JSON: ${e.message}")
|
|
63
|
+
null
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -6,8 +6,11 @@ import okhttp3.Response
|
|
|
6
6
|
import java.util.UUID
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
9
|
+
* Reports SSE connection events to the React Native DevTools Network inspector.
|
|
10
|
+
*
|
|
11
|
+
* Uses Java reflection to dynamically access React Native's internal `InspectorNetworkReporter`.
|
|
12
|
+
* This prevents compilation failure or runtime link errors when running in production builds
|
|
13
|
+
* or environments where network inspection modules are stripped.
|
|
11
14
|
*/
|
|
12
15
|
object NetworkInspector {
|
|
13
16
|
private const val TAG = "NitroSseNetworkInspector"
|
|
@@ -46,7 +49,7 @@ object NetworkInspector {
|
|
|
46
49
|
Long::class.javaPrimitiveType
|
|
47
50
|
)
|
|
48
51
|
val headers = request.headers.toMap()
|
|
49
|
-
//
|
|
52
|
+
// SSE connection requests do not send request bodies; passing empty body minimizes DevTools memory overhead
|
|
50
53
|
val body = ""
|
|
51
54
|
method?.invoke(null, requestId, request.url.toString(), request.method, headers, body, 0L)
|
|
52
55
|
} catch (e: Exception) {
|