@metarouter/react-native-sdk 1.1.2 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -173,6 +173,16 @@ The analytics client provides the following methods:
173
173
  - 🔄 **Reset Capability**: Easily reset analytics state for testing or logout scenarios
174
174
  - 🐛 **Debug Support**: Built-in debugging tools for troubleshooting
175
175
 
176
+ ## ✅ Compatibility
177
+
178
+ | Component | Supported Versions |
179
+ | --------------------- | ------------------ |
180
+ | React Native | >= 0.63 |
181
+ | React | >= 16.8 |
182
+ | iOS Deployment Target | >= iOS 10 |
183
+ | Android Min SDK | >= API 16 |
184
+ | Node.js | >= 16 |
185
+
176
186
  ## Debugging
177
187
 
178
188
  If you're not seeing API calls being made, here are some steps to troubleshoot:
@@ -11,9 +11,9 @@ export declare class IdentityManager {
11
11
  private userId?;
12
12
  private groupId?;
13
13
  /**
14
- * Initializes the manager by loading or generating an anonymous ID.
15
- * Should be called before using other methods.
16
- */
14
+ * Initializes the manager by loading or generating an anonymous ID.
15
+ * Should be called before using other methods.
16
+ */
17
17
  init(): Promise<void>;
18
18
  /**
19
19
  * Retrieves the current anonymous ID.
@@ -1 +1 @@
1
- {"version":3,"file":"IdentityManager.d.ts","sourceRoot":"","sources":["../../src/analytics/IdentityManager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAG1D;;;;;;GAMG;AACH,qBAAa,eAAe;IACxB,OAAO,CAAC,WAAW,CAAuB;IAC1C,OAAO,CAAC,MAAM,CAAC,CAAS;IACxB,OAAO,CAAC,OAAO,CAAC,CAAS;IAEzB;;;KAGC;IACK,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAuB3B;;;OAGG;IACH,cAAc,IAAI,MAAM,GAAG,IAAI;IAI/B;;;OAGG;IACG,QAAQ,CAAC,MAAM,EAAE,MAAM;IAU7B;;;OAGG;IACG,KAAK,CAAC,OAAO,EAAE,MAAM;IAU3B;;;OAGG;IACH,SAAS,IAAI,MAAM,GAAG,SAAS;IAI/B;;;OAGG;IACH,UAAU,IAAI,MAAM,GAAG,SAAS;IAIhC;;;;OAIG;IACH,eAAe,CAAC,CAAC,SAAS,YAAY,EAAE,KAAK,EAAE,CAAC,GAAG,iBAAiB;IASpE;;;OAGG;IACG,KAAK;CAaZ"}
1
+ {"version":3,"file":"IdentityManager.d.ts","sourceRoot":"","sources":["../../src/analytics/IdentityManager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAU1D;;;;;;GAMG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,WAAW,CAAuB;IAC1C,OAAO,CAAC,MAAM,CAAC,CAAS;IACxB,OAAO,CAAC,OAAO,CAAC,CAAS;IAEzB;;;OAGG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAqC3B;;;OAGG;IACH,cAAc,IAAI,MAAM,GAAG,IAAI;IAI/B;;;OAGG;IACG,QAAQ,CAAC,MAAM,EAAE,MAAM;IAU7B;;;OAGG;IACG,KAAK,CAAC,OAAO,EAAE,MAAM;IAU3B;;;OAGG;IACH,SAAS,IAAI,MAAM,GAAG,SAAS;IAI/B;;;OAGG;IACH,UAAU,IAAI,MAAM,GAAG,SAAS;IAIhC;;;;OAIG;IACH,eAAe,CAAC,CAAC,SAAS,YAAY,EAAE,KAAK,EAAE,CAAC,GAAG,iBAAiB;IASpE;;;OAGG;IACG,KAAK;CAaZ"}
@@ -1,5 +1,5 @@
1
1
  import { log, warn } from "./utils/logger";
2
- import { USER_ID_KEY, GROUP_ID_KEY, ANONYMOUS_ID_KEY, getIdentityField, setIdentityField, removeIdentityField } from './utils/identityStorage';
2
+ import { USER_ID_KEY, GROUP_ID_KEY, ANONYMOUS_ID_KEY, getIdentityField, setIdentityField, removeIdentityField, } from "./utils/identityStorage";
3
3
  /**
4
4
  * Manages user, group, and anonymous identity for analytics events.
5
5
  * - Loads or generates a persistent anonymous ID.
@@ -12,30 +12,34 @@ export class IdentityManager {
12
12
  this.anonymousId = null;
13
13
  }
14
14
  /**
15
- * Initializes the manager by loading or generating an anonymous ID.
16
- * Should be called before using other methods.
17
- */
15
+ * Initializes the manager by loading or generating an anonymous ID.
16
+ * Should be called before using other methods.
17
+ */
18
18
  async init() {
19
19
  try {
20
20
  const storedAnonId = await getIdentityField(ANONYMOUS_ID_KEY);
21
21
  if (!storedAnonId) {
22
- const newId = `anon-${Date.now()}-${Math.random().toString(36).substring(2, 10)}`;
22
+ const newId = `anon-${Date.now()}-${Math.random()
23
+ .toString(36)
24
+ .substring(2, 10)}`;
23
25
  await setIdentityField(ANONYMOUS_ID_KEY, newId);
24
26
  this.anonymousId = newId;
25
- log('Generated and stored new anonymous ID:', newId);
27
+ log("Generated and stored new anonymous ID:", newId);
26
28
  }
27
29
  else {
28
30
  this.anonymousId = storedAnonId;
29
- log('Loaded stored anonymous ID:', storedAnonId);
31
+ log("Loaded stored anonymous ID:", storedAnonId);
30
32
  }
31
- this.userId = await getIdentityField(USER_ID_KEY) || undefined;
32
- this.groupId = await getIdentityField(GROUP_ID_KEY) || undefined;
33
- log('IdentityManager initialized with anonymous ID:', this.anonymousId, 'userId:', this.userId, 'groupId:', this.groupId);
33
+ this.userId = (await getIdentityField(USER_ID_KEY)) || undefined;
34
+ this.groupId = (await getIdentityField(GROUP_ID_KEY)) || undefined;
35
+ log("IdentityManager initialized with anonymous ID:", this.anonymousId, "userId:", this.userId, "groupId:", this.groupId);
34
36
  }
35
37
  catch (error) {
36
- warn('Failed to initialize IdentityManager, using fallback anonymous ID', error);
37
- this.anonymousId = `fallback-${Date.now()}-${Math.random().toString(36).substring(2, 10)}`;
38
- log('Using fallback anonymous ID:', this.anonymousId);
38
+ warn("Failed to initialize IdentityManager, using fallback anonymous ID", error);
39
+ this.anonymousId = `fallback-${Date.now()}-${Math.random()
40
+ .toString(36)
41
+ .substring(2, 10)}`;
42
+ log("Using fallback anonymous ID:", this.anonymousId);
39
43
  }
40
44
  }
41
45
  /**
@@ -55,9 +59,9 @@ export class IdentityManager {
55
59
  await setIdentityField(USER_ID_KEY, userId);
56
60
  }
57
61
  catch (error) {
58
- warn('Failed to persist userId', error);
62
+ warn("Failed to persist userId", error);
59
63
  }
60
- log('User identified:', userId);
64
+ log("User identified:", userId);
61
65
  }
62
66
  /**
63
67
  * Sets the group ID for the current session.
@@ -69,9 +73,9 @@ export class IdentityManager {
69
73
  await setIdentityField(GROUP_ID_KEY, groupId);
70
74
  }
71
75
  catch (error) {
72
- warn('Failed to persist groupId', error);
76
+ warn("Failed to persist groupId", error);
73
77
  }
74
- log('User grouped:', groupId);
78
+ log("User grouped:", groupId);
75
79
  }
76
80
  /**
77
81
  * Retrieves the current user ID.
@@ -96,7 +100,7 @@ export class IdentityManager {
96
100
  var _a, _b, _c;
97
101
  return {
98
102
  ...event,
99
- anonymousId: (_a = this.anonymousId) !== null && _a !== void 0 ? _a : 'unknown',
103
+ anonymousId: (_a = this.anonymousId) !== null && _a !== void 0 ? _a : "unknown",
100
104
  userId: (_b = event.userId) !== null && _b !== void 0 ? _b : this.userId,
101
105
  groupId: (_c = event.groupId) !== null && _c !== void 0 ? _c : this.groupId,
102
106
  };
@@ -115,8 +119,8 @@ export class IdentityManager {
115
119
  await removeIdentityField(GROUP_ID_KEY);
116
120
  }
117
121
  catch (error) {
118
- warn('Failed to clear userId/groupId/anonymousId from storage', error);
122
+ warn("Failed to clear userId/groupId/anonymousId from storage", error);
119
123
  }
120
- log('IdentityManager reset');
124
+ log("IdentityManager reset");
121
125
  }
122
126
  }
@@ -1,4 +1,4 @@
1
- import { InitOptions } from "./types";
1
+ import { InitOptions, Lifecycle } from "./types";
2
2
  /**
3
3
  * Analytics client for MetaRouter.
4
4
  * - Handles event queueing, batching, and delivery with retries.
@@ -7,7 +7,8 @@ import { InitOptions } from "./types";
7
7
  * - Provides debug and cleanup utilities.
8
8
  */
9
9
  export declare class MetaRouterAnalyticsClient {
10
- private initialized;
10
+ private lifecycle;
11
+ private initPromise;
11
12
  private queue;
12
13
  private flushIntervalMs;
13
14
  private flushTimer;
@@ -18,6 +19,8 @@ export declare class MetaRouterAnalyticsClient {
18
19
  private appStateSubscription;
19
20
  private identityManager;
20
21
  private static readonly MAX_QUEUE_SIZE;
22
+ private flushInFlight;
23
+ private readonly MAX_BATCH_SIZE;
21
24
  /**
22
25
  * Initializes the analytics client with the provided options.
23
26
  * @param options - The initialization options.
@@ -27,11 +30,24 @@ export declare class MetaRouterAnalyticsClient {
27
30
  * Initializes the analytics client.
28
31
  * @returns A promise that resolves when the client is initialized.
29
32
  */
30
- private init;
33
+ init(): Promise<void>;
31
34
  /**
32
35
  * Starts the flush loop.
33
36
  */
34
37
  private startFlushLoop;
38
+ /**
39
+ * Checks if the analytics client can operate.
40
+ * @returns True if the client is ready to operate, false otherwise.
41
+ */
42
+ private canOperate;
43
+ /**
44
+ * Fetches with a timeout.
45
+ * @param url - The URL to fetch.
46
+ * @param init - The request init.
47
+ * @param timeoutMs - The timeout in milliseconds.
48
+ * @returns The response.
49
+ */
50
+ private fetchWithTimeout;
35
51
  /**
36
52
  * Returns the current timestamp in ISO format.
37
53
  * @returns The current timestamp in ISO format.
@@ -94,8 +110,8 @@ export declare class MetaRouterAnalyticsClient {
94
110
  /**
95
111
  * Get current state for debugging
96
112
  */
97
- getDebugInfo(): {
98
- initialized: boolean;
113
+ getDebugInfo(): Promise<{
114
+ lifecycle: Lifecycle;
99
115
  queueLength: number;
100
116
  ingestionHost: string;
101
117
  writeKey: string | undefined;
@@ -103,27 +119,15 @@ export declare class MetaRouterAnalyticsClient {
103
119
  anonymousId: string | null;
104
120
  userId: string | undefined;
105
121
  groupId: string | undefined;
106
- };
122
+ proxy: boolean;
123
+ }>;
107
124
  /**
108
125
  * Flushes the event queue to the ingestion endpoint.
109
126
  */
110
- flush(): Promise<{
111
- sentAt: string;
112
- type: import("./types").EventType;
113
- event?: string;
114
- userId?: string;
115
- groupId?: string;
116
- traits?: Record<string, any>;
117
- properties?: Record<string, any>;
118
- timestamp?: string;
119
- }[] | undefined>;
120
- /**
121
- * Resets the analytics client:
122
- * - Clears identity (anonymousId, userId, groupId)
123
- * - Clears queued events
124
- * - Stops background flushing
125
- * - Removes app state listeners
126
- */
127
- reset(): void;
127
+ flush(): Promise<void>;
128
+ /**
129
+ * Resets the analytics client.
130
+ */
131
+ reset(): Promise<void>;
128
132
  }
129
133
  //# sourceMappingURL=MetaRouterAnalyticsClient.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"MetaRouterAnalyticsClient.d.ts","sourceRoot":"","sources":["../../src/analytics/MetaRouterAnalyticsClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,WAAW,EAAE,MAAM,SAAS,CAAC;AAQlE;;;;;;GAMG;AACH,qBAAa,yBAAyB;IACpC,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,KAAK,CAAsB;IACnC,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,UAAU,CAA+B;IACjD,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,OAAO,CAAgB;IAC/B,OAAO,CAAC,QAAQ,CAAyC;IACzD,OAAO,CAAC,oBAAoB,CAAwC;IACpE,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAM;IAE5C;;;OAGG;gBACS,OAAO,EAAE,WAAW;IAmChC;;;OAGG;YACW,IAAI;IA8BlB;;OAEG;IACH,OAAO,CAAC,cAAc;IAItB;;;OAGG;IACH,OAAO,CAAC,GAAG;IAIX;;;OAGG;IACH,OAAO,CAAC,OAAO;IAkBf;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAO7B;;;OAGG;IACH,OAAO,CAAC,oBAAoB,CAK1B;IAEF;;;;OAIG;IACH,KAAK,CAAC,KAAK,E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,OAAO,CAAC,IAAI,CAAC;CA4BpC"}
@@ -18,12 +18,15 @@ export class MetaRouterAnalyticsClient {
18
18
  */
19
19
  constructor(options) {
20
20
  var _a;
21
- this.initialized = false;
21
+ this.lifecycle = "idle";
22
+ this.initPromise = null;
22
23
  this.queue = [];
23
24
  this.flushIntervalMs = 10000;
24
25
  this.flushTimer = null;
25
26
  this.appState = AppState.currentState;
26
27
  this.appStateSubscription = null;
28
+ this.flushInFlight = null;
29
+ this.MAX_BATCH_SIZE = 100;
27
30
  /**
28
31
  * Handles the app state change event.
29
32
  * @param nextState - The new app state.
@@ -55,7 +58,6 @@ export class MetaRouterAnalyticsClient {
55
58
  : 10000;
56
59
  setDebugLogging((_a = options.debug) !== null && _a !== void 0 ? _a : false);
57
60
  this.identityManager = new IdentityManager();
58
- this.init();
59
61
  log("Analytics client constructor completed, initialization in progress...");
60
62
  }
61
63
  /**
@@ -63,28 +65,39 @@ export class MetaRouterAnalyticsClient {
63
65
  * @returns A promise that resolves when the client is initialized.
64
66
  */
65
67
  async init() {
66
- if (this.initialized) {
67
- log("Analytics client already initialized");
68
+ if (this.lifecycle === "ready") {
69
+ log("Analytics client already ready");
68
70
  return;
69
71
  }
70
- log("Starting analytics client initialization...");
71
- try {
72
- await this.identityManager.init();
73
- log("IdentityManager initialized successfully");
74
- this.startFlushLoop();
75
- log("Flush loop started with interval:", this.flushIntervalMs, "ms");
76
- this.setupAppStateListener();
77
- log("App state listener setup completed");
78
- this.context = await getContextInfo();
79
- this.initialized = true;
80
- log("Analytics client initialization completed successfully");
72
+ if (this.lifecycle === "initializing" && this.initPromise) {
73
+ log("Analytics client initialization already in-flight");
74
+ return this.initPromise;
81
75
  }
82
- catch (error) {
83
- warn("Analytics client initialization failed:", error);
84
- // Still mark as initialized to prevent infinite retries
85
- this.initialized = true;
86
- throw error;
76
+ if (this.lifecycle === "disabled") {
77
+ warn("Analytics client is disabled — init skipped");
78
+ return;
87
79
  }
80
+ this.lifecycle = "initializing";
81
+ log("Starting analytics client initialization...");
82
+ this.initPromise = (async () => {
83
+ try {
84
+ await this.identityManager.init();
85
+ log("IdentityManager initialized successfully");
86
+ this.startFlushLoop();
87
+ log("Flush loop started with interval:", this.flushIntervalMs, "ms");
88
+ this.setupAppStateListener();
89
+ log("App state listener setup completed");
90
+ this.context = await getContextInfo();
91
+ this.lifecycle = "ready";
92
+ log("Analytics client initialization completed successfully");
93
+ }
94
+ catch (error) {
95
+ this.lifecycle = "idle"; // allow retry
96
+ warn("Analytics client initialization failed:", error);
97
+ throw error;
98
+ }
99
+ })();
100
+ return this.initPromise;
88
101
  }
89
102
  /**
90
103
  * Starts the flush loop.
@@ -92,6 +105,46 @@ export class MetaRouterAnalyticsClient {
92
105
  startFlushLoop() {
93
106
  this.flushTimer = setInterval(() => this.flush(), this.flushIntervalMs);
94
107
  }
108
+ /**
109
+ * Checks if the analytics client can operate.
110
+ * @returns True if the client is ready to operate, false otherwise.
111
+ */
112
+ canOperate() {
113
+ return this.lifecycle === "ready";
114
+ }
115
+ /**
116
+ * Fetches with a timeout.
117
+ * @param url - The URL to fetch.
118
+ * @param init - The request init.
119
+ * @param timeoutMs - The timeout in milliseconds.
120
+ * @returns The response.
121
+ */
122
+ async fetchWithTimeout(url, init, timeoutMs) {
123
+ return new Promise((resolve, reject) => {
124
+ let settled = false;
125
+ const t = setTimeout(() => {
126
+ if (!settled) {
127
+ settled = true;
128
+ reject(new Error(`Fetch timeout after ${timeoutMs}ms`));
129
+ }
130
+ }, timeoutMs);
131
+ fetch(url, init)
132
+ .then((res) => {
133
+ if (!settled) {
134
+ settled = true;
135
+ clearTimeout(t);
136
+ resolve(res);
137
+ }
138
+ })
139
+ .catch((err) => {
140
+ if (!settled) {
141
+ settled = true;
142
+ clearTimeout(t);
143
+ reject(err);
144
+ }
145
+ });
146
+ });
147
+ }
95
148
  /**
96
149
  * Returns the current timestamp in ISO format.
97
150
  * @returns The current timestamp in ISO format.
@@ -104,6 +157,10 @@ export class MetaRouterAnalyticsClient {
104
157
  * @param event - The event to enqueue.
105
158
  */
106
159
  enqueue(event) {
160
+ if (!this.canOperate()) {
161
+ warn("Analytics client is not ready to operate");
162
+ return;
163
+ }
107
164
  const eventWithIdentity = this.identityManager.addIdentityInfo(event);
108
165
  const enrichedEvent = enrichEvent(eventWithIdentity, this.writeKey, this.context);
109
166
  log("Enqueuing event", enrichedEvent);
@@ -202,9 +259,9 @@ export class MetaRouterAnalyticsClient {
202
259
  /**
203
260
  * Get current state for debugging
204
261
  */
205
- getDebugInfo() {
262
+ async getDebugInfo() {
206
263
  return {
207
- initialized: this.initialized,
264
+ lifecycle: this.lifecycle,
208
265
  queueLength: this.queue.length,
209
266
  ingestionHost: this.ingestionHost,
210
267
  writeKey: this.writeKey ? "***" + this.writeKey.slice(-4) : undefined,
@@ -212,75 +269,92 @@ export class MetaRouterAnalyticsClient {
212
269
  anonymousId: this.identityManager.getAnonymousId(),
213
270
  userId: this.identityManager.getUserId(),
214
271
  groupId: this.identityManager.getGroupId(),
272
+ proxy: false,
215
273
  };
216
274
  }
217
275
  /**
218
276
  * Flushes the event queue to the ingestion endpoint.
219
277
  */
220
278
  async flush() {
279
+ if (!this.canOperate())
280
+ return;
281
+ if (!this.queue.length)
282
+ return;
283
+ if (this.flushInFlight)
284
+ return this.flushInFlight; // coalesce
221
285
  const anonId = this.identityManager.getAnonymousId();
222
286
  if (!anonId) {
223
287
  warn("Anonymous ID not yet ready, delaying flush");
224
- // Anon ID not yet ready, delay flushing
225
288
  return;
226
289
  }
227
- if (this.queue.length === 0) {
228
- log("No events to flush");
229
- return;
230
- }
231
- const batch = this.queue.map((event) => ({
232
- ...event,
290
+ const batch = this.queue.map((e) => ({
291
+ ...e,
233
292
  sentAt: new Date().toISOString(),
234
293
  }));
235
- this.queue = [];
236
- log(`Flushing ${batch.length} events to ${this.ingestionHost}/v1/batch`);
237
- try {
294
+ this.queue = []; // optimistic clear; we’ll put them back on failure
295
+ const doFlush = async () => {
238
296
  await retryWithBackoff(async () => {
297
+ if (!this.canOperate())
298
+ throw new Error("Client not ready during flush");
239
299
  log("Making API call to:", this.ingestionHost + "/v1/batch");
240
- const response = await fetch(this.ingestionHost + "/v1/batch", {
300
+ const response = await this.fetchWithTimeout(this.ingestionHost + "/v1/batch", {
241
301
  method: "POST",
242
- headers: {
243
- "Content-Type": "application/json",
244
- },
302
+ headers: { "Content-Type": "application/json" },
245
303
  body: JSON.stringify({ batch }),
246
- });
304
+ }, 8000 // timeout per attempt
305
+ );
247
306
  if (!response.ok) {
248
- error("HTTP error", response);
307
+ error("HTTP error", response.status, response.statusText);
249
308
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
250
309
  }
251
310
  log("API call successful, status:", response.status);
252
- return response;
311
+ }, {
312
+ retries: 5,
313
+ baseDelayMs: 1000,
314
+ shouldContinue: () => this.canOperate(),
253
315
  });
254
316
  log("Flush completed successfully");
255
- return batch;
256
- }
257
- catch (err) {
258
- warn("Flush failed, re-queueing events", err);
259
- this.queue.unshift(...batch);
260
- }
317
+ };
318
+ this.flushInFlight = doFlush()
319
+ .catch((err) => {
320
+ if (this.canOperate()) {
321
+ // Put events back at the **front** in original order
322
+ warn("Flush failed, re-queueing events", err);
323
+ this.queue.unshift(...batch);
324
+ }
325
+ else {
326
+ warn("Flush failed, but client is not ready to operate");
327
+ }
328
+ throw err;
329
+ })
330
+ .finally(() => {
331
+ this.flushInFlight = null;
332
+ });
333
+ return this.flushInFlight;
261
334
  }
262
335
  /**
263
- * Resets the analytics client:
264
- * - Clears identity (anonymousId, userId, groupId)
265
- * - Clears queued events
266
- * - Stops background flushing
267
- * - Removes app state listeners
336
+ * Resets the analytics client.
268
337
  */
269
- reset() {
338
+ async reset() {
270
339
  var _a, _b;
271
340
  log("Resetting analytics client");
272
- // Identity reset
273
- this.identityManager.reset();
274
- // Clear event queue
275
- this.queue = [];
276
- // Clear flush interval
341
+ // Flip lifecycle first so other paths see we're resetting
342
+ this.lifecycle = "resetting";
343
+ // Stop background work
277
344
  if (this.flushTimer) {
278
345
  clearInterval(this.flushTimer);
279
346
  this.flushTimer = null;
280
347
  }
281
- // Remove AppState listener
282
348
  (_b = (_a = this.appStateSubscription) === null || _a === void 0 ? void 0 : _a.remove) === null || _b === void 0 ? void 0 : _b.call(_a);
283
349
  this.appStateSubscription = null;
350
+ // Drop queued events
351
+ this.queue = [];
352
+ // Clear identity (must remove persisted IDs)
353
+ await this.identityManager.reset();
354
+ // Allow a clean future init
355
+ this.initPromise = null;
356
+ // Back to idle: explicit init required
357
+ this.lifecycle = "idle";
284
358
  log("Analytics client reset complete");
285
359
  }
286
360
  }
@@ -1,9 +1,3 @@
1
1
  import type { InitOptions, AnalyticsInterface } from "./types";
2
- /**
3
- * Modular factory for creating an independent analytics client.
4
- * Binds the first created client to the proxy for queued events.
5
- * @param options Initialization options.
6
- * @returns A fully initialized analytics interface.
7
- */
8
- export declare function createAnalyticsClient(options: InitOptions): AnalyticsInterface;
2
+ export declare function createAnalyticsClient(options: InitOptions): Promise<AnalyticsInterface>;
9
3
  //# 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;AAK/D;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,WAAW,GACnB,kBAAkB,CAuBpB"}
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;AAK/D,wBAAsB,qBAAqB,CACzC,OAAO,EAAE,WAAW,GACnB,OAAO,CAAC,kBAAkB,CAAC,CAwC7B"}
@@ -1,31 +1,41 @@
1
1
  import { MetaRouterAnalyticsClient } from "./MetaRouterAnalyticsClient";
2
- import { setRealClient } from "./proxy/proxyClient";
3
- // Tracks whether a client has already been bound to the proxy
4
- let proxyBound = false;
5
- /**
6
- * Modular factory for creating an independent analytics client.
7
- * Binds the first created client to the proxy for queued events.
8
- * @param options Initialization options.
9
- * @returns A fully initialized analytics interface.
10
- */
11
- export function createAnalyticsClient(options) {
12
- const instance = new MetaRouterAnalyticsClient(options);
13
- const analyticsInterface = {
14
- track: (event, props) => instance.track(event, props),
15
- identify: (userId, traits) => instance.identify(userId, traits),
16
- group: (groupId, traits) => instance.group(groupId, traits),
17
- screen: (name, props) => instance.screen(name, props),
18
- page: (name, props) => instance.page(name, props),
19
- alias: (newUserId) => instance.alias(newUserId),
20
- flush: () => instance.flush(),
21
- reset: () => instance.reset(),
22
- enableDebugLogging: () => instance.enableDebugLogging(),
23
- getDebugInfo: () => instance.getDebugInfo(),
24
- };
25
- // Forward proxy calls to this instance (only once)
26
- if (!proxyBound) {
27
- setRealClient(analyticsInterface);
28
- proxyBound = true;
2
+ import { proxyClient, setRealClient } from "./proxy/proxyClient";
3
+ // Single-flight guard so concurrent callers don't double-init
4
+ let inFlight = null;
5
+ export async function createAnalyticsClient(options) {
6
+ if (inFlight)
7
+ return inFlight;
8
+ inFlight = (async () => {
9
+ // 1) Build the real client and fully initialize it
10
+ const instance = new MetaRouterAnalyticsClient(options);
11
+ await instance.init();
12
+ // 2) Wrap the real instance with the public interface
13
+ // Note: reset() also detaches the proxy so you’re "off" until you call createAnalyticsClient() again.
14
+ const boundClient = {
15
+ track: (event, props) => instance.track(event, props),
16
+ identify: (userId, traits) => instance.identify(userId, traits),
17
+ group: (groupId, traits) => instance.group(groupId, traits),
18
+ screen: (name, props) => instance.screen(name, props),
19
+ page: (name, props) => instance.page(name, props),
20
+ alias: (newUserId) => instance.alias(newUserId),
21
+ enableDebugLogging: () => instance.enableDebugLogging(),
22
+ getDebugInfo: () => instance.getDebugInfo(),
23
+ flush: () => instance.flush(),
24
+ // Detach the proxy after a successful reset so nothing leaks out
25
+ reset: async () => {
26
+ await instance.reset();
27
+ setRealClient(null, { dropPending: true }); // proxy goes idle; calls will queue or no-op
28
+ },
29
+ };
30
+ // 3) Bind the proxy to this fully-initialized client
31
+ setRealClient(boundClient);
32
+ // 4) Return the proxy as the single public handle
33
+ return proxyClient;
34
+ })();
35
+ try {
36
+ return await inFlight;
37
+ }
38
+ finally {
39
+ inFlight = null;
29
40
  }
30
- return analyticsInterface;
31
41
  }
@@ -1,17 +1,6 @@
1
1
  import type { AnalyticsInterface } from "../types";
2
- /**
3
- * proxyClient implements a proxy pattern for the AnalyticsInterface.
4
- *
5
- * It allows analytics method calls (track, identify, etc.) to be made before the real analytics client
6
- * is fully initialized. Calls are queued and replayed once the real client is set via setRealClient.
7
- * This ensures that analytics events are not lost if called early in the app lifecycle.
8
- *
9
- * The proxy also provides a fallback for getDebugInfo, returning proxy state if the real client is not ready.
10
- *
11
- * Usage:
12
- * - Use proxyClient as the default analytics client before initialization.
13
- * - Call setRealClient(realClientInstance) once the real client is ready.
14
- */
15
2
  export declare const proxyClient: AnalyticsInterface;
16
- export declare function setRealClient(client: AnalyticsInterface | null): void;
3
+ export declare function setRealClient(client: AnalyticsInterface | null, opts?: {
4
+ dropPending?: boolean;
5
+ }): void;
17
6
  //# sourceMappingURL=proxyClient.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"proxyClient.d.ts","sourceRoot":"","sources":["../../../src/analytics/proxy/proxyClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AA6BnD;;;;;;;;;;;;GAYG;AAEH,eAAO,MAAM,WAAW,EAAE,kBAezB,CAAC;AAEF,wBAAgB,aAAa,CAAC,MAAM,EAAE,kBAAkB,GAAG,IAAI,QAO9D"}
1
+ {"version":3,"file":"proxyClient.d.ts","sourceRoot":"","sources":["../../../src/analytics/proxy/proxyClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAqGnD,eAAO,MAAM,WAAW,EAAE,kBAYzB,CAAC;AAEF,wBAAgB,aAAa,CAC3B,MAAM,EAAE,kBAAkB,GAAG,IAAI,EACjC,IAAI,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,OAAO,CAAA;CAAE,QAgBjC"}
@@ -1,34 +1,80 @@
1
1
  const pendingCalls = [];
2
2
  const MAX_PENDING_CALLS = 20;
3
3
  let realClient = null;
4
+ // Async-returning methods
5
+ const ASYNC_METHODS = {
6
+ flush: true,
7
+ reset: true,
8
+ getDebugInfo: true,
9
+ };
10
+ // One in-flight flush at a time
11
+ let flushInFlight = null;
4
12
  function handleMethodCall(methodName, ...args) {
13
+ // Real client bound
5
14
  if (realClient) {
15
+ if (methodName === "flush") {
16
+ if (flushInFlight)
17
+ return flushInFlight;
18
+ const p = Promise.resolve(realClient.flush(...args)).then(() => undefined);
19
+ flushInFlight = p.finally(() => {
20
+ flushInFlight = null;
21
+ });
22
+ return flushInFlight;
23
+ }
6
24
  return realClient[methodName](...args);
7
25
  }
26
+ // No real client bound yet
8
27
  if (pendingCalls.length >= MAX_PENDING_CALLS) {
9
- // Drop the oldest call
10
28
  pendingCalls.shift();
11
29
  console.warn(`[MetaRouter] Proxy queue reached max size (${MAX_PENDING_CALLS}). Oldest call dropped.`);
12
30
  }
31
+ // Special-cases while unbound:
32
+ if (methodName === "getDebugInfo") {
33
+ // Return immediate proxy snapshot instead of queueing
34
+ return Promise.resolve({
35
+ proxy: true,
36
+ pendingCalls: pendingCalls.length,
37
+ });
38
+ }
39
+ if (methodName === "reset") {
40
+ // Nothing to reset pre-bind; resolve immediately
41
+ return Promise.resolve();
42
+ }
43
+ if (ASYNC_METHODS[String(methodName)]) {
44
+ // Queue async call and return a promise that resolves after bind+run
45
+ return new Promise((resolve, reject) => {
46
+ pendingCalls.push(async () => {
47
+ try {
48
+ if (!realClient)
49
+ return reject(new Error("Proxy detached before real client was bound"));
50
+ if (methodName === "flush") {
51
+ if (!flushInFlight) {
52
+ const p = Promise.resolve(realClient.flush(...args)).then(() => undefined);
53
+ flushInFlight = p.finally(() => {
54
+ flushInFlight = null;
55
+ });
56
+ }
57
+ return flushInFlight.then(resolve, reject);
58
+ }
59
+ const result = realClient[methodName](...args);
60
+ result instanceof Promise
61
+ ? result.then(resolve, reject)
62
+ : resolve(result);
63
+ }
64
+ catch (err) {
65
+ reject(err);
66
+ }
67
+ });
68
+ });
69
+ }
70
+ // Fire-and-forget: queue and return void
13
71
  pendingCalls.push(() => {
14
- if (realClient) {
15
- realClient[methodName](...args);
16
- }
72
+ if (!realClient)
73
+ return;
74
+ realClient[methodName](...args);
17
75
  });
76
+ return undefined;
18
77
  }
19
- /**
20
- * proxyClient implements a proxy pattern for the AnalyticsInterface.
21
- *
22
- * It allows analytics method calls (track, identify, etc.) to be made before the real analytics client
23
- * is fully initialized. Calls are queued and replayed once the real client is set via setRealClient.
24
- * This ensures that analytics events are not lost if called early in the app lifecycle.
25
- *
26
- * The proxy also provides a fallback for getDebugInfo, returning proxy state if the real client is not ready.
27
- *
28
- * Usage:
29
- * - Use proxyClient as the default analytics client before initialization.
30
- * - Call setRealClient(realClientInstance) once the real client is ready.
31
- */
32
78
  export const proxyClient = {
33
79
  track: (event, props) => handleMethodCall("track", event, props),
34
80
  identify: (userId, traits) => handleMethodCall("identify", userId, traits),
@@ -39,18 +85,24 @@ export const proxyClient = {
39
85
  flush: () => handleMethodCall("flush"),
40
86
  reset: () => handleMethodCall("reset"),
41
87
  enableDebugLogging: () => handleMethodCall("enableDebugLogging"),
42
- getDebugInfo: () => {
43
- var _a, _b;
44
- return (_b = (_a = realClient === null || realClient === void 0 ? void 0 : realClient.getDebugInfo) === null || _a === void 0 ? void 0 : _a.call(realClient)) !== null && _b !== void 0 ? _b : {
45
- proxy: true,
46
- pendingCalls: pendingCalls.length,
47
- };
48
- },
88
+ getDebugInfo: () => handleMethodCall("getDebugInfo"),
49
89
  };
50
- export function setRealClient(client) {
90
+ export function setRealClient(client, opts) {
51
91
  realClient = client;
52
92
  if (client) {
53
- pendingCalls.forEach((fn) => fn());
54
- pendingCalls.length = 0;
93
+ const fns = pendingCalls.splice(0, pendingCalls.length);
94
+ for (const fn of fns) {
95
+ try {
96
+ const r = fn();
97
+ if (r instanceof Promise)
98
+ r.catch(() => { });
99
+ }
100
+ catch { }
101
+ }
102
+ }
103
+ else {
104
+ if (opts === null || opts === void 0 ? void 0 : opts.dropPending)
105
+ pendingCalls.length = 0;
106
+ flushInFlight = null; // reset coalescer
55
107
  }
56
108
  }
@@ -30,10 +30,10 @@ export interface AnalyticsInterface {
30
30
  screen: (name: string, props?: Record<string, any>) => void;
31
31
  page: (name: string, props?: Record<string, any>) => void;
32
32
  alias: (newUserId: string) => void;
33
- flush: () => void;
34
- reset: () => void;
35
- enableDebugLogging?: () => void;
36
- getDebugInfo?: () => Record<string, any>;
33
+ flush: () => Promise<void>;
34
+ reset: () => Promise<void>;
35
+ enableDebugLogging: () => void;
36
+ getDebugInfo: () => Promise<Record<string, any>>;
37
37
  }
38
38
  export interface EventContext {
39
39
  app: {
@@ -68,4 +68,5 @@ export interface EventContext {
68
68
  timezone: string;
69
69
  [key: string]: any;
70
70
  }
71
+ export type Lifecycle = "idle" | "initializing" | "ready" | "resetting" | "disabled";
71
72
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/analytics/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,SAAS,GACjB,OAAO,GACP,UAAU,GACV,OAAO,GACP,QAAQ,GACR,OAAO,GACP,MAAM,CAAC;AAEX,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,SAAS,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC7B,UAAU,CAAC,EAAE,MAAM,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
3
- *
4
- * - Attempts to execute the provided async function up to `retries` times.
5
- * - Waits an exponentially increasing delay (with random jitter) between attempts.
6
- * - If all attempts fail, the last error is thrown.
7
- *
8
- * @template T The return type of the async function.
9
- * @param fn The asynchronous function to retry.
10
- * @param retries The maximum number of attempts (default: 5).
11
- * @param baseDelayMs The base delay in milliseconds for backoff (default: 1000).
12
- * @param sleep Optional custom sleep function (default: setTimeout-based Promise).
13
- * @returns A promise that resolves with the result of `fn`, or rejects after all retries fail.
14
- */
15
- export declare function retryWithBackoff<T>(fn: () => Promise<T>, retries?: number, baseDelayMs?: number, sleep?: (ms: number) => Promise<unknown>): Promise<T>;
1
+ export type BackoffOptions = {
2
+ retries?: number;
3
+ baseDelayMs?: number;
4
+ sleep?: (ms: number) => Promise<void>;
5
+ shouldContinue?: () => boolean;
6
+ };
7
+ export declare function retryWithBackoff<T>(fn: () => Promise<T>, opts?: BackoffOptions): Promise<T>;
16
8
  //# sourceMappingURL=retry.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/retry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,wBAAsB,gBAAgB,CAAC,CAAC,EACpC,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACpB,OAAO,SAAI,EACX,WAAW,SAAO,EAClB,KAAK,IAAI,IAAI,MAAM,qBAA8C,GAChE,OAAO,CAAC,CAAC,CAAC,CAiBZ"}
1
+ {"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/retry.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,cAAc,GAAG;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACtC,cAAc,CAAC,EAAE,MAAM,OAAO,CAAC;CAChC,CAAC;AAEF,wBAAsB,gBAAgB,CAAC,CAAC,EACtC,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACpB,IAAI,GAAE,cAAmB,GACxB,OAAO,CAAC,CAAC,CAAC,CA4BZ"}
@@ -1,20 +1,9 @@
1
- /**
2
- * Retries an asynchronous operation with exponential backoff and optional jitter.
3
- *
4
- * - Attempts to execute the provided async function up to `retries` times.
5
- * - Waits an exponentially increasing delay (with random jitter) between attempts.
6
- * - If all attempts fail, the last error is thrown.
7
- *
8
- * @template T The return type of the async function.
9
- * @param fn The asynchronous function to retry.
10
- * @param retries The maximum number of attempts (default: 5).
11
- * @param baseDelayMs The base delay in milliseconds for backoff (default: 1000).
12
- * @param sleep Optional custom sleep function (default: setTimeout-based Promise).
13
- * @returns A promise that resolves with the result of `fn`, or rejects after all retries fail.
14
- */
15
- export async function retryWithBackoff(fn, retries = 5, baseDelayMs = 1000, sleep = (ms) => new Promise((res) => setTimeout(res, ms))) {
1
+ export async function retryWithBackoff(fn, opts = {}) {
2
+ const { retries = 5, baseDelayMs = 1000, sleep = (ms) => new Promise((res) => setTimeout(res, ms)), shouldContinue = () => true, } = opts;
16
3
  let attempt = 0;
17
4
  while (attempt < retries) {
5
+ if (!shouldContinue())
6
+ throw new Error("Retry aborted by shouldContinue");
18
7
  try {
19
8
  return await fn();
20
9
  }
@@ -25,7 +14,10 @@ export async function retryWithBackoff(fn, retries = 5, baseDelayMs = 1000, slee
25
14
  const jitter = Math.random() * 100;
26
15
  const delay = baseDelayMs * 2 ** (attempt - 1) + jitter;
27
16
  await sleep(delay);
17
+ if (!shouldContinue())
18
+ throw new Error("Retry aborted by shouldContinue");
28
19
  }
29
20
  }
30
- throw new Error('Exhausted all retries');
21
+ // Unreachable, but TS likes a return/throw
22
+ throw new Error("Exhausted all retries");
31
23
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metarouter/react-native-sdk",
3
- "version": "1.1.2",
3
+ "version": "1.1.4",
4
4
  "main": "./lib/index.js",
5
5
  "types": "./lib/index.d.ts",
6
6
  "exports": {
@@ -40,9 +40,9 @@
40
40
  "uuid": "^11.1.0"
41
41
  },
42
42
  "peerDependencies": {
43
+ "react-native": ">=0.63.0",
44
+ "react": ">=16.8.0",
43
45
  "@react-native-async-storage/async-storage": ">=2.2.0",
44
- "react": "*",
45
- "react-native": "*",
46
46
  "react-native-device-info": "^14.0.4"
47
47
  },
48
48
  "devDependencies": {