react-native-nitro-sse 3.0.0-beta.2 → 3.1.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 (50) hide show
  1. package/NitroSse.podspec +0 -1
  2. package/README.md +44 -24
  3. package/android/build.gradle +0 -1
  4. package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +33 -10
  5. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +464 -130
  6. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +420 -88
  7. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +23 -0
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +29 -2
  9. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +9 -0
  10. package/ios/NitroSse.swift +353 -64
  11. package/ios/SseConfig+CopyWith.swift +35 -19
  12. package/ios/SseConnectionHandler.swift +647 -97
  13. package/ios/SseEventBuffer.swift +19 -1
  14. package/ios/SseReconnectStrategy.swift +26 -7
  15. package/lib/module/MockSseEngine.js +72 -8
  16. package/lib/module/NitroSseClient.js +79 -8
  17. package/lib/module/createNitroSse.js +24 -0
  18. package/lib/module/index.js +1 -22
  19. package/lib/module/useNitroSse.js +22 -5
  20. package/lib/typescript/src/MockSseEngine.d.ts +16 -0
  21. package/lib/typescript/src/NitroSse.nitro.d.ts +2 -2
  22. package/lib/typescript/src/NitroSseClient.d.ts +7 -3
  23. package/lib/typescript/src/SseInterface.d.ts +60 -10
  24. package/lib/typescript/src/createNitroSse.d.ts +9 -0
  25. package/lib/typescript/src/index.d.ts +1 -8
  26. package/lib/typescript/src/useNitroSse.d.ts +2 -2
  27. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +12 -8
  28. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.hpp +1 -1
  29. package/nitrogen/generated/android/c++/JSseConfig.hpp +1 -18
  30. package/nitrogen/generated/android/c++/JSseDisconnectReason.hpp +67 -0
  31. package/nitrogen/generated/android/c++/JSseStats.hpp +87 -1
  32. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/HybridNitroSseSpec.kt +4 -3
  33. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +4 -13
  34. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseDisconnectReason.kt +26 -0
  35. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseStats.kt +108 -3
  36. package/nitrogen/generated/android/nitrosseOnLoad.cpp +2 -2
  37. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +8 -8
  38. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +114 -96
  39. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +3 -0
  40. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +7 -4
  41. package/nitrogen/generated/ios/swift/HybridNitroSseSpec.swift +1 -1
  42. package/nitrogen/generated/ios/swift/HybridNitroSseSpec_cxx.swift +34 -1
  43. package/nitrogen/generated/ios/swift/SseConfig.swift +1 -48
  44. package/nitrogen/generated/ios/swift/SseDisconnectReason.swift +52 -0
  45. package/nitrogen/generated/ios/swift/SseStats.swift +217 -2
  46. package/nitrogen/generated/shared/c++/HybridNitroSseSpec.hpp +3 -1
  47. package/nitrogen/generated/shared/c++/SseConfig.hpp +2 -8
  48. package/nitrogen/generated/shared/c++/SseDisconnectReason.hpp +88 -0
  49. package/nitrogen/generated/shared/c++/SseStats.hpp +88 -2
  50. package/package.json +2 -2
@@ -12,6 +12,15 @@ class SseEventBuffer {
12
12
  private var maxBufferSize: Int = 1000
13
13
  private weak var dispatcher: SseDispatcher?
14
14
 
15
+ // MARK: - Buffer Metrics
16
+ private(set) var peakBufferedEvents: Int = 0
17
+ private(set) var bufferFlushCount: Int = 0
18
+ private(set) var bufferOverflowCount: Int = 0
19
+
20
+ var eventsBuffered: Int {
21
+ return eventBuffer.count
22
+ }
23
+
15
24
  /// Initializes buffer batching thresholds and dispatch target.
16
25
  func configure(
17
26
  batchingIntervalMs: Double,
@@ -34,7 +43,15 @@ class SseEventBuffer {
34
43
  dispatcher?.assertOnQueue()
35
44
  eventBuffer.append(event)
36
45
 
37
- if eventBuffer.count >= maxBufferSize || batchingIntervalMs <= 0 {
46
+ if eventBuffer.count > peakBufferedEvents {
47
+ peakBufferedEvents = eventBuffer.count
48
+ }
49
+
50
+ if eventBuffer.count >= maxBufferSize && batchingIntervalMs > 0 {
51
+ bufferOverflowCount += 1
52
+ cancelPendingTimer()
53
+ flush()
54
+ } else if eventBuffer.count >= maxBufferSize || batchingIntervalMs <= 0 {
38
55
  cancelPendingTimer()
39
56
  flush()
40
57
  } else if pendingTimer == nil, let dispatcher = dispatcher {
@@ -53,6 +70,7 @@ class SseEventBuffer {
53
70
  cancelPendingTimer()
54
71
  guard !eventBuffer.isEmpty else { return }
55
72
 
73
+ bufferFlushCount += 1
56
74
  let batch = eventBuffer
57
75
  eventBuffer.removeAll()
58
76
 
@@ -82,23 +82,42 @@ class SseReconnectStrategy {
82
82
  currentReconnectAttempts = 0
83
83
  }
84
84
 
85
+ /// Updates base retry interval when server sends a 'retry: <ms>' directive.
86
+ func updateRetryInterval(_ retryMs: Double) {
87
+ if retryMs.isFinite && retryMs >= 0 {
88
+ self.retryInterval = retryMs / 1000.0
89
+ }
90
+ }
91
+
85
92
  /// Parses `Retry-After` HTTP headers per RFC 7231 (integer seconds or RFC 1123 date).
86
- /// Fallback to full jitter backoff when response metadata is omitted by underlying client.
93
+ static func extractRetryAfterSeconds(from response: HTTPURLResponse) -> TimeInterval? {
94
+ guard let retryAfterHeader = response.value(forHTTPHeaderField: "Retry-After") ?? (response.allHeaderFields["Retry-After"] as? String) else { return nil }
95
+ return parseRetryAfterHeader(retryAfterHeader)
96
+ }
97
+
98
+ /// Parses `Retry-After` HTTP headers per RFC 7231 (integer seconds or RFC 1123 date) from NSError userInfo.
87
99
  static func extractRetryAfterSeconds(from error: Error) -> TimeInterval? {
88
100
  let nsError = error as NSError
89
- guard let response = nsError.userInfo["response"] as? HTTPURLResponse else { return nil }
90
- guard let retryAfterHeader = response.value(forHTTPHeaderField: "Retry-After") else { return nil }
91
-
92
- if let seconds = Double(retryAfterHeader) {
101
+ if let response = nsError.userInfo["response"] as? HTTPURLResponse {
102
+ return extractRetryAfterSeconds(from: response)
103
+ }
104
+ return nil
105
+ }
106
+
107
+ private static func parseRetryAfterHeader(_ retryAfterHeader: String) -> TimeInterval? {
108
+ let trimmed = retryAfterHeader.trimmingCharacters(in: .whitespaces)
109
+ // RFC 7231 Section 7.1.3: delay-seconds is a sequence of 1*DIGIT (ASCII digits only)
110
+ if !trimmed.isEmpty && trimmed.allSatisfy({ $0.isASCII && $0.isNumber }), let seconds = Double(trimmed) {
93
111
  return seconds
94
112
  }
95
113
 
96
114
  let rfc1123Formatter = DateFormatter()
97
115
  rfc1123Formatter.locale = Locale(identifier: "en_US_POSIX")
116
+ rfc1123Formatter.timeZone = TimeZone(secondsFromGMT: 0)
98
117
  rfc1123Formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
99
- if let date = rfc1123Formatter.date(from: retryAfterHeader) {
118
+ if let date = rfc1123Formatter.date(from: trimmed) {
100
119
  let timeUntilDate = date.timeIntervalSinceNow
101
- return timeUntilDate > 0 ? timeUntilDate : nil
120
+ return max(0.0, timeUntilDate)
102
121
  }
103
122
  return nil
104
123
  }
@@ -7,6 +7,17 @@
7
7
  export class MockSseEngine {
8
8
  _mockIndex = 0;
9
9
  _totalBytesReceived = 0;
10
+ _chunksReceived = 0;
11
+ _totalEventsReceived = 0;
12
+ _commentsReceived = 0;
13
+ _linesParsed = 0;
14
+ _parseErrors = 0;
15
+ _lastActivityTime = 0;
16
+ _maxEventGapMs = 0;
17
+ _bufferFlushCount = 0;
18
+ _connectionAttempts = 0;
19
+ _reconnectCount = 0;
20
+ _lastProcessedId = null;
10
21
  constructor(config, emitEvents) {
11
22
  this._config = config;
12
23
  this._emitEvents = emitEvents;
@@ -58,6 +69,16 @@ export class MockSseEngine {
58
69
  } = this._config;
59
70
  this._mockIndex = 0;
60
71
  this._totalBytesReceived = 0;
72
+ this._chunksReceived = 0;
73
+ this._totalEventsReceived = 0;
74
+ this._commentsReceived = 0;
75
+ this._linesParsed = 0;
76
+ this._parseErrors = 0;
77
+ this._maxEventGapMs = 0;
78
+ this._lastActivityTime = 0;
79
+ this._connectionAttempts++;
80
+ this._connectedAt = Date.now();
81
+ this._lastProcessedId = null;
61
82
 
62
83
  // Validate and normalize eventsPerSecond (must be a finite positive number, default to 1)
63
84
  let validatedEventsPerSecond = Number(eventsPerSecond);
@@ -88,11 +109,6 @@ export class MockSseEngine {
88
109
  }
89
110
  if (mode === 'replace') {
90
111
  this._setMockState('closed');
91
- const closeEvent = {
92
- type: 'close',
93
- statusCode: 200
94
- };
95
- this._emitEvents([closeEvent]);
96
112
  }
97
113
  return;
98
114
  }
@@ -108,6 +124,9 @@ export class MockSseEngine {
108
124
  message: 'Mock Connection Drop (Simulated Error)',
109
125
  statusCode: 500
110
126
  };
127
+ this._lastErrorTime = Date.now();
128
+ this._lastErrorCode = 'SIMULATED_MOCK_FAILURE';
129
+ this._reconnectCount++;
111
130
  this._emitEvents([errorEvent]);
112
131
 
113
132
  // Retry / reconnect delay simulator (e.g. 2000ms)
@@ -135,11 +154,32 @@ export class MockSseEngine {
135
154
  }
136
155
  }
137
156
  if (batch.length > 0) {
157
+ this._chunksReceived++;
158
+ this._bufferFlushCount++;
159
+ const now = Date.now();
138
160
  for (const ev of batch) {
139
161
  const dataLen = ev.data ? ev.data.length : 0;
140
- const evLen = ev.event ? ev.event.length : 0;
141
- const idLen = ev.id ? ev.id.length : 0;
162
+ const evLen = ev.event && ev.event !== 'message' ? ev.event.length : 0;
163
+ const idLen = ev.id && ev.id !== this._lastProcessedId ? ev.id.length : 0;
164
+ if (ev.id !== undefined) {
165
+ this._lastProcessedId = ev.id === '' ? null : ev.id;
166
+ }
142
167
  this._totalBytesReceived += Math.max(1, dataLen + evLen + idLen);
168
+ this._linesParsed += 2;
169
+ if (ev.type === 'message' || ev.event === 'message') {
170
+ this._totalEventsReceived++;
171
+ this._lastEventTime = now;
172
+ } else if (ev.type === 'heartbeat') {
173
+ this._commentsReceived++;
174
+ this._lastHeartbeatTime = now;
175
+ }
176
+ if (this._lastActivityTime > 0) {
177
+ const gap = now - this._lastActivityTime;
178
+ if (gap > this._maxEventGapMs) {
179
+ this._maxEventGapMs = gap;
180
+ }
181
+ }
182
+ this._lastActivityTime = now;
143
183
  }
144
184
  if (mode === 'replace') {
145
185
  this._setMockState('open');
@@ -175,6 +215,7 @@ export class MockSseEngine {
175
215
  clearTimeout(this._mockIntervalId);
176
216
  this._mockIntervalId = undefined;
177
217
  }
218
+ this._connectedAt = undefined;
178
219
  if (this._config.mode === 'replace') {
179
220
  this._setMockState('closed');
180
221
  }
@@ -188,8 +229,31 @@ export class MockSseEngine {
188
229
  }
189
230
  getStats() {
190
231
  return {
232
+ rawBytesReceived: this._totalBytesReceived,
233
+ decompressedBytesReceived: undefined,
191
234
  totalBytesReceived: this._totalBytesReceived,
192
- reconnectCount: 0
235
+ chunksReceived: this._chunksReceived,
236
+ lastStatusCode: this._mockState === 'open' ? 200 : undefined,
237
+ totalEventsReceived: this._totalEventsReceived,
238
+ commentsReceived: this._commentsReceived,
239
+ linesParsed: this._linesParsed,
240
+ parseErrors: this._parseErrors,
241
+ serverRetryDelayMs: undefined,
242
+ connectedAt: this._connectedAt,
243
+ timeToFirstByteMs: undefined,
244
+ lastEventTime: this._lastEventTime,
245
+ lastHeartbeatTime: this._lastHeartbeatTime,
246
+ maxEventGapMs: this._maxEventGapMs,
247
+ eventsBuffered: 0,
248
+ peakBufferedEvents: 0,
249
+ bufferFlushCount: this._bufferFlushCount,
250
+ bufferOverflowCount: 0,
251
+ connectionAttempts: this._connectionAttempts,
252
+ reconnectCount: this._reconnectCount,
253
+ lastReconnectDelayMs: undefined,
254
+ disconnectReason: this._mockState === 'closed' ? 'user_stop' : undefined,
255
+ lastErrorTime: this._lastErrorTime,
256
+ lastErrorCode: this._lastErrorCode
193
257
  };
194
258
  }
195
259
  getState() {
@@ -21,6 +21,37 @@ export function sanitizeHeaders(headers) {
21
21
  }
22
22
  return clean;
23
23
  }
24
+ const SENSITIVE_HEADER_REGEX = /^(authorization|cookie|proxy-authorization|x-api-key|api-key)$/i;
25
+
26
+ /**
27
+ * Checks whether a URL points to a loopback/local address (localhost, 127.0.0.1, [::1]).
28
+ */
29
+ function isLoopbackUrl(url) {
30
+ try {
31
+ const parsed = new URL(url);
32
+ const hostname = parsed.hostname.toLowerCase();
33
+ return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]' || hostname === '::1' || hostname === '10.0.2.2' || hostname === '10.0.3.3' || hostname.endsWith('.localhost');
34
+ } catch {
35
+ const lower = url.toLowerCase();
36
+ return lower.includes('://localhost') || lower.includes('://127.0.0.1') || lower.includes('://[::1]') || lower.includes('://10.0.2.2') || lower.includes('://10.0.3.3');
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Warns in development when credential headers are transmitted over insecure cleartext HTTP (non-loopback).
42
+ */
43
+ export function warnInsecureCredentials(url, headers) {
44
+ if (typeof __DEV__ === 'undefined' || !__DEV__) return;
45
+ if (!url || typeof url !== 'string' || !headers || typeof headers !== 'object') return;
46
+ const trimmedUrl = url.trim();
47
+ const lowerUrl = trimmedUrl.toLowerCase();
48
+ if (lowerUrl.startsWith('http://') && !isLoopbackUrl(trimmedUrl)) {
49
+ const hasSensitiveHeader = Object.keys(headers).some(key => SENSITIVE_HEADER_REGEX.test(key.trim()));
50
+ if (hasSensitiveHeader) {
51
+ console.warn(`[NitroSse] Security Warning: Sensitive credential header(s) detected over an insecure, unencrypted HTTP connection ("${trimmedUrl}"). Transmitting credentials over plaintext HTTP is vulnerable to interception and token theft. Use HTTPS in production.`);
52
+ }
53
+ }
54
+ }
24
55
 
25
56
  /**
26
57
  * Defensively validates and normalizes the SSE configuration object.
@@ -61,6 +92,7 @@ export function validateConfig(config) {
61
92
  received: config.headers
62
93
  });
63
94
  }
95
+ warnInsecureCredentials(trimmedUrl, config.headers);
64
96
  }
65
97
  let lowerMethod;
66
98
  if (config.method !== undefined) {
@@ -261,6 +293,7 @@ export class NitroSseClient {
261
293
  try {
262
294
  const h = await rawOnBeforeRequest();
263
295
  if (h && typeof h === 'object' && !Array.isArray(h)) {
296
+ warnInsecureCredentials(validatedConfig.url, h);
264
297
  return sanitizeHeaders(h);
265
298
  }
266
299
  if (typeof __DEV__ !== 'undefined' && __DEV__ && h !== undefined && h !== null) {
@@ -272,13 +305,14 @@ export class NitroSseClient {
272
305
  throw err;
273
306
  }
274
307
  } : undefined;
308
+ const pureConfig = {
309
+ ...validatedConfig
310
+ };
311
+ delete pureConfig.onBeforeRequest;
275
312
  this._config = {
276
- ...validatedConfig,
313
+ ...pureConfig,
277
314
  ...(cleanHeaders !== undefined ? {
278
315
  headers: cleanHeaders
279
- } : {}),
280
- ...(safeOnBeforeRequest !== undefined ? {
281
- onBeforeRequest: safeOnBeforeRequest
282
316
  } : {})
283
317
  };
284
318
  this._pendingHeaders = {};
@@ -300,9 +334,15 @@ export class NitroSseClient {
300
334
 
301
335
  // Wrap the native setup to dispatch events to typed listeners when native streaming is active
302
336
  if (mockConfig?.mode !== 'replace') {
303
- this._native.setup(this._config, events => {
304
- this._dispatchEvents(events);
305
- });
337
+ if (safeOnBeforeRequest !== undefined) {
338
+ this._native.setup(this._config, events => {
339
+ this._dispatchEvents(events);
340
+ }, safeOnBeforeRequest);
341
+ } else {
342
+ this._native.setup(this._config, events => {
343
+ this._dispatchEvents(events);
344
+ });
345
+ }
306
346
  }
307
347
  }
308
348
  addEventListener(type, listener) {
@@ -383,6 +423,13 @@ export class NitroSseClient {
383
423
  if (event.event && event.event !== event.type) {
384
424
  this._emit(event.event, event);
385
425
  }
426
+ if (event.type === 'state' && event.state === 'closed') {
427
+ this._emit('close', {
428
+ type: 'close',
429
+ statusCode: event.statusCode ?? 200,
430
+ state: 'closed'
431
+ });
432
+ }
386
433
  }
387
434
  }
388
435
  start() {
@@ -414,8 +461,31 @@ export class NitroSseClient {
414
461
  getStats() {
415
462
  if (this._isDisposed) {
416
463
  return {
464
+ rawBytesReceived: 0,
465
+ decompressedBytesReceived: undefined,
417
466
  totalBytesReceived: 0,
418
- reconnectCount: 0
467
+ chunksReceived: 0,
468
+ lastStatusCode: undefined,
469
+ totalEventsReceived: 0,
470
+ commentsReceived: 0,
471
+ linesParsed: 0,
472
+ parseErrors: 0,
473
+ serverRetryDelayMs: undefined,
474
+ connectedAt: undefined,
475
+ timeToFirstByteMs: undefined,
476
+ lastEventTime: undefined,
477
+ lastHeartbeatTime: undefined,
478
+ maxEventGapMs: 0,
479
+ eventsBuffered: 0,
480
+ peakBufferedEvents: 0,
481
+ bufferFlushCount: 0,
482
+ bufferOverflowCount: 0,
483
+ connectionAttempts: 0,
484
+ reconnectCount: 0,
485
+ lastReconnectDelayMs: undefined,
486
+ disconnectReason: 'user_stop',
487
+ lastErrorTime: undefined,
488
+ lastErrorCode: undefined
419
489
  };
420
490
  }
421
491
  return this._driver.getStats();
@@ -439,6 +509,7 @@ export class NitroSseClient {
439
509
  };
440
510
  this._driver.updateHeaders(clean);
441
511
  } else {
512
+ warnInsecureCredentials(this._config.url, clean);
442
513
  this._config.headers = {
443
514
  ...this._config.headers,
444
515
  ...clean
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+
3
+ import { NitroModules } from 'react-native-nitro-modules';
4
+ import { NitroSseClient } from "./NitroSseClient.js";
5
+ import { NitroSseModuleNotFoundError } from "./NitroSseError.js";
6
+ /**
7
+ * Creates a high-performance SSE client that supports typed event listeners (`addEventListener`) and legacy batching.
8
+ *
9
+ * @returns An SseClient instance wrapping the native NitroSse implementation.
10
+ * @throws {NitroSseModuleNotFoundError} If the native NitroSse module cannot be found. Ensure the library is linked and the app is built for iOS/Android.
11
+ */
12
+ export function createNitroSse() {
13
+ let nativeSse;
14
+ try {
15
+ nativeSse = NitroModules.createHybridObject('NitroSse');
16
+ } catch {
17
+ console.debug('Native NitroSse not found. This might be a test environment or web.');
18
+ }
19
+ if (!nativeSse) {
20
+ throw new NitroSseModuleNotFoundError('NitroSse: Native module not found. Ensure you have linked the library and built the app for iOS/Android.');
21
+ }
22
+ return new NitroSseClient(nativeSse);
23
+ }
24
+ //# sourceMappingURL=createNitroSse.js.map
@@ -1,29 +1,8 @@
1
1
  "use strict";
2
2
 
3
- import { NitroModules } from 'react-native-nitro-modules';
4
- import { NitroSseClient } from "./NitroSseClient.js";
5
- import { NitroSseModuleNotFoundError } from "./NitroSseError.js";
6
3
  export * from "./SseInterface.js";
7
4
  export * from "./useNitroSse.js";
8
5
  export * from "./NitroSseClient.js";
9
6
  export * from "./NitroSseError.js";
10
-
11
- /**
12
- * Creates a high-performance SSE client that supports typed event listeners (`addEventListener`) and legacy batching.
13
- *
14
- * @returns An SseClient instance wrapping the native NitroSse implementation.
15
- * @throws {NitroSseModuleNotFoundError} If the native NitroSse module cannot be found. Ensure the library is linked and the app is built for iOS/Android.
16
- */
17
- export function createNitroSse() {
18
- let nativeSse;
19
- try {
20
- nativeSse = NitroModules.createHybridObject('NitroSse');
21
- } catch {
22
- console.debug('Native NitroSse not found. This might be a test environment or web.');
23
- }
24
- if (!nativeSse) {
25
- throw new NitroSseModuleNotFoundError('NitroSse: Native module not found. Ensure you have linked the library and built the app for iOS/Android.');
26
- }
27
- return new NitroSseClient(nativeSse);
28
- }
7
+ export * from "./createNitroSse.js";
29
8
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  import { useEffect, useRef, useState, useCallback } from 'react';
4
- import { createNitroSse } from "./index.js";
4
+ import { createNitroSse } from "./createNitroSse.js";
5
5
  /**
6
6
  * Safely serializes an object into a stable JSON string:
7
7
  * - Sorts object keys to avoid reconnection on equivalent configs with reordered keys.
@@ -123,6 +123,19 @@ export function useNitroSse(options) {
123
123
  };
124
124
  }, [onMessage, onError, onOpen, onClose, onHeartbeat, onStateChange, events, onBeforeRequest]);
125
125
  const hasBeforeRequest = Boolean(onBeforeRequest);
126
+ // Track undefined transition or key removal to recreate client and purge stale headers (e.g. on logout)
127
+ const isHeadersUndefined = headers === undefined;
128
+ const currentHeaderKeys = headers && typeof headers === 'object' ? Object.keys(headers).sort() : [];
129
+ const prevHeaderKeysRef = useRef(undefined);
130
+ const headerRemovalTokenRef = useRef(0);
131
+ if (prevHeaderKeysRef.current !== undefined && headers !== undefined) {
132
+ const currentKeysSet = new Set(currentHeaderKeys);
133
+ const isKeyRemoved = prevHeaderKeysRef.current.some(k => !currentKeysSet.has(k));
134
+ if (isKeyRemoved) {
135
+ headerRemovalTokenRef.current++;
136
+ }
137
+ }
138
+ prevHeaderKeysRef.current = currentHeaderKeys;
126
139
  const configKey = safeSerializeConfig(restConfig);
127
140
  const headersKey = safeSerializeConfig(headers);
128
141
 
@@ -163,9 +176,12 @@ export function useNitroSse(options) {
163
176
  }
164
177
  if (e.event && e.event !== e.type) {
165
178
  try {
166
- const handler = callbacksRef.current.events?.[e.event];
167
- if (handler) {
168
- handler(e);
179
+ const customEvents = callbacksRef.current.events;
180
+ if (customEvents && typeof customEvents === 'object' && Object.prototype.hasOwnProperty.call(customEvents, e.event)) {
181
+ const handler = customEvents[e.event];
182
+ if (typeof handler === 'function') {
183
+ handler(e);
184
+ }
169
185
  }
170
186
  } catch (err) {
171
187
  console.error(`[useNitroSse] Unhandled error in events['${e.event}'] callback:`, err);
@@ -222,8 +238,9 @@ export function useNitroSse(options) {
222
238
  clientRef.current = null;
223
239
  setClient(null);
224
240
  };
241
+ // Recreate client if headers becomes undefined or keys are removed to purge stale native headers
225
242
  // eslint-disable-next-line react-hooks/exhaustive-deps
226
- }, [configKey, autoStart, hasBeforeRequest, hasValidUrl]);
243
+ }, [configKey, autoStart, hasBeforeRequest, hasValidUrl, isHeadersUndefined, headerRemovalTokenRef.current]);
227
244
 
228
245
  // Synchronize headers dynamically without reconnecting or tearing down active socket
229
246
  const isInitialMount = useRef(true);
@@ -10,6 +10,22 @@ export declare class MockSseEngine {
10
10
  private _mockIndex;
11
11
  private _mockState?;
12
12
  private _totalBytesReceived;
13
+ private _chunksReceived;
14
+ private _totalEventsReceived;
15
+ private _commentsReceived;
16
+ private _linesParsed;
17
+ private _parseErrors;
18
+ private _connectedAt?;
19
+ private _lastEventTime?;
20
+ private _lastHeartbeatTime?;
21
+ private _lastActivityTime;
22
+ private _maxEventGapMs;
23
+ private _bufferFlushCount;
24
+ private _connectionAttempts;
25
+ private _reconnectCount;
26
+ private _lastErrorTime?;
27
+ private _lastErrorCode?;
28
+ private _lastProcessedId;
13
29
  constructor(config: SseMockConfig, emitEvents: (events: SseEvent[]) => void);
14
30
  /**
15
31
  * Transforms a raw mock event definition or partial SSE event into a full SseEvent DTO.
@@ -28,9 +28,9 @@ export interface NitroSse extends HybridObject<{
28
28
  android: 'kotlin';
29
29
  }> {
30
30
  /**
31
- * Configure SSE and setup event callback.
31
+ * Configure SSE, event callback, and optional dynamic request interceptor.
32
32
  */
33
- setup(config: SseConfig, onEvent: (events: SseEvent[]) => void): void;
33
+ setup(config: SseConfig, onEvent: (events: SseEvent[]) => void, onBeforeRequest?: () => Promise<Record<string, string>>): void;
34
34
  /**
35
35
  * Start the SSE connection.
36
36
  */
@@ -1,17 +1,21 @@
1
1
  import type { AnyMap } from 'react-native-nitro-modules';
2
2
  import type { NitroSse } from './NitroSse.nitro';
3
- import type { SseClient, SseConfig, SseEvent, SseListener, SseStats, SseState } from './SseInterface';
3
+ import type { SseClient, SseClientOptions, SseEvent, SseListener, SseStats, SseState } from './SseInterface';
4
4
  /**
5
5
  * Sanitizes HTTP headers by stripping carriage returns, newlines, null bytes,
6
6
  * converting non-string values to strings, and pruning null/undefined values.
7
7
  */
8
8
  export declare function sanitizeHeaders(headers?: Record<string, unknown>): Record<string, string>;
9
+ /**
10
+ * Warns in development when credential headers are transmitted over insecure cleartext HTTP (non-loopback).
11
+ */
12
+ export declare function warnInsecureCredentials(url?: string, headers?: Record<string, unknown>): void;
9
13
  /**
10
14
  * Defensively validates and normalizes the SSE configuration object.
11
15
  * Throws NitroSseValidationError if essential requirements (e.g. valid URL) are violated.
12
16
  * Clamps numeric properties to safe boundaries and warns in __DEV__.
13
17
  */
14
- export declare function validateConfig(config: SseConfig): SseConfig;
18
+ export declare function validateConfig(config: SseClientOptions): SseClientOptions;
15
19
  /**
16
20
  * Public facade and typed event emitter for NitroSse, delegating streaming execution to an SseDriver strategy.
17
21
  */
@@ -26,7 +30,7 @@ export declare class NitroSseClient implements SseClient {
26
30
  constructor(native: NitroSse);
27
31
  get isDisposed(): boolean;
28
32
  private _checkDisposed;
29
- setup(config: SseConfig, onEvent?: (events: SseEvent[]) => void): void;
33
+ setup(config: SseClientOptions, onEvent?: (events: SseEvent[]) => void): void;
30
34
  addEventListener<TData = AnyMap>(type: string, listener: SseListener<TData>): void;
31
35
  removeEventListener<TData = AnyMap>(type: string, listener: SseListener<TData>): void;
32
36
  removeAllEventListeners(type?: string): void;
@@ -104,17 +104,22 @@ export interface SseConfig {
104
104
  * @default true
105
105
  */
106
106
  monitorNetwork?: boolean;
107
+ /**
108
+ * Configuration for mock streaming data.
109
+ * Used for local testing and debugging.
110
+ */
111
+ mock?: SseMockConfig;
112
+ }
113
+ /**
114
+ * Public client setup options, combining connection config with dynamic request interceptor.
115
+ */
116
+ export interface SseClientOptions extends SseConfig {
107
117
  /**
108
118
  * Async interceptor called before every connection attempt (including auto-reconnects).
109
119
  * Use this to refresh tokens or calculate dynamic headers.
110
120
  * Note: This is protected by a native timeout to prevent the app from hanging.
111
121
  */
112
122
  onBeforeRequest?: () => Promise<Record<string, string>>;
113
- /**
114
- * Configuration for mock streaming data.
115
- * Used for local testing and debugging.
116
- */
117
- mock?: SseMockConfig;
118
123
  }
119
124
  export type SseMockMode = 'replace' | 'inject';
120
125
  /**
@@ -195,17 +200,60 @@ export interface SseEvent<TData = AnyMap> {
195
200
  /** The current connection state (only available if type is 'state'). */
196
201
  state?: SseState;
197
202
  }
203
+ export type SseDisconnectReason = 'user_stop' | 'network_error' | 'server_error' | 'parser_error' | 'timeout';
198
204
  /**
199
205
  * Statistics about the SSE connection.
200
206
  */
201
207
  export interface SseStats {
202
- /** Total bytes received so far. */
208
+ /** Raw bytes received from the network socket before decompression. */
209
+ rawBytesReceived: number;
210
+ /** Decompressed bytes received (if gzip/compression applied). */
211
+ decompressedBytesReceived?: number;
212
+ /** Decoded payload byte length (for backward compatibility). */
203
213
  totalBytesReceived: number;
204
- /** Number of times the connection has been re-established. */
214
+ /** Number of data chunks/packets read from the network transport. */
215
+ chunksReceived: number;
216
+ /** HTTP response status code of the current or last connection attempt. */
217
+ lastStatusCode?: number;
218
+ /** Total valid SSE message events parsed and emitted. */
219
+ totalEventsReceived: number;
220
+ /** Total SSE comment lines (':') received as heartbeats. */
221
+ commentsReceived: number;
222
+ /** Total raw lines processed by the SSE parser. */
223
+ linesParsed: number;
224
+ /** Number of parsing errors encountered (line length limit exceeded, invalid UTF-8, etc.). */
225
+ parseErrors: number;
226
+ /** Latest retry delay requested by server via 'retry:' directive (ms). */
227
+ serverRetryDelayMs?: number;
228
+ /** Epoch timestamp (ms) when the active connection was established. */
229
+ connectedAt?: number;
230
+ /** Latency in ms from connection start to first body byte received. */
231
+ timeToFirstByteMs?: number;
232
+ /** Epoch timestamp (ms) of the most recently received event. */
233
+ lastEventTime?: number;
234
+ /** Epoch timestamp (ms) of the most recently received heartbeat/comment. */
235
+ lastHeartbeatTime?: number;
236
+ /** Maximum elapsed time (ms) between consecutive events/heartbeats (stall detection). */
237
+ maxEventGapMs: number;
238
+ /** Number of events currently waiting in the dispatch buffer. */
239
+ eventsBuffered: number;
240
+ /** Maximum number of events queued in the buffer at any one time (high-water mark). */
241
+ peakBufferedEvents: number;
242
+ /** Total number of buffer flushes to JavaScript. */
243
+ bufferFlushCount: number;
244
+ /** Total number of early flushes triggered because buffer reached maxBufferSize. */
245
+ bufferOverflowCount: number;
246
+ /** Total connection attempts made (initial and retries). */
247
+ connectionAttempts: number;
248
+ /** Number of successful reconnections. */
205
249
  reconnectCount: number;
250
+ /** Delay in ms used for the last reconnect attempt. */
251
+ lastReconnectDelayMs?: number;
252
+ /** Reason for the last disconnection. */
253
+ disconnectReason?: SseDisconnectReason;
206
254
  /** Timestamp of the last error event. */
207
255
  lastErrorTime?: number;
208
- /** Error code of the last error. */
256
+ /** Error code or domain of the last error. */
209
257
  lastErrorCode?: string;
210
258
  }
211
259
  /**
@@ -216,12 +264,14 @@ export type SseListener<TData = AnyMap> = (event: SseEvent<TData>) => void;
216
264
  * Public interface for the NitroSse client, supporting typed event listeners.
217
265
  */
218
266
  export interface SseClient {
267
+ /** Whether the client instance has been disposed. */
268
+ readonly isDisposed: boolean;
219
269
  /**
220
270
  * Configure SSE and setup event callback.
221
- * @param config The SSE configuration.
271
+ * @param config The SSE configuration and client options.
222
272
  * @param onEvent Optional legacy batch callback for all events.
223
273
  */
224
- setup(config: SseConfig, onEvent?: (events: SseEvent[]) => void): void;
274
+ setup(config: SseClientOptions, onEvent?: (events: SseEvent[]) => void): void;
225
275
  /**
226
276
  * Register a listener for a specific event type ('message', 'open', etc.)
227
277
  * or a custom SSE event name (from the 'event:' field).
@@ -0,0 +1,9 @@
1
+ import type { SseClient } from './SseInterface';
2
+ /**
3
+ * Creates a high-performance SSE client that supports typed event listeners (`addEventListener`) and legacy batching.
4
+ *
5
+ * @returns An SseClient instance wrapping the native NitroSse implementation.
6
+ * @throws {NitroSseModuleNotFoundError} If the native NitroSse module cannot be found. Ensure the library is linked and the app is built for iOS/Android.
7
+ */
8
+ export declare function createNitroSse(): SseClient;
9
+ //# sourceMappingURL=createNitroSse.d.ts.map