@metarouter/react-native-sdk 1.5.1 → 1.8.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 (64) hide show
  1. package/README.md +190 -60
  2. package/android/build.gradle +41 -0
  3. package/android/src/main/AndroidManifest.xml +4 -0
  4. package/android/src/main/java/com/metarouter/reactnative/MetaRouterNetworkMonitorModule.kt +119 -0
  5. package/android/src/main/java/com/metarouter/reactnative/MetaRouterPackage.kt +23 -0
  6. package/android/src/main/java/com/metarouter/reactnative/MetaRouterQueueStorageModule.kt +124 -0
  7. package/ios/MetaRouterNetworkMonitor.m +76 -0
  8. package/ios/MetaRouterQueueStorage.m +127 -0
  9. package/lib/analytics/MetaRouterAnalyticsClient.d.ts +71 -4
  10. package/lib/analytics/MetaRouterAnalyticsClient.d.ts.map +1 -1
  11. package/lib/analytics/MetaRouterAnalyticsClient.js +396 -112
  12. package/lib/analytics/dispatcher.d.ts +57 -1
  13. package/lib/analytics/dispatcher.d.ts.map +1 -1
  14. package/lib/analytics/dispatcher.js +231 -32
  15. package/lib/analytics/init.d.ts +8 -1
  16. package/lib/analytics/init.d.ts.map +1 -1
  17. package/lib/analytics/init.js +198 -37
  18. package/lib/analytics/lifecycle/lifecycleEvents.d.ts +52 -0
  19. package/lib/analytics/lifecycle/lifecycleEvents.d.ts.map +1 -0
  20. package/lib/analytics/lifecycle/lifecycleEvents.js +66 -0
  21. package/lib/analytics/persistence/NativeQueueStorage.d.ts +5 -0
  22. package/lib/analytics/persistence/NativeQueueStorage.d.ts.map +1 -0
  23. package/lib/analytics/persistence/NativeQueueStorage.js +59 -0
  24. package/lib/analytics/persistence/PersistentEventQueue.d.ts +96 -0
  25. package/lib/analytics/persistence/PersistentEventQueue.d.ts.map +1 -0
  26. package/lib/analytics/persistence/PersistentEventQueue.js +401 -0
  27. package/lib/analytics/persistence/types.d.ts +20 -0
  28. package/lib/analytics/persistence/types.d.ts.map +1 -0
  29. package/lib/analytics/persistence/types.js +10 -0
  30. package/lib/analytics/proxy/proxyClient.d.ts +30 -1
  31. package/lib/analytics/proxy/proxyClient.d.ts.map +1 -1
  32. package/lib/analytics/proxy/proxyClient.js +145 -23
  33. package/lib/analytics/types.d.ts +61 -4
  34. package/lib/analytics/types.d.ts.map +1 -1
  35. package/lib/analytics/utils/appContext.d.ts +20 -0
  36. package/lib/analytics/utils/appContext.d.ts.map +1 -0
  37. package/lib/analytics/utils/appContext.js +22 -0
  38. package/lib/analytics/utils/circuitBreaker.d.ts +4 -1
  39. package/lib/analytics/utils/circuitBreaker.d.ts.map +1 -1
  40. package/lib/analytics/utils/circuitBreaker.js +23 -14
  41. package/lib/analytics/utils/contextInfo.d.ts +8 -4
  42. package/lib/analytics/utils/contextInfo.d.ts.map +1 -1
  43. package/lib/analytics/utils/contextInfo.js +34 -27
  44. package/lib/analytics/utils/debouncedNetworkMonitor.d.ts +25 -0
  45. package/lib/analytics/utils/debouncedNetworkMonitor.d.ts.map +1 -0
  46. package/lib/analytics/utils/debouncedNetworkMonitor.js +68 -0
  47. package/lib/analytics/utils/initOptions.d.ts +22 -0
  48. package/lib/analytics/utils/initOptions.d.ts.map +1 -0
  49. package/lib/analytics/utils/initOptions.js +100 -0
  50. package/lib/analytics/utils/lifecycleStorage.d.ts +13 -0
  51. package/lib/analytics/utils/lifecycleStorage.d.ts.map +1 -0
  52. package/lib/analytics/utils/lifecycleStorage.js +35 -0
  53. package/lib/analytics/utils/networkMonitor.d.ts +30 -0
  54. package/lib/analytics/utils/networkMonitor.d.ts.map +1 -0
  55. package/lib/analytics/utils/networkMonitor.js +90 -0
  56. package/lib/analytics/utils/responseCategory.d.ts +14 -0
  57. package/lib/analytics/utils/responseCategory.d.ts.map +1 -0
  58. package/lib/analytics/utils/responseCategory.js +26 -0
  59. package/lib/index.d.ts +4 -4
  60. package/lib/index.d.ts.map +1 -1
  61. package/lib/index.js +3 -3
  62. package/metarouter-react-native-sdk.podspec +19 -0
  63. package/package.json +6 -3
  64. package/react-native.config.js +15 -0
@@ -1,11 +1,24 @@
1
1
  import type { EventPayload } from './types';
2
2
  import type CircuitBreaker from './utils/circuitBreaker';
3
3
  export type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
4
+ export interface NetworkResponse {
5
+ statusCode: number;
6
+ }
4
7
  export interface DispatcherOptions {
5
- maxQueueEvents: number;
8
+ maxEventCount: number;
9
+ maxQueueBytes: number;
6
10
  autoFlushThreshold: number;
7
11
  maxBatchSize: number;
8
12
  flushIntervalSeconds: number;
13
+ baseRetryDelayMs: number;
14
+ maxRetryDelayMs: number;
15
+ /**
16
+ * Whether disk persistence is enabled. When false, capacity overflow drops
17
+ * the oldest event (ring buffer) instead of splicing the whole queue to
18
+ * the onCapacityOverflow handler, since there is no disk to spill to.
19
+ */
20
+ isPersistenceEnabled: () => boolean;
21
+ isNetworkAvailable: () => boolean;
9
22
  endpoint: (path: string) => string;
10
23
  fetchWithTimeout: (url: string, init: RequestInit, timeoutMs: number) => Promise<Response>;
11
24
  canSend: () => boolean;
@@ -15,6 +28,9 @@ export interface DispatcherOptions {
15
28
  log: (...args: any[]) => void;
16
29
  warn: (...args: any[]) => void;
17
30
  error: (...args: any[]) => void;
31
+ onCapacityOverflow?: (events: EventPayload[]) => void | Promise<void>;
32
+ onFlushToDisk?: (events: EventPayload[]) => void | Promise<void>;
33
+ onFlushComplete?: () => void;
18
34
  onScheduleFlushIn?: (ms: number) => void;
19
35
  onFatalConfig?: () => void;
20
36
  }
@@ -28,17 +44,55 @@ export default class Dispatcher {
28
44
  private maxBatchSize;
29
45
  private readonly initialMaxBatchSize;
30
46
  private circuit;
47
+ private queueSizeBytes;
48
+ private consecutiveRetries;
31
49
  constructor(opts: DispatcherOptions);
32
50
  getQueueRef(): EventPayload[];
51
+ /**
52
+ * Drain the in-memory queue entirely. Returns all events and resets the
53
+ * byte counter. Used by PersistentEventQueue to persist memory to disk
54
+ * without leaving duplicates behind.
55
+ */
56
+ drainQueue(): EventPayload[];
57
+ /**
58
+ * Restore events to the front without applying capacity overflow policy.
59
+ * Used only after a failed durability handoff so events are not lost.
60
+ */
61
+ restoreQueueFront(events: EventPayload[]): void;
33
62
  start(): void;
34
63
  stop(): void;
35
64
  reset(): void;
65
+ /**
66
+ * Retry floor: exponential backoff independent of circuit breaker.
67
+ * Applies from the very first failure so retries aren't immediate while circuit is closed.
68
+ */
69
+ private retryFloorMs;
36
70
  private clearNextTimer;
37
71
  scheduleFlushIn(ms: number): void;
72
+ private static encoder;
73
+ private estimateEventSize;
74
+ private handleCapacityOverflow;
75
+ private isOverCap;
38
76
  enqueue(event: EventPayload): void;
77
+ enqueueFront(events: EventPayload[]): void;
78
+ getQueueSizeBytes(): number;
39
79
  private drainBatch;
80
+ private requeueChunk;
40
81
  private parseRetryAfter;
41
82
  flush(): Promise<void>;
83
+ resetCircuitBreaker(): void;
84
+ /**
85
+ * Coordinate shutdown on a fatal config error (401/403/404).
86
+ * Called by the main flush path and by the disk drain so both paths
87
+ * converge to the same "disable client" signal.
88
+ */
89
+ handleFatalConfig(statusCode: number): void;
90
+ /**
91
+ * Send a batch directly to network, bypassing the memory queue.
92
+ * Used by the disk drain to send events without loading them into the queue.
93
+ * Returns { statusCode } on HTTP response, null on network/transport error.
94
+ */
95
+ sendBatchDirect(events: EventPayload[]): Promise<NetworkResponse | null>;
42
96
  getDebugInfo(): {
43
97
  queueLength: number;
44
98
  flushIntervalSeconds: number;
@@ -48,6 +102,8 @@ export default class Dispatcher {
48
102
  circuitRemainingMs: number;
49
103
  maxQueueEvents: number;
50
104
  maxBatchSize: number;
105
+ consecutiveRetries: number;
106
+ isNetworkAvailable: boolean;
51
107
  };
52
108
  }
53
109
  //# sourceMappingURL=dispatcher.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"dispatcher.d.ts","sourceRoot":"","sources":["../../src/analytics/dispatcher.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC5C,OA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AI,EAAE,iBAAiB;IAOnC,WAAW,IAAI,YAAY,EAAE;IAI7B;;;;OAIG;IACH,UAAU,IAAI,YAAY,EAAE;IAM5B;;;OAGG;IACH,iBAAiB,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,IAAI;IAI/C,KAAK,IAAI,IAAI;IAQb,IAAI,IAAI,IAAI;IAQZ,KAAK,IAAI,IAAI;IASb;;;OAGG;IACH,OAAO,CAAC,YAAY;IASpB,OAAO,CAAC,cAAc;IAQtB,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAkBjC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAqB;IAE3C,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,sBAAsB;IA6C9B,OAAO,CAAC,SAAS;IAOjB,OAAO,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI;IA6BlC,YAAY,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,IAAI;IA0B1C,iBAAiB,IAAI,MAAM;IAI3B,OAAO,CAAC,UAAU;IAWlB,OAAO,CAAC,YAAY;IAYpB,OAAO,CAAC,eAAe;IAQjB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAsM5B,mBAAmB,IAAI,IAAI;IAK3B;;;;OAIG;IACH,iBAAiB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI;IAQ3C;;;;OAIG;IACG,eAAe,CACnB,MAAM,EAAE,YAAY,EAAE,GACrB,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAmClC,YAAY;;;;;;;;;;;;CAcb"}
@@ -1,10 +1,12 @@
1
- export default class Dispatcher {
1
+ class Dispatcher {
2
2
  constructor(opts) {
3
3
  this.queue = [];
4
4
  this.flushTimer = null;
5
5
  this.nextTimer = null;
6
6
  this.nextScheduledAt = null;
7
7
  this.flushInFlight = null;
8
+ this.queueSizeBytes = 0;
9
+ this.consecutiveRetries = 0;
8
10
  this.opts = opts;
9
11
  this.initialMaxBatchSize = Math.max(1, opts.maxBatchSize);
10
12
  this.maxBatchSize = this.initialMaxBatchSize;
@@ -13,6 +15,23 @@ export default class Dispatcher {
13
15
  getQueueRef() {
14
16
  return this.queue;
15
17
  }
18
+ /**
19
+ * Drain the in-memory queue entirely. Returns all events and resets the
20
+ * byte counter. Used by PersistentEventQueue to persist memory to disk
21
+ * without leaving duplicates behind.
22
+ */
23
+ drainQueue() {
24
+ const events = this.queue.splice(0);
25
+ this.queueSizeBytes = 0;
26
+ return events;
27
+ }
28
+ /**
29
+ * Restore events to the front without applying capacity overflow policy.
30
+ * Used only after a failed durability handoff so events are not lost.
31
+ */
32
+ restoreQueueFront(events) {
33
+ this.requeueChunk(events);
34
+ }
16
35
  start() {
17
36
  if (this.flushTimer)
18
37
  clearInterval(this.flushTimer);
@@ -28,9 +47,21 @@ export default class Dispatcher {
28
47
  reset() {
29
48
  this.stop();
30
49
  this.queue.length = 0;
50
+ this.queueSizeBytes = 0;
51
+ this.consecutiveRetries = 0;
31
52
  this.circuit = this.opts.createBreaker();
32
53
  this.maxBatchSize = this.initialMaxBatchSize;
33
54
  }
55
+ /**
56
+ * Retry floor: exponential backoff independent of circuit breaker.
57
+ * Applies from the very first failure so retries aren't immediate while circuit is closed.
58
+ */
59
+ retryFloorMs() {
60
+ if (this.consecutiveRetries <= 0)
61
+ return 0;
62
+ const exponent = Math.min(this.consecutiveRetries - 1, 10);
63
+ return Math.min(this.opts.maxRetryDelayMs, this.opts.baseRetryDelayMs * Math.pow(2, exponent));
64
+ }
34
65
  clearNextTimer() {
35
66
  if (this.nextTimer) {
36
67
  clearTimeout(this.nextTimer);
@@ -53,31 +84,119 @@ export default class Dispatcher {
53
84
  this.flush();
54
85
  }, Math.max(0, ms));
55
86
  }
87
+ estimateEventSize(event) {
88
+ return Dispatcher.encoder.encode(JSON.stringify(event)).byteLength;
89
+ }
90
+ handleCapacityOverflow(triggerDesc) {
91
+ // Persistence disabled (maxDiskEvents === 0): ring-buffer — drop oldest
92
+ // event one at a time instead of draining the whole queue, since there
93
+ // is no disk to spill to.
94
+ if (!this.opts.isPersistenceEnabled()) {
95
+ const dropped = this.queue.shift();
96
+ if (dropped !== undefined) {
97
+ this.queueSizeBytes -= this.estimateEventSize(dropped);
98
+ if (this.queueSizeBytes < 0)
99
+ this.queueSizeBytes = 0;
100
+ this.opts.warn(`Queue cap reached (${triggerDesc}) — dropped oldest event`);
101
+ }
102
+ return;
103
+ }
104
+ // Persistence enabled: splice the whole queue to the disk handler.
105
+ if (this.opts.onCapacityOverflow) {
106
+ const flushed = this.queue.splice(0);
107
+ this.queueSizeBytes = 0;
108
+ try {
109
+ const result = this.opts.onCapacityOverflow(flushed);
110
+ void Promise.resolve(result).catch((err) => {
111
+ this.requeueChunk(flushed);
112
+ this.opts.warn('Capacity overflow persistence failed — restored events to memory', err);
113
+ });
114
+ }
115
+ catch (err) {
116
+ this.requeueChunk(flushed);
117
+ this.opts.warn('Capacity overflow persistence failed — restored events to memory', err);
118
+ }
119
+ }
120
+ else {
121
+ this.opts.warn(`Queue cap reached — dropping ${this.queue.length} event(s) (no overflow handler)`);
122
+ this.queue.length = 0;
123
+ this.queueSizeBytes = 0;
124
+ }
125
+ }
126
+ isOverCap(extraBytes = 0, extraCount = 0) {
127
+ return (this.queue.length + extraCount > this.opts.maxEventCount ||
128
+ this.queueSizeBytes + extraBytes > this.opts.maxQueueBytes);
129
+ }
56
130
  enqueue(event) {
57
- // Hard cap: drop oldest until there's room
58
- while (this.queue.length >= this.opts.maxQueueEvents) {
59
- this.queue.shift();
60
- this.opts.warn(`[MetaRouter] Queue cap ${this.opts.maxQueueEvents} reached — dropped oldest event`);
131
+ const eventSize = this.estimateEventSize(event);
132
+ // Enforce cap: if adding this event would exceed count OR byte limit,
133
+ // flush/evict first so the new event still fits.
134
+ while (this.queue.length > 0 && this.isOverCap(eventSize, 1)) {
135
+ this.handleCapacityOverflow(this.queueSizeBytes + eventSize > this.opts.maxQueueBytes
136
+ ? 'bytes'
137
+ : 'count');
138
+ if (!this.opts.isPersistenceEnabled() && this.queue.length === 0)
139
+ break;
140
+ // When persistence IS enabled, handleCapacityOverflow drains the whole
141
+ // queue so the loop exits naturally.
142
+ if (this.opts.isPersistenceEnabled())
143
+ break;
61
144
  }
62
- this.opts.log('Enqueuing event', {
63
- type: event === null || event === void 0 ? void 0 : event.type,
64
- messageId: event === null || event === void 0 ? void 0 : event.messageId,
65
- });
145
+ this.opts.log(`Enqueuing event {"messageId": "${event === null || event === void 0 ? void 0 : event.messageId}", "type": "${event === null || event === void 0 ? void 0 : event.type}"}`);
66
146
  this.queue.push(event);
147
+ this.queueSizeBytes += eventSize;
148
+ this.opts.log(`Event enqueued, queue length: ${this.queue.length}`);
149
+ if (this.queue.length >= this.opts.autoFlushThreshold) {
150
+ void this.flush();
151
+ }
152
+ }
153
+ enqueueFront(events) {
154
+ // Avoid spread into unshift — large arrays can exceed JS engine argument limit
155
+ const merged = events.concat(this.queue);
156
+ this.queue.length = 0;
157
+ for (let i = 0; i < merged.length; i++) {
158
+ this.queue.push(merged[i]);
159
+ }
160
+ for (const e of events) {
161
+ this.queueSizeBytes += this.estimateEventSize(e);
162
+ }
163
+ // Enforce cap: drain to disk (or ring-buffer drop-oldest in 0-mode).
164
+ while (this.isOverCap()) {
165
+ const before = this.queue.length;
166
+ this.handleCapacityOverflow(this.queueSizeBytes > this.opts.maxQueueBytes ? 'bytes' : 'count');
167
+ if (this.queue.length === before)
168
+ break; // safety: avoid infinite loop
169
+ if (this.opts.isPersistenceEnabled())
170
+ break; // drained entire queue
171
+ }
67
172
  if (this.queue.length >= this.opts.autoFlushThreshold) {
68
- this.opts.log(`Event queue reached ${this.opts.autoFlushThreshold}. Flushing queued events.`);
69
173
  void this.flush();
70
174
  }
71
175
  }
176
+ getQueueSizeBytes() {
177
+ return this.queueSizeBytes;
178
+ }
72
179
  drainBatch() {
73
180
  const n = Math.min(this.queue.length, this.maxBatchSize);
74
181
  const nowIso = new Date().toISOString();
75
- const batch = this.queue.splice(0, n).map((e) => ({
76
- ...e,
77
- sentAt: nowIso,
78
- }));
182
+ const drained = this.queue.splice(0, n);
183
+ const batch = drained.map((e) => {
184
+ this.queueSizeBytes -= this.estimateEventSize(e);
185
+ return { ...e, sentAt: nowIso };
186
+ });
79
187
  return batch;
80
188
  }
189
+ requeueChunk(chunk) {
190
+ // Avoid spread into unshift — large arrays can exceed JS engine argument limit
191
+ const merged = chunk.concat(this.queue);
192
+ this.queue.length = 0;
193
+ for (let i = 0; i < merged.length; i++) {
194
+ this.queue.push(merged[i]);
195
+ }
196
+ for (const e of chunk) {
197
+ this.queueSizeBytes += this.estimateEventSize(e);
198
+ }
199
+ }
81
200
  parseRetryAfter(h) {
82
201
  if (!h)
83
202
  return null;
@@ -92,21 +211,43 @@ export default class Dispatcher {
92
211
  return;
93
212
  if (this.flushInFlight)
94
213
  return this.flushInFlight;
214
+ // A retry is armed — let it fire on its own schedule instead of
215
+ // launching immediately and bypassing the backoff window. The scheduled
216
+ // callback nils nextTimer before calling flush(), so it passes through.
217
+ if (this.nextTimer)
218
+ return;
95
219
  if (!this.opts.canSend())
96
220
  return;
97
221
  const doFlush = async () => {
98
222
  var _a, _b, _c, _d;
99
223
  while (this.queue.length) {
224
+ if (!this.opts.isNetworkAvailable()) {
225
+ if (this.opts.onFlushToDisk && this.opts.isPersistenceEnabled()) {
226
+ const flushed = this.drainQueue();
227
+ try {
228
+ await this.opts.onFlushToDisk(flushed);
229
+ this.opts.warn(`Offline — flushed ${flushed.length} event(s) to disk`);
230
+ }
231
+ catch (err) {
232
+ this.requeueChunk(flushed);
233
+ this.opts.warn(`Offline — failed to flush ${flushed.length} event(s) to disk; restored to memory`, err);
234
+ }
235
+ }
236
+ else {
237
+ this.opts.warn(`Offline — pausing HTTP attempts, ${this.queue.length} event(s) queued`);
238
+ }
239
+ return;
240
+ }
100
241
  if (!this.circuit.allowRequest()) {
101
242
  const state = this.circuit.getState();
102
243
  const wait = this.circuit.remainingCooldownMs();
103
- this.opts.log(`[MetaRouter] Circuit ${state} — skip; wait ${wait}ms`);
244
+ this.opts.warn(`Circuit breaker ${state}, retrying in ${wait}ms (${this.queue.length} event(s) pending)`);
104
245
  this.scheduleFlushIn(wait);
105
246
  return;
106
247
  }
107
248
  const chunk = this.drainBatch();
108
249
  try {
109
- this.opts.log('Making API call to:', this.opts.endpoint('/v1/batch'));
250
+ this.opts.log(`Making API call to: ${this.opts.endpoint('/v1/batch')}`);
110
251
  const headers = {
111
252
  'Content-Type': 'application/json',
112
253
  };
@@ -123,11 +264,12 @@ export default class Dispatcher {
123
264
  // Retryable
124
265
  if (s >= 500 || s === 408) {
125
266
  this.circuit.onFailure();
267
+ this.consecutiveRetries += 1;
126
268
  if (this.opts.isOperational()) {
127
- this.queue.unshift(...chunk);
269
+ this.requeueChunk(chunk);
128
270
  const retryAfter = (_a = this.parseRetryAfter(res.headers.get('retry-after'))) !== null && _a !== void 0 ? _a : 0;
129
- const wait = Math.max(this.circuit.remainingCooldownMs(), retryAfter, 1000);
130
- this.opts.warn(`Retryable status ${s}; scheduling retry in ${wait}ms`);
271
+ const wait = Math.max(this.retryFloorMs(), this.circuit.remainingCooldownMs(), retryAfter, 1000);
272
+ this.opts.warn(`Server error ${s}, will retry ${chunk.length} event(s) in ${wait}ms (circuit: ${this.circuit.getState()}, retry #${this.consecutiveRetries})`);
131
273
  this.scheduleFlushIn(wait);
132
274
  }
133
275
  else {
@@ -137,12 +279,13 @@ export default class Dispatcher {
137
279
  }
138
280
  if (s === 429) {
139
281
  this.circuit.onFailure();
282
+ this.consecutiveRetries += 1;
140
283
  if (this.opts.isOperational()) {
141
- this.queue.unshift(...chunk);
284
+ this.requeueChunk(chunk);
142
285
  const h = (_b = this.parseRetryAfter(res.headers.get('retry-after'))) !== null && _b !== void 0 ? _b : 0;
143
286
  const b = this.circuit.remainingCooldownMs();
144
- const wait = Math.max(h, b, 1000);
145
- this.opts.warn(`429 throttled; scheduling in ${wait}ms (retry-after=${h}, breaker=${b})`);
287
+ const wait = Math.max(this.retryFloorMs(), h, b, 1000);
288
+ this.opts.warn(`Rate limited (429), will retry ${chunk.length} event(s) in ${wait}ms (circuit: ${this.circuit.getState()}, retry #${this.consecutiveRetries})`);
146
289
  this.scheduleFlushIn(wait);
147
290
  }
148
291
  else {
@@ -151,10 +294,7 @@ export default class Dispatcher {
151
294
  return;
152
295
  }
153
296
  if (s === 401 || s === 403 || s === 404) {
154
- this.opts.error(`Fatal config error ${s}. Disabling client.`);
155
- this.queue.length = 0;
156
- this.stop();
157
- (_d = (_c = this.opts).onFatalConfig) === null || _d === void 0 ? void 0 : _d.call(_c);
297
+ this.handleFatalConfig(s);
158
298
  return;
159
299
  }
160
300
  if (s === 413) {
@@ -162,7 +302,7 @@ export default class Dispatcher {
162
302
  if (this.maxBatchSize > 1) {
163
303
  this.maxBatchSize = Math.max(1, Math.floor(this.maxBatchSize / 2));
164
304
  this.opts.warn(`Payload too large; reducing maxBatchSize to ${this.maxBatchSize}`);
165
- this.queue.unshift(...chunk);
305
+ this.requeueChunk(chunk);
166
306
  this.scheduleFlushIn(500);
167
307
  }
168
308
  else {
@@ -180,17 +320,23 @@ export default class Dispatcher {
180
320
  }
181
321
  // Success
182
322
  this.circuit.onSuccess();
323
+ this.consecutiveRetries = 0;
183
324
  if (this.maxBatchSize < this.initialMaxBatchSize) {
184
325
  this.maxBatchSize = Math.min(this.maxBatchSize * 2, this.initialMaxBatchSize);
185
326
  }
186
327
  this.opts.log('API call successful');
328
+ // If queue is now empty after this successful batch, fire onFlushComplete
329
+ if (this.queue.length === 0 && this.opts.isNetworkAvailable()) {
330
+ (_d = (_c = this.opts).onFlushComplete) === null || _d === void 0 ? void 0 : _d.call(_c);
331
+ }
187
332
  }
188
333
  catch (err) {
189
334
  this.circuit.onFailure();
335
+ this.consecutiveRetries += 1;
190
336
  if (this.opts.isOperational()) {
191
- this.queue.unshift(...chunk);
192
- const wait = Math.max(this.circuit.remainingCooldownMs(), 1000);
193
- this.opts.warn('Flush attempt failed; scheduling retry in', wait, 'ms', err === null || err === void 0 ? void 0 : err.message);
337
+ this.requeueChunk(chunk);
338
+ const wait = Math.max(this.retryFloorMs(), this.circuit.remainingCooldownMs(), 1000);
339
+ this.opts.warn(`API call failed: ${err === null || err === void 0 ? void 0 : err.message}, ${chunk.length} event(s) pending retry in ${wait}ms (circuit: ${this.circuit.getState()}, retry #${this.consecutiveRetries})`);
194
340
  this.scheduleFlushIn(wait);
195
341
  }
196
342
  else {
@@ -199,13 +345,62 @@ export default class Dispatcher {
199
345
  return;
200
346
  }
201
347
  }
202
- this.opts.log('Flush completed successfully');
203
348
  };
204
349
  this.flushInFlight = doFlush().finally(() => {
205
350
  this.flushInFlight = null;
206
351
  });
207
352
  return this.flushInFlight;
208
353
  }
354
+ resetCircuitBreaker() {
355
+ this.circuit.reset();
356
+ this.consecutiveRetries = 0;
357
+ }
358
+ /**
359
+ * Coordinate shutdown on a fatal config error (401/403/404).
360
+ * Called by the main flush path and by the disk drain so both paths
361
+ * converge to the same "disable client" signal.
362
+ */
363
+ handleFatalConfig(statusCode) {
364
+ var _a, _b;
365
+ this.opts.error(`Fatal config error ${statusCode}. Disabling client.`);
366
+ this.queue.length = 0;
367
+ this.queueSizeBytes = 0;
368
+ this.stop();
369
+ (_b = (_a = this.opts).onFatalConfig) === null || _b === void 0 ? void 0 : _b.call(_a);
370
+ }
371
+ /**
372
+ * Send a batch directly to network, bypassing the memory queue.
373
+ * Used by the disk drain to send events without loading them into the queue.
374
+ * Returns { statusCode } on HTTP response, null on network/transport error.
375
+ */
376
+ async sendBatchDirect(events) {
377
+ try {
378
+ const nowIso = new Date().toISOString();
379
+ const batch = events.map((e) => ({ ...e, sentAt: nowIso }));
380
+ const headers = {
381
+ 'Content-Type': 'application/json',
382
+ };
383
+ if (this.opts.isTracingEnabled()) {
384
+ headers.Trace = 'true';
385
+ }
386
+ const res = await this.opts.fetchWithTimeout(this.opts.endpoint('/v1/batch'), {
387
+ method: 'POST',
388
+ headers,
389
+ body: JSON.stringify({ batch }),
390
+ }, 8000);
391
+ if (res.ok) {
392
+ this.opts.log(`Direct batch send successful (${events.length} events)`);
393
+ }
394
+ else {
395
+ this.opts.warn(`Direct batch send failed with status ${res.status}`);
396
+ }
397
+ return { statusCode: res.status };
398
+ }
399
+ catch (err) {
400
+ this.opts.warn(`Direct batch send failed: ${err === null || err === void 0 ? void 0 : err.message}`);
401
+ return null;
402
+ }
403
+ }
209
404
  getDebugInfo() {
210
405
  return {
211
406
  queueLength: this.queue.length,
@@ -214,8 +409,12 @@ export default class Dispatcher {
214
409
  flushInFlight: !!this.flushInFlight,
215
410
  circuitState: this.circuit.getState(),
216
411
  circuitRemainingMs: this.circuit.remainingCooldownMs(),
217
- maxQueueEvents: this.opts.maxQueueEvents,
412
+ maxQueueEvents: this.opts.maxEventCount,
218
413
  maxBatchSize: this.maxBatchSize,
414
+ consecutiveRetries: this.consecutiveRetries,
415
+ isNetworkAvailable: this.opts.isNetworkAvailable(),
219
416
  };
220
417
  }
221
418
  }
419
+ Dispatcher.encoder = new TextEncoder();
420
+ export default Dispatcher;
@@ -1,3 +1,10 @@
1
- import type { InitOptions, AnalyticsInterface } from "./types";
1
+ import type { InitOptions, AnalyticsInterface } from './types';
2
+ /**
3
+ * Whether this is a development build. Injectable so tests can exercise the
4
+ * release path; production reads React Native's `__DEV__`.
5
+ */
6
+ export declare const buildConfig: {
7
+ isDevelopmentBuild: () => boolean;
8
+ };
2
9
  export declare function createAnalyticsClient(options: InitOptions): AnalyticsInterface;
3
10
  //# sourceMappingURL=init.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/analytics/init.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAM/D,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,WAAW,GACnB,kBAAkB,CAwCpB"}
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/analytics/init.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,WAAW,EAAE,kBAAkB,EAAe,MAAM,SAAS,CAAC;AA0B5E;;;GAGG;AACH,eAAO,MAAM,WAAW;8BACE,OAAO;CAEhC,CAAC;AAoCF,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,WAAW,GACnB,kBAAkB,CAsCpB"}