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.
- package/README.md +209 -95
- package/android/src/main/java/com/margelo/nitro/nitrosse/AndroidSseDispatcher.kt +5 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +11 -18
- package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +79 -38
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +194 -100
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +40 -15
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseDispatcher.kt +1 -0
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +34 -28
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseLifecycleManager.kt +8 -1
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +7 -4
- package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +6 -4
- package/ios/NitroSse.swift +244 -190
- package/ios/SseConfig+CopyWith.swift +2 -1
- package/ios/SseConnectionHandler.swift +59 -29
- package/ios/SseDispatchQueueDispatcher.swift +15 -2
- package/ios/SseDispatcher.swift +7 -1
- package/ios/SseEventBuffer.swift +23 -7
- package/ios/SseLifecycleManager.swift +10 -1
- package/ios/SseNetworkMonitor.swift +8 -2
- package/ios/SseReconnectStrategy.swift +9 -3
- package/lib/module/MockSseEngine.js +203 -0
- package/lib/module/NitroSseClient.js +411 -214
- package/lib/module/NitroSseError.js +61 -0
- package/lib/module/SseDriver.js +156 -0
- package/lib/module/index.js +6 -3
- package/lib/module/useNitroSse.js +359 -0
- package/lib/typescript/src/MockSseEngine.d.ts +31 -0
- package/lib/typescript/src/NitroSse.nitro.d.ts +25 -2
- package/lib/typescript/src/NitroSseClient.d.ts +25 -7
- package/lib/typescript/src/NitroSseError.d.ts +38 -0
- package/lib/typescript/src/SseDriver.d.ts +80 -0
- package/lib/typescript/src/SseInterface.d.ts +25 -7
- package/lib/typescript/src/index.d.ts +4 -2
- package/lib/typescript/src/useNitroSse.d.ts +69 -0
- package/nitrogen/generated/android/c++/JSseConfig.hpp +7 -1
- package/nitrogen/generated/android/c++/JSseMockConfig.hpp +2 -0
- package/nitrogen/generated/android/c++/JSseMockEvent.hpp +9 -3
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +9 -4
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseMockEvent.kt +9 -4
- package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +15 -15
- package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +3 -3
- package/nitrogen/generated/ios/swift/SseConfig.swift +19 -1
- package/nitrogen/generated/ios/swift/SseMockEvent.swift +12 -1
- package/nitrogen/generated/shared/c++/SseConfig.hpp +5 -1
- package/nitrogen/generated/shared/c++/SseMockEvent.hpp +9 -2
- package/package.json +10 -11
- package/android/jacoco.gradle +0 -33
- package/lib/module/NitroSse.nitro.js.map +0 -1
- package/lib/module/NitroSseClient.js.map +0 -1
- package/lib/module/SseInterface.js.map +0 -1
- package/lib/module/index.js.map +0 -1
- package/lib/typescript/src/NitroSse.nitro.d.ts.map +0 -1
- package/lib/typescript/src/NitroSseClient.d.ts.map +0 -1
- package/lib/typescript/src/SseInterface.d.ts.map +0 -1
- package/lib/typescript/src/index.d.ts.map +0 -1
- package/src/NitroSse.nitro.ts +0 -58
- package/src/NitroSseClient.ts +0 -337
- package/src/SseInterface.ts +0 -272
- package/src/index.ts +0 -31
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Error codes identifying specific categories of NitroSse failures.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Base structured error class for all errors thrown by react-native-nitro-sse.
|
|
9
|
+
* Carries a machine-readable `code` and optional `details` payload for defensive debugging.
|
|
10
|
+
*/
|
|
11
|
+
export class NitroSseError extends Error {
|
|
12
|
+
constructor(message, code, details) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = 'NitroSseError';
|
|
15
|
+
this.code = code;
|
|
16
|
+
this.details = details;
|
|
17
|
+
// Maintain proper prototype chain for instanceof checks
|
|
18
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Thrown when the native Nitro hybrid module cannot be resolved or linked.
|
|
24
|
+
*/
|
|
25
|
+
export class NitroSseModuleNotFoundError extends NitroSseError {
|
|
26
|
+
constructor(message, details) {
|
|
27
|
+
super(message ?? 'NitroSse: Native module not found. Ensure you have linked the library and built the app for iOS/Android.', 'NATIVE_MODULE_NOT_FOUND', details);
|
|
28
|
+
this.name = 'NitroSseModuleNotFoundError';
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Thrown when configuration parameters, URLs, headers, or arguments fail defensive validation.
|
|
34
|
+
*/
|
|
35
|
+
export class NitroSseValidationError extends NitroSseError {
|
|
36
|
+
constructor(message, code = 'INVALID_CONFIG', details) {
|
|
37
|
+
super(message, code, details);
|
|
38
|
+
this.name = 'NitroSseValidationError';
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Thrown when an operation is attempted in an invalid state (e.g. calling operations on an unconfigured client).
|
|
44
|
+
*/
|
|
45
|
+
export class NitroSseStateError extends NitroSseError {
|
|
46
|
+
constructor(message, details) {
|
|
47
|
+
super(message, 'INVALID_STATE', details);
|
|
48
|
+
this.name = 'NitroSseStateError';
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Thrown when any method is invoked on a client instance that has already been disposed.
|
|
54
|
+
*/
|
|
55
|
+
export class NitroSseDisposedError extends NitroSseError {
|
|
56
|
+
constructor(message, details) {
|
|
57
|
+
super(message ?? '[NitroSse] Cannot perform operation on a disposed NitroSseClient instance.', 'CLIENT_DISPOSED', details);
|
|
58
|
+
this.name = 'NitroSseDisposedError';
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
//# sourceMappingURL=NitroSseError.js.map
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
import { MockSseEngine } from "./MockSseEngine.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Internal execution strategy driving the SSE lifecycle.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Driver delegating all operations to the native JSI NitroSse module.
|
|
11
|
+
*/
|
|
12
|
+
export class NativeDriver {
|
|
13
|
+
constructor(_native, _dispatchEvents) {
|
|
14
|
+
this._native = _native;
|
|
15
|
+
this._dispatchEvents = _dispatchEvents;
|
|
16
|
+
}
|
|
17
|
+
start() {
|
|
18
|
+
this._native.start();
|
|
19
|
+
}
|
|
20
|
+
stop() {
|
|
21
|
+
this._native.stop();
|
|
22
|
+
}
|
|
23
|
+
restart() {
|
|
24
|
+
this._native.restart();
|
|
25
|
+
}
|
|
26
|
+
flush() {
|
|
27
|
+
this._native.flush();
|
|
28
|
+
}
|
|
29
|
+
isConnected() {
|
|
30
|
+
return this._native.isConnected();
|
|
31
|
+
}
|
|
32
|
+
getStats() {
|
|
33
|
+
return this._native.getStats();
|
|
34
|
+
}
|
|
35
|
+
getState() {
|
|
36
|
+
return this._native.getState();
|
|
37
|
+
}
|
|
38
|
+
updateHeaders(headers) {
|
|
39
|
+
this._native.updateHeaders(headers);
|
|
40
|
+
}
|
|
41
|
+
setLastProcessedId(id) {
|
|
42
|
+
this._native.setLastProcessedId(id);
|
|
43
|
+
}
|
|
44
|
+
injectMockEvent(event) {
|
|
45
|
+
const sseEvent = MockSseEngine.createSseEvent(event);
|
|
46
|
+
this._dispatchEvents([sseEvent]);
|
|
47
|
+
}
|
|
48
|
+
dispose() {
|
|
49
|
+
// Note: dispose() is a built-in method provided by the HybridObject base class in react-native-nitro-modules
|
|
50
|
+
// (registered on the JSI prototype via HybridObject::loadHybridMethods in C++). It forwards to native
|
|
51
|
+
// dispose() implementations (NitroSse.swift and NitroSse.kt) without needing to be re-declared in NitroSse.nitro.ts.
|
|
52
|
+
if (typeof this._native.dispose === 'function') {
|
|
53
|
+
this._native.dispose();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Driver simulating the entire SSE stream in JavaScript without native networking.
|
|
60
|
+
*/
|
|
61
|
+
export class MockReplaceDriver {
|
|
62
|
+
_headers = {};
|
|
63
|
+
constructor(_mockEngine) {
|
|
64
|
+
this._mockEngine = _mockEngine;
|
|
65
|
+
}
|
|
66
|
+
get headers() {
|
|
67
|
+
return this._headers;
|
|
68
|
+
}
|
|
69
|
+
get lastProcessedId() {
|
|
70
|
+
return this._lastProcessedId;
|
|
71
|
+
}
|
|
72
|
+
start() {
|
|
73
|
+
this._mockEngine.start();
|
|
74
|
+
}
|
|
75
|
+
stop() {
|
|
76
|
+
this._mockEngine.stop();
|
|
77
|
+
}
|
|
78
|
+
restart() {
|
|
79
|
+
this._mockEngine.restart();
|
|
80
|
+
}
|
|
81
|
+
flush() {}
|
|
82
|
+
isConnected() {
|
|
83
|
+
return this._mockEngine.isConnected();
|
|
84
|
+
}
|
|
85
|
+
getStats() {
|
|
86
|
+
return this._mockEngine.getStats();
|
|
87
|
+
}
|
|
88
|
+
getState() {
|
|
89
|
+
return this._mockEngine.getState();
|
|
90
|
+
}
|
|
91
|
+
updateHeaders(headers) {
|
|
92
|
+
this._headers = {
|
|
93
|
+
...this._headers,
|
|
94
|
+
...headers
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
setLastProcessedId(id) {
|
|
98
|
+
this._lastProcessedId = id;
|
|
99
|
+
}
|
|
100
|
+
injectMockEvent(event) {
|
|
101
|
+
this._mockEngine.injectEvent(event);
|
|
102
|
+
}
|
|
103
|
+
dispose() {
|
|
104
|
+
this._mockEngine.stop();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Driver running native networking in parallel with mock event injection.
|
|
110
|
+
*/
|
|
111
|
+
export class MockInjectDriver {
|
|
112
|
+
constructor(_native, _mockEngine) {
|
|
113
|
+
this._native = _native;
|
|
114
|
+
this._mockEngine = _mockEngine;
|
|
115
|
+
}
|
|
116
|
+
start() {
|
|
117
|
+
this._mockEngine.start();
|
|
118
|
+
this._native.start();
|
|
119
|
+
}
|
|
120
|
+
stop() {
|
|
121
|
+
this._mockEngine.stop();
|
|
122
|
+
this._native.stop();
|
|
123
|
+
}
|
|
124
|
+
restart() {
|
|
125
|
+
this._mockEngine.restart();
|
|
126
|
+
this._native.restart();
|
|
127
|
+
}
|
|
128
|
+
flush() {
|
|
129
|
+
this._native.flush();
|
|
130
|
+
}
|
|
131
|
+
isConnected() {
|
|
132
|
+
return this._native.isConnected();
|
|
133
|
+
}
|
|
134
|
+
getStats() {
|
|
135
|
+
return this._native.getStats();
|
|
136
|
+
}
|
|
137
|
+
getState() {
|
|
138
|
+
return this._native.getState();
|
|
139
|
+
}
|
|
140
|
+
updateHeaders(headers) {
|
|
141
|
+
this._native.updateHeaders(headers);
|
|
142
|
+
}
|
|
143
|
+
setLastProcessedId(id) {
|
|
144
|
+
this._native.setLastProcessedId(id);
|
|
145
|
+
}
|
|
146
|
+
injectMockEvent(event) {
|
|
147
|
+
this._mockEngine.injectEvent(event);
|
|
148
|
+
}
|
|
149
|
+
dispose() {
|
|
150
|
+
this._mockEngine.stop();
|
|
151
|
+
if (typeof this._native.dispose === 'function') {
|
|
152
|
+
this._native.dispose();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
//# sourceMappingURL=SseDriver.js.map
|
package/lib/module/index.js
CHANGED
|
@@ -2,14 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
import { NitroModules } from 'react-native-nitro-modules';
|
|
4
4
|
import { NitroSseClient } from "./NitroSseClient.js";
|
|
5
|
+
import { NitroSseModuleNotFoundError } from "./NitroSseError.js";
|
|
5
6
|
export * from "./SseInterface.js";
|
|
6
|
-
export * from "./
|
|
7
|
+
export * from "./useNitroSse.js";
|
|
8
|
+
export * from "./NitroSseClient.js";
|
|
9
|
+
export * from "./NitroSseError.js";
|
|
7
10
|
|
|
8
11
|
/**
|
|
9
12
|
* Creates a high-performance SSE client that supports typed event listeners (`addEventListener`) and legacy batching.
|
|
10
13
|
*
|
|
11
14
|
* @returns An SseClient instance wrapping the native NitroSse implementation.
|
|
12
|
-
* @throws If the native NitroSse module cannot be found. Ensure the library is linked and the app is built for iOS/Android.
|
|
15
|
+
* @throws {NitroSseModuleNotFoundError} If the native NitroSse module cannot be found. Ensure the library is linked and the app is built for iOS/Android.
|
|
13
16
|
*/
|
|
14
17
|
export function createNitroSse() {
|
|
15
18
|
let nativeSse;
|
|
@@ -19,7 +22,7 @@ export function createNitroSse() {
|
|
|
19
22
|
console.debug('Native NitroSse not found. This might be a test environment or web.');
|
|
20
23
|
}
|
|
21
24
|
if (!nativeSse) {
|
|
22
|
-
throw new
|
|
25
|
+
throw new NitroSseModuleNotFoundError('NitroSse: Native module not found. Ensure you have linked the library and built the app for iOS/Android.');
|
|
23
26
|
}
|
|
24
27
|
return new NitroSseClient(nativeSse);
|
|
25
28
|
}
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
import { useEffect, useRef, useState, useCallback } from 'react';
|
|
4
|
+
import { createNitroSse } from "./index.js";
|
|
5
|
+
/**
|
|
6
|
+
* Safely serializes an object into a stable JSON string:
|
|
7
|
+
* - Sorts object keys to avoid reconnection on equivalent configs with reordered keys.
|
|
8
|
+
* - Handles circular structures by substituting '[Circular]'.
|
|
9
|
+
* - Handles BigInt by converting to string.
|
|
10
|
+
* - Catches any unexpected serialization error and falls back gracefully.
|
|
11
|
+
*/
|
|
12
|
+
export function safeSerializeConfig(obj) {
|
|
13
|
+
if (obj === null || typeof obj !== 'object') {
|
|
14
|
+
return String(obj);
|
|
15
|
+
}
|
|
16
|
+
const seen = new WeakSet();
|
|
17
|
+
try {
|
|
18
|
+
return JSON.stringify(obj, (_key, value) => {
|
|
19
|
+
if (typeof value === 'bigint') {
|
|
20
|
+
return value.toString();
|
|
21
|
+
}
|
|
22
|
+
if (typeof value === 'object' && value !== null) {
|
|
23
|
+
if (seen.has(value)) {
|
|
24
|
+
return '[Circular]';
|
|
25
|
+
}
|
|
26
|
+
seen.add(value);
|
|
27
|
+
if (!Array.isArray(value)) {
|
|
28
|
+
const sorted = {};
|
|
29
|
+
for (const [k, v] of Object.entries(value).sort(([a], [b]) => a.localeCompare(b))) {
|
|
30
|
+
sorted[k] = v;
|
|
31
|
+
}
|
|
32
|
+
return sorted;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return value;
|
|
36
|
+
});
|
|
37
|
+
} catch (e) {
|
|
38
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
39
|
+
console.warn('[useNitroSse] Failed to serialize config object, falling back to string representation:', e);
|
|
40
|
+
}
|
|
41
|
+
return String(obj);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Derives the `isConnected` flag from the connection state without a native JSI call.
|
|
47
|
+
* Matches the semantics of `SseClient.isConnected()`: true for 'connecting', 'open', or 'reconnecting'.
|
|
48
|
+
*/
|
|
49
|
+
function isConnectedState(s) {
|
|
50
|
+
return s === 'connecting' || s === 'open' || s === 'reconnecting';
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Automatically handles client instantiation, listener attachment, state tracking, and lifecycle disposal on unmount.
|
|
55
|
+
*
|
|
56
|
+
* @param options SSE configuration options, callbacks, and custom event handlers.
|
|
57
|
+
* @returns State, client instance, and imperative control methods.
|
|
58
|
+
*/
|
|
59
|
+
export function useNitroSse(options) {
|
|
60
|
+
const isValidOptions = Boolean(options) && typeof options === 'object' && !Array.isArray(options);
|
|
61
|
+
const safeOptions = isValidOptions ? options : {};
|
|
62
|
+
if (!isValidOptions && typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
63
|
+
console.error('[useNitroSse] Invalid options provided. Expected an options object.');
|
|
64
|
+
}
|
|
65
|
+
const {
|
|
66
|
+
autoStart = true,
|
|
67
|
+
headers,
|
|
68
|
+
onMessage,
|
|
69
|
+
onError,
|
|
70
|
+
onOpen,
|
|
71
|
+
onClose,
|
|
72
|
+
onHeartbeat,
|
|
73
|
+
onStateChange,
|
|
74
|
+
events,
|
|
75
|
+
onBeforeRequest,
|
|
76
|
+
...restConfig
|
|
77
|
+
} = safeOptions;
|
|
78
|
+
|
|
79
|
+
// Underlying client reference for imperative callbacks
|
|
80
|
+
const clientRef = useRef(null);
|
|
81
|
+
const [client, setClient] = useState(null);
|
|
82
|
+
const [state, setState] = useState('idle');
|
|
83
|
+
const isConnected = isConnectedState(state);
|
|
84
|
+
|
|
85
|
+
// Validate URL presence for connection guard
|
|
86
|
+
const hasValidUrl = typeof restConfig.url === 'string' && restConfig.url.trim().length > 0;
|
|
87
|
+
|
|
88
|
+
// Keep references to latest options and guard without causing teardown
|
|
89
|
+
const headersRef = useRef(headers);
|
|
90
|
+
const restConfigRef = useRef(restConfig);
|
|
91
|
+
const hasValidUrlRef = useRef(hasValidUrl);
|
|
92
|
+
|
|
93
|
+
// Synchronize options and guard references after render commit without render-phase mutation
|
|
94
|
+
useEffect(() => {
|
|
95
|
+
headersRef.current = headers;
|
|
96
|
+
restConfigRef.current = restConfig;
|
|
97
|
+
hasValidUrlRef.current = hasValidUrl;
|
|
98
|
+
}, [headers, restConfig, hasValidUrl]);
|
|
99
|
+
|
|
100
|
+
// Callback ref holding the latest handler references across renders
|
|
101
|
+
const callbacksRef = useRef({
|
|
102
|
+
onMessage,
|
|
103
|
+
onError,
|
|
104
|
+
onOpen,
|
|
105
|
+
onClose,
|
|
106
|
+
onHeartbeat,
|
|
107
|
+
onStateChange,
|
|
108
|
+
events,
|
|
109
|
+
onBeforeRequest
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
// Synchronize callback references on each render pass to prevent stale closures without render-phase mutation
|
|
113
|
+
useEffect(() => {
|
|
114
|
+
callbacksRef.current = {
|
|
115
|
+
onMessage,
|
|
116
|
+
onError,
|
|
117
|
+
onOpen,
|
|
118
|
+
onClose,
|
|
119
|
+
onHeartbeat,
|
|
120
|
+
onStateChange,
|
|
121
|
+
events,
|
|
122
|
+
onBeforeRequest
|
|
123
|
+
};
|
|
124
|
+
}, [onMessage, onError, onOpen, onClose, onHeartbeat, onStateChange, events, onBeforeRequest]);
|
|
125
|
+
const hasBeforeRequest = Boolean(onBeforeRequest);
|
|
126
|
+
const configKey = safeSerializeConfig(restConfig);
|
|
127
|
+
const headersKey = safeSerializeConfig(headers);
|
|
128
|
+
|
|
129
|
+
// Instantiates the SseClient, attaches typed event listeners, applies configuration, and disposes on unmount
|
|
130
|
+
useEffect(() => {
|
|
131
|
+
let clientInstance = null;
|
|
132
|
+
if (!hasValidUrl) {
|
|
133
|
+
if (autoStart && typeof __DEV__ !== 'undefined' && __DEV__ && restConfig.url !== undefined) {
|
|
134
|
+
console.warn('[useNitroSse] Missing or empty url in options. Connection will not start until a valid URL is provided.');
|
|
135
|
+
}
|
|
136
|
+
setState('idle');
|
|
137
|
+
clientRef.current = null;
|
|
138
|
+
setClient(null);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
try {
|
|
142
|
+
clientInstance = createNitroSse();
|
|
143
|
+
clientRef.current = clientInstance;
|
|
144
|
+
setClient(clientInstance);
|
|
145
|
+
const config = {
|
|
146
|
+
...restConfigRef.current,
|
|
147
|
+
url: restConfigRef.current.url ?? '',
|
|
148
|
+
...(headersRef.current !== undefined ? {
|
|
149
|
+
headers: headersRef.current
|
|
150
|
+
} : {}),
|
|
151
|
+
onBeforeRequest: callbacksRef.current.onBeforeRequest ? async () => {
|
|
152
|
+
return callbacksRef.current.onBeforeRequest();
|
|
153
|
+
} : undefined
|
|
154
|
+
};
|
|
155
|
+
clientInstance.setup(config);
|
|
156
|
+
|
|
157
|
+
// Attach typed event listeners
|
|
158
|
+
clientInstance.addEventListener('message', e => {
|
|
159
|
+
try {
|
|
160
|
+
callbacksRef.current.onMessage?.(e);
|
|
161
|
+
} catch (err) {
|
|
162
|
+
console.error('[useNitroSse] Unhandled error in onMessage callback:', err);
|
|
163
|
+
}
|
|
164
|
+
if (e.event && e.event !== e.type) {
|
|
165
|
+
try {
|
|
166
|
+
const handler = callbacksRef.current.events?.[e.event];
|
|
167
|
+
if (handler) {
|
|
168
|
+
handler(e);
|
|
169
|
+
}
|
|
170
|
+
} catch (err) {
|
|
171
|
+
console.error(`[useNitroSse] Unhandled error in events['${e.event}'] callback:`, err);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
clientInstance.addEventListener('error', e => {
|
|
176
|
+
callbacksRef.current.onError?.(e);
|
|
177
|
+
});
|
|
178
|
+
clientInstance.addEventListener('open', e => {
|
|
179
|
+
callbacksRef.current.onOpen?.(e);
|
|
180
|
+
});
|
|
181
|
+
clientInstance.addEventListener('close', e => {
|
|
182
|
+
callbacksRef.current.onClose?.(e);
|
|
183
|
+
});
|
|
184
|
+
clientInstance.addEventListener('heartbeat', e => {
|
|
185
|
+
callbacksRef.current.onHeartbeat?.(e);
|
|
186
|
+
});
|
|
187
|
+
clientInstance.addEventListener('state', e => {
|
|
188
|
+
const newState = e.state ?? 'idle';
|
|
189
|
+
setState(newState);
|
|
190
|
+
callbacksRef.current.onStateChange?.(newState);
|
|
191
|
+
});
|
|
192
|
+
if (autoStart) {
|
|
193
|
+
clientInstance.start();
|
|
194
|
+
}
|
|
195
|
+
const initialState = clientInstance.getState();
|
|
196
|
+
setState(initialState);
|
|
197
|
+
} catch (e) {
|
|
198
|
+
const errorMsg = e instanceof Error ? e.message : String(e);
|
|
199
|
+
console.error('[useNitroSse] Failed to initialize NitroSse client:', e);
|
|
200
|
+
clientInstance?.dispose();
|
|
201
|
+
clientRef.current = null;
|
|
202
|
+
setClient(null);
|
|
203
|
+
setState('failed');
|
|
204
|
+
try {
|
|
205
|
+
callbacksRef.current.onError?.({
|
|
206
|
+
type: 'error',
|
|
207
|
+
message: errorMsg,
|
|
208
|
+
statusCode: -1
|
|
209
|
+
});
|
|
210
|
+
} catch (err) {
|
|
211
|
+
console.error('[useNitroSse] Unhandled error in onError during initialization failure:', err);
|
|
212
|
+
}
|
|
213
|
+
try {
|
|
214
|
+
callbacksRef.current.onStateChange?.('failed');
|
|
215
|
+
} catch (err) {
|
|
216
|
+
console.error('[useNitroSse] Unhandled error in onStateChange during initialization failure:', err);
|
|
217
|
+
}
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
return () => {
|
|
221
|
+
clientInstance?.dispose();
|
|
222
|
+
clientRef.current = null;
|
|
223
|
+
setClient(null);
|
|
224
|
+
};
|
|
225
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
226
|
+
}, [configKey, autoStart, hasBeforeRequest, hasValidUrl]);
|
|
227
|
+
|
|
228
|
+
// Synchronize headers dynamically without reconnecting or tearing down active socket
|
|
229
|
+
const isInitialMount = useRef(true);
|
|
230
|
+
useEffect(() => {
|
|
231
|
+
if (isInitialMount.current) {
|
|
232
|
+
isInitialMount.current = false;
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (clientRef.current && headers !== undefined) {
|
|
236
|
+
try {
|
|
237
|
+
clientRef.current.updateHeaders(headers);
|
|
238
|
+
} catch (err) {
|
|
239
|
+
console.error('[useNitroSse] Failed to dynamically update headers:', err);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
243
|
+
}, [headersKey]);
|
|
244
|
+
|
|
245
|
+
// Imperative control callbacks wrapped in useCallback for stable references
|
|
246
|
+
const start = useCallback(() => {
|
|
247
|
+
if (clientRef.current) {
|
|
248
|
+
try {
|
|
249
|
+
clientRef.current.start();
|
|
250
|
+
const s = clientRef.current.getState();
|
|
251
|
+
setState(s);
|
|
252
|
+
} catch (err) {
|
|
253
|
+
console.error('[useNitroSse] Failed to start client:', err);
|
|
254
|
+
}
|
|
255
|
+
} else if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
256
|
+
if (!hasValidUrlRef.current) {
|
|
257
|
+
console.warn('[useNitroSse] Cannot start SSE stream: url is empty or invalid.');
|
|
258
|
+
} else {
|
|
259
|
+
console.warn('[useNitroSse] start() was called before the client was initialized.');
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}, []);
|
|
263
|
+
const stop = useCallback(() => {
|
|
264
|
+
if (clientRef.current) {
|
|
265
|
+
try {
|
|
266
|
+
clientRef.current.stop();
|
|
267
|
+
const s = clientRef.current.getState();
|
|
268
|
+
setState(s);
|
|
269
|
+
} catch (err) {
|
|
270
|
+
console.error('[useNitroSse] Failed to stop client:', err);
|
|
271
|
+
}
|
|
272
|
+
} else if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
273
|
+
console.warn('[useNitroSse] stop() was called before the client was initialized.');
|
|
274
|
+
}
|
|
275
|
+
}, []);
|
|
276
|
+
const restart = useCallback(() => {
|
|
277
|
+
if (clientRef.current) {
|
|
278
|
+
try {
|
|
279
|
+
clientRef.current.restart();
|
|
280
|
+
const s = clientRef.current.getState();
|
|
281
|
+
setState(s);
|
|
282
|
+
} catch (err) {
|
|
283
|
+
console.error('[useNitroSse] Failed to restart client:', err);
|
|
284
|
+
}
|
|
285
|
+
} else if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
286
|
+
if (!hasValidUrlRef.current) {
|
|
287
|
+
console.warn('[useNitroSse] Cannot restart SSE stream: url is empty or invalid.');
|
|
288
|
+
} else {
|
|
289
|
+
console.warn('[useNitroSse] restart() was called before the client was initialized.');
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}, []);
|
|
293
|
+
const flush = useCallback(() => {
|
|
294
|
+
if (clientRef.current) {
|
|
295
|
+
try {
|
|
296
|
+
clientRef.current.flush();
|
|
297
|
+
} catch (err) {
|
|
298
|
+
console.error('[useNitroSse] Failed to flush events:', err);
|
|
299
|
+
}
|
|
300
|
+
} else if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
301
|
+
console.warn('[useNitroSse] flush() was called before the client was initialized.');
|
|
302
|
+
}
|
|
303
|
+
}, []);
|
|
304
|
+
const updateHeaders = useCallback(newHeaders => {
|
|
305
|
+
if (clientRef.current) {
|
|
306
|
+
try {
|
|
307
|
+
clientRef.current.updateHeaders(newHeaders);
|
|
308
|
+
} catch (err) {
|
|
309
|
+
console.error('[useNitroSse] Failed to update headers:', err);
|
|
310
|
+
}
|
|
311
|
+
} else if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
312
|
+
console.warn('[useNitroSse] updateHeaders() was called before the client was initialized.');
|
|
313
|
+
}
|
|
314
|
+
}, []);
|
|
315
|
+
const setLastProcessedId = useCallback(id => {
|
|
316
|
+
if (clientRef.current) {
|
|
317
|
+
try {
|
|
318
|
+
clientRef.current.setLastProcessedId(id);
|
|
319
|
+
} catch (err) {
|
|
320
|
+
console.error('[useNitroSse] Failed to set last processed ID:', err);
|
|
321
|
+
}
|
|
322
|
+
} else if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
323
|
+
console.warn('[useNitroSse] setLastProcessedId() was called before the client was initialized.');
|
|
324
|
+
}
|
|
325
|
+
}, []);
|
|
326
|
+
const getStats = useCallback(() => {
|
|
327
|
+
try {
|
|
328
|
+
return clientRef.current?.getStats();
|
|
329
|
+
} catch {
|
|
330
|
+
return undefined;
|
|
331
|
+
}
|
|
332
|
+
}, []);
|
|
333
|
+
const injectMockEvent = useCallback(event => {
|
|
334
|
+
if (clientRef.current) {
|
|
335
|
+
try {
|
|
336
|
+
clientRef.current.injectMockEvent(event);
|
|
337
|
+
} catch (err) {
|
|
338
|
+
console.error('[useNitroSse] Failed to inject mock event:', err);
|
|
339
|
+
}
|
|
340
|
+
} else if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
341
|
+
console.warn('[useNitroSse] injectMockEvent() was called before the client was initialized.');
|
|
342
|
+
}
|
|
343
|
+
}, []);
|
|
344
|
+
return {
|
|
345
|
+
client: client ?? clientRef.current,
|
|
346
|
+
isReady: Boolean(client ?? clientRef.current),
|
|
347
|
+
state,
|
|
348
|
+
isConnected,
|
|
349
|
+
start,
|
|
350
|
+
stop,
|
|
351
|
+
restart,
|
|
352
|
+
flush,
|
|
353
|
+
updateHeaders,
|
|
354
|
+
setLastProcessedId,
|
|
355
|
+
getStats,
|
|
356
|
+
injectMockEvent
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
//# sourceMappingURL=useNitroSse.js.map
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { SseEvent, SseMockConfig, SseMockEvent, SseState, SseStats } from './SseInterface';
|
|
2
|
+
/**
|
|
3
|
+
* Encapsulates mock streaming logic for testing and offline simulation.
|
|
4
|
+
* Handles timer intervals, looping, custom delays, simulated error rates, and mock state tracking.
|
|
5
|
+
*/
|
|
6
|
+
export declare class MockSseEngine {
|
|
7
|
+
private _config;
|
|
8
|
+
private _emitEvents;
|
|
9
|
+
private _mockIntervalId?;
|
|
10
|
+
private _mockIndex;
|
|
11
|
+
private _mockState?;
|
|
12
|
+
private _totalBytesReceived;
|
|
13
|
+
constructor(config: SseMockConfig, emitEvents: (events: SseEvent[]) => void);
|
|
14
|
+
/**
|
|
15
|
+
* Transforms a raw mock event definition or partial SSE event into a full SseEvent DTO.
|
|
16
|
+
*/
|
|
17
|
+
static createSseEvent(rawMock: Partial<SseMockEvent> | Partial<SseEvent>): SseEvent;
|
|
18
|
+
private _setMockState;
|
|
19
|
+
/**
|
|
20
|
+
* Starts mock stream scheduling.
|
|
21
|
+
* @returns true if native stream should be skipped (replace mode), false otherwise (inject mode).
|
|
22
|
+
*/
|
|
23
|
+
start(): boolean;
|
|
24
|
+
stop(): void;
|
|
25
|
+
restart(): void;
|
|
26
|
+
isConnected(): boolean;
|
|
27
|
+
getStats(): SseStats;
|
|
28
|
+
getState(): SseState;
|
|
29
|
+
injectEvent(event: Partial<SseEvent>): void;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=MockSseEngine.d.ts.map
|
|
@@ -1,5 +1,28 @@
|
|
|
1
|
-
import type { HybridObject } from 'react-native-nitro-modules';
|
|
2
|
-
import type { SseConfig,
|
|
1
|
+
import type { HybridObject, AnyMap } from 'react-native-nitro-modules';
|
|
2
|
+
import type { SseConfig, SseStats, SseState, SseEventType } from './SseInterface';
|
|
3
|
+
/**
|
|
4
|
+
* Concrete SSE event representation passed across the JSI barrier.
|
|
5
|
+
*/
|
|
6
|
+
export interface SseEvent {
|
|
7
|
+
/** The type of the event. */
|
|
8
|
+
type: SseEventType;
|
|
9
|
+
/** The data payload of the event as a raw string. */
|
|
10
|
+
data?: string;
|
|
11
|
+
/** The parsed JSON data, if autoParseJSON is enabled and parsing succeeds. */
|
|
12
|
+
parsedData?: AnyMap;
|
|
13
|
+
/** The event ID, if provided. */
|
|
14
|
+
id?: string;
|
|
15
|
+
/** The event name, if provided (internal 'event' field in SSE). */
|
|
16
|
+
event?: string;
|
|
17
|
+
/** System message or error description. */
|
|
18
|
+
message?: string;
|
|
19
|
+
/** HTTP status code if applicable. */
|
|
20
|
+
statusCode?: number;
|
|
21
|
+
/** Server-requested retry delay in milliseconds. */
|
|
22
|
+
retry?: number;
|
|
23
|
+
/** The current connection state (only available if type is 'state'). */
|
|
24
|
+
state?: SseState;
|
|
25
|
+
}
|
|
3
26
|
export interface NitroSse extends HybridObject<{
|
|
4
27
|
ios: 'swift';
|
|
5
28
|
android: 'kotlin';
|