@shamilovtim/react-native-nitro-sse 2.3.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.
Files changed (98) hide show
  1. package/LICENSE +21 -0
  2. package/NitroSse.podspec +37 -0
  3. package/README.md +144 -0
  4. package/android/CMakeLists.txt +24 -0
  5. package/android/build.gradle +124 -0
  6. package/android/src/main/AndroidManifest.xml +4 -0
  7. package/android/src/main/cpp/cpp-adapter.cpp +10 -0
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +94 -0
  9. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +889 -0
  10. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSsePackage.kt +22 -0
  11. package/ios/NitroSse.swift +760 -0
  12. package/ios/NitroSseNetworkInspector.h +24 -0
  13. package/ios/NitroSseNetworkInspector.mm +68 -0
  14. package/lib/module/NitroSse.nitro.js +4 -0
  15. package/lib/module/NitroSse.nitro.js.map +1 -0
  16. package/lib/module/NitroSseClient.js +244 -0
  17. package/lib/module/NitroSseClient.js.map +1 -0
  18. package/lib/module/SseInterface.js +4 -0
  19. package/lib/module/SseInterface.js.map +1 -0
  20. package/lib/module/index.js +26 -0
  21. package/lib/module/index.js.map +1 -0
  22. package/lib/module/package.json +1 -0
  23. package/lib/typescript/package.json +1 -0
  24. package/lib/typescript/src/NitroSse.nitro.d.ts +48 -0
  25. package/lib/typescript/src/NitroSse.nitro.d.ts.map +1 -0
  26. package/lib/typescript/src/NitroSseClient.d.ts +26 -0
  27. package/lib/typescript/src/NitroSseClient.d.ts.map +1 -0
  28. package/lib/typescript/src/SseInterface.d.ts +237 -0
  29. package/lib/typescript/src/SseInterface.d.ts.map +1 -0
  30. package/lib/typescript/src/index.d.ts +11 -0
  31. package/lib/typescript/src/index.d.ts.map +1 -0
  32. package/nitro.json +23 -0
  33. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.hpp +138 -0
  34. package/nitrogen/generated/android/c++/JFunc_void_std__vector_SseEvent_.hpp +102 -0
  35. package/nitrogen/generated/android/c++/JHttpMethod.hpp +58 -0
  36. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +134 -0
  37. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +71 -0
  38. package/nitrogen/generated/android/c++/JSseConfig.hpp +162 -0
  39. package/nitrogen/generated/android/c++/JSseEvent.hpp +90 -0
  40. package/nitrogen/generated/android/c++/JSseEventType.hpp +67 -0
  41. package/nitrogen/generated/android/c++/JSseMockConfig.hpp +101 -0
  42. package/nitrogen/generated/android/c++/JSseMockEvent.hpp +94 -0
  43. package/nitrogen/generated/android/c++/JSseMockMode.hpp +58 -0
  44. package/nitrogen/generated/android/c++/JSseStats.hpp +70 -0
  45. 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 +80 -0
  46. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_void_std__vector_SseEvent_.kt +80 -0
  47. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HttpMethod.kt +23 -0
  48. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +91 -0
  49. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +135 -0
  50. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +86 -0
  51. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEventType.kt +26 -0
  52. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockConfig.kt +71 -0
  53. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockEvent.kt +91 -0
  54. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockMode.kt +23 -0
  55. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +66 -0
  56. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/nitrosseOnLoad.kt +35 -0
  57. package/nitrogen/generated/android/nitrosse+autolinking.cmake +81 -0
  58. package/nitrogen/generated/android/nitrosse+autolinking.gradle +27 -0
  59. package/nitrogen/generated/android/nitrosseOnLoad.cpp +58 -0
  60. package/nitrogen/generated/android/nitrosseOnLoad.hpp +34 -0
  61. package/nitrogen/generated/ios/NitroSse+autolinking.rb +62 -0
  62. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +74 -0
  63. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +415 -0
  64. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +74 -0
  65. package/nitrogen/generated/ios/NitroSseAutolinking.mm +33 -0
  66. package/nitrogen/generated/ios/NitroSseAutolinking.swift +26 -0
  67. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.cpp +11 -0
  68. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +161 -0
  69. package/nitrogen/generated/ios/swift/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.swift +67 -0
  70. package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +46 -0
  71. package/nitrogen/generated/ios/swift/Func_void_std__shared_ptr_Promise_std__unordered_map_std__string__std__string___.swift +66 -0
  72. package/nitrogen/generated/ios/swift/Func_void_std__unordered_map_std__string__std__string_.swift +54 -0
  73. package/nitrogen/generated/ios/swift/Func_void_std__vector_SseEvent_.swift +46 -0
  74. package/nitrogen/generated/ios/swift/HttpMethod.swift +40 -0
  75. package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +63 -0
  76. package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +246 -0
  77. package/nitrogen/generated/ios/swift/SseConfig.swift +346 -0
  78. package/nitrogen/generated/ios/swift/SseEvent.swift +155 -0
  79. package/nitrogen/generated/ios/swift/SseEventType.swift +52 -0
  80. package/nitrogen/generated/ios/swift/SseMockConfig.swift +94 -0
  81. package/nitrogen/generated/ios/swift/SseMockEvent.swift +179 -0
  82. package/nitrogen/generated/ios/swift/SseMockMode.swift +40 -0
  83. package/nitrogen/generated/ios/swift/SseStats.swift +70 -0
  84. package/nitrogen/generated/shared/c++/HttpMethod.hpp +76 -0
  85. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.cpp +29 -0
  86. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +81 -0
  87. package/nitrogen/generated/shared/c++/SseConfig.hpp +156 -0
  88. package/nitrogen/generated/shared/c++/SseEvent.hpp +115 -0
  89. package/nitrogen/generated/shared/c++/SseEventType.hpp +88 -0
  90. package/nitrogen/generated/shared/c++/SseMockConfig.hpp +105 -0
  91. package/nitrogen/generated/shared/c++/SseMockEvent.hpp +119 -0
  92. package/nitrogen/generated/shared/c++/SseMockMode.hpp +76 -0
  93. package/nitrogen/generated/shared/c++/SseStats.hpp +96 -0
  94. package/package.json +186 -0
  95. package/src/NitroSse.nitro.ts +53 -0
  96. package/src/NitroSseClient.ts +297 -0
  97. package/src/SseInterface.ts +248 -0
  98. package/src/index.ts +31 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 IAmTester35
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,37 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "NitroSse"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+ s.homepage = package["homepage"]
10
+ s.license = package["license"]
11
+ s.authors = package["author"]
12
+
13
+ s.platforms = { :ios => min_ios_version_supported, :osx => "10.15" }
14
+ s.source = { :git => "https://github.com/shamilovtim/react-native-nitro-sse.git", :tag => "#{s.version}" }
15
+
16
+ s.source_files = [
17
+ "ios/*.{h,m,mm,swift}",
18
+ "cpp/**/*.{h,hpp,cpp}",
19
+ ]
20
+
21
+ s.public_header_files = [
22
+ "ios/NitroSseNetworkInspector.h",
23
+ ]
24
+
25
+ s.test_spec 'Tests' do |test_spec|
26
+ test_spec.source_files = 'ios/Tests/**/*.{swift}'
27
+ end
28
+
29
+ s.dependency 'React-jsi'
30
+ s.dependency 'React-callinvoker'
31
+ s.dependency 'LDSwiftEventSource'
32
+
33
+ load 'nitrogen/generated/ios/NitroSse+autolinking.rb'
34
+ add_nitrogen_files(s)
35
+
36
+ install_modules_dependencies(s)
37
+ end
package/README.md ADDED
@@ -0,0 +1,144 @@
1
+ # 🚀 react-native-nitro-sse
2
+
3
+ High-performance Server-Sent Events (SSE) client for React Native, built on top of **Nitro Modules (JSI)**. Designed for mission-critical systems requiring extreme stability, high-throughput data streaming, and absolute battery optimization.
4
+
5
+ ## 🌟 Why NitroSSE?
6
+
7
+ Unlike traditional EventSource libraries that run on the JS thread or use the legacy Bridge, NitroSSE moves the entire control logic down to the deepest Native layer:
8
+
9
+ - **🚀 Zero-Latency JSI**: Communication between JS and Native is instantaneous, bypassing the asynchronous bridge.
10
+ - **🧠 Smart Reconnect**: Automatic reconnection strategy using **Exponential Backoff** and **Jitter** to prevent thundering herd problems.
11
+ - **🛡️ DoS Protection**: Respects RFC `Retry-After` headers and enforces strict connection frequency limits.
12
+ - **🌊 Backpressure Handling**: Advanced **Batching** mechanism aggregates messages and employs **Tail Drop** strategies to protect the UI thread from freezing during data surges.
13
+ - **🔋 Mobile-First Architecture**: Automatically hibernates when the app enters the background and seamlessly reconnects upon foregrounding to conserve battery.
14
+ - **💓 Heartbeat Detection**: Native-side detection of keep-alive signals (comments) to maintain a reliable connection watchdog.
15
+ - **🔍 DevTools Integration**: Plug-and-play support for **React Native 0.83+ DevTools Network Tab**. Monitor connection status, request/response headers, and timing directly in the official desktop debugger.
16
+ - **🛠️ Full Protocol Support**: Comprehensive support for GET/POST methods and dynamic header updates.
17
+
18
+ ---
19
+
20
+ ## 📦 Installation
21
+
22
+ ```sh
23
+ yarn add @shamilovtim/react-native-nitro-sse react-native-nitro-modules
24
+ # or
25
+ npm install @shamilovtim/react-native-nitro-sse react-native-nitro-modules
26
+ ```
27
+
28
+ > **Note**: `react-native-nitro-modules` is required as the core foundation for JSI performance.
29
+
30
+ ---
31
+
32
+ ## 📊 Compatibility
33
+
34
+ | react-native-nitro-sse | react-native-nitro-modules |
35
+ | :--------------------- | :------------------------- |
36
+ | **2.2.0 - latest** | **0.35.4** |
37
+ | **2.0.0 - 2.1.1** | **0.35.2** |
38
+ | **1.6.2** | **0.35.2** |
39
+ | **1.4.0 - 1.6.1** | **0.35.0** |
40
+ | **1.2.2 - 1.3.1** | **0.34.1** |
41
+ | **1.2.0 - 1.2.1** | **0.34.0** |
42
+ | **1.1.0** | **0.33.9** |
43
+ | **1.0.0** | **0.33.8** |
44
+
45
+
46
+ ---
47
+
48
+ ## 🚀 Usage
49
+
50
+ ### 1. Basic Initialization
51
+
52
+ Initialize the module with your endpoint configuration and an event listener.
53
+
54
+ ```tsx
55
+ import { createNitroSse } from '@shamilovtim/react-native-nitro-sse';
56
+
57
+ const nitroSse = createNitroSse();
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
+ );
83
+
84
+ // Start the connection
85
+ nitroSse.start();
86
+ ```
87
+
88
+ ### 2. Monitoring & Statistics
89
+
90
+ NitroSSE provides synchronous access to connection health and throughput data.
91
+
92
+ ```tsx
93
+ const stats = nitroSse.getStats();
94
+ console.log(`Downloaded: ${stats.totalBytesReceived / 1024} KB`);
95
+ console.log(`Reconnections: ${stats.reconnectCount}`);
96
+ ```
97
+
98
+ ---
99
+
100
+ ## ⚙️ Configuration (SseConfig)
101
+
102
+ | Parameter | Type | Default | Description |
103
+ | :--- | :--- | :--- | :--- |
104
+ | `url` | `string` | - | **Required**. The URL of the SSE endpoint. |
105
+ | `method` | `'get' \| 'post'` | `get` | HTTP method. |
106
+ | `headers` | `Record<string, string>` | `{}` | Custom HTTP headers. |
107
+ | `body` | `string` | - | Request body (payload) for POST requests. |
108
+ | `batchingIntervalMs` | `number` | `0` | Time window (ms) to group events. `0` = real-time. |
109
+ | `maxBufferSize` | `number` | `1000` | Native queue limit to prevent memory overflow. |
110
+ | `connectionTimeoutMs`| `number` | `15000` | Max time for initial handshake / connect. |
111
+ | `readTimeoutMs` | `number` | `300000`| Max idle time between data packets before reconnecting. |
112
+ | `backgroundExecution` | `boolean` | `false` | (iOS) Attempt to maintain connection via background tasks. |
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. |
115
+ | `onBeforeRequest` | `function`| - | Async hook to refresh headers/tokens before every attempt. |
116
+
117
+ ---
118
+
119
+ ## 🛡️ Reliability Features (v1.5.1+)
120
+
121
+ - **Atomic State Management**: Calling `.start()` or `.stop()` updates the instance status immediately on the JSI thread, ensuring the UI (e.g., `isConnected()`) never feels laggy or stuck.
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.
125
+
126
+ ---
127
+
128
+ ## 🏗️ System Architecture
129
+
130
+ This project employs a robust **Producer-Consumer** model:
131
+
132
+ 1. **Native (Producer)**: Collects data from the socket on a dedicated Background Thread, handling all backpressure logic.
133
+ 2. **Nitro (Bridge)**: Snapshots data and securely transports it via the JSI CallInvoker.
134
+ 3. **JavaScript (Consumer)**: Consumes data in batches, ensuring the UI Loop remains buttery smooth even under heavy load.
135
+
136
+ ---
137
+
138
+ ## 📄 License
139
+
140
+ MIT
141
+
142
+ ---
143
+
144
+ Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
@@ -0,0 +1,24 @@
1
+ project(nitrosse)
2
+ cmake_minimum_required(VERSION 3.9.0)
3
+
4
+ set(PACKAGE_NAME nitrosse)
5
+ set(CMAKE_VERBOSE_MAKEFILE ON)
6
+ set(CMAKE_CXX_STANDARD 20)
7
+
8
+ # Define C++ library and add all sources
9
+ add_library(${PACKAGE_NAME} SHARED src/main/cpp/cpp-adapter.cpp)
10
+
11
+ # Add Nitrogen specs :)
12
+ include(${CMAKE_SOURCE_DIR}/../nitrogen/generated/android/nitrosse+autolinking.cmake)
13
+
14
+ # Set up local includes
15
+ include_directories("src/main/cpp" "../cpp")
16
+
17
+ find_library(LOG_LIB log)
18
+
19
+ # Link all libraries together
20
+ target_link_libraries(
21
+ ${PACKAGE_NAME}
22
+ ${LOG_LIB}
23
+ android # <-- Android core
24
+ )
@@ -0,0 +1,124 @@
1
+ buildscript {
2
+ ext.NitroSse = [
3
+ kotlinVersion: "2.0.21",
4
+ minSdkVersion: 24,
5
+ compileSdkVersion: 36,
6
+ targetSdkVersion: 36
7
+ ]
8
+
9
+ ext.getExtOrDefault = { prop ->
10
+ if (rootProject.ext.has(prop)) {
11
+ return rootProject.ext.get(prop)
12
+ }
13
+
14
+ return NitroSse[prop]
15
+ }
16
+
17
+ repositories {
18
+ google()
19
+ mavenCentral()
20
+ }
21
+
22
+ dependencies {
23
+ classpath "com.android.tools.build:gradle:8.7.2"
24
+ // noinspection DifferentKotlinGradleVersion
25
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${getExtOrDefault('kotlinVersion')}"
26
+ }
27
+ }
28
+
29
+ def reactNativeArchitectures() {
30
+ def value = rootProject.getProperties().get("reactNativeArchitectures")
31
+ return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
32
+ }
33
+
34
+ apply plugin: "com.android.library"
35
+ apply plugin: "kotlin-android"
36
+ apply from: '../nitrogen/generated/android/nitrosse+autolinking.gradle'
37
+
38
+ apply plugin: "com.facebook.react"
39
+
40
+ android {
41
+ namespace "com.margelo.nitro.nitrosse"
42
+
43
+ compileSdkVersion getExtOrDefault("compileSdkVersion")
44
+
45
+ defaultConfig {
46
+ minSdkVersion getExtOrDefault("minSdkVersion")
47
+ targetSdkVersion getExtOrDefault("targetSdkVersion")
48
+
49
+ externalNativeBuild {
50
+ cmake {
51
+ cppFlags "-frtti -fexceptions -Wall -fstack-protector-all"
52
+ arguments "-DANDROID_STL=c++_shared", "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON"
53
+ abiFilters (*reactNativeArchitectures())
54
+
55
+ buildTypes {
56
+ debug {
57
+ cppFlags "-O1 -g"
58
+ }
59
+ release {
60
+ cppFlags "-O2"
61
+ }
62
+ }
63
+ }
64
+ }
65
+ }
66
+
67
+ externalNativeBuild {
68
+ cmake {
69
+ path "CMakeLists.txt"
70
+ }
71
+ }
72
+
73
+ packagingOptions {
74
+ excludes = [
75
+ "META-INF",
76
+ "META-INF/**",
77
+ "**/libc++_shared.so",
78
+ "**/libfbjni.so",
79
+ "**/libjsi.so",
80
+ "**/libfolly_json.so",
81
+ "**/libfolly_runtime.so",
82
+ "**/libglog.so",
83
+ "**/libhermes.so",
84
+ "**/libhermes-executor-debug.so",
85
+ "**/libhermes_executor.so",
86
+ "**/libreactnative.so",
87
+ "**/libreactnativejni.so",
88
+ "**/libturbomodulejsijni.so",
89
+ "**/libreact_nativemodule_core.so",
90
+ "**/libjscexecutor.so"
91
+ ]
92
+ }
93
+
94
+ buildFeatures {
95
+ buildConfig true
96
+ prefab true
97
+ }
98
+
99
+ buildTypes {
100
+ release {
101
+ minifyEnabled false
102
+ }
103
+ }
104
+
105
+ lint {
106
+ disable "GradleCompatible"
107
+ }
108
+
109
+ compileOptions {
110
+ sourceCompatibility JavaVersion.VERSION_1_8
111
+ targetCompatibility JavaVersion.VERSION_1_8
112
+ }
113
+ }
114
+
115
+ dependencies {
116
+ implementation "com.facebook.react:react-android"
117
+ implementation project(":react-native-nitro-modules")
118
+ implementation "com.squareup.okhttp3:okhttp:4.12.0"
119
+ implementation "com.squareup.okhttp3:okhttp-sse:4.12.0"
120
+ implementation "androidx.lifecycle:lifecycle-process:2.8.7"
121
+
122
+ testImplementation "junit:junit:4.13.2"
123
+ testImplementation "org.json:json:20240303"
124
+ }
@@ -0,0 +1,4 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.INTERNET" />
3
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
4
+ </manifest>
@@ -0,0 +1,10 @@
1
+ #include <jni.h>
2
+ #include <fbjni/fbjni.h>
3
+ #include "nitrosseOnLoad.hpp"
4
+
5
+ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*) {
6
+ return facebook::jni::initialize(vm, []() {
7
+ margelo::nitro::nitrosse::registerAllNatives();
8
+ });
9
+ }
10
+
@@ -0,0 +1,94 @@
1
+ package com.margelo.nitro.nitrosse
2
+
3
+ import android.util.Log
4
+ import okhttp3.Request
5
+ import okhttp3.Response
6
+ import java.util.UUID
7
+
8
+ /**
9
+ * A utility to report network events to the React Native DevTools Network Tab.
10
+ * It uses reflection to access the internal InspectorNetworkReporter class in RN.
11
+ */
12
+ object NetworkInspector {
13
+ private const val TAG = "NitroSseNetworkInspector"
14
+ private var reporterClass: Class<*>? = null
15
+ private var isEnabledCached: Boolean = false
16
+
17
+ init {
18
+ try {
19
+ reporterClass = Class.forName("com.facebook.react.modules.network.InspectorNetworkReporter")
20
+ Log.d(TAG, "InspectorNetworkReporter found. Network tracing is available.")
21
+ } catch (e: Exception) {
22
+ Log.d(TAG, "InspectorNetworkReporter not found. Network tracing is disabled.")
23
+ }
24
+ }
25
+
26
+ private fun isEnabled(): Boolean {
27
+ if (reporterClass == null) return false
28
+ return try {
29
+ val method = reporterClass?.getDeclaredMethod("isDebuggingEnabled")
30
+ method?.invoke(null) as? Boolean ?: false
31
+ } catch (e: Exception) {
32
+ false
33
+ }
34
+ }
35
+
36
+ fun reportRequestStart(requestId: String, request: Request) {
37
+ if (reporterClass == null || !isEnabled()) return
38
+ try {
39
+ val method = reporterClass?.getDeclaredMethod(
40
+ "reportRequestStart",
41
+ String::class.java,
42
+ String::class.java,
43
+ String::class.java,
44
+ Map::class.java,
45
+ String::class.java,
46
+ Long::class.javaPrimitiveType
47
+ )
48
+ val headers = request.headers.toMap()
49
+ // We send an empty body string as SSE setup usually doesn't have a large body
50
+ val body = ""
51
+ method?.invoke(null, requestId, request.url.toString(), request.method, headers, body, 0L)
52
+ } catch (e: Exception) {
53
+ Log.e(TAG, "Error reporting request start", e)
54
+ }
55
+ }
56
+
57
+ fun reportResponseStart(requestId: String, request: Request, response: Response) {
58
+ if (reporterClass == null || !isEnabled()) return
59
+ try {
60
+ val method = reporterClass?.getDeclaredMethod(
61
+ "reportResponseStart",
62
+ String::class.java,
63
+ String::class.java,
64
+ Int::class.javaPrimitiveType,
65
+ Map::class.java,
66
+ Long::class.javaPrimitiveType
67
+ )
68
+ val headers = response.headers.toMap()
69
+ method?.invoke(null, requestId, request.url.toString(), response.code, headers, -1L)
70
+ } catch (e: Exception) {
71
+ Log.e(TAG, "Error reporting response start", e)
72
+ }
73
+ }
74
+
75
+ fun reportResponseEnd(requestId: String, totalBytes: Long) {
76
+ if (reporterClass == null || !isEnabled()) return
77
+ try {
78
+ val method = reporterClass?.getDeclaredMethod("reportResponseEnd", String::class.java, Long::class.javaPrimitiveType)
79
+ method?.invoke(null, requestId, totalBytes)
80
+ } catch (e: Exception) {
81
+ Log.e(TAG, "Error reporting response end", e)
82
+ }
83
+ }
84
+
85
+ fun reportRequestFailed(requestId: String, cancelled: Boolean) {
86
+ if (reporterClass == null || !isEnabled()) return
87
+ try {
88
+ val method = reporterClass?.getDeclaredMethod("reportRequestFailed", String::class.java, Boolean::class.javaPrimitiveType)
89
+ method?.invoke(null, requestId, cancelled)
90
+ } catch (e: Exception) {
91
+ Log.e(TAG, "Error reporting request failure", e)
92
+ }
93
+ }
94
+ }