@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
package/lib/analytics/init.js
CHANGED
|
@@ -1,42 +1,203 @@
|
|
|
1
|
-
import { MetaRouterAnalyticsClient } from
|
|
2
|
-
import { proxyClient, setRealClient } from
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
import { MetaRouterAnalyticsClient } from './MetaRouterAnalyticsClient';
|
|
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
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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
|
-
flush: () => instance.flush(),
|
|
31
|
-
reset: async () => {
|
|
32
|
-
await instance.reset();
|
|
33
|
-
setRealClient(null, { dropPending: true });
|
|
34
|
-
initPromise = null;
|
|
35
|
-
currentOptions = null;
|
|
36
|
-
},
|
|
37
|
-
};
|
|
38
|
-
setRealClient(boundClient);
|
|
39
|
-
})();
|
|
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;
|
|
40
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);
|
|
41
89
|
return proxyClient;
|
|
42
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
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Names + property keys for the four Application lifecycle events.
|
|
3
|
+
*/
|
|
4
|
+
import Dispatcher from '../dispatcher';
|
|
5
|
+
import { EnrichedEventPayload } from '../types';
|
|
6
|
+
import { AppContext } from '../utils/appContext';
|
|
7
|
+
export declare const APPLICATION_INSTALLED = "Application Installed";
|
|
8
|
+
export declare const APPLICATION_UPDATED = "Application Updated";
|
|
9
|
+
export declare const APPLICATION_OPENED = "Application Opened";
|
|
10
|
+
export declare const APPLICATION_BACKGROUNDED = "Application Backgrounded";
|
|
11
|
+
export declare const PROP_VERSION = "version";
|
|
12
|
+
export declare const PROP_BUILD = "build";
|
|
13
|
+
export declare const PROP_PREVIOUS_VERSION = "previous_version";
|
|
14
|
+
export declare const PROP_PREVIOUS_BUILD = "previous_build";
|
|
15
|
+
export declare const PROP_FROM_BACKGROUND = "from_background";
|
|
16
|
+
export declare const PROP_REFERRING_APPLICATION = "referring_application";
|
|
17
|
+
export declare const PROP_URL = "url";
|
|
18
|
+
/** Unknown previous_version/previous_build for SDK upgrades from a pre-lifecycle build. */
|
|
19
|
+
export declare const UNKNOWN_PREVIOUS = "unknown";
|
|
20
|
+
export interface DeepLinkInfo {
|
|
21
|
+
url?: string;
|
|
22
|
+
referringApplication?: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Builds a fully-enriched track-type EnrichedEventPayload (identity + writeKey
|
|
26
|
+
* + context + messageId + timestamp). Provided by the analytics client so the
|
|
27
|
+
* emitter does not need to know how identity/enrichment are wired.
|
|
28
|
+
*/
|
|
29
|
+
export type CreateTrackEvent = (event: string, properties?: Record<string, any>) => EnrichedEventPayload;
|
|
30
|
+
/**
|
|
31
|
+
* Thin emitter that wraps the dispatch path with the lifecycle event shapes.
|
|
32
|
+
* Mirrors the iOS LifecycleEventEmitter: takes a Dispatcher and an enrichment
|
|
33
|
+
* callable plus a process-stable AppContext, then constructs Installed /
|
|
34
|
+
* Updated / Opened / Backgrounded payloads. Construct only when lifecycle
|
|
35
|
+
* tracking is enabled; callers should skip construction entirely when the
|
|
36
|
+
* flag is off.
|
|
37
|
+
*/
|
|
38
|
+
export declare class LifecycleEmitter {
|
|
39
|
+
private readonly dispatcher;
|
|
40
|
+
private readonly createTrackEvent;
|
|
41
|
+
private readonly appContext;
|
|
42
|
+
constructor(dispatcher: Dispatcher, createTrackEvent: CreateTrackEvent, appContext: AppContext);
|
|
43
|
+
emitInstalled(): void;
|
|
44
|
+
emitUpdated(previous: {
|
|
45
|
+
version: string;
|
|
46
|
+
build: string;
|
|
47
|
+
}): void;
|
|
48
|
+
emitOpened(fromBackground: boolean, deepLink?: DeepLinkInfo): void;
|
|
49
|
+
emitBackgrounded(): void;
|
|
50
|
+
private dispatch;
|
|
51
|
+
}
|
|
52
|
+
//# sourceMappingURL=lifecycleEvents.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lifecycleEvents.d.ts","sourceRoot":"","sources":["../../../src/analytics/lifecycle/lifecycleEvents.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,UAAU,MAAM,eAAe,CAAC;AACvC,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEjD,eAAO,MAAM,qBAAqB,0BAA0B,CAAC;AAC7D,eAAO,MAAM,mBAAmB,wBAAwB,CAAC;AACzD,eAAO,MAAM,kBAAkB,uBAAuB,CAAC;AACvD,eAAO,MAAM,wBAAwB,6BAA6B,CAAC;AAEnE,eAAO,MAAM,YAAY,YAAY,CAAC;AACtC,eAAO,MAAM,UAAU,UAAU,CAAC;AAClC,eAAO,MAAM,qBAAqB,qBAAqB,CAAC;AACxD,eAAO,MAAM,mBAAmB,mBAAmB,CAAC;AACpD,eAAO,MAAM,oBAAoB,oBAAoB,CAAC;AACtD,eAAO,MAAM,0BAA0B,0BAA0B,CAAC;AAClE,eAAO,MAAM,QAAQ,QAAQ,CAAC;AAE9B,2FAA2F;AAC3F,eAAO,MAAM,gBAAgB,YAAY,CAAC;AAE1C,MAAM,WAAW,YAAY;IAC3B,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B;AAED;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAC7B,KAAK,EAAE,MAAM,EACb,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAC7B,oBAAoB,CAAC;AAE1B;;;;;;;GAOG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAa;IACxC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAmB;IACpD,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAa;gBAGtC,UAAU,EAAE,UAAU,EACtB,gBAAgB,EAAE,gBAAgB,EAClC,UAAU,EAAE,UAAU;IAOxB,aAAa,IAAI,IAAI;IAOrB,WAAW,CAAC,QAAQ,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI;IAS/D,UAAU,CAAC,cAAc,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,YAAY,GAAG,IAAI;IAelE,gBAAgB,IAAI,IAAI;IAIxB,OAAO,CAAC,QAAQ;CAIjB"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Names + property keys for the four Application lifecycle events.
|
|
3
|
+
*/
|
|
4
|
+
export const APPLICATION_INSTALLED = 'Application Installed';
|
|
5
|
+
export const APPLICATION_UPDATED = 'Application Updated';
|
|
6
|
+
export const APPLICATION_OPENED = 'Application Opened';
|
|
7
|
+
export const APPLICATION_BACKGROUNDED = 'Application Backgrounded';
|
|
8
|
+
export const PROP_VERSION = 'version';
|
|
9
|
+
export const PROP_BUILD = 'build';
|
|
10
|
+
export const PROP_PREVIOUS_VERSION = 'previous_version';
|
|
11
|
+
export const PROP_PREVIOUS_BUILD = 'previous_build';
|
|
12
|
+
export const PROP_FROM_BACKGROUND = 'from_background';
|
|
13
|
+
export const PROP_REFERRING_APPLICATION = 'referring_application';
|
|
14
|
+
export const PROP_URL = 'url';
|
|
15
|
+
/** Unknown previous_version/previous_build for SDK upgrades from a pre-lifecycle build. */
|
|
16
|
+
export const UNKNOWN_PREVIOUS = 'unknown';
|
|
17
|
+
/**
|
|
18
|
+
* Thin emitter that wraps the dispatch path with the lifecycle event shapes.
|
|
19
|
+
* Mirrors the iOS LifecycleEventEmitter: takes a Dispatcher and an enrichment
|
|
20
|
+
* callable plus a process-stable AppContext, then constructs Installed /
|
|
21
|
+
* Updated / Opened / Backgrounded payloads. Construct only when lifecycle
|
|
22
|
+
* tracking is enabled; callers should skip construction entirely when the
|
|
23
|
+
* flag is off.
|
|
24
|
+
*/
|
|
25
|
+
export class LifecycleEmitter {
|
|
26
|
+
constructor(dispatcher, createTrackEvent, appContext) {
|
|
27
|
+
this.dispatcher = dispatcher;
|
|
28
|
+
this.createTrackEvent = createTrackEvent;
|
|
29
|
+
this.appContext = appContext;
|
|
30
|
+
}
|
|
31
|
+
emitInstalled() {
|
|
32
|
+
this.dispatch(APPLICATION_INSTALLED, {
|
|
33
|
+
[PROP_VERSION]: this.appContext.version,
|
|
34
|
+
[PROP_BUILD]: this.appContext.build,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
emitUpdated(previous) {
|
|
38
|
+
this.dispatch(APPLICATION_UPDATED, {
|
|
39
|
+
[PROP_VERSION]: this.appContext.version,
|
|
40
|
+
[PROP_BUILD]: this.appContext.build,
|
|
41
|
+
[PROP_PREVIOUS_VERSION]: previous.version,
|
|
42
|
+
[PROP_PREVIOUS_BUILD]: previous.build,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
emitOpened(fromBackground, deepLink) {
|
|
46
|
+
const props = {
|
|
47
|
+
[PROP_FROM_BACKGROUND]: fromBackground,
|
|
48
|
+
[PROP_VERSION]: this.appContext.version,
|
|
49
|
+
[PROP_BUILD]: this.appContext.build,
|
|
50
|
+
};
|
|
51
|
+
if (deepLink === null || deepLink === void 0 ? void 0 : deepLink.url) {
|
|
52
|
+
props[PROP_URL] = deepLink.url;
|
|
53
|
+
}
|
|
54
|
+
if (deepLink === null || deepLink === void 0 ? void 0 : deepLink.referringApplication) {
|
|
55
|
+
props[PROP_REFERRING_APPLICATION] = deepLink.referringApplication;
|
|
56
|
+
}
|
|
57
|
+
this.dispatch(APPLICATION_OPENED, props);
|
|
58
|
+
}
|
|
59
|
+
emitBackgrounded() {
|
|
60
|
+
this.dispatch(APPLICATION_BACKGROUNDED, {});
|
|
61
|
+
}
|
|
62
|
+
dispatch(event, properties) {
|
|
63
|
+
const enriched = this.createTrackEvent(event, properties);
|
|
64
|
+
this.dispatcher.enqueue(enriched);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare function exists(): Promise<boolean>;
|
|
2
|
+
export declare function readSnapshot(): Promise<string | null>;
|
|
3
|
+
export declare function writeSnapshot(data: string): Promise<void>;
|
|
4
|
+
export declare function deleteSnapshot(): Promise<void>;
|
|
5
|
+
//# sourceMappingURL=NativeQueueStorage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NativeQueueStorage.d.ts","sourceRoot":"","sources":["../../../src/analytics/persistence/NativeQueueStorage.ts"],"names":[],"mappings":"AAmCA,wBAAsB,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC,CAS/C;AAED,wBAAsB,YAAY,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAS3D;AAED,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAa/D;AAED,wBAAsB,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC,CASpD"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { NativeModules } from 'react-native';
|
|
2
|
+
import { warn } from '../utils/logger';
|
|
3
|
+
function getModule() {
|
|
4
|
+
const mod = NativeModules.MetaRouterQueueStorage;
|
|
5
|
+
if (!mod) {
|
|
6
|
+
warn('MetaRouterQueueStorage native module is not available. Queue persistence is disabled.');
|
|
7
|
+
return null;
|
|
8
|
+
}
|
|
9
|
+
return mod;
|
|
10
|
+
}
|
|
11
|
+
export async function exists() {
|
|
12
|
+
const mod = getModule();
|
|
13
|
+
if (!(mod === null || mod === void 0 ? void 0 : mod.exists))
|
|
14
|
+
return false;
|
|
15
|
+
try {
|
|
16
|
+
return await mod.exists();
|
|
17
|
+
}
|
|
18
|
+
catch (err) {
|
|
19
|
+
warn('Failed to check queue snapshot existence:', err);
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export async function readSnapshot() {
|
|
24
|
+
const mod = getModule();
|
|
25
|
+
if (!mod)
|
|
26
|
+
return null;
|
|
27
|
+
try {
|
|
28
|
+
return await mod.readSnapshot();
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
warn('Failed to read queue snapshot from disk:', err);
|
|
32
|
+
throw err;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export async function writeSnapshot(data) {
|
|
36
|
+
const mod = getModule();
|
|
37
|
+
if (!mod) {
|
|
38
|
+
throw new Error('MetaRouterQueueStorage native module is not available; cannot write queue snapshot.');
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
await mod.writeSnapshot(data);
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
warn('Failed to write queue snapshot to disk:', err);
|
|
45
|
+
throw err;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export async function deleteSnapshot() {
|
|
49
|
+
const mod = getModule();
|
|
50
|
+
if (!mod)
|
|
51
|
+
return;
|
|
52
|
+
try {
|
|
53
|
+
await mod.deleteSnapshot();
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
warn('Failed to delete queue snapshot from disk:', err);
|
|
57
|
+
throw err;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { EventPayload } from '../types';
|
|
2
|
+
import type Dispatcher from '../dispatcher';
|
|
3
|
+
/**
|
|
4
|
+
* Memory + disk coordination for the event queue.
|
|
5
|
+
*
|
|
6
|
+
* Single disk file (queue.v1.json) backs both crash-safety (background flush)
|
|
7
|
+
* and offline overflow. All native file mutations run through one serialized
|
|
8
|
+
* lane so append, drain, and delete operations cannot interleave.
|
|
9
|
+
*
|
|
10
|
+
* On boot, {@link checkForPersistedEvents} does a cheap existence check and
|
|
11
|
+
* sets {@link hasDiskData}. The in-memory queue starts empty; when online,
|
|
12
|
+
* the dispatcher drains disk events directly to the network via
|
|
13
|
+
* {@link drainDiskToNetwork} instead of rehydrating into memory.
|
|
14
|
+
*/
|
|
15
|
+
export declare class PersistentEventQueue {
|
|
16
|
+
private readonly dispatcher;
|
|
17
|
+
private readonly maxDiskEvents;
|
|
18
|
+
private _hasDiskData;
|
|
19
|
+
/** Serializes every native file mutation: append, drain rewrite/delete, reset delete. */
|
|
20
|
+
private diskMutation;
|
|
21
|
+
/**
|
|
22
|
+
* Capacity overflow happens from a synchronous enqueue path. These events
|
|
23
|
+
* are owned here until a native write succeeds, so a failed write does not
|
|
24
|
+
* silently discard them from JS memory.
|
|
25
|
+
*/
|
|
26
|
+
private pendingDiskEvents;
|
|
27
|
+
private pendingFlushInFlight;
|
|
28
|
+
/** Guards drainDiskToNetwork (read-then-delete semantics). */
|
|
29
|
+
private drainInFlight;
|
|
30
|
+
constructor(dispatcher: Dispatcher, opts?: {
|
|
31
|
+
maxDiskEvents?: number;
|
|
32
|
+
});
|
|
33
|
+
private enqueueDiskMutation;
|
|
34
|
+
private waitForDiskIdle;
|
|
35
|
+
/** True when a disk snapshot existed at boot or was written since. */
|
|
36
|
+
get hasDiskData(): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Boot-time cheap existence check.
|
|
39
|
+
* Sets {@link hasDiskData} without reading or parsing the snapshot file,
|
|
40
|
+
* so we can decide whether to trigger a drain without paying the cost of
|
|
41
|
+
* loading a potentially-large snapshot into memory.
|
|
42
|
+
*/
|
|
43
|
+
checkForPersistedEvents(): Promise<boolean>;
|
|
44
|
+
/**
|
|
45
|
+
* Flush the in-memory queue to disk (append + cap).
|
|
46
|
+
* Called on app background and when the flush-to-disk threshold is hit.
|
|
47
|
+
* Serialized against other disk writes.
|
|
48
|
+
*
|
|
49
|
+
* No-op when persistence is disabled (maxDiskEvents === 0). Memory queue
|
|
50
|
+
* is left intact so a subsequent foreground flush can still try to send
|
|
51
|
+
* those events; on app kill they are lost (documented tradeoff).
|
|
52
|
+
*/
|
|
53
|
+
flushToDisk(): Promise<void>;
|
|
54
|
+
/**
|
|
55
|
+
* Append explicit events to the disk store (read-merge-cap-write).
|
|
56
|
+
* Called by lifecycle/offline paths that can await disk durability.
|
|
57
|
+
* Serialized against every other disk mutation.
|
|
58
|
+
*
|
|
59
|
+
* No-op when persistence is disabled (maxDiskEvents === 0).
|
|
60
|
+
*/
|
|
61
|
+
flushEventsToDisk(events: EventPayload[]): Promise<void>;
|
|
62
|
+
/**
|
|
63
|
+
* Own events from synchronous overflow paths until they are durable.
|
|
64
|
+
* The write is started immediately but errors are retained in the pending
|
|
65
|
+
* buffer for a later retry instead of being dropped.
|
|
66
|
+
*/
|
|
67
|
+
bufferEventsForDisk(events: EventPayload[]): void;
|
|
68
|
+
flushPendingDiskWrites(): Promise<void>;
|
|
69
|
+
private _flushPendingDiskWrites;
|
|
70
|
+
private appendPendingDiskEvents;
|
|
71
|
+
private _doFlushEventsToDisk;
|
|
72
|
+
/**
|
|
73
|
+
* Check if the queue has crossed a flush-to-disk threshold.
|
|
74
|
+
*/
|
|
75
|
+
shouldFlushToDisk(): boolean;
|
|
76
|
+
/**
|
|
77
|
+
* Drain disk events directly to network in batches. Does NOT load events
|
|
78
|
+
* into the memory queue. Called on offline→online transition and after
|
|
79
|
+
* successful online flushes.
|
|
80
|
+
*
|
|
81
|
+
* Response handling:
|
|
82
|
+
* - 2xx: advances and deletes sent events; restores batch size after 413
|
|
83
|
+
* - 413: halves batch size, retries. Drops at batchSize=1
|
|
84
|
+
* - 5xx/408/429: stops, writes remainder back, retries on next online transition
|
|
85
|
+
* - 401/403/404: fatal, deletes disk store
|
|
86
|
+
* - Other 4xx: drops batch, continues
|
|
87
|
+
*/
|
|
88
|
+
drainDiskToNetwork(dispatcher: Dispatcher): Promise<void>;
|
|
89
|
+
private _doDrainDiskToNetwork;
|
|
90
|
+
/**
|
|
91
|
+
* Delete the disk store (used during reset).
|
|
92
|
+
*/
|
|
93
|
+
deleteSnapshot(): Promise<void>;
|
|
94
|
+
private _readExistingEvents;
|
|
95
|
+
}
|
|
96
|
+
//# sourceMappingURL=PersistentEventQueue.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PersistentEventQueue.d.ts","sourceRoot":"","sources":["../../../src/analytics/persistence/PersistentEventQueue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,KAAK,UAAU,MAAM,eAAe,CAAC;AA2B5C;;;;;;;;;;;GAWG;AACH,qBAAa,oBAAoB;IAC/B,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAa;IACxC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;IACvC,OAAO,CAAC,YAAY,CAAkB;IAEtC,yFAAyF;IACzF,OAAO,CAAC,YAAY,CAAoC;IACxD;;;;OAIG;IACH,OAAO,CAAC,iBAAiB,CAAsB;IAC/C,OAAO,CAAC,oBAAoB,CAA8B;IAC1D,8DAA8D;IAC9D,OAAO,CAAC,aAAa,CAA8B;gBAEvC,UAAU,EAAE,UAAU,EAAE,IAAI,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,MAAM,CAAA;KAAE;IAKrE,OAAO,CAAC,mBAAmB;IAS3B,OAAO,CAAC,eAAe;IAIvB,sEAAsE;IACtE,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED;;;;;OAKG;IACG,uBAAuB,IAAI,OAAO,CAAC,OAAO,CAAC;IAcjD;;;;;;;;OAQG;IACG,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAclC;;;;;;OAMG;IACG,iBAAiB,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ9D;;;;OAIG;IACH,mBAAmB,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,IAAI;IAQ3C,sBAAsB,IAAI,OAAO,CAAC,IAAI,CAAC;YAa/B,uBAAuB;IAarC,OAAO,CAAC,uBAAuB;YAWjB,oBAAoB;IAgClC;;OAEG;IACH,iBAAiB,IAAI,OAAO;IAO5B;;;;;;;;;;;OAWG;IACG,kBAAkB,CAAC,UAAU,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;YAkBjD,qBAAqB;IAuKnC;;OAEG;IACG,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;YAgBvB,mBAAmB;CAiBlC"}
|