react-native-nitro-sse 2.4.2 → 3.0.0-beta.2

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 (59) hide show
  1. package/README.md +209 -95
  2. package/android/build.gradle +4 -1
  3. package/android/src/main/java/com/margelo/nitro/nitrosse/AndroidSseDispatcher.kt +5 -0
  4. package/android/src/main/java/com/margelo/nitro/nitrosse/JsonUtils.kt +11 -18
  5. package/android/src/main/java/com/margelo/nitro/nitrosse/NetworkInspector.kt +79 -36
  6. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +164 -88
  7. package/android/src/main/java/com/margelo/nitro/nitrosse/SseConnectionHandler.kt +40 -15
  8. package/android/src/main/java/com/margelo/nitro/nitrosse/SseDispatcher.kt +1 -0
  9. package/android/src/main/java/com/margelo/nitro/nitrosse/SseEventBuffer.kt +34 -25
  10. package/android/src/main/java/com/margelo/nitro/nitrosse/SseLifecycleManager.kt +8 -1
  11. package/android/src/main/java/com/margelo/nitro/nitrosse/SseNetworkMonitor.kt +7 -4
  12. package/android/src/main/java/com/margelo/nitro/nitrosse/SseReconnectStrategy.kt +2 -4
  13. package/ios/NitroSse.swift +229 -191
  14. package/ios/SseConfig+CopyWith.swift +2 -1
  15. package/ios/SseConnectionHandler.swift +40 -29
  16. package/ios/SseDispatchQueueDispatcher.swift +15 -2
  17. package/ios/SseDispatcher.swift +7 -1
  18. package/ios/SseEventBuffer.swift +23 -7
  19. package/ios/SseLifecycleManager.swift +10 -1
  20. package/ios/SseNetworkMonitor.swift +5 -0
  21. package/ios/SseReconnectStrategy.swift +4 -3
  22. package/lib/module/MockSseEngine.js +12 -21
  23. package/lib/module/NitroSseClient.js +385 -12
  24. package/lib/module/NitroSseError.js +61 -0
  25. package/lib/module/SseDriver.js +33 -2
  26. package/lib/module/index.js +6 -3
  27. package/lib/module/useNitroSse.js +359 -0
  28. package/lib/typescript/src/MockSseEngine.d.ts +1 -1
  29. package/lib/typescript/src/NitroSse.nitro.d.ts +25 -2
  30. package/lib/typescript/src/NitroSseClient.d.ts +20 -2
  31. package/lib/typescript/src/NitroSseError.d.ts +38 -0
  32. package/lib/typescript/src/SseDriver.d.ts +10 -2
  33. package/lib/typescript/src/SseInterface.d.ts +23 -7
  34. package/lib/typescript/src/index.d.ts +4 -2
  35. package/lib/typescript/src/useNitroSse.d.ts +69 -0
  36. package/nitrogen/generated/android/c++/JSseConfig.hpp +5 -1
  37. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +9 -4
  38. package/nitrogen/generated/ios/swift/SseConfig.swift +19 -1
  39. package/nitrogen/generated/shared/c++/SseConfig.hpp +5 -1
  40. package/package.json +8 -7
  41. package/android/jacoco.gradle +0 -33
  42. package/lib/module/MockSseEngine.js.map +0 -1
  43. package/lib/module/NitroSse.nitro.js.map +0 -1
  44. package/lib/module/NitroSseClient.js.map +0 -1
  45. package/lib/module/SseDriver.js.map +0 -1
  46. package/lib/module/SseInterface.js.map +0 -1
  47. package/lib/module/index.js.map +0 -1
  48. package/lib/typescript/src/MockSseEngine.d.ts.map +0 -1
  49. package/lib/typescript/src/NitroSse.nitro.d.ts.map +0 -1
  50. package/lib/typescript/src/NitroSseClient.d.ts.map +0 -1
  51. package/lib/typescript/src/SseDriver.d.ts.map +0 -1
  52. package/lib/typescript/src/SseInterface.d.ts.map +0 -1
  53. package/lib/typescript/src/index.d.ts.map +0 -1
  54. package/src/MockSseEngine.ts +0 -254
  55. package/src/NitroSse.nitro.ts +0 -58
  56. package/src/NitroSseClient.ts +0 -154
  57. package/src/SseDriver.ts +0 -161
  58. package/src/SseInterface.ts +0 -274
  59. package/src/index.ts +0 -31
@@ -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
@@ -9,6 +9,7 @@ export declare class MockSseEngine {
9
9
  private _mockIntervalId?;
10
10
  private _mockIndex;
11
11
  private _mockState?;
12
+ private _totalBytesReceived;
12
13
  constructor(config: SseMockConfig, emitEvents: (events: SseEvent[]) => void);
13
14
  /**
14
15
  * Transforms a raw mock event definition or partial SSE event into a full SseEvent DTO.
@@ -25,7 +26,6 @@ export declare class MockSseEngine {
25
26
  isConnected(): boolean;
26
27
  getStats(): SseStats;
27
28
  getState(): SseState;
28
- resetState(): void;
29
29
  injectEvent(event: Partial<SseEvent>): void;
30
30
  }
31
31
  //# sourceMappingURL=MockSseEngine.d.ts.map
@@ -1,5 +1,28 @@
1
- import type { HybridObject } from 'react-native-nitro-modules';
2
- import type { SseConfig, SseEvent, SseStats, SseState } from './SseInterface';
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';
@@ -1,5 +1,17 @@
1
+ import type { AnyMap } from 'react-native-nitro-modules';
1
2
  import type { NitroSse } from './NitroSse.nitro';
2
3
  import type { SseClient, SseConfig, SseEvent, SseListener, SseStats, SseState } from './SseInterface';
4
+ /**
5
+ * Sanitizes HTTP headers by stripping carriage returns, newlines, null bytes,
6
+ * converting non-string values to strings, and pruning null/undefined values.
7
+ */
8
+ export declare function sanitizeHeaders(headers?: Record<string, unknown>): Record<string, string>;
9
+ /**
10
+ * Defensively validates and normalizes the SSE configuration object.
11
+ * Throws NitroSseValidationError if essential requirements (e.g. valid URL) are violated.
12
+ * Clamps numeric properties to safe boundaries and warns in __DEV__.
13
+ */
14
+ export declare function validateConfig(config: SseConfig): SseConfig;
3
15
  /**
4
16
  * Public facade and typed event emitter for NitroSse, delegating streaming execution to an SseDriver strategy.
5
17
  */
@@ -9,10 +21,15 @@ export declare class NitroSseClient implements SseClient {
9
21
  private _listeners;
10
22
  private _legacyCallback?;
11
23
  private _config?;
24
+ private _isDisposed;
25
+ private _pendingHeaders;
12
26
  constructor(native: NitroSse);
27
+ get isDisposed(): boolean;
28
+ private _checkDisposed;
13
29
  setup(config: SseConfig, onEvent?: (events: SseEvent[]) => void): void;
14
- addEventListener(type: string, listener: SseListener): void;
15
- removeEventListener(type: string, listener: SseListener): void;
30
+ addEventListener<TData = AnyMap>(type: string, listener: SseListener<TData>): void;
31
+ removeEventListener<TData = AnyMap>(type: string, listener: SseListener<TData>): void;
32
+ removeAllEventListeners(type?: string): void;
16
33
  private _emit;
17
34
  private _dispatchEvents;
18
35
  start(): void;
@@ -25,5 +42,6 @@ export declare class NitroSseClient implements SseClient {
25
42
  updateHeaders(headers: Record<string, string>): void;
26
43
  setLastProcessedId(id: string): void;
27
44
  injectMockEvent(event: Partial<SseEvent>): void;
45
+ dispose(): void;
28
46
  }
29
47
  //# sourceMappingURL=NitroSseClient.d.ts.map
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Error codes identifying specific categories of NitroSse failures.
3
+ */
4
+ export type NitroSseErrorCode = 'NATIVE_MODULE_NOT_FOUND' | 'INVALID_CONFIG' | 'INVALID_ARGUMENT' | 'INVALID_STATE' | 'CLIENT_DISPOSED';
5
+ /**
6
+ * Base structured error class for all errors thrown by react-native-nitro-sse.
7
+ * Carries a machine-readable `code` and optional `details` payload for defensive debugging.
8
+ */
9
+ export declare class NitroSseError extends Error {
10
+ readonly code: NitroSseErrorCode;
11
+ readonly details?: unknown;
12
+ constructor(message: string, code: NitroSseErrorCode, details?: unknown);
13
+ }
14
+ /**
15
+ * Thrown when the native Nitro hybrid module cannot be resolved or linked.
16
+ */
17
+ export declare class NitroSseModuleNotFoundError extends NitroSseError {
18
+ constructor(message?: string, details?: unknown);
19
+ }
20
+ /**
21
+ * Thrown when configuration parameters, URLs, headers, or arguments fail defensive validation.
22
+ */
23
+ export declare class NitroSseValidationError extends NitroSseError {
24
+ constructor(message: string, code?: 'INVALID_CONFIG' | 'INVALID_ARGUMENT', details?: unknown);
25
+ }
26
+ /**
27
+ * Thrown when an operation is attempted in an invalid state (e.g. calling operations on an unconfigured client).
28
+ */
29
+ export declare class NitroSseStateError extends NitroSseError {
30
+ constructor(message: string, details?: unknown);
31
+ }
32
+ /**
33
+ * Thrown when any method is invoked on a client instance that has already been disposed.
34
+ */
35
+ export declare class NitroSseDisposedError extends NitroSseError {
36
+ constructor(message?: string, details?: unknown);
37
+ }
38
+ //# sourceMappingURL=NitroSseError.d.ts.map
@@ -15,6 +15,7 @@ export interface SseDriver {
15
15
  updateHeaders(headers: Record<string, string>): void;
16
16
  setLastProcessedId(id: string): void;
17
17
  injectMockEvent(event: Partial<SseEvent>): void;
18
+ dispose(): void;
18
19
  }
19
20
  /**
20
21
  * Driver delegating all operations to the native JSI NitroSse module.
@@ -33,13 +34,18 @@ export declare class NativeDriver implements SseDriver {
33
34
  updateHeaders(headers: Record<string, string>): void;
34
35
  setLastProcessedId(id: string): void;
35
36
  injectMockEvent(event: Partial<SseEvent>): void;
37
+ dispose(): void;
36
38
  }
37
39
  /**
38
40
  * Driver simulating the entire SSE stream in JavaScript without native networking.
39
41
  */
40
42
  export declare class MockReplaceDriver implements SseDriver {
41
43
  private _mockEngine;
44
+ private _headers;
45
+ private _lastProcessedId?;
42
46
  constructor(_mockEngine: MockSseEngine);
47
+ get headers(): Record<string, string>;
48
+ get lastProcessedId(): string | undefined;
43
49
  start(): void;
44
50
  stop(): void;
45
51
  restart(): void;
@@ -47,9 +53,10 @@ export declare class MockReplaceDriver implements SseDriver {
47
53
  isConnected(): boolean;
48
54
  getStats(): SseStats;
49
55
  getState(): SseState;
50
- updateHeaders(_headers: Record<string, string>): void;
51
- setLastProcessedId(_id: string): void;
56
+ updateHeaders(headers: Record<string, string>): void;
57
+ setLastProcessedId(id: string): void;
52
58
  injectMockEvent(event: Partial<SseEvent>): void;
59
+ dispose(): void;
53
60
  }
54
61
  /**
55
62
  * Driver running native networking in parallel with mock event injection.
@@ -68,5 +75,6 @@ export declare class MockInjectDriver implements SseDriver {
68
75
  updateHeaders(headers: Record<string, string>): void;
69
76
  setLastProcessedId(id: string): void;
70
77
  injectMockEvent(event: Partial<SseEvent>): void;
78
+ dispose(): void;
71
79
  }
72
80
  //# sourceMappingURL=SseDriver.d.ts.map
@@ -64,6 +64,7 @@ export interface SseConfig {
64
64
  /**
65
65
  * Initial delay (in ms) for reconnection attempts.
66
66
  * Subsequent attempts use exponential backoff.
67
+ * Note: Native applies a minimum floor of 1000ms.
67
68
  * @default 1000
68
69
  */
69
70
  retryIntervalMs?: number;
@@ -84,9 +85,15 @@ export interface SseConfig {
84
85
  * @default -1
85
86
  */
86
87
  maxReconnectAttempts?: number;
88
+ /**
89
+ * Maximum number of retries when encountering HTTP 401/403 auth errors before stopping.
90
+ * @default 3
91
+ */
92
+ maxAuthRetries?: number;
87
93
  /**
88
94
  * Whether to automatically parse message data as JSON in a background native thread.
89
- * If true, and parsing succeeds, the result will be available in the 'parsedData' field.
95
+ * If true and data is a root JSON Object ('{...}'), the parsed result is available in 'parsedData'.
96
+ * Returns null for JSON arrays or primitives due to Nitro AnyMap object constraints.
90
97
  * @default false
91
98
  */
92
99
  autoParseJSON?: boolean;
@@ -168,13 +175,13 @@ export interface SseMockConfig {
168
175
  /**
169
176
  * Represents a single SSE event.
170
177
  */
171
- export interface SseEvent {
178
+ export interface SseEvent<TData = AnyMap> {
172
179
  /** The type of the event. */
173
180
  type: SseEventType;
174
181
  /** The data payload of the event as a raw string. */
175
182
  data?: string;
176
183
  /** The parsed JSON data, if autoParseJSON is enabled and parsing succeeds. */
177
- parsedData?: AnyMap;
184
+ parsedData?: TData;
178
185
  /** The event ID, if provided. */
179
186
  id?: string;
180
187
  /** The event name, if provided (internal 'event' field in SSE). */
@@ -204,7 +211,7 @@ export interface SseStats {
204
211
  /**
205
212
  * Listener for a specific SSE event.
206
213
  */
207
- export type SseListener = (event: SseEvent) => void;
214
+ export type SseListener<TData = AnyMap> = (event: SseEvent<TData>) => void;
208
215
  /**
209
216
  * Public interface for the NitroSse client, supporting typed event listeners.
210
217
  */
@@ -219,11 +226,15 @@ export interface SseClient {
219
226
  * Register a listener for a specific event type ('message', 'open', etc.)
220
227
  * or a custom SSE event name (from the 'event:' field).
221
228
  */
222
- addEventListener(type: string, listener: SseListener): void;
229
+ addEventListener<TData = AnyMap>(type: string, listener: SseListener<TData>): void;
223
230
  /**
224
231
  * Unregister a listener.
225
232
  */
226
- removeEventListener(type: string, listener: SseListener): void;
233
+ removeEventListener<TData = AnyMap>(type: string, listener: SseListener<TData>): void;
234
+ /**
235
+ * Unregister all listeners, optionally filtered by event type.
236
+ */
237
+ removeAllEventListeners(type?: string): void;
227
238
  /** Start the connection. */
228
239
  start(): void;
229
240
  /** Stop the connection. */
@@ -232,7 +243,10 @@ export interface SseClient {
232
243
  restart(): void;
233
244
  /** Force flush buffered events to JS. */
234
245
  flush(): void;
235
- /** Check if active. */
246
+ /**
247
+ * Check if the client engine is currently running ('connecting', 'open', or 'reconnecting').
248
+ * Use `getState() === 'open'` to check if the stream is actively open and ready.
249
+ */
236
250
  isConnected(): boolean;
237
251
  /** Get stats. */
238
252
  getStats(): SseStats;
@@ -244,5 +258,7 @@ export interface SseClient {
244
258
  injectMockEvent(event: Partial<SseEvent>): void;
245
259
  /** Get current connection state. */
246
260
  getState(): SseState;
261
+ /** Explicitly dispose instance and release native threads/observers. */
262
+ dispose(): void;
247
263
  }
248
264
  //# sourceMappingURL=SseInterface.d.ts.map
@@ -1,11 +1,13 @@
1
1
  import type { SseClient } from './SseInterface';
2
2
  export * from './SseInterface';
3
- export * from './NitroSse.nitro';
3
+ export * from './useNitroSse';
4
+ export * from './NitroSseClient';
5
+ export * from './NitroSseError';
4
6
  /**
5
7
  * Creates a high-performance SSE client that supports typed event listeners (`addEventListener`) and legacy batching.
6
8
  *
7
9
  * @returns An SseClient instance wrapping the native NitroSse implementation.
8
- * @throws If the native NitroSse module cannot be found. Ensure the library is linked and the app is built for iOS/Android.
10
+ * @throws {NitroSseModuleNotFoundError} If the native NitroSse module cannot be found. Ensure the library is linked and the app is built for iOS/Android.
9
11
  */
10
12
  export declare function createNitroSse(): SseClient;
11
13
  //# sourceMappingURL=index.d.ts.map