@metarouter/react-native-sdk 1.7.0 → 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 (31) hide show
  1. package/README.md +164 -56
  2. package/lib/analytics/MetaRouterAnalyticsClient.d.ts +50 -2
  3. package/lib/analytics/MetaRouterAnalyticsClient.d.ts.map +1 -1
  4. package/lib/analytics/MetaRouterAnalyticsClient.js +239 -44
  5. package/lib/analytics/init.d.ts +7 -0
  6. package/lib/analytics/init.d.ts.map +1 -1
  7. package/lib/analytics/init.js +197 -37
  8. package/lib/analytics/lifecycle/lifecycleEvents.d.ts +52 -0
  9. package/lib/analytics/lifecycle/lifecycleEvents.d.ts.map +1 -0
  10. package/lib/analytics/lifecycle/lifecycleEvents.js +66 -0
  11. package/lib/analytics/proxy/proxyClient.d.ts +29 -0
  12. package/lib/analytics/proxy/proxyClient.d.ts.map +1 -1
  13. package/lib/analytics/proxy/proxyClient.js +125 -5
  14. package/lib/analytics/types.d.ts +50 -1
  15. package/lib/analytics/types.d.ts.map +1 -1
  16. package/lib/analytics/utils/appContext.d.ts +20 -0
  17. package/lib/analytics/utils/appContext.d.ts.map +1 -0
  18. package/lib/analytics/utils/appContext.js +22 -0
  19. package/lib/analytics/utils/contextInfo.d.ts +7 -3
  20. package/lib/analytics/utils/contextInfo.d.ts.map +1 -1
  21. package/lib/analytics/utils/contextInfo.js +12 -9
  22. package/lib/analytics/utils/initOptions.d.ts +22 -0
  23. package/lib/analytics/utils/initOptions.d.ts.map +1 -0
  24. package/lib/analytics/utils/initOptions.js +100 -0
  25. package/lib/analytics/utils/lifecycleStorage.d.ts +13 -0
  26. package/lib/analytics/utils/lifecycleStorage.d.ts.map +1 -0
  27. package/lib/analytics/utils/lifecycleStorage.js +35 -0
  28. package/lib/index.d.ts +4 -4
  29. package/lib/index.d.ts.map +1 -1
  30. package/lib/index.js +3 -3
  31. package/package.json +1 -1
@@ -3,12 +3,16 @@ import { log, setDebugLogging, warn, error } from './utils/logger';
3
3
  import { IdentityManager } from './IdentityManager';
4
4
  import { enrichEvent } from './utils/enrichEvent';
5
5
  import { getContextInfo, clearContextCache } from './utils/contextInfo';
6
- import { getIdentityField, setIdentityField, removeIdentityField, ADVERTISING_ID_KEY, } from './utils/identityStorage';
6
+ import { loadAppContext } from './utils/appContext';
7
+ import { getIdentityField, setIdentityField, removeIdentityField, ADVERTISING_ID_KEY, ANONYMOUS_ID_KEY, USER_ID_KEY, GROUP_ID_KEY, } from './utils/identityStorage';
8
+ import { getLifecycleVersion, getLifecycleBuild, setLifecycleVersionBuild, } from './utils/lifecycleStorage';
9
+ import { LifecycleEmitter, UNKNOWN_PREVIOUS, } from './lifecycle/lifecycleEvents';
7
10
  import CircuitBreaker from './utils/circuitBreaker';
8
11
  import Dispatcher from './dispatcher';
9
12
  import { PersistentEventQueue } from './persistence/PersistentEventQueue';
10
13
  import { NetworkMonitor, } from './utils/networkMonitor';
11
14
  import { DebouncedNetworkMonitor } from './utils/debouncedNetworkMonitor';
15
+ import { DEFAULT_MAX_DISK_EVENTS, validateInitOptions, } from './utils/initOptions';
12
16
  /**
13
17
  * Analytics client for MetaRouter.
14
18
  * - Handles event queueing, batching, and delivery with retries.
@@ -29,17 +33,59 @@ export class MetaRouterAnalyticsClient {
29
33
  this.flushIntervalSeconds = 10;
30
34
  this.appState = AppState.currentState;
31
35
  this.appStateSubscription = null;
32
- this.maxDiskEvents = MetaRouterAnalyticsClient.DEFAULT_MAX_DISK_EVENTS;
36
+ this.maxDiskEvents = DEFAULT_MAX_DISK_EVENTS;
33
37
  this.tracingEnabled = false;
34
38
  this.networkStatus = 'connected';
35
39
  this.unsubscribeNetwork = null;
40
+ // Only constructed when trackLifecycleEvents is true, so every emit site
41
+ // is a null-safe call and a disabled client never builds lifecycle payloads.
42
+ this.lifecycleEmitter = null;
43
+ // Opt-in by default. Existing customers upgrading the SDK do not begin
44
+ // emitting lifecycle events without explicitly setting this to true.
45
+ this.trackLifecycleEvents = false;
46
+ // Buffers a URL forwarded through recordOpenedURL() so the next
47
+ // Application Opened can carry it. One-shot — cleared on emit.
48
+ this.pendingDeepLink = null;
49
+ // Suppressed cold-launch Application Opened (process woke in background).
50
+ // The next background→active transition emits an Opened with from_background:false.
51
+ this.coldLaunchOpenDeferred = false;
52
+ // Set when the app leaves the foreground for background, cleared on the
53
+ // next return to active. The resume Opened keys on this rather than on the
54
+ // last reported state: a return can pass through `inactive` (a FaceID or
55
+ // passcode prompt on resume), and comparing only the previous state would
56
+ // mistake it for a Control Center blip and drop the Opened.
57
+ this.wasBackgrounded = false;
36
58
  /**
37
59
  * Handles the app state change event.
38
60
  * @param nextState - The new app state.
39
61
  */
40
62
  this.handleAppStateChange = async (nextState) => {
41
- if (this.appState === 'active' && nextState.match(/inactive|background/)) {
63
+ var _a, _b, _c;
64
+ const previousState = this.appState;
65
+ this.appState = nextState;
66
+ const leavingForeground = previousState === 'active' &&
67
+ (nextState === 'inactive' || nextState === 'background');
68
+ // Accepts inactive as well as active as the previous state: on iOS, RN
69
+ // always reports active → inactive → background (RCTAppState emits
70
+ // `inactive` on WillResignActive first), so requiring active → background
71
+ // would mean Backgrounded never fires on iOS. Android has no `inactive`
72
+ // and goes straight to background. Other previous states (`unknown` or
73
+ // `extension` while a headless or push-woken process settles) never
74
+ // reached the foreground, so they must not emit a Backgrounded without
75
+ // an Opened before it.
76
+ const enteringBackground = nextState === 'background' &&
77
+ (previousState === 'active' || previousState === 'inactive');
78
+ if (leavingForeground || enteringBackground) {
42
79
  log('App moved to background');
80
+ // Enqueued synchronously before the flush below so the event is part
81
+ // of the same drain. On iOS the inactive step already flushed, so the
82
+ // background step flushes again just to carry this one event out.
83
+ if (enteringBackground) {
84
+ this.wasBackgrounded = true;
85
+ if (this.lifecycle === 'ready') {
86
+ (_a = this.lifecycleEmitter) === null || _a === void 0 ? void 0 : _a.emitBackgrounded();
87
+ }
88
+ }
43
89
  this.stopFlushLoop();
44
90
  this.clearNextTimer();
45
91
  try {
@@ -51,46 +97,52 @@ export class MetaRouterAnalyticsClient {
51
97
  warn('Failed to persist queue while moving to background:', err);
52
98
  }
53
99
  }
100
+ // Cleared on any arrival in the foreground, ready or not: a
101
+ // background → active cycle completed while init() is in flight is
102
+ // covered by the cold-launch Opened, and must not leave the flag set
103
+ // for the next active → inactive → active blip to report as a resume.
104
+ const returningFromBackground = nextState === 'active' && this.wasBackgrounded;
105
+ if (nextState === 'active') {
106
+ this.wasBackgrounded = false;
107
+ }
54
108
  if (nextState === 'active' && this.lifecycle === 'ready') {
55
109
  log('App moved to foreground');
110
+ // Application Opened semantics:
111
+ // - return after a background entry (directly or via inactive): emit
112
+ // with from_background=true
113
+ // - active→inactive→active (Control Center, FaceID, system alert):
114
+ // suppressed
115
+ // - first foreground after a background-launched cold start: emit
116
+ // with from_background=false (deferred cold-launch Opened)
117
+ if (this.coldLaunchOpenDeferred) {
118
+ (_b = this.lifecycleEmitter) === null || _b === void 0 ? void 0 : _b.emitOpened(false, this.consumePendingDeepLink());
119
+ this.coldLaunchOpenDeferred = false;
120
+ }
121
+ else if (returningFromBackground) {
122
+ (_c = this.lifecycleEmitter) === null || _c === void 0 ? void 0 : _c.emitOpened(true, this.consumePendingDeepLink());
123
+ }
56
124
  this.startFlushLoop();
57
125
  this.flush();
58
126
  }
59
- this.appState = nextState;
60
127
  };
61
- const { writeKey, ingestionHost, flushIntervalSeconds } = options;
62
- if (!writeKey || typeof writeKey !== 'string' || writeKey.trim() === '') {
63
- throw new Error('MetaRouterAnalyticsClient initialization failed: `writeKey` is required and must be a non-empty string.');
64
- }
65
- try {
66
- // Validate it's a proper absolute URL
67
- // and ensure it does not end with a trailing slash
68
- // e.g., "https://example.com" or "https://example.com/api" are valid,
69
- // but "https://example.com/" or "https://example.com/api/" are not.
70
- // eslint-disable-next-line no-new
71
- new URL(ingestionHost);
72
- if (ingestionHost.endsWith('/')) {
73
- throw new Error();
74
- }
75
- }
76
- catch {
77
- throw new Error('MetaRouterAnalyticsClient initialization failed: `ingestionHost` must be a valid URL and not end in a slash.');
78
- }
79
- this.ingestionHost = ingestionHost;
80
- this.writeKey = writeKey;
81
- this.flushIntervalSeconds = flushIntervalSeconds !== null && flushIntervalSeconds !== void 0 ? flushIntervalSeconds : 10;
82
- // Validate + normalize persistence caps.
83
- const rawMaxDisk = (_a = options.maxDiskEvents) !== null && _a !== void 0 ? _a : MetaRouterAnalyticsClient.DEFAULT_MAX_DISK_EVENTS;
84
- if (rawMaxDisk < 0) {
85
- throw new Error('MetaRouterAnalyticsClient initialization failed: `maxDiskEvents` must be >= 0 (use 0 to disable disk persistence).');
86
- }
87
- this.maxDiskEvents = rawMaxDisk;
88
- const rawMaxQueue = (_b = options.maxQueueEvents) !== null && _b !== void 0 ? _b : MetaRouterAnalyticsClient.DEFAULT_MAX_QUEUE_EVENTS;
89
- const maxQueueEvents = Math.max(1, rawMaxQueue);
90
- if (this.maxDiskEvents > 0 && this.maxDiskEvents < maxQueueEvents) {
91
- warn(`maxDiskEvents (${this.maxDiskEvents}) is less than maxQueueEvents (${maxQueueEvents}) — memory can hold more events than disk can preserve; events may be dropped during background flush`);
128
+ // Same rules as the createAnalyticsClient gate, without logging: the
129
+ // gate already logged this call's warnings, and logging here would print
130
+ // every cleartext/clamp warning twice. Constructed directly (bypassing the
131
+ // gate), invalid options throw on every build type, like Android's direct
132
+ // client entry point — this path has no inert session to fall back to.
133
+ const { options: normalized, configError } = validateInitOptions(options, {
134
+ logWarnings: false,
135
+ });
136
+ if (configError) {
137
+ throw new Error(`Invalid InitOptions: ${configError.description}`);
92
138
  }
93
- setDebugLogging((_c = options.debug) !== null && _c !== void 0 ? _c : false);
139
+ this.ingestionHost = normalized.ingestionHost;
140
+ this.writeKey = normalized.writeKey;
141
+ this.flushIntervalSeconds = Math.max(1, (_a = normalized.flushIntervalSeconds) !== null && _a !== void 0 ? _a : 10);
142
+ this.maxDiskEvents = normalized.maxDiskEvents;
143
+ const maxQueueEvents = normalized.maxQueueEvents;
144
+ setDebugLogging((_b = options.debug) !== null && _b !== void 0 ? _b : false);
145
+ this.trackLifecycleEvents = (_c = options.trackLifecycleEvents) !== null && _c !== void 0 ? _c : false;
94
146
  this.identityManager = new IdentityManager();
95
147
  // Default: wrap the raw native monitor with the asymmetric debounce
96
148
  // (immediate offline, 2s stable-online). If a caller injects their own
@@ -168,6 +220,13 @@ export class MetaRouterAnalyticsClient {
168
220
  this.lifecycle = 'initializing';
169
221
  this.initPromise = (async () => {
170
222
  try {
223
+ // Must be read before identityManager.init(): init() generates and
224
+ // persists an anonymousId on first launch, so checking afterwards
225
+ // would make every fresh install look like an upgrade from a
226
+ // pre-lifecycle build and emit Updated(unknown) instead of Installed.
227
+ const hadIdentityBeforeInit = this.trackLifecycleEvents
228
+ ? await this.hasIdentityState()
229
+ : false;
171
230
  await this.identityManager.init();
172
231
  // Cheap existence check — memory queue starts empty. Any on-disk
173
232
  // events are drained directly to the network below (if online) via
@@ -178,8 +237,22 @@ export class MetaRouterAnalyticsClient {
178
237
  this.setupAppStateListener();
179
238
  // Load persisted advertising ID if available
180
239
  const persistedAdvertisingId = await getIdentityField(ADVERTISING_ID_KEY);
181
- this.context = await getContextInfo(persistedAdvertisingId || undefined);
240
+ this.appContext = loadAppContext();
241
+ this.context = await getContextInfo(this.appContext, persistedAdvertisingId || undefined);
242
+ if (this.trackLifecycleEvents) {
243
+ this.lifecycleEmitter = new LifecycleEmitter(this.dispatcher, (event, properties) => this.buildEnrichedEvent({
244
+ type: 'track',
245
+ event,
246
+ properties,
247
+ timestamp: this.now(),
248
+ }), this.appContext);
249
+ }
182
250
  this.lifecycle = 'ready';
251
+ // Lifecycle: detect install/update + capture deep link, then emit
252
+ // the cold-launch sequence. Runs after `ready` so the events carry
253
+ // the final identity/context, and before the network/disk drain
254
+ // block below so they join the first flush batch.
255
+ await this.runColdLaunchLifecycle(hadIdentityBeforeInit);
183
256
  // Set initial network state and subscribe to changes
184
257
  this.networkStatus = this.networkMonitor.currentStatus;
185
258
  this.unsubscribeNetwork = this.networkMonitor.onStatusChange((status) => {
@@ -251,6 +324,15 @@ export class MetaRouterAnalyticsClient {
251
324
  now() {
252
325
  return new Date().toISOString();
253
326
  }
327
+ /**
328
+ * Adds identity, writeKey, context and messageId to a raw event. Shared by
329
+ * enqueue() and the lifecycle emitter so both paths produce identical
330
+ * payloads.
331
+ */
332
+ buildEnrichedEvent(event) {
333
+ const eventWithIdentity = this.identityManager.addIdentityInfo(event);
334
+ return enrichEvent(eventWithIdentity, this.writeKey, this.context);
335
+ }
254
336
  /**
255
337
  * Enqueues an event for processing.
256
338
  * @param event - The event to enqueue.
@@ -260,9 +342,7 @@ export class MetaRouterAnalyticsClient {
260
342
  warn('Analytics client is not ready to operate');
261
343
  return;
262
344
  }
263
- const eventWithIdentity = this.identityManager.addIdentityInfo(event);
264
- const enrichedEvent = enrichEvent(eventWithIdentity, this.writeKey, this.context);
265
- this.dispatcher.enqueue(enrichedEvent);
345
+ this.dispatcher.enqueue(this.buildEnrichedEvent(event));
266
346
  // Check if we should flush to disk based on thresholds
267
347
  if (this.persistentQueue.shouldFlushToDisk()) {
268
348
  void this.persistentQueue.flushToDisk().catch((err) => {
@@ -287,6 +367,119 @@ export class MetaRouterAnalyticsClient {
287
367
  setupAppStateListener() {
288
368
  this.appStateSubscription = AppState.addEventListener('change', this.handleAppStateChange);
289
369
  }
370
+ /**
371
+ * Runs the cold-launch lifecycle sequence: detect install vs update vs
372
+ * neither, persist the current version/build, capture any cold-launch
373
+ * deep link, and (when the process is foregrounded) emit Application
374
+ * Opened with from_background=false.
375
+ *
376
+ * No-ops when trackLifecycleEvents is false.
377
+ *
378
+ * @param hadIdentityBeforeInit - Whether identity existed in storage before
379
+ * IdentityManager.init() ran on this launch (see init()).
380
+ */
381
+ async runColdLaunchLifecycle(hadIdentityBeforeInit) {
382
+ const emitter = this.lifecycleEmitter;
383
+ if (!emitter) {
384
+ return;
385
+ }
386
+ const { version, build } = this.appContext;
387
+ try {
388
+ const [storedVersion, storedBuild] = await Promise.all([
389
+ getLifecycleVersion(),
390
+ getLifecycleBuild(),
391
+ ]);
392
+ if (storedVersion == null && storedBuild == null) {
393
+ if (hadIdentityBeforeInit) {
394
+ emitter.emitUpdated({
395
+ version: UNKNOWN_PREVIOUS,
396
+ build: UNKNOWN_PREVIOUS,
397
+ });
398
+ }
399
+ else {
400
+ emitter.emitInstalled();
401
+ }
402
+ }
403
+ else if (storedVersion !== version || storedBuild !== build) {
404
+ emitter.emitUpdated({
405
+ version: storedVersion !== null && storedVersion !== void 0 ? storedVersion : UNKNOWN_PREVIOUS,
406
+ build: storedBuild !== null && storedBuild !== void 0 ? storedBuild : UNKNOWN_PREVIOUS,
407
+ });
408
+ }
409
+ await setLifecycleVersionBuild(version, build);
410
+ }
411
+ catch (err) {
412
+ warn('Lifecycle install/update detection failed:', err);
413
+ }
414
+ // Cold-launch Opened only fires when the process is in foreground.
415
+ // Background-launched processes (push, headless JS) defer to the next
416
+ // background→active transition.
417
+ if (AppState.currentState === 'active') {
418
+ emitter.emitOpened(false, this.consumePendingDeepLink());
419
+ }
420
+ else {
421
+ this.coldLaunchOpenDeferred = true;
422
+ }
423
+ }
424
+ /**
425
+ * True if any identity field is present in storage. Used to distinguish a
426
+ * fresh install from an existing user upgrading from a pre-lifecycle SDK
427
+ * build. Best-effort: failures are treated as "no identity state".
428
+ */
429
+ async hasIdentityState() {
430
+ try {
431
+ const [anon, user, group] = await Promise.all([
432
+ getIdentityField(ANONYMOUS_ID_KEY),
433
+ getIdentityField(USER_ID_KEY),
434
+ getIdentityField(GROUP_ID_KEY),
435
+ ]);
436
+ return !!(anon || user || group);
437
+ }
438
+ catch {
439
+ return false;
440
+ }
441
+ }
442
+ consumePendingDeepLink() {
443
+ if (!this.pendingDeepLink)
444
+ return undefined;
445
+ const dl = this.pendingDeepLink;
446
+ this.pendingDeepLink = null;
447
+ return dl;
448
+ }
449
+ /**
450
+ * Forward a URL the host received (e.g. from `Linking.getInitialURL`,
451
+ * `Linking.addEventListener('url', ...)`, a UIScene URL handler, or an
452
+ * Android Intent) so it is attached to the next `Application Opened`
453
+ * event as `url` (and `referring_application` if `sourceApplication`
454
+ * is provided). One-shot — the buffer is cleared on the next Opened
455
+ * emit. Last-write-wins if called multiple times before the next Opened.
456
+ *
457
+ * The SDK never reads `Linking` itself: deep links routinely carry auth
458
+ * tokens and OTPs, and an automatic capture would race the host's own
459
+ * sanitized forward for the same one-slot buffer. Only what the host
460
+ * passes here reaches the event (parity with iOS recordOpenedURL and
461
+ * Android recordOpenedUrl).
462
+ *
463
+ * No-op with an always-on warning when `trackLifecycleEvents` is
464
+ * disabled — silent no-ops are bad DX, hosts wiring this up should know
465
+ * they have the feature flag off.
466
+ */
467
+ recordOpenedURL(url, sourceApplication) {
468
+ // Gated on the option, not the emitter: the emitter is null until init()
469
+ // builds it and again after reset(), and in those windows the
470
+ // "disabled" warning would be wrong.
471
+ if (!this.trackLifecycleEvents) {
472
+ warn('recordOpenedURL called but trackLifecycleEvents is disabled — buffered URL ignored. Set trackLifecycleEvents: true in InitOptions to enable.');
473
+ return;
474
+ }
475
+ if (!url || typeof url !== 'string') {
476
+ warn('recordOpenedURL called with invalid url — ignored');
477
+ return;
478
+ }
479
+ this.pendingDeepLink = sourceApplication
480
+ ? { url, referringApplication: sourceApplication }
481
+ : { url };
482
+ }
290
483
  /**
291
484
  * Tracks an event.
292
485
  * @param event - The event to track.
@@ -372,7 +565,7 @@ export class MetaRouterAnalyticsClient {
372
565
  log('Setting advertising ID');
373
566
  await setIdentityField(ADVERTISING_ID_KEY, advertisingId);
374
567
  clearContextCache();
375
- this.context = await getContextInfo(advertisingId);
568
+ this.context = await getContextInfo(this.appContext, advertisingId);
376
569
  log('Advertising ID updated, persisted, and context refreshed');
377
570
  }
378
571
  /**
@@ -390,7 +583,7 @@ export class MetaRouterAnalyticsClient {
390
583
  log('Clearing advertising ID');
391
584
  await removeIdentityField(ADVERTISING_ID_KEY);
392
585
  clearContextCache();
393
- this.context = await getContextInfo();
586
+ this.context = await getContextInfo(this.appContext);
394
587
  log('Advertising ID cleared from storage and context');
395
588
  }
396
589
  /**
@@ -481,6 +674,10 @@ export class MetaRouterAnalyticsClient {
481
674
  this.dispatcher.stop();
482
675
  (_c = (_b = this.appStateSubscription) === null || _b === void 0 ? void 0 : _b.remove) === null || _c === void 0 ? void 0 : _c.call(_b);
483
676
  this.appStateSubscription = null;
677
+ this.pendingDeepLink = null;
678
+ this.coldLaunchOpenDeferred = false;
679
+ this.wasBackgrounded = false;
680
+ this.lifecycleEmitter = null;
484
681
  this.dispatcher.reset();
485
682
  await this.persistentQueue.deleteSnapshot();
486
683
  // Clear identity (must remove persisted IDs)
@@ -496,8 +693,6 @@ export class MetaRouterAnalyticsClient {
496
693
  }
497
694
  }
498
695
  MetaRouterAnalyticsClient.AUTO_FLUSH_THRESHOLD = 20;
499
- MetaRouterAnalyticsClient.DEFAULT_MAX_QUEUE_EVENTS = 2000;
500
- MetaRouterAnalyticsClient.DEFAULT_MAX_DISK_EVENTS = 10000;
501
696
  // Byte cap is intentionally internal (parity with iOS/Android). Not a
502
697
  // public option. 5MB — revisit only if a customer actually needs to tune.
503
698
  MetaRouterAnalyticsClient.MAX_QUEUE_BYTES = 5 * 1024 * 1024;
@@ -1,3 +1,10 @@
1
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,CA2CpB"}
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"}
@@ -1,43 +1,203 @@
1
1
  import { MetaRouterAnalyticsClient } from './MetaRouterAnalyticsClient';
2
- import { proxyClient, setRealClient } from './proxy/proxyClient';
3
- // Only one initialization in flight
4
- let initPromise = null;
2
+ import { clearConfigDisabled, markConfigDisabled, proxyClient, setInitializingClient, setRealClient, setResetHandler, takePendingOpenedURLs, } from './proxy/proxyClient';
3
+ import { validateInitOptions } from './utils/initOptions';
4
+ /*
5
+ * Session choreography. Init, disable and reset work runs strictly FIFO on
6
+ * `workChain`, and the flags below follow one rule (the one the Android SDK
7
+ * settled on after its review): flags are written only when work is queued,
8
+ * synchronously in the public call; state changes only when the queued work
9
+ * runs; running work never writes flags. Writing a flag at execution time lets
10
+ * work queued earlier overwrite a decision made by a later call — e.g. an init
11
+ * finishing after a reset was queued would mark the session started again,
12
+ * and the next createAnalyticsClient would silently return an unbound proxy.
13
+ * The single exception is the rollback after a failed init (see runInit).
14
+ */
15
+ let initializationStarted = false;
16
+ let sessionRefused = false;
5
17
  let currentOptions = null;
18
+ // Bumped on every createAnalyticsClient / reset decision, at enqueue time. A
19
+ // queued disable compares it when it runs: if a later call has been made since,
20
+ // the refusal is already superseded (read, never written, at execution time).
21
+ let decisionCount = 0;
22
+ let workChain = Promise.resolve();
23
+ let activeClient = null;
24
+ /**
25
+ * Whether this is a development build. Injectable so tests can exercise the
26
+ * release path; production reads React Native's `__DEV__`.
27
+ */
28
+ export const buildConfig = {
29
+ isDevelopmentBuild: () => typeof __DEV__ !== 'undefined' && __DEV__ === true,
30
+ };
31
+ // For fire-and-forget enqueues: the runners catch everything today, but a
32
+ // future throw must not surface as an unhandled rejection in the host.
33
+ const ignoreFailure = () => { };
34
+ function enqueue(work) {
35
+ const run = workChain.then(work);
36
+ // The chain itself must survive a failed step; callers that await the
37
+ // returned promise still see the failure.
38
+ workChain = run.catch(() => { });
39
+ return run;
40
+ }
41
+ /**
42
+ * The config gate. Development builds fail fast with a throw (a red screen at
43
+ * the call site); release builds log an always-on error, call `onConfigError`
44
+ * synchronously and leave the SDK inert for the session — a misconfigured SDK
45
+ * must never take down the host app. Returns false when the session is refused.
46
+ */
47
+ function passesConfigGate(options, configError) {
48
+ var _a;
49
+ if (configError === null)
50
+ return true;
51
+ const { description } = configError;
52
+ if (buildConfig.isDevelopmentBuild()) {
53
+ throw new Error(`Invalid InitOptions: ${description}`);
54
+ }
55
+ console.error(`[MetaRouter] MetaRouter disabled for this session — ${description}`);
56
+ (_a = options.onConfigError) === null || _a === void 0 ? void 0 : _a.call(options, configError);
57
+ return false;
58
+ }
6
59
  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
- }
13
- if (!initPromise) {
14
- currentOptions = options;
15
- initPromise = (async () => {
16
- const instance = new MetaRouterAnalyticsClient(options);
17
- await instance.init();
18
- const boundClient = {
19
- track: (event, props) => instance.track(event, props),
20
- identify: (userId, traits) => instance.identify(userId, traits),
21
- group: (groupId, traits) => instance.group(groupId, traits),
22
- screen: (name, props) => instance.screen(name, props),
23
- page: (name, props) => instance.page(name, props),
24
- alias: (newUserId) => instance.alias(newUserId),
25
- setAdvertisingId: (advertisingId) => instance.setAdvertisingId(advertisingId),
26
- clearAdvertisingId: () => instance.clearAdvertisingId(),
27
- setTracing: (enabled) => instance.setTracing(enabled),
28
- enableDebugLogging: () => instance.enableDebugLogging(),
29
- getDebugInfo: () => instance.getDebugInfo(),
30
- getAnonymousId: () => instance.getAnonymousId(),
31
- flush: () => instance.flush(),
32
- reset: async () => {
33
- await instance.reset();
34
- setRealClient(null, { dropPending: true });
35
- initPromise = null;
36
- currentOptions = null;
37
- },
38
- };
39
- setRealClient(boundClient);
40
- })();
60
+ const { options: normalized, configError } = validateInitOptions(options);
61
+ if (!passesConfigGate(options, configError)) {
62
+ // An invalid call disables the whole session, even over a running valid
63
+ // client: keeping the stale client would mask the config error.
64
+ initializationStarted = true;
65
+ sessionRefused = true;
66
+ currentOptions = null;
67
+ const { description } = configError;
68
+ const decision = ++decisionCount;
69
+ enqueue(() => runDisable(description, decision)).catch(ignoreFailure);
70
+ return proxyClient;
41
71
  }
72
+ if (initializationStarted && !sessionRefused) {
73
+ if (currentOptions &&
74
+ JSON.stringify(currentOptions) !== JSON.stringify(normalized)) {
75
+ console.warn('[MetaRouter] Config changed but client not reset. Call await client.reset() before reinitializing with new options.');
76
+ }
77
+ return proxyClient;
78
+ }
79
+ // First init, or the one valid call that recovers a refused session. The
80
+ // refusal is lifted now, not when the init runs: calls made right after
81
+ // this one (getAnonymousId above all) must wait for the incoming session
82
+ // instead of resolving against the old verdict.
83
+ initializationStarted = true;
84
+ sessionRefused = false;
85
+ currentOptions = normalized;
86
+ clearConfigDisabled();
87
+ const decision = ++decisionCount;
88
+ enqueue(() => runInit(normalized, decision)).catch(ignoreFailure);
42
89
  return proxyClient;
43
90
  }
91
+ async function runInit(options, decision) {
92
+ // Unreachable today: every path that queues an init has a disable or reset
93
+ // queued ahead of it, or no bound client at all. Kept so a future path that
94
+ // breaks that invariant leaves the bound client alone instead of orphaning
95
+ // it with its flush loop still running.
96
+ if (activeClient)
97
+ return;
98
+ clearConfigDisabled();
99
+ let instance;
100
+ try {
101
+ instance = new MetaRouterAnalyticsClient(options);
102
+ for (const args of takePendingOpenedURLs()) {
103
+ instance.recordOpenedURL(...args);
104
+ }
105
+ setInitializingClient(instance);
106
+ await instance.init();
107
+ }
108
+ catch (err) {
109
+ console.error('[MetaRouter] Initialization failed:', err);
110
+ // The one execution-time flag write: restores retryability so the next
111
+ // createAnalyticsClient can try again. Skipped when a later call was made
112
+ // after this init was queued — that call's decision (a reset, another
113
+ // init, a refusal) is newer and must not be overwritten.
114
+ if (decision === decisionCount) {
115
+ initializationStarted = false;
116
+ currentOptions = null;
117
+ }
118
+ return;
119
+ }
120
+ finally {
121
+ setInitializingClient(null);
122
+ }
123
+ activeClient = instance;
124
+ setRealClient(bindClient(instance));
125
+ }
126
+ async function runDisable(description, decision) {
127
+ const previous = activeClient;
128
+ activeClient = null;
129
+ // Reset rather than drop the old client: dropped live, its dispatcher would
130
+ // keep flushing, and a disabled session must not send events.
131
+ await resetQuietly(previous);
132
+ if (decision !== decisionCount) {
133
+ // A valid init (or a reset) was requested after this refusal and is
134
+ // queued behind it. Unbind, but keep pending calls — a getAnonymousId
135
+ // made after that later call must resolve against the incoming session,
136
+ // not against this superseded verdict.
137
+ setRealClient(null);
138
+ return;
139
+ }
140
+ markConfigDisabled(description);
141
+ }
142
+ async function runReset(decision) {
143
+ const previous = activeClient;
144
+ activeClient = null;
145
+ await resetQuietly(previous);
146
+ if (decision !== decisionCount) {
147
+ // A createAnalyticsClient came after this reset and is queued behind it:
148
+ // calls made since belong to that incoming session, so they wait for its
149
+ // bind instead of being dropped (or, for promises, rejected) here.
150
+ setRealClient(null);
151
+ return;
152
+ }
153
+ setRealClient(null, { dropPending: true });
154
+ }
155
+ /**
156
+ * Resets a client being torn down. A failure (e.g. a storage error while
157
+ * deleting the snapshot) is logged, not thrown: the unbind or refusal that
158
+ * follows must still happen, or the proxy stays bound to a half-reset client.
159
+ */
160
+ async function resetQuietly(client) {
161
+ if (!client)
162
+ return;
163
+ try {
164
+ await client.reset();
165
+ }
166
+ catch (err) {
167
+ console.error('[MetaRouter] Reset of the previous client failed:', err);
168
+ }
169
+ }
170
+ /**
171
+ * `reset()` from the public API, in any state: flags clear now, the teardown
172
+ * runs in order behind anything already queued. A createAnalyticsClient issued
173
+ * right after (even without awaiting) queues a real init behind it.
174
+ */
175
+ function resetSession() {
176
+ if (!initializationStarted)
177
+ return Promise.resolve();
178
+ initializationStarted = false;
179
+ sessionRefused = false;
180
+ currentOptions = null;
181
+ const decision = ++decisionCount;
182
+ return enqueue(() => runReset(decision));
183
+ }
184
+ setResetHandler(resetSession);
185
+ function bindClient(instance) {
186
+ return {
187
+ track: (event, props) => instance.track(event, props),
188
+ identify: (userId, traits) => instance.identify(userId, traits),
189
+ group: (groupId, traits) => instance.group(groupId, traits),
190
+ screen: (name, props) => instance.screen(name, props),
191
+ page: (name, props) => instance.page(name, props),
192
+ alias: (newUserId) => instance.alias(newUserId),
193
+ recordOpenedURL: (url, sourceApplication) => instance.recordOpenedURL(url, sourceApplication),
194
+ setAdvertisingId: (advertisingId) => instance.setAdvertisingId(advertisingId),
195
+ clearAdvertisingId: () => instance.clearAdvertisingId(),
196
+ setTracing: (enabled) => instance.setTracing(enabled),
197
+ enableDebugLogging: () => instance.enableDebugLogging(),
198
+ getDebugInfo: () => instance.getDebugInfo(),
199
+ getAnonymousId: () => instance.getAnonymousId(),
200
+ flush: () => instance.flush(),
201
+ reset: () => resetSession(),
202
+ };
203
+ }