react-native-nitro-sse 2.4.2 → 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 -36
- package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +164 -88
- 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 -25
- 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 +2 -4
- package/ios/NitroSse.swift +229 -191
- package/ios/SseConfig+CopyWith.swift +2 -1
- package/ios/SseConnectionHandler.swift +40 -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 +5 -0
- package/ios/SseReconnectStrategy.swift +4 -3
- package/lib/module/MockSseEngine.js +12 -21
- package/lib/module/NitroSseClient.js +385 -12
- package/lib/module/NitroSseError.js +61 -0
- package/lib/module/SseDriver.js +33 -2
- package/lib/module/index.js +6 -3
- package/lib/module/useNitroSse.js +359 -0
- package/lib/typescript/src/MockSseEngine.d.ts +1 -1
- package/lib/typescript/src/NitroSse.nitro.d.ts +25 -2
- package/lib/typescript/src/NitroSseClient.d.ts +20 -2
- package/lib/typescript/src/NitroSseError.d.ts +38 -0
- package/lib/typescript/src/SseDriver.d.ts +10 -2
- package/lib/typescript/src/SseInterface.d.ts +23 -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 +5 -1
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +9 -4
- package/nitrogen/generated/ios/swift/SseConfig.swift +19 -1
- package/nitrogen/generated/shared/c++/SseConfig.hpp +5 -1
- package/package.json +8 -7
- package/android/jacoco.gradle +0 -33
- package/lib/module/MockSseEngine.js.map +0 -1
- package/lib/module/NitroSse.nitro.js.map +0 -1
- package/lib/module/NitroSseClient.js.map +0 -1
- package/lib/module/SseDriver.js.map +0 -1
- package/lib/module/SseInterface.js.map +0 -1
- package/lib/module/index.js.map +0 -1
- package/lib/typescript/src/MockSseEngine.d.ts.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/SseDriver.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/MockSseEngine.ts +0 -254
- package/src/NitroSse.nitro.ts +0 -58
- package/src/NitroSseClient.ts +0 -154
- package/src/SseDriver.ts +0 -161
- package/src/SseInterface.ts +0 -274
- package/src/index.ts +0 -31
|
@@ -2,20 +2,286 @@
|
|
|
2
2
|
|
|
3
3
|
import { MockSseEngine } from "./MockSseEngine.js";
|
|
4
4
|
import { NativeDriver, MockReplaceDriver, MockInjectDriver } from "./SseDriver.js";
|
|
5
|
+
import { NitroSseValidationError, NitroSseDisposedError, NitroSseStateError } from "./NitroSseError.js";
|
|
6
|
+
/**
|
|
7
|
+
* Sanitizes HTTP headers by stripping carriage returns, newlines, null bytes,
|
|
8
|
+
* converting non-string values to strings, and pruning null/undefined values.
|
|
9
|
+
*/
|
|
10
|
+
export function sanitizeHeaders(headers) {
|
|
11
|
+
if (!headers || typeof headers !== 'object' || Array.isArray(headers)) {
|
|
12
|
+
return {};
|
|
13
|
+
}
|
|
14
|
+
const clean = {};
|
|
15
|
+
for (const [key, rawValue] of Object.entries(headers)) {
|
|
16
|
+
if (rawValue === null || rawValue === undefined) continue;
|
|
17
|
+
const cleanKey = String(key).replace(/[\r\n\0]+/g, '').trim();
|
|
18
|
+
if (!cleanKey) continue;
|
|
19
|
+
const cleanVal = String(rawValue).replace(/[\r\n\0]+/g, '');
|
|
20
|
+
clean[cleanKey] = cleanVal;
|
|
21
|
+
}
|
|
22
|
+
return clean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Defensively validates and normalizes the SSE configuration object.
|
|
27
|
+
* Throws NitroSseValidationError if essential requirements (e.g. valid URL) are violated.
|
|
28
|
+
* Clamps numeric properties to safe boundaries and warns in __DEV__.
|
|
29
|
+
*/
|
|
30
|
+
export function validateConfig(config) {
|
|
31
|
+
if (!config || typeof config !== 'object' || Array.isArray(config)) {
|
|
32
|
+
throw new NitroSseValidationError('[NitroSse] Invalid config: Expected a configuration object.', 'INVALID_CONFIG', {
|
|
33
|
+
received: config
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
const rawUrl = config.url;
|
|
37
|
+
if (typeof rawUrl !== 'string' || !rawUrl.trim()) {
|
|
38
|
+
throw new NitroSseValidationError("[NitroSse] Invalid config: 'url' must be a non-empty string.", 'INVALID_CONFIG', {
|
|
39
|
+
received: rawUrl
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
const trimmedUrl = config.url.trim();
|
|
43
|
+
const lowerUrl = trimmedUrl.toLowerCase();
|
|
44
|
+
if (
|
|
45
|
+
// eslint-disable-next-line no-script-url
|
|
46
|
+
lowerUrl.startsWith('javascript:') || lowerUrl.startsWith('data:') || lowerUrl.startsWith('file:') || lowerUrl.startsWith('ftp:') || lowerUrl.startsWith('ws:') || lowerUrl.startsWith('wss:')) {
|
|
47
|
+
const isWs = lowerUrl.startsWith('ws:') || lowerUrl.startsWith('wss:');
|
|
48
|
+
const reason = isWs ? `Unsupported protocol (WebSocket "${trimmedUrl}"). SSE requires HTTP or HTTPS.` : `Unsupported protocol in URL "${trimmedUrl}". SSE requires HTTP or HTTPS.`;
|
|
49
|
+
throw new NitroSseValidationError(`[NitroSse] Invalid config: ${reason}`, 'INVALID_CONFIG', {
|
|
50
|
+
url: trimmedUrl
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
if (!lowerUrl.startsWith('http://') && !lowerUrl.startsWith('https://')) {
|
|
54
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
55
|
+
console.warn(`[NitroSse] URL "${trimmedUrl}" does not start with http:// or https://. Ensure it is an absolute URL; relative paths will fail on native.`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (config.headers !== undefined) {
|
|
59
|
+
if (!config.headers || typeof config.headers !== 'object' || Array.isArray(config.headers)) {
|
|
60
|
+
throw new NitroSseValidationError("[NitroSse] Invalid config: 'headers' must be an object of key-value pairs.", 'INVALID_CONFIG', {
|
|
61
|
+
received: config.headers
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
let lowerMethod;
|
|
66
|
+
if (config.method !== undefined) {
|
|
67
|
+
if (typeof config.method !== 'string') {
|
|
68
|
+
throw new NitroSseValidationError(`[NitroSse] Invalid config: 'method' must be a string ('get' or 'post').`, 'INVALID_CONFIG', {
|
|
69
|
+
received: config.method
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
const lm = config.method.toLowerCase();
|
|
73
|
+
if (lm === 'get' || lm === 'post') {
|
|
74
|
+
lowerMethod = lm;
|
|
75
|
+
} else {
|
|
76
|
+
throw new NitroSseValidationError(`[NitroSse] Invalid config: 'method' must be 'get' or 'post', received '${config.method}'.`, 'INVALID_CONFIG', {
|
|
77
|
+
received: config.method
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (config.onBeforeRequest !== undefined && typeof config.onBeforeRequest !== 'function') {
|
|
82
|
+
throw new NitroSseValidationError("[NitroSse] Invalid config: 'onBeforeRequest' must be a function.", 'INVALID_CONFIG', {
|
|
83
|
+
received: typeof config.onBeforeRequest
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
let connectionTimeoutMs = config.connectionTimeoutMs;
|
|
87
|
+
if (connectionTimeoutMs !== undefined) {
|
|
88
|
+
if (!Number.isFinite(connectionTimeoutMs) || connectionTimeoutMs < 0) {
|
|
89
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
90
|
+
console.warn(`[NitroSse] Invalid connectionTimeoutMs (${connectionTimeoutMs}). Resetting to default 15000.`);
|
|
91
|
+
}
|
|
92
|
+
connectionTimeoutMs = 15000;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
let readTimeoutMs = config.readTimeoutMs;
|
|
96
|
+
if (readTimeoutMs !== undefined) {
|
|
97
|
+
if (!Number.isFinite(readTimeoutMs) || readTimeoutMs <= 0) {
|
|
98
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
99
|
+
console.warn(`[NitroSse] Invalid readTimeoutMs (${readTimeoutMs}). Resetting to default 300000.`);
|
|
100
|
+
}
|
|
101
|
+
readTimeoutMs = 300000;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
let batchingIntervalMs = config.batchingIntervalMs;
|
|
105
|
+
if (batchingIntervalMs !== undefined) {
|
|
106
|
+
if (!Number.isFinite(batchingIntervalMs) || batchingIntervalMs < 0) {
|
|
107
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
108
|
+
console.warn(`[NitroSse] Invalid batchingIntervalMs (${batchingIntervalMs}). Clamping to 0.`);
|
|
109
|
+
}
|
|
110
|
+
batchingIntervalMs = 0;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
let maxBufferSize = config.maxBufferSize;
|
|
114
|
+
if (maxBufferSize !== undefined) {
|
|
115
|
+
if (!Number.isFinite(maxBufferSize) || maxBufferSize <= 0) {
|
|
116
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
117
|
+
console.warn(`[NitroSse] Invalid maxBufferSize (${maxBufferSize}). Resetting to default 1000.`);
|
|
118
|
+
}
|
|
119
|
+
maxBufferSize = 1000;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
let retryIntervalMs = config.retryIntervalMs;
|
|
123
|
+
let maxRetryIntervalMs = config.maxRetryIntervalMs;
|
|
124
|
+
if (retryIntervalMs !== undefined) {
|
|
125
|
+
if (!Number.isFinite(retryIntervalMs) || retryIntervalMs < 0) {
|
|
126
|
+
retryIntervalMs = 1000;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (maxRetryIntervalMs !== undefined) {
|
|
130
|
+
if (!Number.isFinite(maxRetryIntervalMs) || maxRetryIntervalMs < 0) {
|
|
131
|
+
maxRetryIntervalMs = 30000;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (retryIntervalMs !== undefined && maxRetryIntervalMs !== undefined && retryIntervalMs > maxRetryIntervalMs) {
|
|
135
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
136
|
+
console.warn(`[NitroSse] retryIntervalMs (${retryIntervalMs}) cannot exceed maxRetryIntervalMs (${maxRetryIntervalMs}). Clamping retryIntervalMs.`);
|
|
137
|
+
}
|
|
138
|
+
retryIntervalMs = maxRetryIntervalMs;
|
|
139
|
+
}
|
|
140
|
+
let jitterFactor = config.jitterFactor;
|
|
141
|
+
if (jitterFactor !== undefined) {
|
|
142
|
+
if (!Number.isFinite(jitterFactor) || jitterFactor < 0 || jitterFactor > 1) {
|
|
143
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
144
|
+
console.warn(`[NitroSse] Invalid jitterFactor (${jitterFactor}). Clamping between 0.0 and 1.0.`);
|
|
145
|
+
}
|
|
146
|
+
jitterFactor = Math.max(0, Math.min(1, Number.isFinite(jitterFactor) ? jitterFactor : 0.5));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
let maxReconnectAttempts = config.maxReconnectAttempts;
|
|
150
|
+
if (maxReconnectAttempts !== undefined) {
|
|
151
|
+
if (!Number.isFinite(maxReconnectAttempts) || maxReconnectAttempts < -1) {
|
|
152
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
153
|
+
console.warn(`[NitroSse] Invalid maxReconnectAttempts (${maxReconnectAttempts}). Defaulting to -1 (infinite).`);
|
|
154
|
+
}
|
|
155
|
+
maxReconnectAttempts = -1;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
let maxAuthRetries = config.maxAuthRetries;
|
|
159
|
+
if (maxAuthRetries !== undefined) {
|
|
160
|
+
if (!Number.isFinite(maxAuthRetries) || maxAuthRetries < 0) {
|
|
161
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
162
|
+
console.warn(`[NitroSse] Invalid maxAuthRetries (${maxAuthRetries}). Defaulting to 3.`);
|
|
163
|
+
}
|
|
164
|
+
maxAuthRetries = 3;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (config.mock !== undefined) {
|
|
168
|
+
if (!config.mock || typeof config.mock !== 'object') {
|
|
169
|
+
throw new NitroSseValidationError('[NitroSse] Invalid mock config: Expected an object.', 'INVALID_CONFIG', {
|
|
170
|
+
received: config.mock
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
const mode = config.mock.mode;
|
|
174
|
+
if (mode !== 'replace' && mode !== 'inject') {
|
|
175
|
+
throw new NitroSseValidationError(`[NitroSse] Invalid mock config: 'mode' must be 'replace' or 'inject', received '${String(mode)}'.`, 'INVALID_CONFIG', {
|
|
176
|
+
received: mode
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
if (!Array.isArray(config.mock.data)) {
|
|
180
|
+
throw new NitroSseValidationError("[NitroSse] Invalid mock config: 'data' must be an array of mock events.", 'INVALID_CONFIG', {
|
|
181
|
+
received: typeof config.mock.data
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return {
|
|
186
|
+
...config,
|
|
187
|
+
url: trimmedUrl,
|
|
188
|
+
...(lowerMethod !== undefined ? {
|
|
189
|
+
method: lowerMethod
|
|
190
|
+
} : {}),
|
|
191
|
+
...(connectionTimeoutMs !== undefined ? {
|
|
192
|
+
connectionTimeoutMs
|
|
193
|
+
} : {}),
|
|
194
|
+
...(readTimeoutMs !== undefined ? {
|
|
195
|
+
readTimeoutMs
|
|
196
|
+
} : {}),
|
|
197
|
+
...(batchingIntervalMs !== undefined ? {
|
|
198
|
+
batchingIntervalMs
|
|
199
|
+
} : {}),
|
|
200
|
+
...(maxBufferSize !== undefined ? {
|
|
201
|
+
maxBufferSize
|
|
202
|
+
} : {}),
|
|
203
|
+
...(retryIntervalMs !== undefined ? {
|
|
204
|
+
retryIntervalMs
|
|
205
|
+
} : {}),
|
|
206
|
+
...(maxRetryIntervalMs !== undefined ? {
|
|
207
|
+
maxRetryIntervalMs
|
|
208
|
+
} : {}),
|
|
209
|
+
...(jitterFactor !== undefined ? {
|
|
210
|
+
jitterFactor
|
|
211
|
+
} : {}),
|
|
212
|
+
...(maxReconnectAttempts !== undefined ? {
|
|
213
|
+
maxReconnectAttempts
|
|
214
|
+
} : {}),
|
|
215
|
+
...(maxAuthRetries !== undefined ? {
|
|
216
|
+
maxAuthRetries
|
|
217
|
+
} : {})
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
5
221
|
/**
|
|
6
222
|
* Public facade and typed event emitter for NitroSse, delegating streaming execution to an SseDriver strategy.
|
|
7
223
|
*/
|
|
8
224
|
export class NitroSseClient {
|
|
9
225
|
_listeners = new Map();
|
|
226
|
+
_isDisposed = false;
|
|
227
|
+
_pendingHeaders = {};
|
|
10
228
|
constructor(native) {
|
|
11
229
|
this._native = native;
|
|
12
230
|
this._driver = new NativeDriver(native, events => this._dispatchEvents(events));
|
|
13
231
|
}
|
|
232
|
+
get isDisposed() {
|
|
233
|
+
return this._isDisposed;
|
|
234
|
+
}
|
|
235
|
+
_checkDisposed() {
|
|
236
|
+
if (this._isDisposed) {
|
|
237
|
+
throw new NitroSseDisposedError();
|
|
238
|
+
}
|
|
239
|
+
}
|
|
14
240
|
setup(config, onEvent) {
|
|
15
|
-
this.
|
|
241
|
+
this._checkDisposed();
|
|
242
|
+
if (onEvent !== undefined && typeof onEvent !== 'function') {
|
|
243
|
+
throw new NitroSseValidationError("[NitroSse] setup: 'onEvent' must be a function.", 'INVALID_ARGUMENT', {
|
|
244
|
+
received: typeof onEvent
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
const validatedConfig = validateConfig(config);
|
|
248
|
+
if (this.isConnected()) {
|
|
249
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
250
|
+
console.warn('[NitroSse] setup() called while connection is active; stopping previous stream before reconfiguring.');
|
|
251
|
+
}
|
|
252
|
+
this._driver?.stop();
|
|
253
|
+
}
|
|
254
|
+
const hasHeaders = Object.keys(this._pendingHeaders).length > 0 || validatedConfig.headers !== undefined;
|
|
255
|
+
const cleanHeaders = hasHeaders ? sanitizeHeaders({
|
|
256
|
+
...this._pendingHeaders,
|
|
257
|
+
...validatedConfig.headers
|
|
258
|
+
}) : undefined;
|
|
259
|
+
const rawOnBeforeRequest = validatedConfig.onBeforeRequest;
|
|
260
|
+
const safeOnBeforeRequest = rawOnBeforeRequest ? async () => {
|
|
261
|
+
try {
|
|
262
|
+
const h = await rawOnBeforeRequest();
|
|
263
|
+
if (h && typeof h === 'object' && !Array.isArray(h)) {
|
|
264
|
+
return sanitizeHeaders(h);
|
|
265
|
+
}
|
|
266
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__ && h !== undefined && h !== null) {
|
|
267
|
+
console.warn('[NitroSse] onBeforeRequest returned an invalid headers value (expected an object):', h);
|
|
268
|
+
}
|
|
269
|
+
return {};
|
|
270
|
+
} catch (err) {
|
|
271
|
+
console.error('[NitroSse] Error in onBeforeRequest interceptor:', err);
|
|
272
|
+
throw err;
|
|
273
|
+
}
|
|
274
|
+
} : undefined;
|
|
16
275
|
this._config = {
|
|
17
|
-
...
|
|
276
|
+
...validatedConfig,
|
|
277
|
+
...(cleanHeaders !== undefined ? {
|
|
278
|
+
headers: cleanHeaders
|
|
279
|
+
} : {}),
|
|
280
|
+
...(safeOnBeforeRequest !== undefined ? {
|
|
281
|
+
onBeforeRequest: safeOnBeforeRequest
|
|
282
|
+
} : {})
|
|
18
283
|
};
|
|
284
|
+
this._pendingHeaders = {};
|
|
19
285
|
this._legacyCallback = onEvent;
|
|
20
286
|
const isDev = typeof __DEV__ !== 'undefined' ? __DEV__ === true : false;
|
|
21
287
|
const mockConfig = isDev ? this._config.mock : undefined;
|
|
@@ -40,64 +306,171 @@ export class NitroSseClient {
|
|
|
40
306
|
}
|
|
41
307
|
}
|
|
42
308
|
addEventListener(type, listener) {
|
|
43
|
-
|
|
44
|
-
|
|
309
|
+
this._checkDisposed();
|
|
310
|
+
if (typeof type !== 'string' || !type.trim()) {
|
|
311
|
+
throw new NitroSseValidationError("[NitroSse] addEventListener: 'type' must be a non-empty string.", 'INVALID_ARGUMENT', {
|
|
312
|
+
received: type
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
if (typeof listener !== 'function') {
|
|
316
|
+
throw new NitroSseValidationError("[NitroSse] addEventListener: 'listener' must be a function.", 'INVALID_ARGUMENT', {
|
|
317
|
+
received: typeof listener
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
const cleanType = type.trim();
|
|
321
|
+
if (!this._listeners.has(cleanType)) {
|
|
322
|
+
this._listeners.set(cleanType, new Set());
|
|
45
323
|
}
|
|
46
|
-
this._listeners.get(
|
|
324
|
+
this._listeners.get(cleanType).add(listener);
|
|
47
325
|
}
|
|
48
326
|
removeEventListener(type, listener) {
|
|
49
|
-
this.
|
|
327
|
+
this._checkDisposed();
|
|
328
|
+
if (typeof type !== 'string' || typeof listener !== 'function') {
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
this._listeners.get(type.trim())?.delete(listener);
|
|
332
|
+
}
|
|
333
|
+
removeAllEventListeners(type) {
|
|
334
|
+
this._checkDisposed();
|
|
335
|
+
if (type !== undefined) {
|
|
336
|
+
if (typeof type === 'string' && type.trim()) {
|
|
337
|
+
this._listeners.delete(type.trim());
|
|
338
|
+
}
|
|
339
|
+
} else {
|
|
340
|
+
this._listeners.clear();
|
|
341
|
+
}
|
|
50
342
|
}
|
|
51
343
|
_emit(type, event) {
|
|
52
344
|
const listeners = this._listeners.get(type);
|
|
53
|
-
if (listeners)
|
|
54
|
-
|
|
345
|
+
if (!listeners || listeners.size === 0) return;
|
|
346
|
+
|
|
347
|
+
// Fast-path for the most common case (single listener)
|
|
348
|
+
if (listeners.size === 1) {
|
|
349
|
+
for (const listener of listeners) {
|
|
55
350
|
try {
|
|
56
351
|
listener(event);
|
|
57
352
|
} catch (e) {
|
|
58
353
|
console.error(`[NitroSse] Error in event listener for "${type}":`, e);
|
|
59
354
|
}
|
|
60
|
-
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// Multi-listener path: snapshot count to skip listeners added mid-iteration
|
|
360
|
+
const snapshot = listeners.size;
|
|
361
|
+
let i = 0;
|
|
362
|
+
for (const listener of listeners) {
|
|
363
|
+
if (i++ >= snapshot) break;
|
|
364
|
+
try {
|
|
365
|
+
listener(event);
|
|
366
|
+
} catch (e) {
|
|
367
|
+
console.error(`[NitroSse] Error in event listener for "${type}":`, e);
|
|
368
|
+
}
|
|
61
369
|
}
|
|
62
370
|
}
|
|
63
371
|
_dispatchEvents(events) {
|
|
64
|
-
this.
|
|
372
|
+
if (this._isDisposed || !Array.isArray(events)) return;
|
|
373
|
+
try {
|
|
374
|
+
this._legacyCallback?.(events);
|
|
375
|
+
} catch (e) {
|
|
376
|
+
console.error('[NitroSse] Error in legacy onEvent callback:', e);
|
|
377
|
+
}
|
|
65
378
|
for (const event of events) {
|
|
66
|
-
|
|
379
|
+
if (!event || typeof event !== 'object') continue;
|
|
380
|
+
if (event.type) {
|
|
381
|
+
this._emit(event.type, event);
|
|
382
|
+
}
|
|
67
383
|
if (event.event && event.event !== event.type) {
|
|
68
384
|
this._emit(event.event, event);
|
|
69
385
|
}
|
|
70
386
|
}
|
|
71
387
|
}
|
|
72
388
|
start() {
|
|
389
|
+
this._checkDisposed();
|
|
390
|
+
if (!this._config) {
|
|
391
|
+
throw new NitroSseStateError('[NitroSse] Cannot start SSE stream: client is not configured. Call setup(config) first.');
|
|
392
|
+
}
|
|
73
393
|
this._driver.start();
|
|
74
394
|
}
|
|
75
395
|
stop() {
|
|
396
|
+
this._checkDisposed();
|
|
76
397
|
this._driver.stop();
|
|
77
398
|
}
|
|
78
399
|
restart() {
|
|
400
|
+
this._checkDisposed();
|
|
401
|
+
if (!this._config) {
|
|
402
|
+
throw new NitroSseStateError('[NitroSse] Cannot restart SSE stream: client is not configured. Call setup(config) first.');
|
|
403
|
+
}
|
|
79
404
|
this._driver.restart();
|
|
80
405
|
}
|
|
81
406
|
flush() {
|
|
407
|
+
this._checkDisposed();
|
|
82
408
|
this._driver.flush();
|
|
83
409
|
}
|
|
84
410
|
isConnected() {
|
|
411
|
+
if (this._isDisposed) return false;
|
|
85
412
|
return this._driver.isConnected();
|
|
86
413
|
}
|
|
87
414
|
getStats() {
|
|
415
|
+
if (this._isDisposed) {
|
|
416
|
+
return {
|
|
417
|
+
totalBytesReceived: 0,
|
|
418
|
+
reconnectCount: 0
|
|
419
|
+
};
|
|
420
|
+
}
|
|
88
421
|
return this._driver.getStats();
|
|
89
422
|
}
|
|
90
423
|
getState() {
|
|
424
|
+
if (this._isDisposed) return 'closed';
|
|
91
425
|
return this._driver.getState();
|
|
92
426
|
}
|
|
93
427
|
updateHeaders(headers) {
|
|
94
|
-
this.
|
|
428
|
+
this._checkDisposed();
|
|
429
|
+
if (!headers || typeof headers !== 'object' || Array.isArray(headers)) {
|
|
430
|
+
throw new NitroSseValidationError("[NitroSse] updateHeaders: 'headers' must be an object of key-value pairs.", 'INVALID_ARGUMENT', {
|
|
431
|
+
received: headers
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
const clean = sanitizeHeaders(headers);
|
|
435
|
+
if (!this._config) {
|
|
436
|
+
this._pendingHeaders = {
|
|
437
|
+
...this._pendingHeaders,
|
|
438
|
+
...clean
|
|
439
|
+
};
|
|
440
|
+
this._driver.updateHeaders(clean);
|
|
441
|
+
} else {
|
|
442
|
+
this._config.headers = {
|
|
443
|
+
...this._config.headers,
|
|
444
|
+
...clean
|
|
445
|
+
};
|
|
446
|
+
this._driver.updateHeaders(this._config.headers);
|
|
447
|
+
}
|
|
95
448
|
}
|
|
96
449
|
setLastProcessedId(id) {
|
|
450
|
+
this._checkDisposed();
|
|
451
|
+
if (typeof id !== 'string') {
|
|
452
|
+
throw new NitroSseValidationError("[NitroSse] setLastProcessedId: 'id' must be a string.", 'INVALID_ARGUMENT', {
|
|
453
|
+
received: id
|
|
454
|
+
});
|
|
455
|
+
}
|
|
97
456
|
this._driver.setLastProcessedId(id);
|
|
98
457
|
}
|
|
99
458
|
injectMockEvent(event) {
|
|
459
|
+
this._checkDisposed();
|
|
460
|
+
if (!event || typeof event !== 'object' || Array.isArray(event)) {
|
|
461
|
+
throw new NitroSseValidationError("[NitroSse] injectMockEvent: 'event' must be an object.", 'INVALID_ARGUMENT', {
|
|
462
|
+
received: event
|
|
463
|
+
});
|
|
464
|
+
}
|
|
100
465
|
this._driver.injectMockEvent(event);
|
|
101
466
|
}
|
|
467
|
+
dispose() {
|
|
468
|
+
if (this._isDisposed) return;
|
|
469
|
+
this._isDisposed = true;
|
|
470
|
+
this._listeners.clear();
|
|
471
|
+
this._legacyCallback = undefined;
|
|
472
|
+
this._pendingHeaders = {};
|
|
473
|
+
this._driver?.dispose();
|
|
474
|
+
}
|
|
102
475
|
}
|
|
103
476
|
//# sourceMappingURL=NitroSseClient.js.map
|
|
@@ -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
|
package/lib/module/SseDriver.js
CHANGED
|
@@ -45,15 +45,30 @@ export class NativeDriver {
|
|
|
45
45
|
const sseEvent = MockSseEngine.createSseEvent(event);
|
|
46
46
|
this._dispatchEvents([sseEvent]);
|
|
47
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
|
+
}
|
|
48
56
|
}
|
|
49
57
|
|
|
50
58
|
/**
|
|
51
59
|
* Driver simulating the entire SSE stream in JavaScript without native networking.
|
|
52
60
|
*/
|
|
53
61
|
export class MockReplaceDriver {
|
|
62
|
+
_headers = {};
|
|
54
63
|
constructor(_mockEngine) {
|
|
55
64
|
this._mockEngine = _mockEngine;
|
|
56
65
|
}
|
|
66
|
+
get headers() {
|
|
67
|
+
return this._headers;
|
|
68
|
+
}
|
|
69
|
+
get lastProcessedId() {
|
|
70
|
+
return this._lastProcessedId;
|
|
71
|
+
}
|
|
57
72
|
start() {
|
|
58
73
|
this._mockEngine.start();
|
|
59
74
|
}
|
|
@@ -73,11 +88,21 @@ export class MockReplaceDriver {
|
|
|
73
88
|
getState() {
|
|
74
89
|
return this._mockEngine.getState();
|
|
75
90
|
}
|
|
76
|
-
updateHeaders(
|
|
77
|
-
|
|
91
|
+
updateHeaders(headers) {
|
|
92
|
+
this._headers = {
|
|
93
|
+
...this._headers,
|
|
94
|
+
...headers
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
setLastProcessedId(id) {
|
|
98
|
+
this._lastProcessedId = id;
|
|
99
|
+
}
|
|
78
100
|
injectMockEvent(event) {
|
|
79
101
|
this._mockEngine.injectEvent(event);
|
|
80
102
|
}
|
|
103
|
+
dispose() {
|
|
104
|
+
this._mockEngine.stop();
|
|
105
|
+
}
|
|
81
106
|
}
|
|
82
107
|
|
|
83
108
|
/**
|
|
@@ -121,5 +146,11 @@ export class MockInjectDriver {
|
|
|
121
146
|
injectMockEvent(event) {
|
|
122
147
|
this._mockEngine.injectEvent(event);
|
|
123
148
|
}
|
|
149
|
+
dispose() {
|
|
150
|
+
this._mockEngine.stop();
|
|
151
|
+
if (typeof this._native.dispose === 'function') {
|
|
152
|
+
this._native.dispose();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
124
155
|
}
|
|
125
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
|
}
|