@metarouter/react-native-sdk 1.5.1 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +190 -60
- package/android/build.gradle +41 -0
- package/android/src/main/AndroidManifest.xml +4 -0
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterNetworkMonitorModule.kt +119 -0
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterPackage.kt +23 -0
- package/android/src/main/java/com/metarouter/reactnative/MetaRouterQueueStorageModule.kt +124 -0
- package/ios/MetaRouterNetworkMonitor.m +76 -0
- package/ios/MetaRouterQueueStorage.m +127 -0
- package/lib/analytics/MetaRouterAnalyticsClient.d.ts +71 -4
- package/lib/analytics/MetaRouterAnalyticsClient.d.ts.map +1 -1
- package/lib/analytics/MetaRouterAnalyticsClient.js +396 -112
- package/lib/analytics/dispatcher.d.ts +57 -1
- package/lib/analytics/dispatcher.d.ts.map +1 -1
- package/lib/analytics/dispatcher.js +231 -32
- package/lib/analytics/init.d.ts +8 -1
- package/lib/analytics/init.d.ts.map +1 -1
- package/lib/analytics/init.js +198 -37
- package/lib/analytics/lifecycle/lifecycleEvents.d.ts +52 -0
- package/lib/analytics/lifecycle/lifecycleEvents.d.ts.map +1 -0
- package/lib/analytics/lifecycle/lifecycleEvents.js +66 -0
- package/lib/analytics/persistence/NativeQueueStorage.d.ts +5 -0
- package/lib/analytics/persistence/NativeQueueStorage.d.ts.map +1 -0
- package/lib/analytics/persistence/NativeQueueStorage.js +59 -0
- package/lib/analytics/persistence/PersistentEventQueue.d.ts +96 -0
- package/lib/analytics/persistence/PersistentEventQueue.d.ts.map +1 -0
- package/lib/analytics/persistence/PersistentEventQueue.js +401 -0
- package/lib/analytics/persistence/types.d.ts +20 -0
- package/lib/analytics/persistence/types.d.ts.map +1 -0
- package/lib/analytics/persistence/types.js +10 -0
- package/lib/analytics/proxy/proxyClient.d.ts +30 -1
- package/lib/analytics/proxy/proxyClient.d.ts.map +1 -1
- package/lib/analytics/proxy/proxyClient.js +145 -23
- package/lib/analytics/types.d.ts +61 -4
- package/lib/analytics/types.d.ts.map +1 -1
- package/lib/analytics/utils/appContext.d.ts +20 -0
- package/lib/analytics/utils/appContext.d.ts.map +1 -0
- package/lib/analytics/utils/appContext.js +22 -0
- package/lib/analytics/utils/circuitBreaker.d.ts +4 -1
- package/lib/analytics/utils/circuitBreaker.d.ts.map +1 -1
- package/lib/analytics/utils/circuitBreaker.js +23 -14
- package/lib/analytics/utils/contextInfo.d.ts +8 -4
- package/lib/analytics/utils/contextInfo.d.ts.map +1 -1
- package/lib/analytics/utils/contextInfo.js +34 -27
- package/lib/analytics/utils/debouncedNetworkMonitor.d.ts +25 -0
- package/lib/analytics/utils/debouncedNetworkMonitor.d.ts.map +1 -0
- package/lib/analytics/utils/debouncedNetworkMonitor.js +68 -0
- package/lib/analytics/utils/initOptions.d.ts +22 -0
- package/lib/analytics/utils/initOptions.d.ts.map +1 -0
- package/lib/analytics/utils/initOptions.js +100 -0
- package/lib/analytics/utils/lifecycleStorage.d.ts +13 -0
- package/lib/analytics/utils/lifecycleStorage.d.ts.map +1 -0
- package/lib/analytics/utils/lifecycleStorage.js +35 -0
- package/lib/analytics/utils/networkMonitor.d.ts +30 -0
- package/lib/analytics/utils/networkMonitor.d.ts.map +1 -0
- package/lib/analytics/utils/networkMonitor.js +90 -0
- package/lib/analytics/utils/responseCategory.d.ts +14 -0
- package/lib/analytics/utils/responseCategory.d.ts.map +1 -0
- package/lib/analytics/utils/responseCategory.js +26 -0
- package/lib/index.d.ts +4 -4
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +3 -3
- package/metarouter-react-native-sdk.podspec +19 -0
- package/package.json +6 -3
- package/react-native.config.js +15 -0
|
@@ -1,11 +1,18 @@
|
|
|
1
|
-
import { AppState } from
|
|
2
|
-
import { log, setDebugLogging, warn, error } from
|
|
3
|
-
import { IdentityManager } from
|
|
4
|
-
import { enrichEvent } from
|
|
5
|
-
import { getContextInfo, clearContextCache } from
|
|
6
|
-
import {
|
|
7
|
-
import
|
|
8
|
-
import
|
|
1
|
+
import { AppState } from 'react-native';
|
|
2
|
+
import { log, setDebugLogging, warn, error } from './utils/logger';
|
|
3
|
+
import { IdentityManager } from './IdentityManager';
|
|
4
|
+
import { enrichEvent } from './utils/enrichEvent';
|
|
5
|
+
import { getContextInfo, clearContextCache } from './utils/contextInfo';
|
|
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';
|
|
10
|
+
import CircuitBreaker from './utils/circuitBreaker';
|
|
11
|
+
import Dispatcher from './dispatcher';
|
|
12
|
+
import { PersistentEventQueue } from './persistence/PersistentEventQueue';
|
|
13
|
+
import { NetworkMonitor, } from './utils/networkMonitor';
|
|
14
|
+
import { DebouncedNetworkMonitor } from './utils/debouncedNetworkMonitor';
|
|
15
|
+
import { DEFAULT_MAX_DISK_EVENTS, validateInitOptions, } from './utils/initOptions';
|
|
9
16
|
/**
|
|
10
17
|
* Analytics client for MetaRouter.
|
|
11
18
|
* - Handles event queueing, batching, and delivery with retries.
|
|
@@ -18,66 +25,145 @@ export class MetaRouterAnalyticsClient {
|
|
|
18
25
|
* Initializes the analytics client with the provided options.
|
|
19
26
|
* @param options - The initialization options.
|
|
20
27
|
*/
|
|
21
|
-
constructor(options) {
|
|
22
|
-
var _a, _b;
|
|
23
|
-
this.lifecycle =
|
|
28
|
+
constructor(options, deps) {
|
|
29
|
+
var _a, _b, _c, _d;
|
|
30
|
+
this.lifecycle = 'idle';
|
|
24
31
|
this.initPromise = null;
|
|
25
32
|
this.queue = [];
|
|
26
33
|
this.flushIntervalSeconds = 10;
|
|
27
34
|
this.appState = AppState.currentState;
|
|
28
35
|
this.appStateSubscription = null;
|
|
29
|
-
this.
|
|
36
|
+
this.maxDiskEvents = DEFAULT_MAX_DISK_EVENTS;
|
|
30
37
|
this.tracingEnabled = false;
|
|
38
|
+
this.networkStatus = 'connected';
|
|
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;
|
|
31
58
|
/**
|
|
32
59
|
* Handles the app state change event.
|
|
33
60
|
* @param nextState - The new app state.
|
|
34
61
|
*/
|
|
35
|
-
this.handleAppStateChange = (nextState) => {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
62
|
+
this.handleAppStateChange = async (nextState) => {
|
|
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) {
|
|
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
|
+
}
|
|
89
|
+
this.stopFlushLoop();
|
|
90
|
+
this.clearNextTimer();
|
|
91
|
+
try {
|
|
92
|
+
await this.flush();
|
|
93
|
+
await this.persistentQueue.flushToDisk();
|
|
94
|
+
await this.persistentQueue.flushPendingDiskWrites();
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
warn('Failed to persist queue while moving to background:', err);
|
|
98
|
+
}
|
|
40
99
|
}
|
|
41
|
-
|
|
42
|
-
|
|
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
|
+
}
|
|
108
|
+
if (nextState === 'active' && this.lifecycle === 'ready') {
|
|
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
|
+
}
|
|
124
|
+
this.startFlushLoop();
|
|
43
125
|
this.flush();
|
|
44
126
|
}
|
|
45
|
-
this.appState = nextState;
|
|
46
127
|
};
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
// eslint-disable-next-line no-new
|
|
58
|
-
new URL(ingestionHost);
|
|
59
|
-
if (ingestionHost.endsWith("/")) {
|
|
60
|
-
throw new Error();
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
catch {
|
|
64
|
-
throw new Error("MetaRouterAnalyticsClient initialization failed: `ingestionHost` must be a valid URL and not end in a slash.");
|
|
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}`);
|
|
65
138
|
}
|
|
66
|
-
this.ingestionHost = ingestionHost;
|
|
67
|
-
this.writeKey = writeKey;
|
|
68
|
-
this.flushIntervalSeconds = flushIntervalSeconds !== null &&
|
|
69
|
-
|
|
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;
|
|
70
146
|
this.identityManager = new IdentityManager();
|
|
71
|
-
|
|
147
|
+
// Default: wrap the raw native monitor with the asymmetric debounce
|
|
148
|
+
// (immediate offline, 2s stable-online). If a caller injects their own
|
|
149
|
+
// monitor (e.g. in tests), use it as-is so they control the debounce
|
|
150
|
+
// behavior explicitly.
|
|
151
|
+
this.networkMonitor =
|
|
152
|
+
(_d = deps === null || deps === void 0 ? void 0 : deps.networkMonitor) !== null && _d !== void 0 ? _d : new DebouncedNetworkMonitor(new NetworkMonitor());
|
|
72
153
|
this.dispatcher = new Dispatcher({
|
|
73
|
-
|
|
74
|
-
|
|
154
|
+
maxEventCount: maxQueueEvents,
|
|
155
|
+
maxQueueBytes: MetaRouterAnalyticsClient.MAX_QUEUE_BYTES,
|
|
156
|
+
autoFlushThreshold: MetaRouterAnalyticsClient.AUTO_FLUSH_THRESHOLD,
|
|
75
157
|
maxBatchSize: 100,
|
|
76
158
|
flushIntervalSeconds: this.flushIntervalSeconds,
|
|
159
|
+
baseRetryDelayMs: 1000,
|
|
160
|
+
maxRetryDelayMs: 8000,
|
|
161
|
+
isPersistenceEnabled: () => this.maxDiskEvents > 0,
|
|
162
|
+
isNetworkAvailable: () => this.networkStatus === 'connected',
|
|
77
163
|
endpoint: (path) => this.endpoint(path),
|
|
78
164
|
fetchWithTimeout: (url, init, timeoutMs) => this.fetchWithTimeout(url, init, timeoutMs),
|
|
79
|
-
canSend: () => this.lifecycle ===
|
|
80
|
-
isOperational: () => this.lifecycle ===
|
|
165
|
+
canSend: () => this.lifecycle === 'ready' && !!this.identityManager.getAnonymousId(),
|
|
166
|
+
isOperational: () => this.lifecycle === 'ready',
|
|
81
167
|
isTracingEnabled: () => this.tracingEnabled,
|
|
82
168
|
createBreaker: () => new CircuitBreaker({
|
|
83
169
|
failureThreshold: 3,
|
|
@@ -89,68 +175,120 @@ export class MetaRouterAnalyticsClient {
|
|
|
89
175
|
log(`[MetaRouter] Circuit ${prev} → ${next}` +
|
|
90
176
|
(meta.cooldownMs != null
|
|
91
177
|
? ` (cooldown=${meta.cooldownMs}ms)`
|
|
92
|
-
:
|
|
178
|
+
: ''), { failures: meta.failures, openCount: meta.openCount });
|
|
93
179
|
},
|
|
94
180
|
}),
|
|
95
181
|
log,
|
|
96
182
|
warn,
|
|
97
183
|
error,
|
|
184
|
+
onCapacityOverflow: (events) => this.persistentQueue.bufferEventsForDisk(events),
|
|
185
|
+
onFlushToDisk: (events) => this.persistentQueue.flushEventsToDisk(events),
|
|
186
|
+
onFlushComplete: () => {
|
|
187
|
+
if (this.networkStatus === 'connected') {
|
|
188
|
+
void this.persistentQueue.drainDiskToNetwork(this.dispatcher);
|
|
189
|
+
}
|
|
190
|
+
},
|
|
98
191
|
onScheduleFlushIn: (ms) => {
|
|
99
192
|
this.scheduleFlushIn(ms, { fromDispatcher: true });
|
|
100
193
|
},
|
|
101
194
|
onFatalConfig: () => {
|
|
102
|
-
this.lifecycle =
|
|
195
|
+
this.lifecycle = 'disabled';
|
|
103
196
|
},
|
|
104
197
|
});
|
|
105
198
|
this.queue = this.dispatcher.getQueueRef();
|
|
106
|
-
|
|
199
|
+
this.persistentQueue = new PersistentEventQueue(this.dispatcher, {
|
|
200
|
+
maxDiskEvents: this.maxDiskEvents,
|
|
201
|
+
});
|
|
107
202
|
}
|
|
108
203
|
/**
|
|
109
204
|
* Initializes the analytics client.
|
|
110
205
|
* @returns A promise that resolves when the client is initialized.
|
|
111
206
|
*/
|
|
112
207
|
async init() {
|
|
113
|
-
if (this.lifecycle ===
|
|
114
|
-
log(
|
|
208
|
+
if (this.lifecycle === 'ready') {
|
|
209
|
+
log('Analytics client already ready');
|
|
115
210
|
return;
|
|
116
211
|
}
|
|
117
|
-
if (this.lifecycle ===
|
|
118
|
-
log(
|
|
212
|
+
if (this.lifecycle === 'initializing' && this.initPromise) {
|
|
213
|
+
log('Analytics client initialization already in-flight');
|
|
119
214
|
return this.initPromise;
|
|
120
215
|
}
|
|
121
|
-
if (this.lifecycle ===
|
|
122
|
-
warn(
|
|
216
|
+
if (this.lifecycle === 'disabled') {
|
|
217
|
+
warn('Analytics client is disabled — init skipped');
|
|
123
218
|
return;
|
|
124
219
|
}
|
|
125
|
-
this.lifecycle =
|
|
126
|
-
log("Starting analytics client initialization...");
|
|
220
|
+
this.lifecycle = 'initializing';
|
|
127
221
|
this.initPromise = (async () => {
|
|
128
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;
|
|
129
230
|
await this.identityManager.init();
|
|
130
|
-
|
|
231
|
+
// Cheap existence check — memory queue starts empty. Any on-disk
|
|
232
|
+
// events are drained directly to the network below (if online) via
|
|
233
|
+
// drainDiskToNetwork, avoiding a memory spike from rehydrating a
|
|
234
|
+
// potentially-large backlog.
|
|
235
|
+
await this.persistentQueue.checkForPersistedEvents();
|
|
131
236
|
this.startFlushLoop();
|
|
132
|
-
log("Flush loop started with interval:", this.flushIntervalSeconds, "seconds");
|
|
133
237
|
this.setupAppStateListener();
|
|
134
|
-
log("App state listener setup completed");
|
|
135
238
|
// Load persisted advertising ID if available
|
|
136
239
|
const persistedAdvertisingId = await getIdentityField(ADVERTISING_ID_KEY);
|
|
137
|
-
this.
|
|
138
|
-
|
|
139
|
-
|
|
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
|
+
}
|
|
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);
|
|
256
|
+
// Set initial network state and subscribe to changes
|
|
257
|
+
this.networkStatus = this.networkMonitor.currentStatus;
|
|
258
|
+
this.unsubscribeNetwork = this.networkMonitor.onStatusChange((status) => {
|
|
259
|
+
const wasOffline = this.networkStatus === 'disconnected';
|
|
260
|
+
this.networkStatus = status;
|
|
261
|
+
log(`Network status changed: ${wasOffline ? 'disconnected' : 'connected'} -> ${status}`);
|
|
262
|
+
if (wasOffline && status === 'connected') {
|
|
263
|
+
log('Dispatcher resumed — device is online, triggering flush');
|
|
264
|
+
this.dispatcher.resetCircuitBreaker();
|
|
265
|
+
// (1) Memory queue → network (existing path)
|
|
266
|
+
void this.flush();
|
|
267
|
+
// (2) Disk → network directly (no load into memory queue)
|
|
268
|
+
void this.persistentQueue.drainDiskToNetwork(this.dispatcher);
|
|
269
|
+
}
|
|
270
|
+
else if (status === 'disconnected') {
|
|
271
|
+
log('Dispatcher paused — device is offline');
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
log('MetaRouter SDK initialized');
|
|
275
|
+
// If online at launch with on-disk events, drain them to the network.
|
|
276
|
+
// Memory queue starts empty, so there's no cold-start flush to run.
|
|
277
|
+
if (this.networkStatus === 'connected' &&
|
|
278
|
+
this.persistentQueue.hasDiskData) {
|
|
279
|
+
void this.persistentQueue.drainDiskToNetwork(this.dispatcher);
|
|
140
280
|
}
|
|
141
|
-
this.lifecycle = "ready";
|
|
142
|
-
log("Analytics client initialization completed successfully");
|
|
143
281
|
}
|
|
144
282
|
catch (error) {
|
|
145
|
-
this.lifecycle =
|
|
146
|
-
warn(
|
|
283
|
+
this.lifecycle = 'idle'; // allow retry
|
|
284
|
+
warn('Analytics client initialization failed:', error);
|
|
147
285
|
throw error;
|
|
148
286
|
}
|
|
149
287
|
})();
|
|
150
288
|
return this.initPromise;
|
|
151
289
|
}
|
|
152
290
|
endpoint(path) {
|
|
153
|
-
return `${this.ingestionHost}${path.startsWith(
|
|
291
|
+
return `${this.ingestionHost}${path.startsWith('/') ? path : `/${path}`}`;
|
|
154
292
|
}
|
|
155
293
|
/**
|
|
156
294
|
* Starts the flush loop.
|
|
@@ -159,7 +297,7 @@ export class MetaRouterAnalyticsClient {
|
|
|
159
297
|
this.dispatcher.start();
|
|
160
298
|
}
|
|
161
299
|
isReady() {
|
|
162
|
-
return this.lifecycle ===
|
|
300
|
+
return this.lifecycle === 'ready';
|
|
163
301
|
}
|
|
164
302
|
/**
|
|
165
303
|
* Fetches with a timeout.
|
|
@@ -186,18 +324,31 @@ export class MetaRouterAnalyticsClient {
|
|
|
186
324
|
now() {
|
|
187
325
|
return new Date().toISOString();
|
|
188
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
|
+
}
|
|
189
336
|
/**
|
|
190
337
|
* Enqueues an event for processing.
|
|
191
338
|
* @param event - The event to enqueue.
|
|
192
339
|
*/
|
|
193
340
|
enqueue(event) {
|
|
194
341
|
if (!this.isReady()) {
|
|
195
|
-
warn(
|
|
342
|
+
warn('Analytics client is not ready to operate');
|
|
196
343
|
return;
|
|
197
344
|
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
this.
|
|
345
|
+
this.dispatcher.enqueue(this.buildEnrichedEvent(event));
|
|
346
|
+
// Check if we should flush to disk based on thresholds
|
|
347
|
+
if (this.persistentQueue.shouldFlushToDisk()) {
|
|
348
|
+
void this.persistentQueue.flushToDisk().catch((err) => {
|
|
349
|
+
warn('Failed to flush queue to disk after threshold:', err);
|
|
350
|
+
});
|
|
351
|
+
}
|
|
201
352
|
}
|
|
202
353
|
scheduleFlushIn(ms, opts) {
|
|
203
354
|
if (opts === null || opts === void 0 ? void 0 : opts.fromDispatcher)
|
|
@@ -214,7 +365,120 @@ export class MetaRouterAnalyticsClient {
|
|
|
214
365
|
* Sets up the app state listener.
|
|
215
366
|
*/
|
|
216
367
|
setupAppStateListener() {
|
|
217
|
-
this.appStateSubscription = AppState.addEventListener(
|
|
368
|
+
this.appStateSubscription = AppState.addEventListener('change', this.handleAppStateChange);
|
|
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 };
|
|
218
482
|
}
|
|
219
483
|
/**
|
|
220
484
|
* Tracks an event.
|
|
@@ -222,9 +486,7 @@ export class MetaRouterAnalyticsClient {
|
|
|
222
486
|
* @param properties - The properties to track.
|
|
223
487
|
*/
|
|
224
488
|
track(event, properties) {
|
|
225
|
-
|
|
226
|
-
this.enqueue({ type: "track", event, properties, timestamp: this.now() });
|
|
227
|
-
log("Event enqueued, queue length:", this.queue.length);
|
|
489
|
+
this.enqueue({ type: 'track', event, properties, timestamp: this.now() });
|
|
228
490
|
}
|
|
229
491
|
/**
|
|
230
492
|
* Identifies a user.
|
|
@@ -232,10 +494,8 @@ export class MetaRouterAnalyticsClient {
|
|
|
232
494
|
* @param traits - The traits to identify the user with.
|
|
233
495
|
*/
|
|
234
496
|
identify(userId, traits) {
|
|
235
|
-
log("Identifying user:", userId, "with traits:", traits);
|
|
236
497
|
this.identityManager.identify(userId);
|
|
237
|
-
this.enqueue({ type:
|
|
238
|
-
log("Identify event enqueued, queue length:", this.queue.length);
|
|
498
|
+
this.enqueue({ type: 'identify', userId, traits, timestamp: this.now() });
|
|
239
499
|
}
|
|
240
500
|
/**
|
|
241
501
|
* Tracks a page view.
|
|
@@ -243,14 +503,12 @@ export class MetaRouterAnalyticsClient {
|
|
|
243
503
|
* @param properties - The properties to track.
|
|
244
504
|
*/
|
|
245
505
|
page(name, properties) {
|
|
246
|
-
log("Tracking page:", name, "with properties:", properties);
|
|
247
506
|
this.enqueue({
|
|
248
|
-
type:
|
|
507
|
+
type: 'page',
|
|
249
508
|
event: name,
|
|
250
509
|
properties,
|
|
251
510
|
timestamp: this.now(),
|
|
252
511
|
});
|
|
253
|
-
log("Page event enqueued, queue length:", this.queue.length);
|
|
254
512
|
}
|
|
255
513
|
/**
|
|
256
514
|
* Groups a user.
|
|
@@ -258,10 +516,8 @@ export class MetaRouterAnalyticsClient {
|
|
|
258
516
|
* @param traits - The traits to group the user with.
|
|
259
517
|
*/
|
|
260
518
|
group(groupId, traits) {
|
|
261
|
-
log("Grouping user:", groupId, "with traits:", traits);
|
|
262
519
|
this.identityManager.group(groupId);
|
|
263
|
-
this.enqueue({ type:
|
|
264
|
-
log("Group event enqueued, queue length:", this.queue.length);
|
|
520
|
+
this.enqueue({ type: 'group', groupId, traits, timestamp: this.now() });
|
|
265
521
|
}
|
|
266
522
|
/**
|
|
267
523
|
* Tracks a screen view.
|
|
@@ -269,14 +525,12 @@ export class MetaRouterAnalyticsClient {
|
|
|
269
525
|
* @param properties - The properties to track.
|
|
270
526
|
*/
|
|
271
527
|
screen(name, properties) {
|
|
272
|
-
log("Tracking screen:", name, "with properties:", properties);
|
|
273
528
|
this.enqueue({
|
|
274
|
-
type:
|
|
529
|
+
type: 'screen',
|
|
275
530
|
event: name,
|
|
276
531
|
properties,
|
|
277
532
|
timestamp: this.now(),
|
|
278
533
|
});
|
|
279
|
-
log("Screen event enqueued, queue length:", this.queue.length);
|
|
280
534
|
}
|
|
281
535
|
/**
|
|
282
536
|
* Alias an anonymous user to a known user ID.
|
|
@@ -284,10 +538,8 @@ export class MetaRouterAnalyticsClient {
|
|
|
284
538
|
* @param newUserId - The new user ID to alias to.
|
|
285
539
|
*/
|
|
286
540
|
alias(newUserId) {
|
|
287
|
-
log("Aliasing user to:", newUserId);
|
|
288
541
|
this.identityManager.identify(newUserId);
|
|
289
|
-
this.enqueue({ type:
|
|
290
|
-
log("Alias event enqueued, queue length:", this.queue.length);
|
|
542
|
+
this.enqueue({ type: 'alias', userId: newUserId, timestamp: this.now() });
|
|
291
543
|
}
|
|
292
544
|
/**
|
|
293
545
|
* Sets the advertising identifier for ad tracking and attribution.
|
|
@@ -301,18 +553,20 @@ export class MetaRouterAnalyticsClient {
|
|
|
301
553
|
*/
|
|
302
554
|
async setAdvertisingId(advertisingId) {
|
|
303
555
|
if (!this.isReady()) {
|
|
304
|
-
warn(
|
|
556
|
+
warn('Analytics client is not ready. Call init() before setAdvertisingId()');
|
|
305
557
|
return;
|
|
306
558
|
}
|
|
307
|
-
if (!advertisingId ||
|
|
308
|
-
|
|
559
|
+
if (!advertisingId ||
|
|
560
|
+
typeof advertisingId !== 'string' ||
|
|
561
|
+
advertisingId.trim() === '') {
|
|
562
|
+
warn('Invalid advertising ID provided. Must be a non-empty string.');
|
|
309
563
|
return;
|
|
310
564
|
}
|
|
311
|
-
log(
|
|
565
|
+
log('Setting advertising ID');
|
|
312
566
|
await setIdentityField(ADVERTISING_ID_KEY, advertisingId);
|
|
313
567
|
clearContextCache();
|
|
314
|
-
this.context = await getContextInfo(advertisingId);
|
|
315
|
-
log(
|
|
568
|
+
this.context = await getContextInfo(this.appContext, advertisingId);
|
|
569
|
+
log('Advertising ID updated, persisted, and context refreshed');
|
|
316
570
|
}
|
|
317
571
|
/**
|
|
318
572
|
* Clears the advertising identifier from storage and context.
|
|
@@ -323,14 +577,14 @@ export class MetaRouterAnalyticsClient {
|
|
|
323
577
|
*/
|
|
324
578
|
async clearAdvertisingId() {
|
|
325
579
|
if (!this.isReady()) {
|
|
326
|
-
warn(
|
|
580
|
+
warn('Analytics client is not ready. Call init() before clearAdvertisingId()');
|
|
327
581
|
return;
|
|
328
582
|
}
|
|
329
|
-
log(
|
|
583
|
+
log('Clearing advertising ID');
|
|
330
584
|
await removeIdentityField(ADVERTISING_ID_KEY);
|
|
331
585
|
clearContextCache();
|
|
332
|
-
this.context = await getContextInfo();
|
|
333
|
-
log(
|
|
586
|
+
this.context = await getContextInfo(this.appContext);
|
|
587
|
+
log('Advertising ID cleared from storage and context');
|
|
334
588
|
}
|
|
335
589
|
/**
|
|
336
590
|
* Enable or disable tracing headers on outgoing requests.
|
|
@@ -355,7 +609,22 @@ export class MetaRouterAnalyticsClient {
|
|
|
355
609
|
*/
|
|
356
610
|
enableDebugLogging() {
|
|
357
611
|
setDebugLogging(true);
|
|
358
|
-
log(
|
|
612
|
+
log('Debug logging enabled');
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Returns the current anonymous ID managed by the JS identity layer.
|
|
616
|
+
* Awaits init() if it is still in-flight. Throws only if the client was
|
|
617
|
+
* never initialized or a reset() races with this call.
|
|
618
|
+
*/
|
|
619
|
+
async getAnonymousId() {
|
|
620
|
+
if (this.initPromise) {
|
|
621
|
+
await this.initPromise;
|
|
622
|
+
}
|
|
623
|
+
const id = this.identityManager.getAnonymousId();
|
|
624
|
+
if (!id) {
|
|
625
|
+
throw new Error('getAnonymousId: no anonymous ID available (client was reset or never initialized)');
|
|
626
|
+
}
|
|
627
|
+
return id;
|
|
359
628
|
}
|
|
360
629
|
/**
|
|
361
630
|
* Get current state for debugging
|
|
@@ -366,7 +635,7 @@ export class MetaRouterAnalyticsClient {
|
|
|
366
635
|
lifecycle: this.lifecycle,
|
|
367
636
|
queueLength: d.queueLength,
|
|
368
637
|
ingestionHost: this.ingestionHost,
|
|
369
|
-
writeKey: this.writeKey ?
|
|
638
|
+
writeKey: this.writeKey ? '***' + this.writeKey.slice(-4) : undefined,
|
|
370
639
|
flushIntervalSeconds: this.flushIntervalSeconds,
|
|
371
640
|
anonymousId: this.identityManager.getAnonymousId(),
|
|
372
641
|
userId: this.identityManager.getUserId(),
|
|
@@ -376,7 +645,10 @@ export class MetaRouterAnalyticsClient {
|
|
|
376
645
|
circuitState: d.circuitState,
|
|
377
646
|
circuitRemainingMs: d.circuitRemainingMs,
|
|
378
647
|
maxQueueEvents: d.maxQueueEvents,
|
|
648
|
+
maxDiskEvents: this.maxDiskEvents,
|
|
379
649
|
tracingEnabled: this.tracingEnabled,
|
|
650
|
+
hasDiskData: this.persistentQueue.hasDiskData,
|
|
651
|
+
networkStatus: this.networkStatus,
|
|
380
652
|
};
|
|
381
653
|
}
|
|
382
654
|
/**
|
|
@@ -390,15 +662,24 @@ export class MetaRouterAnalyticsClient {
|
|
|
390
662
|
* Resets the analytics client.
|
|
391
663
|
*/
|
|
392
664
|
async reset() {
|
|
393
|
-
var _a, _b;
|
|
394
|
-
log(
|
|
665
|
+
var _a, _b, _c;
|
|
666
|
+
log('Resetting analytics client');
|
|
395
667
|
// Flip lifecycle first so other paths see we're resetting
|
|
396
|
-
this.lifecycle =
|
|
668
|
+
this.lifecycle = 'resetting';
|
|
669
|
+
// Stop network monitoring
|
|
670
|
+
(_a = this.unsubscribeNetwork) === null || _a === void 0 ? void 0 : _a.call(this);
|
|
671
|
+
this.unsubscribeNetwork = null;
|
|
672
|
+
this.networkMonitor.stop();
|
|
397
673
|
// Stop background work
|
|
398
674
|
this.dispatcher.stop();
|
|
399
|
-
(
|
|
675
|
+
(_c = (_b = this.appStateSubscription) === null || _b === void 0 ? void 0 : _b.remove) === null || _c === void 0 ? void 0 : _c.call(_b);
|
|
400
676
|
this.appStateSubscription = null;
|
|
677
|
+
this.pendingDeepLink = null;
|
|
678
|
+
this.coldLaunchOpenDeferred = false;
|
|
679
|
+
this.wasBackgrounded = false;
|
|
680
|
+
this.lifecycleEmitter = null;
|
|
401
681
|
this.dispatcher.reset();
|
|
682
|
+
await this.persistentQueue.deleteSnapshot();
|
|
402
683
|
// Clear identity (must remove persisted IDs)
|
|
403
684
|
await this.identityManager.reset();
|
|
404
685
|
// Clear advertising ID from storage
|
|
@@ -406,9 +687,12 @@ export class MetaRouterAnalyticsClient {
|
|
|
406
687
|
// Allow a clean future init
|
|
407
688
|
this.initPromise = null;
|
|
408
689
|
// Back to idle: explicit init required
|
|
409
|
-
this.lifecycle =
|
|
690
|
+
this.lifecycle = 'idle';
|
|
410
691
|
this.clearNextTimer();
|
|
411
|
-
log(
|
|
692
|
+
log('Analytics client reset complete');
|
|
412
693
|
}
|
|
413
694
|
}
|
|
414
|
-
MetaRouterAnalyticsClient.
|
|
695
|
+
MetaRouterAnalyticsClient.AUTO_FLUSH_THRESHOLD = 20;
|
|
696
|
+
// Byte cap is intentionally internal (parity with iOS/Android). Not a
|
|
697
|
+
// public option. 5MB — revisit only if a customer actually needs to tune.
|
|
698
|
+
MetaRouterAnalyticsClient.MAX_QUEUE_BYTES = 5 * 1024 * 1024;
|