@metarouter/react-native-sdk 1.4.0 → 1.5.1

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
@@ -5,6 +5,22 @@
5
5
 
6
6
  A lightweight React Native analytics SDK that transmits events to your MetaRouter cluster.
7
7
 
8
+ ## Table of Contents
9
+
10
+ - [Installation](#installation)
11
+ - [Usage](#usage)
12
+ - [Basic Setup](#basic-setup)
13
+ - [React Context Usage](#react-context-usage)
14
+ - [Direct Usage](#direct-usage)
15
+ - [API Reference](#api-reference)
16
+ - [Features](#features)
17
+ - [Compatibility](#-compatibility)
18
+ - [Debugging](#debugging)
19
+ - [Identity Persistence](#identity-persistence)
20
+ - [Advertising ID (IDFA/GAID)](#advertising-id-idfagaid)
21
+ - [Using the alias() Method](#using-the-alias-method)
22
+ - [License](#license)
23
+
8
24
  ## Installation
9
25
 
10
26
  ```sh
@@ -88,7 +104,8 @@ const MyComponent = () => {
88
104
  ```js
89
105
  import { createAnalyticsClient } from "@metarouter/react-native-sdk";
90
106
 
91
- // Initialize optionally await it but can use at anytime with events transmitted when client is available.
107
+ // Initialize the client (optionally await it), but you can use it at any time
108
+ // with events transmitted when the client is ready.
92
109
  const analytics = await createAnalyticsClient({
93
110
  writeKey: "your-write-key",
94
111
  ingestionHost: "https://your-ingestion-endpoint.com",
@@ -111,6 +128,12 @@ analytics.screen("Home Screen", {
111
128
  category: "navigation",
112
129
  });
113
130
 
131
+ // Track page views
132
+ analytics.page("Home Page", {
133
+ url: "/home",
134
+ referrer: "/landing",
135
+ });
136
+
114
137
  // Group users
115
138
  analytics.group("company123", {
116
139
  name: "Acme Corp",
@@ -124,6 +147,33 @@ analytics.flush();
124
147
  await analytics.reset();
125
148
  ```
126
149
 
150
+ ### Reconfiguring the Analytics Client
151
+
152
+ ⚠️ **Important**: If you need to change the analytics configuration (e.g., different `writeKey` or `ingestionHost`), you must call `reset()` first:
153
+
154
+ ```js
155
+ // Initial configuration
156
+ const analytics = await createAnalyticsClient({
157
+ writeKey: "key-1",
158
+ ingestionHost: "https://endpoint-1.com",
159
+ });
160
+
161
+ // Later, if you need to change configuration:
162
+ await analytics.reset(); // Must reset first!
163
+
164
+ // Now reconfigure with new options
165
+ const analytics = await createAnalyticsClient({
166
+ writeKey: "key-2",
167
+ ingestionHost: "https://endpoint-2.com",
168
+ });
169
+ ```
170
+
171
+ If you call `createAnalyticsClient()` with different options without resetting first, you'll see this warning:
172
+
173
+ ```
174
+ [MetaRouter] Config changed but client not reset. Call await client.reset() before reinitializing with new options.
175
+ ```
176
+
127
177
  ## API Reference
128
178
 
129
179
  ### createAnalyticsClient(options)
@@ -157,9 +207,11 @@ The analytics client provides the following methods:
157
207
  - `identify(userId: string, traits?: Record<string, any>)`: Identify users
158
208
  - `group(groupId: string, traits?: Record<string, any>)`: Group users
159
209
  - `screen(name: string, properties?: Record<string, any>)`: Track screen views
160
- - `alias(newUserId: string)`: Alias user IDs
210
+ - `page(name: string, properties?: Record<string, any>)`: Track page views
211
+ - `alias(newUserId: string)`: Connect anonymous users to known user IDs. See [Using the alias() Method](#using-the-alias-method) for details
161
212
  - `setAdvertisingId(advertisingId: string)`: Set the advertising identifier (IDFA on iOS, GAID on Android) for ad tracking. See [Advertising ID](#advertising-id-idfagaid) section for usage and compliance requirements
162
213
  - `clearAdvertisingId()`: Clear the advertising identifier from storage and context. Useful for GDPR/CCPA compliance when users opt out of ad tracking
214
+ - `setTracing(enabled: boolean)`: Enable or disable tracing headers on API requests. When enabled, includes a `Trace: true` header for debugging request flows
163
215
  - `flush()`: Flush events immediately
164
216
  - `reset()`: Reset analytics state and clear all stored data (includes clearing advertising ID)
165
217
  - `enableDebugLogging()`: Enable debug logging
@@ -185,13 +237,13 @@ The analytics client provides the following methods:
185
237
 
186
238
  ## ✅ Compatibility
187
239
 
188
- | Component | Supported Versions |
189
- | --------------------- | ------------------ |
190
- | React Native | >= 0.63 |
191
- | React | >= 16.8 |
192
- | iOS Deployment Target | >= iOS 10 |
193
- | Android Min SDK | >= API 16 |
194
- | Node.js | >= 16 |
240
+ | Component | Supported Versions |
241
+ | -------------------------- | ------------------ |
242
+ | React Native | >= 0.63 |
243
+ | React | >= 16.8 |
244
+ | iOS Deployment Target | >= iOS 13 |
245
+ | Android Min SDK | >= API 21 |
246
+ | Node.js | >= 16 |
195
247
 
196
248
  ## Debugging
197
249
 
@@ -229,7 +281,7 @@ await analytics.flush();
229
281
  ### 4. Common Issues
230
282
 
231
283
  - **Network Permissions**: Ensure your app has network permissions
232
- - **AsyncStorage**: The SDK uses AsyncStorage for anonymous ID persistence
284
+ - **AsyncStorage**: The SDK uses AsyncStorage for identity persistence (anonymousId, userId, groupId, advertisingId)
233
285
  - **Endpoint URL**: Verify your ingestion endpoint is correct and accessible
234
286
  - **Write Key**: Ensure your write key is valid
235
287
 
@@ -268,6 +320,301 @@ sentAt semantics: sentAt is stamped when the event is enqueued. If the client is
268
320
  - `anonymousId` is a stable, persisted UUID for the device/user before identify; it does **not** include timestamps.
269
321
  - `messageId` is generated as `<epochMillis>-<uuid>` (e.g., `1734691572843-6f0c7e85-...`) to aid debugging.
270
322
 
323
+ ## Identity Persistence
324
+
325
+ The MetaRouter React Native SDK automatically manages and persists user identifiers across app sessions using React Native's AsyncStorage. This ensures consistent user tracking even after app restarts.
326
+
327
+ ### The Four Identity Fields
328
+
329
+ #### 1. userId (Common User ID)
330
+
331
+ The `userId` is set when you identify a user and represents their unique identifier in your system (e.g., database ID, email, employee ID).
332
+
333
+ **How to set:**
334
+
335
+ ```js
336
+ analytics.identify("user123", {
337
+ name: "John Doe",
338
+ email: "john@example.com",
339
+ role: "Sales Associate",
340
+ });
341
+ ```
342
+
343
+ **Behavior:**
344
+
345
+ - Persisted to device storage (`AsyncStorage` key: `metarouter:user_id`)
346
+ - Automatically loaded on app restart
347
+ - Automatically included in **all** subsequent events (`track`, `page`, `screen`, `group`)
348
+ - Remains set until `reset()` is called or app is uninstalled
349
+
350
+ **Example flow:**
351
+
352
+ ```js
353
+ // Day 1: User logs in
354
+ analytics.identify("employeeID", { name: "Jane" });
355
+ analytics.track("Product Viewed", { sku: "ABC123" });
356
+ // Event includes: userId: "employeeID"
357
+
358
+ // App restarts...
359
+
360
+ // Day 2: User opens app
361
+ analytics.track("App Opened");
362
+ // Event STILL includes: userId: "employeeID" (auto-loaded from storage)
363
+ ```
364
+
365
+ #### 2. anonymousId
366
+
367
+ The `anonymousId` is a unique identifier automatically generated for each device/installation before a user is identified.
368
+
369
+ **How it's set:**
370
+
371
+ - **Automatically** generated as a UUID v4 on first SDK initialization
372
+ - No manual action required
373
+
374
+ **Behavior:**
375
+
376
+ - Persisted to device storage (`AsyncStorage` key: `metarouter:anonymous_id`)
377
+ - Automatically loaded on app restart
378
+ - Automatically included in **all** events
379
+ - Remains stable across app sessions until `reset()` is called
380
+ - Cleared on `reset()` and a **new** UUID is generated on next `init()`
381
+
382
+ **Use case:**
383
+ Track user behavior before they log in or create an account, then connect pre-login and post-login activity using the `alias()` method.
384
+
385
+ #### 3. groupId
386
+
387
+ The `groupId` associates a user with an organization, team, account, or other group entity.
388
+
389
+ **How to set:**
390
+
391
+ ```js
392
+ analytics.group("company123", {
393
+ name: "Acme Corp",
394
+ plan: "Enterprise",
395
+ industry: "Technology",
396
+ });
397
+ ```
398
+
399
+ **Behavior:**
400
+
401
+ - Persisted to device storage (`AsyncStorage` key: `metarouter:group_id`)
402
+ - Automatically loaded on app restart
403
+ - Automatically included in **all** subsequent events after being set
404
+ - Remains set until `reset()` is called
405
+
406
+ **Example use case:**
407
+
408
+ ```js
409
+ // User logs into their company account
410
+ analytics.identify("user123", { name: "Jane" });
411
+ analytics.group("acme-corp", { name: "Acme Corp" });
412
+
413
+ // All future events include both userId and groupId
414
+ analytics.track("Report Generated");
415
+ // Event includes: userId: "user123", groupId: "acme-corp"
416
+ ```
417
+
418
+ #### 4. advertisingId (Optional)
419
+
420
+ The `advertisingId` is used for ad tracking and attribution (IDFA on iOS, GAID on Android). See the [Advertising ID](#advertising-id-idfagaid) section below for detailed usage and compliance requirements.
421
+
422
+ ### Persistence Summary
423
+
424
+ | Field | Set By | Storage Key | Auto-Attached | Cleared By |
425
+ | ----------------- | ------------------------ | --------------------------- | -------------------- | ----------------------------------------- |
426
+ | **userId** | `identify(userId)` | `metarouter:user_id` | All events | `reset()` |
427
+ | **anonymousId** | Auto-generated (UUID v4) | `metarouter:anonymous_id` | All events | `reset()` (new ID generated on next init) |
428
+ | **groupId** | `group(groupId)` | `metarouter:group_id` | All events after set | `reset()` |
429
+ | **advertisingId** | `setAdvertisingId(id)` | `metarouter:advertising_id` | Event context | `clearAdvertisingId()`, `reset()` |
430
+
431
+ ### Event Enrichment Flow
432
+
433
+ Every event you send (track, page, screen, group) is automatically enriched with persisted identity information:
434
+
435
+ ```js
436
+ // You call:
437
+ analytics.track("Button Clicked", { buttonName: "Submit" });
438
+
439
+ // SDK automatically adds:
440
+ {
441
+ "type": "track",
442
+ "event": "Button Clicked",
443
+ "properties": { "buttonName": "Submit" },
444
+ "userId": "employeeID", // ← Auto-added from storage
445
+ "anonymousId": "a1b2c3d4-...", // ← Auto-added from storage
446
+ "groupId": "company123", // ← Auto-added from storage (if set)
447
+ "timestamp": "2025-10-23T...",
448
+ "context": {
449
+ "device": {
450
+ "advertisingId": "..." // ← Auto-added from storage (if set)
451
+ }
452
+ }
453
+ }
454
+ ```
455
+
456
+ ### Resetting Identity
457
+
458
+ Call `reset()` to clear **all** identity data, typically when a user logs out:
459
+
460
+ ```js
461
+ await analytics.reset();
462
+ ```
463
+
464
+ **What `reset()` does:**
465
+
466
+ - Clears `userId`, `anonymousId`, `groupId`, and `advertisingId` from memory
467
+ - Removes all identity fields from AsyncStorage
468
+ - Stops background flush loops
469
+ - Clears event queue
470
+ - Next `init()` will generate a **new** `anonymousId`
471
+
472
+ **Common logout flow:**
473
+
474
+ ```js
475
+ // User logs out
476
+ await analytics.reset();
477
+
478
+ // User is now tracked with a new anonymousId (auto-generated on next event)
479
+ // No userId or groupId until they log in again
480
+ ```
481
+
482
+ ### Best Practices
483
+
484
+ 1. **On Login:** Call `identify()` immediately after successful authentication
485
+ 2. **On Logout:** Call `reset()` to clear user identity
486
+ 3. **Cross-Session Tracking:** The SDK handles this automatically - no action needed
487
+ 4. **Group Associations:** Set `groupId` after determining the user's organization/team
488
+ 5. **Pre-Login Tracking:** Events are tracked with `anonymousId` before login
489
+ 6. **Connecting Sessions:** Use `alias()` to connect pre-login and post-login activity
490
+
491
+ ### Example: Complete User Journey
492
+
493
+ ```js
494
+ // App starts - SDK initializes
495
+ const analytics = await createAnalyticsClient({...});
496
+ // anonymousId: "abc-123" (auto-generated and persisted)
497
+
498
+ // User browses before login
499
+ analytics.track("Product Viewed", { sku: "XYZ" });
500
+ // Includes: anonymousId: "abc-123"
501
+
502
+ // User logs in
503
+ analytics.identify("user456", { name: "John", email: "john@example.com" });
504
+ // userId: "user456" is now persisted
505
+
506
+ // User performs actions
507
+ analytics.track("Added to Cart", { sku: "XYZ" });
508
+ // Includes: userId: "user456", anonymousId: "abc-123"
509
+
510
+ // App closes and reopens...
511
+
512
+ // SDK auto-loads userId from storage
513
+ analytics.track("App Reopened");
514
+ // STILL includes: userId: "user456", anonymousId: "abc-123"
515
+
516
+ // User logs out
517
+ await analytics.reset();
518
+ // All IDs cleared, new anonymousId will be generated on next init
519
+ ```
520
+
521
+ ### Storage Location
522
+
523
+ All identity data is stored in **React Native AsyncStorage**, which provides:
524
+
525
+ - Persistent storage across app sessions
526
+ - Automatic data encryption on iOS (Keychain-backed)
527
+ - Secure local storage on Android
528
+ - Cleared only on app uninstall or explicit `reset()` call
529
+
530
+ ## Using the alias() Method
531
+
532
+ The `alias()` method connects an **anonymous user** (tracked by `anonymousId`) to a **known user ID**. It's used to link pre-login activity to post-login identity.
533
+
534
+ ### When to Use alias()
535
+
536
+ Use `alias()` when a user **signs up** or **logs in for the first time**, and you want to connect their pre-login browsing activity to their new account.
537
+
538
+ **Primary use case:** Connecting anonymous browsing sessions to newly created user accounts.
539
+
540
+ ### How It Works
541
+
542
+ ```js
543
+ analytics.alias(newUserId);
544
+ ```
545
+
546
+ This does two things:
547
+
548
+ 1. Sets the new `userId` (same as `identify()`)
549
+ 2. Sends an `alias` event to your analytics backend, telling it: "This anonymousId and this userId are the same person"
550
+
551
+ ### Example: User Sign-Up Flow
552
+
553
+ ```js
554
+ // App starts - user is anonymous
555
+ const analytics = await createAnalyticsClient({...});
556
+ // anonymousId: "abc-123" (auto-generated)
557
+
558
+ // User browses anonymously
559
+ analytics.track("Product Viewed", { productId: "XYZ" });
560
+ analytics.track("Add to Cart", { productId: "XYZ" });
561
+ // Both events tracked with anonymousId: "abc-123"
562
+
563
+ // User creates an account / signs up
564
+ analytics.alias("user-456");
565
+ // Sends alias event connecting: anonymousId "abc-123" → userId "user-456"
566
+
567
+ // Optionally add user traits
568
+ analytics.identify("user-456", {
569
+ name: "John Doe",
570
+ email: "john@example.com"
571
+ });
572
+
573
+ // Future events now tracked as authenticated user
574
+ analytics.track("Purchase Complete", { orderId: "789" });
575
+ // Event includes: userId: "user-456", anonymousId: "abc-123"
576
+ ```
577
+
578
+ ### alias() vs identify()
579
+
580
+ | Method | When to Use | What It Does |
581
+ | ---------------- | --------------------------------------------------------------- | -------------------------------------------------------------- |
582
+ | **`alias()`** | **First-time sign-up/login** when connecting anonymous activity | Sets userId + sends `alias` event to link anonymousId → userId |
583
+ | **`identify()`** | Subsequent logins or updating user traits | Sets userId + sends `identify` event with user traits |
584
+
585
+ ### Best Practices
586
+
587
+ 1. **First-time sign-up:** Call `alias()` to connect anonymous activity to the new account
588
+ 2. **Subsequent logins:** Use `identify()` - no need to alias again
589
+ 3. **Backend support:** Ensure your analytics backend supports alias events for merging user profiles
590
+ 4. **One-time operation:** You typically only need `alias()` once per user - when they first create an account
591
+
592
+ ### Real-World Example: E-Commerce App
593
+
594
+ ```js
595
+ // Day 1: Anonymous browsing
596
+ analytics.track("App Opened");
597
+ analytics.track("Product Viewed", { sku: "SHOE-123" });
598
+ analytics.track("Product Viewed", { sku: "SHIRT-456" });
599
+ // All tracked with anonymousId: "anon-xyz"
600
+
601
+ // User signs up
602
+ analytics.alias("user-789");
603
+ analytics.identify("user-789", {
604
+ name: "Jane Doe",
605
+ email: "jane@example.com",
606
+ });
607
+
608
+ // User continues shopping (now authenticated)
609
+ analytics.track("Added to Cart", { sku: "SHIRT-456" });
610
+ analytics.track("Purchase", { total: 49.99 });
611
+
612
+ // Your analytics platform can now show the complete customer journey:
613
+ // - Pre-signup activity (anonymous product views)
614
+ // - Post-signup activity (cart additions, purchase)
615
+ // - Full conversion funnel from anonymous → identified → converted
616
+ ```
617
+
271
618
  ## Advertising ID (IDFA/GAID)
272
619
 
273
620
  The SDK supports including advertising identifiers (IDFA on iOS, GAID on Android) in event context for ad tracking and attribution purposes.
@@ -316,8 +663,8 @@ Once set, the `advertisingId` will be automatically included in the device conte
316
663
  > **Note:** The examples below use third-party libraries for demonstration purposes. You should choose appropriate packages that fit your project's needs and are actively maintained.
317
664
 
318
665
  ```js
319
- import { AppTrackingTransparency } from 'react-native-tracking-transparency';
320
- import { getAdvertisingId } from '@react-native-community/google-advertiser-id'; // or similar library
666
+ import { AppTrackingTransparency } from "react-native-tracking-transparency";
667
+ import { getAdvertisingId } from "@react-native-community/google-advertiser-id"; // or similar library
321
668
 
322
669
  // Initialize analytics first
323
670
  const analytics = await createAnalyticsClient({
@@ -326,9 +673,10 @@ const analytics = await createAnalyticsClient({
326
673
  });
327
674
 
328
675
  // Request tracking permission
329
- const trackingStatus = await AppTrackingTransparency.requestTrackingAuthorization();
676
+ const trackingStatus =
677
+ await AppTrackingTransparency.requestTrackingAuthorization();
330
678
 
331
- if (trackingStatus === 'authorized') {
679
+ if (trackingStatus === "authorized") {
332
680
  // Get and set IDFA only if authorized
333
681
  const advertisingId = await getAdvertisingId();
334
682
  await analytics.setAdvertisingId(advertisingId);
@@ -338,7 +686,7 @@ if (trackingStatus === 'authorized') {
338
686
  ### Android Example
339
687
 
340
688
  ```js
341
- import { getAdvertisingId } from '@react-native-community/google-advertiser-id'; // or similar library
689
+ import { getAdvertisingId } from "@react-native-community/google-advertiser-id"; // or similar library
342
690
 
343
691
  // Initialize analytics first
344
692
  const analytics = await createAnalyticsClient({
@@ -371,6 +719,7 @@ analytics.track("Event After Opt Out");
371
719
  ### Validation
372
720
 
373
721
  The SDK validates advertising IDs before setting them:
722
+
374
723
  - Must be a non-empty string
375
724
  - Cannot be only whitespace
376
725
  - Invalid values are rejected and logged as warnings
@@ -20,6 +20,7 @@ export declare class MetaRouterAnalyticsClient {
20
20
  private static readonly MAX_QUEUE_SIZE;
21
21
  private maxQueueEvents;
22
22
  private dispatcher;
23
+ private tracingEnabled;
23
24
  /**
24
25
  * Initializes the analytics client with the provided options.
25
26
  * @param options - The initialization options.
@@ -121,6 +122,19 @@ export declare class MetaRouterAnalyticsClient {
121
122
  * their advertising ID without performing a full analytics reset.
122
123
  */
123
124
  clearAdvertisingId(): Promise<void>;
125
+ /**
126
+ * Enable or disable tracing headers on outgoing requests.
127
+ * When enabled, a "Trace: true" header is included in all API calls to the cluster.
128
+ * This is useful for debugging and troubleshooting request flows.
129
+ *
130
+ * @param enabled - Whether to enable tracing headers
131
+ */
132
+ setTracing(enabled: boolean): void;
133
+ /**
134
+ * Returns whether tracing is currently enabled.
135
+ * @returns True if tracing is enabled
136
+ */
137
+ isTracingEnabled(): boolean;
124
138
  /**
125
139
  * Enable debug logging for troubleshooting
126
140
  */
@@ -142,6 +156,7 @@ export declare class MetaRouterAnalyticsClient {
142
156
  circuitState: import("./utils/circuitBreaker").CircuitState;
143
157
  circuitRemainingMs: number;
144
158
  maxQueueEvents: number;
159
+ tracingEnabled: boolean;
145
160
  }>;
146
161
  /**
147
162
  * Flushes the event queue to the ingestion endpoint in chunks.
@@ -1 +1 @@
1
- {"version":3,"file":"MetaRouterAnalyticsClient.d.ts","sourceRoot":"","sources":["../../src/analytics/MetaRouterAnalyticsClient.ts"],"names":[],"mappings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OAGG;IACH,gBAAgB,IAAI,OAAO;IAI3B;;OAEG;IACH,kBAAkB;IAKlB;;OAEG;IACG,YAAY;;;;;;;;;;;;;;;;IAoBlB;;;OAGG;IACG,KAAK;IAIX;;OAEG;IACU,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CA4BpC"}
@@ -27,6 +27,7 @@ export class MetaRouterAnalyticsClient {
27
27
  this.appState = AppState.currentState;
28
28
  this.appStateSubscription = null;
29
29
  this.maxQueueEvents = 2000;
30
+ this.tracingEnabled = false;
30
31
  /**
31
32
  * Handles the app state change event.
32
33
  * @param nextState - The new app state.
@@ -77,6 +78,7 @@ export class MetaRouterAnalyticsClient {
77
78
  fetchWithTimeout: (url, init, timeoutMs) => this.fetchWithTimeout(url, init, timeoutMs),
78
79
  canSend: () => this.lifecycle === "ready" && !!this.identityManager.getAnonymousId(),
79
80
  isOperational: () => this.lifecycle === "ready",
81
+ isTracingEnabled: () => this.tracingEnabled,
80
82
  createBreaker: () => new CircuitBreaker({
81
83
  failureThreshold: 3,
82
84
  cooldownMs: 10000,
@@ -330,6 +332,24 @@ export class MetaRouterAnalyticsClient {
330
332
  this.context = await getContextInfo();
331
333
  log("Advertising ID cleared from storage and context");
332
334
  }
335
+ /**
336
+ * Enable or disable tracing headers on outgoing requests.
337
+ * When enabled, a "Trace: true" header is included in all API calls to the cluster.
338
+ * This is useful for debugging and troubleshooting request flows.
339
+ *
340
+ * @param enabled - Whether to enable tracing headers
341
+ */
342
+ setTracing(enabled) {
343
+ log(`Tracing ${enabled ? 'enabled' : 'disabled'}`);
344
+ this.tracingEnabled = enabled;
345
+ }
346
+ /**
347
+ * Returns whether tracing is currently enabled.
348
+ * @returns True if tracing is enabled
349
+ */
350
+ isTracingEnabled() {
351
+ return this.tracingEnabled;
352
+ }
333
353
  /**
334
354
  * Enable debug logging for troubleshooting
335
355
  */
@@ -356,6 +376,7 @@ export class MetaRouterAnalyticsClient {
356
376
  circuitState: d.circuitState,
357
377
  circuitRemainingMs: d.circuitRemainingMs,
358
378
  maxQueueEvents: d.maxQueueEvents,
379
+ tracingEnabled: this.tracingEnabled,
359
380
  };
360
381
  }
361
382
  /**
@@ -1,6 +1,6 @@
1
- import type { EventPayload } from "./types";
2
- import type CircuitBreaker from "./utils/circuitBreaker";
3
- export type CircuitState = "CLOSED" | "OPEN" | "HALF_OPEN";
1
+ import type { EventPayload } from './types';
2
+ import type CircuitBreaker from './utils/circuitBreaker';
3
+ export type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
4
4
  export interface DispatcherOptions {
5
5
  maxQueueEvents: number;
6
6
  autoFlushThreshold: number;
@@ -10,6 +10,7 @@ export interface DispatcherOptions {
10
10
  fetchWithTimeout: (url: string, init: RequestInit, timeoutMs: number) => Promise<Response>;
11
11
  canSend: () => boolean;
12
12
  isOperational: () => boolean;
13
+ isTracingEnabled: () => boolean;
13
14
  createBreaker: () => CircuitBreaker;
14
15
  log: (...args: any[]) => void;
15
16
  warn: (...args: any[]) => void;
@@ -25,6 +26,7 @@ export default class Dispatcher {
25
26
  private nextScheduledAt;
26
27
  private flushInFlight;
27
28
  private maxBatchSize;
29
+ private readonly initialMaxBatchSize;
28
30
  private circuit;
29
31
  constructor(opts: DispatcherOptions);
30
32
  getQueueRef(): EventPayload[];
@@ -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,OAAO,KAAK,cAAc,MAAM,wBAAwB,CAAC;AAEzD,MAAM,MAAM,YAAY,GAAG,QAAQ,GAAG,MAAM,GAAG,WAAW,CAAC;AAE3D,MAAM,WAAW,iBAAiB;IAChC,cAAc,EAAE,MAAM,CAAC;IACvB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,YAAY,EAAE,MAAM,CAAC;IACrB,oBAAoB,EAAE,MAAM,CAAC;IAE7B,QAAQ,EAAE,C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C,IAAI,CAAoB;IACzC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAsB;IAC5C,OAAO,CAAC,UAAU,CAA+B;IACjD,OAAO,CAAC,SAAS,CAA+B;IAChD,OAAO,CAAC,eAAe,CAAuB;IAC9C,OAAO,CAAC,aAAa,CAA8B;IACnD,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAS;IAC7C,OAAO,CAAC,OAAO,CAAiB;gBAEpB,IAAI,EAAE,iBAAiB;IAOnC,WAAW,IAAI,YAAY,EAAE;IAI7B,KAAK,IAAI,IAAI;IAQb,IAAI,IAAI,IAAI;IAQZ,KAAK,IAAI,IAAI;IAOb,OAAO,CAAC,cAAc;IAQtB,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAkBjC,OAAO,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI;IAuBlC,OAAO,CAAC,UAAU;IAUlB,OAAO,CAAC,eAAe;IAQjB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAiK5B,YAAY;;;;;;;;;;CAYb"}
@@ -6,7 +6,8 @@ export default class Dispatcher {
6
6
  this.nextScheduledAt = null;
7
7
  this.flushInFlight = null;
8
8
  this.opts = opts;
9
- this.maxBatchSize = Math.max(1, opts.maxBatchSize);
9
+ this.initialMaxBatchSize = Math.max(1, opts.maxBatchSize);
10
+ this.maxBatchSize = this.initialMaxBatchSize;
10
11
  this.circuit = opts.createBreaker();
11
12
  }
12
13
  getQueueRef() {
@@ -28,7 +29,7 @@ export default class Dispatcher {
28
29
  this.stop();
29
30
  this.queue.length = 0;
30
31
  this.circuit = this.opts.createBreaker();
31
- this.maxBatchSize = Math.max(1, this.opts.maxBatchSize);
32
+ this.maxBatchSize = this.initialMaxBatchSize;
32
33
  }
33
34
  clearNextTimer() {
34
35
  if (this.nextTimer) {
@@ -58,7 +59,7 @@ export default class Dispatcher {
58
59
  this.queue.shift();
59
60
  this.opts.warn(`[MetaRouter] Queue cap ${this.opts.maxQueueEvents} reached — dropped oldest event`);
60
61
  }
61
- this.opts.log("Enqueuing event", {
62
+ this.opts.log('Enqueuing event', {
62
63
  type: event === null || event === void 0 ? void 0 : event.type,
63
64
  messageId: event === null || event === void 0 ? void 0 : event.messageId,
64
65
  });
@@ -105,10 +106,16 @@ export default class Dispatcher {
105
106
  }
106
107
  const chunk = this.drainBatch();
107
108
  try {
108
- this.opts.log("Making API call to:", this.opts.endpoint("/v1/batch"));
109
- const res = await this.opts.fetchWithTimeout(this.opts.endpoint("/v1/batch"), {
110
- method: "POST",
111
- headers: { "Content-Type": "application/json" },
109
+ this.opts.log('Making API call to:', this.opts.endpoint('/v1/batch'));
110
+ const headers = {
111
+ 'Content-Type': 'application/json',
112
+ };
113
+ if (this.opts.isTracingEnabled()) {
114
+ headers.Trace = 'true';
115
+ }
116
+ const res = await this.opts.fetchWithTimeout(this.opts.endpoint('/v1/batch'), {
117
+ method: 'POST',
118
+ headers,
112
119
  body: JSON.stringify({ batch: chunk }),
113
120
  }, 8000);
114
121
  if (!res.ok) {
@@ -118,13 +125,13 @@ export default class Dispatcher {
118
125
  this.circuit.onFailure();
119
126
  if (this.opts.isOperational()) {
120
127
  this.queue.unshift(...chunk);
121
- const retryAfter = (_a = this.parseRetryAfter(res.headers.get("retry-after"))) !== null && _a !== void 0 ? _a : 0;
128
+ const retryAfter = (_a = this.parseRetryAfter(res.headers.get('retry-after'))) !== null && _a !== void 0 ? _a : 0;
122
129
  const wait = Math.max(this.circuit.remainingCooldownMs(), retryAfter, 1000);
123
130
  this.opts.warn(`Retryable status ${s}; scheduling retry in ${wait}ms`);
124
131
  this.scheduleFlushIn(wait);
125
132
  }
126
133
  else {
127
- this.opts.warn("Flush aborted during reset/disable — dropping current chunk");
134
+ this.opts.warn('Flush aborted during reset/disable — dropping current chunk');
128
135
  }
129
136
  return;
130
137
  }
@@ -132,14 +139,14 @@ export default class Dispatcher {
132
139
  this.circuit.onFailure();
133
140
  if (this.opts.isOperational()) {
134
141
  this.queue.unshift(...chunk);
135
- const h = (_b = this.parseRetryAfter(res.headers.get("retry-after"))) !== null && _b !== void 0 ? _b : 0;
142
+ const h = (_b = this.parseRetryAfter(res.headers.get('retry-after'))) !== null && _b !== void 0 ? _b : 0;
136
143
  const b = this.circuit.remainingCooldownMs();
137
144
  const wait = Math.max(h, b, 1000);
138
145
  this.opts.warn(`429 throttled; scheduling in ${wait}ms (retry-after=${h}, breaker=${b})`);
139
146
  this.scheduleFlushIn(wait);
140
147
  }
141
148
  else {
142
- this.opts.warn("Throttle received but client resetting/disabled — dropping chunk");
149
+ this.opts.warn('Throttle received but client resetting/disabled — dropping chunk');
143
150
  }
144
151
  return;
145
152
  }
@@ -161,7 +168,7 @@ export default class Dispatcher {
161
168
  else {
162
169
  const ids = chunk
163
170
  .map((e) => e.messageId)
164
- .join(",");
171
+ .join(',');
165
172
  this.opts.warn(`Dropping oversize event(s) after 413 at batchSize=1; messageIds=${ids}`);
166
173
  }
167
174
  return;
@@ -173,23 +180,26 @@ export default class Dispatcher {
173
180
  }
174
181
  // Success
175
182
  this.circuit.onSuccess();
176
- this.opts.log("API call successful");
183
+ if (this.maxBatchSize < this.initialMaxBatchSize) {
184
+ this.maxBatchSize = Math.min(this.maxBatchSize * 2, this.initialMaxBatchSize);
185
+ }
186
+ this.opts.log('API call successful');
177
187
  }
178
188
  catch (err) {
179
189
  this.circuit.onFailure();
180
190
  if (this.opts.isOperational()) {
181
191
  this.queue.unshift(...chunk);
182
192
  const wait = Math.max(this.circuit.remainingCooldownMs(), 1000);
183
- this.opts.warn("Flush attempt failed; scheduling retry in", wait, "ms", err === null || err === void 0 ? void 0 : err.message);
193
+ this.opts.warn('Flush attempt failed; scheduling retry in', wait, 'ms', err === null || err === void 0 ? void 0 : err.message);
184
194
  this.scheduleFlushIn(wait);
185
195
  }
186
196
  else {
187
- this.opts.warn("Flush failed during reset/disable — dropping current chunk");
197
+ this.opts.warn('Flush failed during reset/disable — dropping current chunk');
188
198
  }
189
199
  return;
190
200
  }
191
201
  }
192
- this.opts.log("Flush completed successfully");
202
+ this.opts.log('Flush completed successfully');
193
203
  };
194
204
  this.flushInFlight = doFlush().finally(() => {
195
205
  this.flushInFlight = null;
@@ -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,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,WAAW,GACnB,kBAAkB,CA2BpB"}
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"}
@@ -2,8 +2,16 @@ import { MetaRouterAnalyticsClient } from "./MetaRouterAnalyticsClient";
2
2
  import { proxyClient, setRealClient } from "./proxy/proxyClient";
3
3
  // Only one initialization in flight
4
4
  let initPromise = null;
5
+ let currentOptions = null;
5
6
  export function createAnalyticsClient(options) {
7
+ // Check if options have changed - if so, force reset first
8
+ const optionsChanged = currentOptions &&
9
+ JSON.stringify(currentOptions) !== JSON.stringify(options);
10
+ if (optionsChanged && initPromise) {
11
+ console.warn('[MetaRouter] Config changed but client not reset. Call await client.reset() before reinitializing with new options.');
12
+ }
6
13
  if (!initPromise) {
14
+ currentOptions = options;
7
15
  initPromise = (async () => {
8
16
  const instance = new MetaRouterAnalyticsClient(options);
9
17
  await instance.init();
@@ -16,6 +24,7 @@ export function createAnalyticsClient(options) {
16
24
  alias: (newUserId) => instance.alias(newUserId),
17
25
  setAdvertisingId: (advertisingId) => instance.setAdvertisingId(advertisingId),
18
26
  clearAdvertisingId: () => instance.clearAdvertisingId(),
27
+ setTracing: (enabled) => instance.setTracing(enabled),
19
28
  enableDebugLogging: () => instance.enableDebugLogging(),
20
29
  getDebugInfo: () => instance.getDebugInfo(),
21
30
  flush: () => instance.flush(),
@@ -23,6 +32,7 @@ export function createAnalyticsClient(options) {
23
32
  await instance.reset();
24
33
  setRealClient(null, { dropPending: true });
25
34
  initPromise = null;
35
+ currentOptions = null;
26
36
  },
27
37
  };
28
38
  setRealClient(boundClient);
@@ -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;AA8InD,eAAO,MAAM,WAAW,EAAE,kBAczB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,kBAAkB,GAAG,IAAI,EACjC,IAAI,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,OAAO,CAAA;CAAE,QAqBjC"}
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;AAqInD,eAAO,MAAM,WAAW,EAAE,kBAezB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,kBAAkB,GAAG,IAAI,EACjC,IAAI,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,OAAO,CAAA;CAAE,QAqBjC"}
@@ -21,11 +21,10 @@ let flushInFlight = null;
21
21
  *
22
22
  * - **Pre-bind:**
23
23
  * - Queues the call in `pendingCalls` for replay after binding.
24
- * - For async methods (`flush`, `reset`, `getDebugInfo`), returns a Promise
25
- * that resolves/rejects after replay. Keeps a `reject` handle so
24
+ * - For async methods (`flush`, `getDebugInfo`, `setAdvertisingId`, `clearAdvertisingId`),
25
+ * returns a Promise that resolves/rejects after replay. Keeps a `reject` handle so
26
26
  * `dropPending` can fail them immediately.
27
27
  * - For sync "fire-and-forget" methods, returns `void` immediately.
28
- * - For `getDebugInfo`, returns an immediate proxy snapshot without queuing.
29
28
  * - For `reset`, returns an immediate resolved Promise (no-op).
30
29
  * - If the queue exceeds `MAX_PENDING_CALLS`, drops the oldest call
31
30
  * (rejecting it if async) and logs a warning.
@@ -56,13 +55,6 @@ function handleMethodCall(methodName, ...args) {
56
55
  console.warn(`[MetaRouter] Oldest call dropped (queue cap ${MAX_PENDING_CALLS})`);
57
56
  }
58
57
  // Special-cases while unbound:
59
- if (methodName === "getDebugInfo") {
60
- // Return immediate proxy snapshot instead of queueing
61
- return Promise.resolve({
62
- proxy: true,
63
- pendingCalls: pendingCalls.length,
64
- });
65
- }
66
58
  if (methodName === "reset") {
67
59
  // Nothing to reset pre-bind; resolve immediately
68
60
  return Promise.resolve();
@@ -115,6 +107,7 @@ export const proxyClient = {
115
107
  alias: (newUserId) => handleMethodCall("alias", newUserId),
116
108
  setAdvertisingId: (advertisingId) => handleMethodCall("setAdvertisingId", advertisingId),
117
109
  clearAdvertisingId: () => handleMethodCall("clearAdvertisingId"),
110
+ setTracing: (enabled) => handleMethodCall("setTracing", enabled),
118
111
  flush: () => handleMethodCall("flush"),
119
112
  reset: () => handleMethodCall("reset"),
120
113
  enableDebugLogging: () => handleMethodCall("enableDebugLogging"),
@@ -33,6 +33,7 @@ export interface AnalyticsInterface {
33
33
  alias: (newUserId: string) => void;
34
34
  setAdvertisingId: (advertisingId: string) => Promise<void>;
35
35
  clearAdvertisingId: () => Promise<void>;
36
+ setTracing: (enabled: boolean) => void;
36
37
  flush: () => Promise<void>;
37
38
  reset: () => Promise<void>;
38
39
  enableDebugLogging: () => void;
@@ -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,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AAC;QACb,OAAO,EAAE,MAAM,CAAC;QAChB,KAAK,EAAE,MAAM,CAAC;QACd,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;IACF,MAAM,EAAE;QACN,YAAY,EAAE,MAAM,CAAC;QACrB,KAAK,EAAE,MAAM,CAAC;QACd,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;QACb,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB,CAAC;IACF,OAAO,EAAE;QACP,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC;IACF,EAAE,EAAE;QACF,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC;IACF,MAAM,EAAE;QACN,OAAO,EAAE,MAAM,CAAC;QAChB,KAAK,EAAE,MAAM,CAAC;QACd,MAAM,EAAE,MAAM,CAAC;KAChB,CAAC;IACF,OAAO,CAAC,EAAE;QACR,IAAI,EAAE,OAAO,CAAC;KACf,CAAC;IACF,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAED,MAAM,MAAM,SAAS,GACjB,MAAM,GACN,cAAc,GACd,OAAO,GACP,WAAW,GACX,UAAU,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metarouter/react-native-sdk",
3
- "version": "1.4.0",
3
+ "version": "1.5.1",
4
4
  "main": "./lib/index.js",
5
5
  "types": "./lib/index.d.ts",
6
6
  "exports": {
@@ -17,7 +17,7 @@
17
17
  "scripts": {
18
18
  "clean": "rm -rf lib",
19
19
  "build": "tsc --project tsconfig.build.json",
20
- "prepare": "npm run build",
20
+ "prepare": "husky",
21
21
  "prepublishOnly": "npm run clean && npm run build",
22
22
  "test": "jest"
23
23
  },
@@ -42,16 +42,30 @@
42
42
  "@react-native-async-storage/async-storage": ">=2.2.0",
43
43
  "react": ">=16.8.0",
44
44
  "react-native": ">=0.63.0",
45
- "react-native-device-info": "^14.0.4"
45
+ "react-native-device-info": ">=14.0.4"
46
46
  },
47
47
  "devDependencies": {
48
+ "@commitlint/cli": "^20.3.0",
49
+ "@commitlint/config-conventional": "^20.3.0",
50
+ "@eslint/compat": "^2.0.0",
51
+ "@eslint/eslintrc": "^3.3.3",
52
+ "@eslint/js": "^9.39.2",
48
53
  "@react-native-async-storage/async-storage": ">=2.2.0",
54
+ "@react-native/eslint-config": "^0.84.0-nightly-20260106-36a0d9ef6",
49
55
  "@types/jest": "^30.0.0",
50
- "@types/react": "^19.1.8",
51
- "jest": "^30.0.4",
56
+ "@types/react": "^19.2.7",
57
+ "eslint": "^9.39.2",
58
+ "eslint-plugin-prettier": "^5.5.4",
59
+ "husky": "^9.1.7",
60
+ "jest": "^30.2.0",
61
+ "lint-staged": "^16.2.7",
52
62
  "metro-react-native-babel-preset": "^0.77.0",
53
- "react-native-device-info": "^14.0.4",
54
- "typescript": "^5.8.3"
63
+ "prettier": "^3.7.4",
64
+ "react-native-device-info": "^15.0.1",
65
+ "typescript": "^5.9.3"
55
66
  },
56
- "react-native": "./lib/index.js"
67
+ "react-native": "./lib/index.js",
68
+ "lint-staged": {
69
+ "*.{ts,js}": "eslint --fix"
70
+ }
57
71
  }