react-native-nitro-sse 1.4.0 → 1.5.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 (33) hide show
  1. package/NitroSse.podspec +2 -3
  2. package/README.md +4 -1
  3. package/android/src/main/java/com/margelo/nitro/nitrosse/NitroSse.kt +148 -20
  4. package/android/src/test/java/com/margelo/nitro/nitrosse/NitroSseLogicTest.kt +2 -2
  5. package/ios/NitroSse.swift +178 -46
  6. package/lib/module/index.js +3 -2
  7. package/lib/module/index.js.map +1 -1
  8. package/lib/typescript/src/SseInterface.d.ts +17 -0
  9. package/lib/typescript/src/SseInterface.d.ts.map +1 -1
  10. package/lib/typescript/src/index.d.ts.map +1 -1
  11. package/nitrogen/generated/android/c++/JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.hpp +138 -0
  12. package/nitrogen/generated/android/c++/JHybridNitroSseSpec.cpp +5 -2
  13. package/nitrogen/generated/android/c++/JSseConfig.hpp +28 -3
  14. package/nitrogen/generated/android/c++/JSseEvent.hpp +11 -3
  15. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.kt +80 -0
  16. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseConfig.kt +18 -5
  17. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitrosse/SseEvent.kt +9 -3
  18. package/nitrogen/generated/android/nitrosseOnLoad.cpp +2 -0
  19. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.cpp +33 -0
  20. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Bridge.hpp +130 -0
  21. package/nitrogen/generated/ios/NitroSse-Swift-Cxx-Umbrella.hpp +1 -0
  22. package/nitrogen/generated/ios/c++/HybridNitroSseSpecSwift.hpp +2 -1
  23. package/nitrogen/generated/ios/swift/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.swift +67 -0
  24. package/nitrogen/generated/ios/swift/Func_void_std__exception_ptr.swift +46 -0
  25. package/nitrogen/generated/ios/swift/Func_void_std__shared_ptr_Promise_std__unordered_map_std__string__std__string___.swift +66 -0
  26. package/nitrogen/generated/ios/swift/Func_void_std__unordered_map_std__string__std__string_.swift +54 -0
  27. package/nitrogen/generated/ios/swift/SseConfig.swift +84 -1
  28. package/nitrogen/generated/ios/swift/SseEvent.swift +37 -1
  29. package/nitrogen/generated/shared/c++/SseConfig.hpp +17 -3
  30. package/nitrogen/generated/shared/c++/SseEvent.hpp +10 -2
  31. package/package.json +2 -2
  32. package/src/SseInterface.ts +17 -0
  33. package/src/{index.tsx → index.ts} +4 -3
@@ -19,8 +19,9 @@ class NitroSse: HybridNitroSseSpec {
19
19
  private var config: SseConfig?
20
20
  private var onEventsCallback: ((_ events: [SseEvent]) -> Void)?
21
21
  private var isRunning: Bool = false
22
- private var requestId: String?
23
-
22
+ private var consecutiveAuthErrors: Int = 0
23
+ private let maxAuthRetries: Int = 3
24
+ private var requestId: String? = nil
24
25
  private var eventBuffer: [SseEvent] = []
25
26
  private var isFlushPending: Bool = false
26
27
 
@@ -33,13 +34,22 @@ class NitroSse: HybridNitroSseSpec {
33
34
  private var lastErrorCode: String? = nil
34
35
 
35
36
  private let defaultRetryDelay: TimeInterval = 3.0
36
- private let baseBackoffDelay: TimeInterval = 2.0
37
+ private let baseBackoffDelay: TimeInterval = 1.0
37
38
  private let maxBackoffDelay: TimeInterval = 30.0
38
39
 
39
40
  private let sseQueue = DispatchQueue(label: "com.margelo.nitro.sse", qos: .utility)
41
+ private var connectionAttemptVersion: Int = 0
40
42
  private var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = .invalid
41
43
  private var wasRunningBeforeHibernation: Bool = false
42
44
 
45
+ /**
46
+ * Set up the NitroSse instance with configuration and an event callback.
47
+ * This prepares the lifecycle observers and internal dispatch queue.
48
+ *
49
+ * - Parameters:
50
+ * - config: The SSE configuration containing URL, headers, and more.
51
+ * - onEvent: Callback function to receive batched SSE events.
52
+ */
43
53
  func setup(config: SseConfig, onEvent: @escaping ((_ events: [SseEvent]) -> Void)) throws {
44
54
  self.config = config
45
55
  self.onEventsCallback = onEvent
@@ -126,28 +136,41 @@ class NitroSse: HybridNitroSseSpec {
126
136
  onEventsCallback?(batch)
127
137
  }
128
138
 
139
+ /**
140
+ * Manually set the last seen event ID.
141
+ * This will be used as the 'Last-Event-ID' header on the next connection attempt.
142
+ */
129
143
  func setLastProcessedId(id: String) {
130
144
  sseQueue.async {
131
145
  self.lastProcessedId = id
132
146
  }
133
147
  }
134
148
 
149
+ /**
150
+ * Dynamically update the headers for subsequent connection attempts.
151
+ */
135
152
  func updateHeaders(headers: [String: String]) throws {
136
153
  sseQueue.async {
137
- guard let currentConfig = self.config else { return }
154
+ guard var config = self.config else { return }
138
155
  self.config = SseConfig(
139
- url: currentConfig.url,
140
- method: currentConfig.method,
156
+ url: config.url,
157
+ method: config.method,
141
158
  headers: headers,
142
- body: currentConfig.body,
143
- backgroundExecution: currentConfig.backgroundExecution,
144
- batchingIntervalMs: currentConfig.batchingIntervalMs,
145
- maxBufferSize: currentConfig.maxBufferSize
159
+ body: config.body,
160
+ backgroundExecution: config.backgroundExecution,
161
+ batchingIntervalMs: config.batchingIntervalMs,
162
+ maxBufferSize: config.maxBufferSize,
163
+ connectionTimeoutMs: config.connectionTimeoutMs,
164
+ readTimeoutMs: config.readTimeoutMs,
165
+ onBeforeRequest: config.onBeforeRequest // Ensure onBeforeRequest is copied
146
166
  )
147
167
  print("[NitroSse] Headers updated for subsequent connections.")
148
168
  }
149
169
  }
150
170
 
171
+ /**
172
+ * Returns runtime statistics about the SSE connection.
173
+ */
151
174
  func getStats() throws -> SseStats {
152
175
  return sseQueue.sync {
153
176
  return SseStats(
@@ -159,33 +182,99 @@ class NitroSse: HybridNitroSseSpec {
159
182
  }
160
183
  }
161
184
 
185
+ /**
186
+ * Start the SSE connection.
187
+ * This triggers the initial request and handles subsequent reconnections.
188
+ */
162
189
  func start() throws {
163
190
  sseQueue.async {
164
191
  guard !self.isRunning else { return }
165
192
  self.isRunning = true
193
+ self.consecutiveAuthErrors = 0 // Reset auth retry state
166
194
  self.backoffCounter = 0
167
- self.establishConnection()
195
+ self.connectionAttemptVersion += 1
196
+ let version = self.connectionAttemptVersion
197
+ self.establishConnection(attemptVersion: version)
198
+ }
199
+ }
200
+
201
+ private func establishConnection(attemptVersion: Int) {
202
+ dispatchPrecondition(condition: .onQueue(sseQueue))
203
+ guard isRunning, let config = config, attemptVersion == self.connectionAttemptVersion else { return }
204
+
205
+ if let interceptor = config.onBeforeRequest {
206
+ // Strong reference to config to avoid it changing under us during async call
207
+ let capturedConfig = config
208
+ interceptor().then { [weak self] promise2 in
209
+ promise2.then { [weak self] newHeaders in
210
+ self?.sseQueue.async {
211
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
212
+ var mergedHeaders = capturedConfig.headers ?? [:]
213
+ for (k, v) in newHeaders {
214
+ mergedHeaders[k] = v
215
+ }
216
+ self.config = SseConfig(
217
+ url: capturedConfig.url,
218
+ method: capturedConfig.method,
219
+ headers: mergedHeaders,
220
+ body: capturedConfig.body,
221
+ backgroundExecution: capturedConfig.backgroundExecution,
222
+ batchingIntervalMs: capturedConfig.batchingIntervalMs,
223
+ maxBufferSize: capturedConfig.maxBufferSize,
224
+ connectionTimeoutMs: capturedConfig.connectionTimeoutMs,
225
+ readTimeoutMs: capturedConfig.readTimeoutMs,
226
+ onBeforeRequest: capturedConfig.onBeforeRequest
227
+ )
228
+ self.performEstablishConnection(attemptVersion: attemptVersion)
229
+ }
230
+ }.catch { [weak self] error in
231
+ self?.handleInterceptorError(error, attemptVersion: attemptVersion)
232
+ }
233
+ }.catch { [weak self] error in
234
+ self?.handleInterceptorError(error, attemptVersion: attemptVersion)
235
+ }
236
+ } else {
237
+ self.performEstablishConnection(attemptVersion: attemptVersion)
168
238
  }
169
239
  }
170
240
 
171
- private func establishConnection() {
241
+ private func handleInterceptorError(_ error: Error, attemptVersion: Int) {
242
+ sseQueue.async {
243
+ guard self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
244
+ print("[NitroSse] Interceptor failed: \(error.localizedDescription)")
245
+ self.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Interceptor Error: \(error.localizedDescription)", statusCode: -1, retry: nil))
246
+ // Reconnect after delay
247
+ self.scheduleAutomaticReconnect(isError: true, attemptVersion: attemptVersion)
248
+ }
249
+ }
250
+
251
+ private func performEstablishConnection(attemptVersion: Int) {
172
252
  dispatchPrecondition(condition: .onQueue(sseQueue))
173
- guard isRunning, let config = config, let url = URL(string: config.url) else { return }
253
+ guard isRunning, let config = config, let url = URL(string: config.url), attemptVersion == self.connectionAttemptVersion else { return }
174
254
 
175
255
  if let rid = self.requestId {
176
256
  NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(self.totalBytesReceived))
177
257
  self.requestId = nil
178
258
  }
179
259
 
180
- let handler = SseHandler(parent: self)
260
+
261
+ let sessionConfig = URLSessionConfiguration.default
262
+ sessionConfig.timeoutIntervalForRequest = (config.readTimeoutMs ?? 35000.0) / 1000.0
263
+ sessionConfig.timeoutIntervalForResource = (config.readTimeoutMs ?? 35000.0) / 1000.0
264
+ if let connTimeout = config.connectionTimeoutMs {
265
+ sessionConfig.timeoutIntervalForRequest = connTimeout / 1000.0
266
+ }
267
+
268
+ let handler = SseHandler(parent: self, attemptVersion: attemptVersion)
181
269
  var esConfig = EventSource.Config(handler: handler, url: url)
270
+ esConfig.urlSessionConfiguration = sessionConfig
182
271
  esConfig.headers = config.headers ?? [:]
183
272
 
184
273
  if let lastId = self.lastProcessedId, !lastId.isEmpty {
185
274
  esConfig.headers["Last-Event-ID"] = lastId
186
275
  }
187
276
 
188
- esConfig.idleTimeout = 35.0
277
+ esConfig.lastEventId = self.lastProcessedId ?? ""
189
278
  esConfig.method = config.method?.stringValue.uppercased() ?? "GET"
190
279
  esConfig.body = config.body?.data(using: .utf8)
191
280
 
@@ -199,6 +288,9 @@ class NitroSse: HybridNitroSseSpec {
199
288
  es.start()
200
289
  }
201
290
 
291
+ /**
292
+ * Stop the SSE connection and clear any pending reconnect timers.
293
+ */
202
294
  func stop() {
203
295
  sseQueue.async {
204
296
  self.stopInternal()
@@ -214,27 +306,36 @@ class NitroSse: HybridNitroSseSpec {
214
306
  self.requestId = nil
215
307
  }
216
308
  self.backoffCounter = 0
217
- self.eventBuffer.removeAll()
218
309
  self.isFlushPending = false
219
310
  self.cleanupBackgroundTask()
220
311
  }
221
312
 
313
+ /**
314
+ * Immediately emit any pending buffered events to the JS bridge.
315
+ */
222
316
  func flush() {
223
317
  sseQueue.async {
224
318
  self.flushEventsToJs()
225
319
  }
226
320
  }
227
321
 
322
+ /**
323
+ * Restart the SSE connection by stopping and starting again.
324
+ */
228
325
  func restart() {
229
326
  sseQueue.async {
230
327
  self.stopInternal()
231
328
  guard !self.isRunning else { return } // Should be false now
232
329
  self.isRunning = true
233
330
  self.requestId = nil
234
- self.establishConnection()
331
+ self.connectionAttemptVersion += 1
332
+ self.establishConnection(attemptVersion: self.connectionAttemptVersion)
235
333
  }
236
334
  }
237
335
 
336
+ /**
337
+ * Indicates if the SSE connection is currently active or trying to connect.
338
+ */
238
339
  func isConnected() -> Bool {
239
340
  return sseQueue.sync {
240
341
  return isRunning
@@ -263,17 +364,17 @@ class NitroSse: HybridNitroSseSpec {
263
364
  // EventSource callback handling is done via SseHandler class below.
264
365
 
265
366
 
266
- private func scheduleAutomaticReconnectWithFixedDelay(_ delay: TimeInterval) {
367
+ private func scheduleAutomaticReconnectWithFixedDelay(_ delay: TimeInterval, attemptVersion: Int) {
267
368
  dispatchPrecondition(condition: .onQueue(sseQueue))
268
369
  eventSource?.stop()
269
370
  eventSource = nil
270
371
  sseQueue.asyncAfter(deadline: .now() + delay) { [weak self] in
271
- guard let self = self, self.isRunning else { return }
272
- self.establishConnection()
372
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
373
+ self.establishConnection(attemptVersion: attemptVersion)
273
374
  }
274
375
  }
275
376
 
276
- private func scheduleAutomaticReconnect(isError: Bool) {
377
+ private func scheduleAutomaticReconnect(isError: Bool, attemptVersion: Int) {
277
378
  dispatchPrecondition(condition: .onQueue(sseQueue))
278
379
  eventSource?.stop()
279
380
  var delay: TimeInterval = defaultRetryDelay
@@ -290,39 +391,43 @@ class NitroSse: HybridNitroSseSpec {
290
391
  eventSource?.stop()
291
392
  eventSource = nil
292
393
  sseQueue.asyncAfter(deadline: .now() + safeDelay) { [weak self] in
293
- guard let self = self, self.isRunning else { return }
294
- self.establishConnection()
394
+ guard let self = self, self.isRunning, attemptVersion == self.connectionAttemptVersion else { return }
395
+ self.establishConnection(attemptVersion: attemptVersion)
295
396
  }
296
397
  }
297
398
 
298
399
  private class SseHandler: EventHandler {
299
400
  weak var parent: NitroSse?
300
401
  weak var source: EventSource?
402
+ let attemptVersion: Int
301
403
 
302
- init(parent: NitroSse) {
404
+ init(parent: NitroSse, attemptVersion: Int) {
303
405
  self.parent = parent
406
+ self.attemptVersion = attemptVersion
304
407
  }
305
408
 
306
409
  func onOpened() {
307
410
  guard let parent = parent, source === parent.eventSource else { return }
308
411
  parent.sseQueue.async { [weak parent] in
309
- guard let parent = parent else { return }
412
+ guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
310
413
  parent.backoffCounter = 0
311
- NitroSseNetworkInspector.reportResponseStart(parent.requestId, url: parent.config?.url, response: nil, statusCode: 200, headers: [:])
312
- parent.pushEventToBuffer(SseEvent(type: .open, data: nil, id: nil, event: nil, message: nil))
414
+ parent.consecutiveAuthErrors = 0 // Successful connection, reset error counter
415
+ // LDSwiftEventSource doesn't easily expose the response code in onOpened,
416
+ // but we assume 200 if onOpened is called.
417
+ parent.pushEventToBuffer(SseEvent(type: .open, data: nil, id: nil, event: nil, message: nil, statusCode: 200, retry: nil))
313
418
  }
314
419
  }
315
420
 
316
421
  func onClosed() {
317
422
  guard let parent = parent, source === parent.eventSource else { return }
318
423
  parent.sseQueue.async { [weak parent] in
319
- guard let parent = parent else { return }
424
+ guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
320
425
  if let rid = parent.requestId {
321
426
  NitroSseNetworkInspector.reportResponseEnd(rid, encodedDataLength: Int(parent.totalBytesReceived))
322
427
  parent.requestId = nil
323
428
  }
324
429
  if parent.isRunning {
325
- parent.scheduleAutomaticReconnect(isError: false)
430
+ parent.scheduleAutomaticReconnect(isError: false, attemptVersion: self.attemptVersion)
326
431
  }
327
432
  }
328
433
  }
@@ -330,7 +435,7 @@ class NitroSse: HybridNitroSseSpec {
330
435
  func onMessage(eventType: String, messageEvent: MessageEvent) {
331
436
  guard let parent = parent, source === parent.eventSource else { return }
332
437
  parent.sseQueue.async { [weak parent] in
333
- guard let parent = parent else { return }
438
+ guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
334
439
  let encodedDataSize = Double(messageEvent.data.utf8.count)
335
440
  let metadataSize = Double(eventType.utf8.count) + Double((messageEvent.lastEventId).utf8.count)
336
441
  parent.totalBytesReceived += encodedDataSize + metadataSize
@@ -339,23 +444,23 @@ class NitroSse: HybridNitroSseSpec {
339
444
  parent.lastProcessedId = messageEvent.lastEventId
340
445
  }
341
446
 
342
- parent.pushEventToBuffer(SseEvent(type: .message, data: messageEvent.data, id: messageEvent.lastEventId, event: eventType, message: nil))
447
+ parent.pushEventToBuffer(SseEvent(type: .message, data: messageEvent.data, id: messageEvent.lastEventId, event: eventType, message: nil, statusCode: 200, retry: nil))
343
448
  }
344
449
  }
345
450
 
346
451
  func onComment(comment: String) {
347
452
  guard let parent = parent, source === parent.eventSource else { return }
348
453
  parent.sseQueue.async { [weak parent] in
349
- guard let parent = parent else { return }
454
+ guard let parent = parent, self.attemptVersion == parent.connectionAttemptVersion else { return }
350
455
  parent.totalBytesReceived += Double(comment.utf8.count)
351
- parent.pushEventToBuffer(SseEvent(type: .heartbeat, data: nil, id: nil, event: nil, message: comment))
456
+ parent.pushEventToBuffer(SseEvent(type: .heartbeat, data: nil, id: nil, event: nil, message: comment, statusCode: nil, retry: nil))
352
457
  }
353
458
  }
354
459
 
355
460
  func onError(error: Error) {
356
461
  guard let parent = parent, source === parent.eventSource else { return }
357
462
  parent.sseQueue.async { [weak parent] in
358
- guard let parent = parent, parent.isRunning else { return }
463
+ guard let parent = parent, parent.isRunning, self.attemptVersion == parent.connectionAttemptVersion else { return }
359
464
  let nsError = error as NSError
360
465
  let statusCode = nsError.code
361
466
 
@@ -366,30 +471,57 @@ class NitroSse: HybridNitroSseSpec {
366
471
  NitroSseNetworkInspector.reportRequestFailed(parent.requestId, cancelled: false)
367
472
  parent.requestId = nil
368
473
 
369
- let isFatalError = (statusCode == 401 || statusCode == 403 || statusCode == 400)
370
- if isFatalError {
371
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Fatal Error (\(statusCode)). Stopping."))
474
+
475
+ if statusCode == 204 {
476
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "No Content (204). Stopping.", statusCode: 204, retry: nil))
477
+ parent.stopInternal()
478
+ return
479
+ }
480
+
481
+ // 401/403 are recoverable if we have an interceptor, but with a limit
482
+ if statusCode == 401 || statusCode == 403 {
483
+ if parent.config?.onBeforeRequest == nil {
484
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - No interceptor provided. Stopping.", statusCode: Double(statusCode), retry: nil))
485
+ parent.stopInternal()
486
+ return
487
+ }
488
+
489
+ parent.consecutiveAuthErrors += 1
490
+ if parent.consecutiveAuthErrors >= parent.maxAuthRetries {
491
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - Retry limit reached (\(parent.maxAuthRetries)). Stopping.", statusCode: Double(statusCode), retry: nil))
492
+ parent.stopInternal()
493
+ return
494
+ }
495
+
496
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Auth Error (\(statusCode)) - Retry \(parent.consecutiveAuthErrors)/\(parent.maxAuthRetries). Refreshing token...", statusCode: Double(statusCode), retry: nil))
497
+ parent.scheduleAutomaticReconnect(isError: true, attemptVersion: self.attemptVersion)
498
+ return
499
+ }
500
+
501
+ let isFatal = (statusCode == 400)
502
+ if isFatal {
503
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Fatal Error (\(statusCode)). Stopping.", statusCode: Double(statusCode), retry: nil))
372
504
  parent.stopInternal()
373
505
  return
374
506
  }
375
507
 
376
508
  let retryAfterSeconds = parent.extractRetryAfterSeconds(error: error)
377
- if (statusCode == 429 || statusCode == 503), let delay = retryAfterSeconds {
378
- let jitter = Double.random(in: 0.5...2.0)
379
- let totalDelay = delay + jitter
380
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Retry-After received (\(statusCode))"))
381
- parent.scheduleAutomaticReconnectWithFixedDelay(totalDelay)
509
+ if (statusCode == 429 || statusCode == 503), let retryAfter = retryAfterSeconds {
510
+ let jitter = Double.random(in: 0.5...1.5)
511
+ let totalDelay = retryAfter + jitter
512
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Retry-After received: \(Int(totalDelay))s", statusCode: Double(statusCode), retry: totalDelay * 1000.0))
513
+ parent.scheduleAutomaticReconnectWithFixedDelay(totalDelay, attemptVersion: self.attemptVersion)
382
514
  return
383
515
  }
384
516
 
385
517
  if statusCode == 429 {
386
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Rate Limited (429) without Retry-After. Stopping."))
518
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: "Rate Limited (429) without Retry-After. Stopping.", statusCode: 429, retry: nil))
387
519
  parent.stopInternal()
388
520
  return
389
521
  }
390
-
391
- parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: error.localizedDescription))
392
- parent.scheduleAutomaticReconnect(isError: true)
522
+
523
+ parent.pushEventToBuffer(SseEvent(type: .error, data: nil, id: nil, event: nil, message: error.localizedDescription, statusCode: Double(statusCode), retry: nil))
524
+ parent.scheduleAutomaticReconnect(isError: true, attemptVersion: self.attemptVersion)
393
525
  }
394
526
  }
395
527
  }
@@ -7,9 +7,10 @@ export function createNitroSse() {
7
7
  let nativeSse;
8
8
  try {
9
9
  nativeSse = NitroModules.createHybridObject('NitroSse');
10
- } catch {}
11
- if (!nativeSse) {
10
+ } catch {
12
11
  console.debug('Native NitroSse not found. This might be a test environment or web.');
12
+ }
13
+ if (!nativeSse) {
13
14
  throw new Error('NitroSse: Native module not found. Ensure you have linked the library and built the app for iOS/Android.');
14
15
  }
15
16
  return nativeSse;
@@ -1 +1 @@
1
- {"version":3,"names":["NitroModules","createNitroSse","nativeSse","createHybridObject","console","debug","Error"],"sourceRoot":"../../src","sources":["index.tsx"],"mappings":";;AAAA,SAASA,YAAY,QAAQ,4BAA4B;AAGzD,cAAc,mBAAgB;AAC9B,cAAc,qBAAkB;AAEhC,OAAO,SAASC,cAAcA,CAAA,EAAa;EACzC,IAAIC,SAA+B;EACnC,IAAI;IACFA,SAAS,GAAGF,YAAY,CAACG,kBAAkB,CAAW,UAAU,CAAC;EACnE,CAAC,CAAC,MAAM,CAAC;EAET,IAAI,CAACD,SAAS,EAAE;IACdE,OAAO,CAACC,KAAK,CACX,qEACF,CAAC;IACD,MAAM,IAAIC,KAAK,CACb,0GACF,CAAC;EACH;EACA,OAAOJ,SAAS;AAClB","ignoreList":[]}
1
+ {"version":3,"names":["NitroModules","createNitroSse","nativeSse","createHybridObject","console","debug","Error"],"sourceRoot":"../../src","sources":["index.ts"],"mappings":";;AAAA,SAASA,YAAY,QAAQ,4BAA4B;AAGzD,cAAc,mBAAgB;AAC9B,cAAc,qBAAkB;AAEhC,OAAO,SAASC,cAAcA,CAAA,EAAa;EACzC,IAAIC,SAA+B;EACnC,IAAI;IACFA,SAAS,GAAGF,YAAY,CAACG,kBAAkB,CAAW,UAAU,CAAC;EACnE,CAAC,CAAC,MAAM;IACNC,OAAO,CAACC,KAAK,CACX,qEACF,CAAC;EACH;EAEA,IAAI,CAACH,SAAS,EAAE;IACd,MAAM,IAAII,KAAK,CACb,0GACF,CAAC;EACH;EACA,OAAOJ,SAAS;AAClB","ignoreList":[]}
@@ -38,6 +38,19 @@ export interface SseConfig {
38
38
  * Maximum number of events to hold in the buffer before forced flushing.
39
39
  */
40
40
  maxBufferSize?: number;
41
+ /**
42
+ * Connection timeout in milliseconds.
43
+ */
44
+ connectionTimeoutMs?: number;
45
+ /**
46
+ * Read timeout in milliseconds.
47
+ */
48
+ readTimeoutMs?: number;
49
+ /**
50
+ * Optional interceptor called before every request.
51
+ * Useful for refreshing tokens or adding dynamic parameters.
52
+ */
53
+ onBeforeRequest?: () => Promise<Record<string, string>>;
41
54
  }
42
55
  /**
43
56
  * Represents a single SSE event.
@@ -53,6 +66,10 @@ export interface SseEvent {
53
66
  event?: string;
54
67
  /** System message or error description. */
55
68
  message?: string;
69
+ /** HTTP status code if applicable. */
70
+ statusCode?: number;
71
+ /** Server-requested retry delay in milliseconds. */
72
+ retry?: number;
56
73
  }
57
74
  /**
58
75
  * Statistics about the SSE connection.
@@ -1 +1 @@
1
- {"version":3,"file":"SseInterface.d.ts","sourceRoot":"","sources":["../../../src/SseInterface.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,MAAM,CAAC;AAExC;;;;;;;GAOG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,GAAG,WAAW,CAAC;AAEhF;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,mCAAmC;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,oCAAoC;IACpC,MAAM,CAAC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E,MAAM,kBAAkB,CAAC;AAEjD,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC;AAEjC,wBAAgB,cAAc,IAAI,QAAQ,CAezC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAEjD,cAAc,gBAAgB,CAAC;AAC/B,cAAc,kBAAkB,CAAC;AAEjC,wBAAgB,cAAc,IAAI,QAAQ,CAgBzC"}
@@ -0,0 +1,138 @@
1
+ ///
2
+ /// JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.hpp
3
+ /// This file was generated by nitrogen. DO NOT MODIFY THIS FILE.
4
+ /// https://github.com/mrousavy/nitro
5
+ /// Copyright © Marc Rousavy @ Margelo
6
+ ///
7
+
8
+ #pragma once
9
+
10
+ #include <fbjni/fbjni.h>
11
+ #include <functional>
12
+
13
+ #include <string>
14
+ #include <unordered_map>
15
+ #include <NitroModules/Promise.hpp>
16
+ #include <functional>
17
+ #include <NitroModules/JNICallable.hpp>
18
+ #include <NitroModules/JPromise.hpp>
19
+
20
+ namespace margelo::nitro::nitrosse {
21
+
22
+ using namespace facebook;
23
+
24
+ /**
25
+ * Represents the Java/Kotlin callback `() -> Promise<Promise<Map<String, String>>>`.
26
+ * This can be passed around between C++ and Java/Kotlin.
27
+ */
28
+ struct JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____: public jni::JavaClass<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____> {
29
+ public:
30
+ static auto constexpr kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____;";
31
+
32
+ public:
33
+ /**
34
+ * Invokes the function this `JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____` instance holds through JNI.
35
+ */
36
+ std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>> invoke() const {
37
+ static const auto method = javaClassStatic()->getMethod<jni::local_ref<JPromise::javaobject>()>("invoke");
38
+ auto __result = method(self());
39
+ return [&]() {
40
+ auto __promise = Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>::create();
41
+ __result->cthis()->addOnResolvedListener([=](const jni::alias_ref<jni::JObject>& __boxedResult) {
42
+ auto __result = jni::static_ref_cast<JPromise::javaobject>(__boxedResult);
43
+ __promise->resolve([&]() {
44
+ auto __promise = Promise<std::unordered_map<std::string, std::string>>::create();
45
+ __result->cthis()->addOnResolvedListener([=](const jni::alias_ref<jni::JObject>& __boxedResult) {
46
+ auto __result = jni::static_ref_cast<jni::JMap<jni::JString, jni::JString>>(__boxedResult);
47
+ __promise->resolve([&]() {
48
+ std::unordered_map<std::string, std::string> __map;
49
+ __map.reserve(__result->size());
50
+ for (const auto& __entry : *__result) {
51
+ __map.emplace(__entry.first->toStdString(), __entry.second->toStdString());
52
+ }
53
+ return __map;
54
+ }());
55
+ });
56
+ __result->cthis()->addOnRejectedListener([=](const jni::alias_ref<jni::JThrowable>& __throwable) {
57
+ jni::JniException __jniError(__throwable);
58
+ __promise->reject(std::make_exception_ptr(__jniError));
59
+ });
60
+ return __promise;
61
+ }());
62
+ });
63
+ __result->cthis()->addOnRejectedListener([=](const jni::alias_ref<jni::JThrowable>& __throwable) {
64
+ jni::JniException __jniError(__throwable);
65
+ __promise->reject(std::make_exception_ptr(__jniError));
66
+ });
67
+ return __promise;
68
+ }();
69
+ }
70
+ };
71
+
72
+ /**
73
+ * An implementation of Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____ that is backed by a C++ implementation (using `std::function<...>`)
74
+ */
75
+ class JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx final: public jni::HybridClass<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx, JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____> {
76
+ public:
77
+ static jni::local_ref<JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____::javaobject> fromCpp(const std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>& func) {
78
+ return JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx::newObjectCxxArgs(func);
79
+ }
80
+
81
+ public:
82
+ /**
83
+ * Invokes the C++ `std::function<...>` this `JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx` instance holds.
84
+ */
85
+ jni::local_ref<JPromise::javaobject> invoke_cxx() {
86
+ std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>> __result = _func();
87
+ return [&]() {
88
+ jni::local_ref<JPromise::javaobject> __localPromise = JPromise::create();
89
+ jni::global_ref<JPromise::javaobject> __promise = jni::make_global(__localPromise);
90
+ __result->addOnResolvedListener([=](const std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>& __result) {
91
+ __promise->cthis()->resolve([&]() {
92
+ jni::local_ref<JPromise::javaobject> __localPromise = JPromise::create();
93
+ jni::global_ref<JPromise::javaobject> __promise = jni::make_global(__localPromise);
94
+ __result->addOnResolvedListener([=](const std::unordered_map<std::string, std::string>& __result) {
95
+ __promise->cthis()->resolve([&]() -> jni::local_ref<jni::JMap<jni::JString, jni::JString>> {
96
+ auto __map = jni::JHashMap<jni::JString, jni::JString>::create(__result.size());
97
+ for (const auto& __entry : __result) {
98
+ __map->put(jni::make_jstring(__entry.first), jni::make_jstring(__entry.second));
99
+ }
100
+ return __map;
101
+ }());
102
+ });
103
+ __result->addOnRejectedListener([=](const std::exception_ptr& __error) {
104
+ auto __jniError = jni::getJavaExceptionForCppException(__error);
105
+ __promise->cthis()->reject(__jniError);
106
+ });
107
+ return __localPromise;
108
+ }());
109
+ });
110
+ __result->addOnRejectedListener([=](const std::exception_ptr& __error) {
111
+ auto __jniError = jni::getJavaExceptionForCppException(__error);
112
+ __promise->cthis()->reject(__jniError);
113
+ });
114
+ return __localPromise;
115
+ }();
116
+ }
117
+
118
+ public:
119
+ [[nodiscard]]
120
+ inline const std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>& getFunction() const {
121
+ return _func;
122
+ }
123
+
124
+ public:
125
+ static auto constexpr kJavaDescriptor = "Lcom/margelo/nitro/nitrosse/Func_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx;";
126
+ static void registerNatives() {
127
+ registerHybrid({makeNativeMethod("invoke_cxx", JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx::invoke_cxx)});
128
+ }
129
+
130
+ private:
131
+ explicit JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string______cxx(const std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()>& func): _func(func) { }
132
+
133
+ private:
134
+ friend HybridBase;
135
+ std::function<std::shared_ptr<Promise<std::shared_ptr<Promise<std::unordered_map<std::string, std::string>>>>>()> _func;
136
+ };
137
+
138
+ } // namespace margelo::nitro::nitrosse
@@ -27,11 +27,14 @@ namespace margelo::nitro::nitrosse { enum class SseEventType; }
27
27
  #include "HttpMethod.hpp"
28
28
  #include "JHttpMethod.hpp"
29
29
  #include <unordered_map>
30
+ #include <NitroModules/Promise.hpp>
31
+ #include <functional>
32
+ #include "JFunc_std__shared_ptr_Promise_std__shared_ptr_Promise_std__unordered_map_std__string__std__string_____.hpp"
33
+ #include <NitroModules/JNICallable.hpp>
34
+ #include <NitroModules/JPromise.hpp>
30
35
  #include "SseEvent.hpp"
31
36
  #include <vector>
32
- #include <functional>
33
37
  #include "JFunc_void_std__vector_SseEvent_.hpp"
34
- #include <NitroModules/JNICallable.hpp>
35
38
  #include "JSseEvent.hpp"
36
39
  #include "SseEventType.hpp"
37
40
  #include "JSseEventType.hpp"