@metarouter/react-native-sdk 1.7.0 → 1.9.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 (66) hide show
  1. package/README.md +302 -61
  2. package/android/build.gradle +2 -0
  3. package/android/src/main/java/com/metarouter/reactnative/MetaRouterClockModule.kt +24 -0
  4. package/android/src/main/java/com/metarouter/reactnative/MetaRouterPackage.kt +3 -1
  5. package/android/src/main/java/com/metarouter/reactnative/MetaRouterWebViewSupportModule.kt +27 -0
  6. package/ios/MetaRouterClock.m +31 -0
  7. package/lib/analytics/MetaRouterAnalyticsClient.d.ts +71 -2
  8. package/lib/analytics/MetaRouterAnalyticsClient.d.ts.map +1 -1
  9. package/lib/analytics/MetaRouterAnalyticsClient.js +313 -51
  10. package/lib/analytics/init.d.ts +7 -0
  11. package/lib/analytics/init.d.ts.map +1 -1
  12. package/lib/analytics/init.js +210 -37
  13. package/lib/analytics/lifecycle/lifecycleEvents.d.ts +52 -0
  14. package/lib/analytics/lifecycle/lifecycleEvents.d.ts.map +1 -0
  15. package/lib/analytics/lifecycle/lifecycleEvents.js +66 -0
  16. package/lib/analytics/proxy/proxyClient.d.ts +31 -0
  17. package/lib/analytics/proxy/proxyClient.d.ts.map +1 -1
  18. package/lib/analytics/proxy/proxyClient.js +153 -6
  19. package/lib/analytics/session/sessionManager.d.ts +108 -0
  20. package/lib/analytics/session/sessionManager.d.ts.map +1 -0
  21. package/lib/analytics/session/sessionManager.js +193 -0
  22. package/lib/analytics/types.d.ts +108 -1
  23. package/lib/analytics/types.d.ts.map +1 -1
  24. package/lib/analytics/utils/appContext.d.ts +22 -0
  25. package/lib/analytics/utils/appContext.d.ts.map +1 -0
  26. package/lib/analytics/utils/appContext.js +23 -0
  27. package/lib/analytics/utils/contextInfo.d.ts +7 -3
  28. package/lib/analytics/utils/contextInfo.d.ts.map +1 -1
  29. package/lib/analytics/utils/contextInfo.js +12 -9
  30. package/lib/analytics/utils/enrichEvent.d.ts +6 -2
  31. package/lib/analytics/utils/enrichEvent.d.ts.map +1 -1
  32. package/lib/analytics/utils/enrichEvent.js +20 -3
  33. package/lib/analytics/utils/initOptions.d.ts +22 -0
  34. package/lib/analytics/utils/initOptions.d.ts.map +1 -0
  35. package/lib/analytics/utils/initOptions.js +107 -0
  36. package/lib/analytics/utils/lifecycleStorage.d.ts +13 -0
  37. package/lib/analytics/utils/lifecycleStorage.d.ts.map +1 -0
  38. package/lib/analytics/utils/lifecycleStorage.js +35 -0
  39. package/lib/analytics/utils/monotonicClock.d.ts +15 -0
  40. package/lib/analytics/utils/monotonicClock.d.ts.map +1 -0
  41. package/lib/analytics/utils/monotonicClock.js +52 -0
  42. package/lib/analytics/utils/sessionStorage.d.ts +27 -0
  43. package/lib/analytics/utils/sessionStorage.d.ts.map +1 -0
  44. package/lib/analytics/utils/sessionStorage.js +85 -0
  45. package/lib/analytics/webview/bridgeDedupStore.d.ts +37 -0
  46. package/lib/analytics/webview/bridgeDedupStore.d.ts.map +1 -0
  47. package/lib/analytics/webview/bridgeDedupStore.js +63 -0
  48. package/lib/analytics/webview/bridgeEnvelope.d.ts +68 -0
  49. package/lib/analytics/webview/bridgeEnvelope.d.ts.map +1 -0
  50. package/lib/analytics/webview/bridgeEnvelope.js +140 -0
  51. package/lib/analytics/webview/bridgeMessageProcessor.d.ts +38 -0
  52. package/lib/analytics/webview/bridgeMessageProcessor.d.ts.map +1 -0
  53. package/lib/analytics/webview/bridgeMessageProcessor.js +67 -0
  54. package/lib/analytics/webview/bridgeWrapperScript.d.ts +53 -0
  55. package/lib/analytics/webview/bridgeWrapperScript.d.ts.map +1 -0
  56. package/lib/analytics/webview/bridgeWrapperScript.js +161 -0
  57. package/lib/analytics/webview/webViewBridge.d.ts +39 -0
  58. package/lib/analytics/webview/webViewBridge.d.ts.map +1 -0
  59. package/lib/analytics/webview/webViewBridge.js +211 -0
  60. package/lib/analytics/webview/webViewSupport.d.ts +16 -0
  61. package/lib/analytics/webview/webViewSupport.d.ts.map +1 -0
  62. package/lib/analytics/webview/webViewSupport.js +52 -0
  63. package/lib/index.d.ts +4 -4
  64. package/lib/index.d.ts.map +1 -1
  65. package/lib/index.js +3 -3
  66. package/package.json +11 -3
@@ -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":"AAWA,OAAO,KAAK,EAAE,WAAW,EAAE,kBAAkB,EAAe,MAAM,SAAS,CAAC;AA4B5E;;;GAGG;AACH,eAAO,MAAM,WAAW;8BACE,OAAO;CAEhC,CAAC;AAoCF,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,WAAW,GACnB,kBAAkB,CAsCpB"}
@@ -1,43 +1,216 @@
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, setAttachWebViewHandler, setResetHandler, takePendingOpenedURLs, } from './proxy/proxyClient';
3
+ import { validateInitOptions } from './utils/initOptions';
4
+ import { BridgeMessageProcessor } from './webview/bridgeMessageProcessor';
5
+ import { attachWebViewBridge } from './webview/webViewBridge';
6
+ /*
7
+ * Session choreography. Init, disable and reset work runs strictly FIFO on
8
+ * `workChain`, and the flags below follow one rule (the one the Android SDK
9
+ * settled on after its review): flags are written only when work is queued,
10
+ * synchronously in the public call; state changes only when the queued work
11
+ * runs; running work never writes flags. Writing a flag at execution time lets
12
+ * work queued earlier overwrite a decision made by a later call — e.g. an init
13
+ * finishing after a reset was queued would mark the session started again,
14
+ * and the next createAnalyticsClient would silently return an unbound proxy.
15
+ * The single exception is the rollback after a failed init (see runInit).
16
+ */
17
+ let initializationStarted = false;
18
+ let sessionRefused = false;
5
19
  let currentOptions = null;
20
+ // Bumped on every createAnalyticsClient / reset decision, at enqueue time. A
21
+ // queued disable compares it when it runs: if a later call has been made since,
22
+ // the refusal is already superseded (read, never written, at execution time).
23
+ let decisionCount = 0;
24
+ let workChain = Promise.resolve();
25
+ let activeClient = null;
26
+ /**
27
+ * Whether this is a development build. Injectable so tests can exercise the
28
+ * release path; production reads React Native's `__DEV__`.
29
+ */
30
+ export const buildConfig = {
31
+ isDevelopmentBuild: () => typeof __DEV__ !== 'undefined' && __DEV__ === true,
32
+ };
33
+ // For fire-and-forget enqueues: the runners catch everything today, but a
34
+ // future throw must not surface as an unhandled rejection in the host.
35
+ const ignoreFailure = () => { };
36
+ function enqueue(work) {
37
+ const run = workChain.then(work);
38
+ // The chain itself must survive a failed step; callers that await the
39
+ // returned promise still see the failure.
40
+ workChain = run.catch(() => { });
41
+ return run;
42
+ }
43
+ /**
44
+ * The config gate. Development builds fail fast with a throw (a red screen at
45
+ * the call site); release builds log an always-on error, call `onConfigError`
46
+ * synchronously and leave the SDK inert for the session — a misconfigured SDK
47
+ * must never take down the host app. Returns false when the session is refused.
48
+ */
49
+ function passesConfigGate(options, configError) {
50
+ var _a;
51
+ if (configError === null)
52
+ return true;
53
+ const { description } = configError;
54
+ if (buildConfig.isDevelopmentBuild()) {
55
+ throw new Error(`Invalid InitOptions: ${description}`);
56
+ }
57
+ console.error(`[MetaRouter] MetaRouter disabled for this session — ${description}`);
58
+ (_a = options.onConfigError) === null || _a === void 0 ? void 0 : _a.call(options, configError);
59
+ return false;
60
+ }
6
61
  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
- })();
62
+ const { options: normalized, configError } = validateInitOptions(options);
63
+ if (!passesConfigGate(options, configError)) {
64
+ // An invalid call disables the whole session, even over a running valid
65
+ // client: keeping the stale client would mask the config error.
66
+ initializationStarted = true;
67
+ sessionRefused = true;
68
+ currentOptions = null;
69
+ const { description } = configError;
70
+ const decision = ++decisionCount;
71
+ enqueue(() => runDisable(description, decision)).catch(ignoreFailure);
72
+ return proxyClient;
41
73
  }
74
+ if (initializationStarted && !sessionRefused) {
75
+ if (currentOptions &&
76
+ JSON.stringify(currentOptions) !== JSON.stringify(normalized)) {
77
+ console.warn('[MetaRouter] Config changed but client not reset. Call await client.reset() before reinitializing with new options.');
78
+ }
79
+ return proxyClient;
80
+ }
81
+ // First init, or the one valid call that recovers a refused session. The
82
+ // refusal is lifted now, not when the init runs: calls made right after
83
+ // this one (getAnonymousId above all) must wait for the incoming session
84
+ // instead of resolving against the old verdict.
85
+ initializationStarted = true;
86
+ sessionRefused = false;
87
+ currentOptions = normalized;
88
+ clearConfigDisabled();
89
+ const decision = ++decisionCount;
90
+ enqueue(() => runInit(normalized, decision)).catch(ignoreFailure);
42
91
  return proxyClient;
43
92
  }
93
+ async function runInit(options, decision) {
94
+ // Unreachable today: every path that queues an init has a disable or reset
95
+ // queued ahead of it, or no bound client at all. Kept so a future path that
96
+ // breaks that invariant leaves the bound client alone instead of orphaning
97
+ // it with its flush loop still running.
98
+ if (activeClient)
99
+ return;
100
+ clearConfigDisabled();
101
+ let instance;
102
+ try {
103
+ instance = new MetaRouterAnalyticsClient(options);
104
+ for (const args of takePendingOpenedURLs()) {
105
+ instance.recordOpenedURL(...args);
106
+ }
107
+ setInitializingClient(instance);
108
+ await instance.init();
109
+ }
110
+ catch (err) {
111
+ console.error('[MetaRouter] Initialization failed:', err);
112
+ // The one execution-time flag write: restores retryability so the next
113
+ // createAnalyticsClient can try again. Skipped when a later call was made
114
+ // after this init was queued — that call's decision (a reset, another
115
+ // init, a refusal) is newer and must not be overwritten.
116
+ if (decision === decisionCount) {
117
+ initializationStarted = false;
118
+ currentOptions = null;
119
+ }
120
+ return;
121
+ }
122
+ finally {
123
+ setInitializingClient(null);
124
+ }
125
+ activeClient = instance;
126
+ setRealClient(bindClient(instance));
127
+ }
128
+ async function runDisable(description, decision) {
129
+ const previous = activeClient;
130
+ activeClient = null;
131
+ // Reset rather than drop the old client: dropped live, its dispatcher would
132
+ // keep flushing, and a disabled session must not send events.
133
+ await resetQuietly(previous);
134
+ if (decision !== decisionCount) {
135
+ // A valid init (or a reset) was requested after this refusal and is
136
+ // queued behind it. Unbind, but keep pending calls — a getAnonymousId
137
+ // made after that later call must resolve against the incoming session,
138
+ // not against this superseded verdict.
139
+ setRealClient(null);
140
+ return;
141
+ }
142
+ markConfigDisabled(description);
143
+ }
144
+ async function runReset(decision) {
145
+ const previous = activeClient;
146
+ activeClient = null;
147
+ await resetQuietly(previous);
148
+ if (decision !== decisionCount) {
149
+ // A createAnalyticsClient came after this reset and is queued behind it:
150
+ // calls made since belong to that incoming session, so they wait for its
151
+ // bind instead of being dropped (or, for promises, rejected) here.
152
+ setRealClient(null);
153
+ return;
154
+ }
155
+ setRealClient(null, { dropPending: true });
156
+ }
157
+ /**
158
+ * Resets a client being torn down. A failure (e.g. a storage error while
159
+ * deleting the snapshot) is logged, not thrown: the unbind or refusal that
160
+ * follows must still happen, or the proxy stays bound to a half-reset client.
161
+ */
162
+ async function resetQuietly(client) {
163
+ if (!client)
164
+ return;
165
+ try {
166
+ await client.reset();
167
+ }
168
+ catch (err) {
169
+ console.error('[MetaRouter] Reset of the previous client failed:', err);
170
+ }
171
+ }
172
+ /**
173
+ * `reset()` from the public API, in any state: flags clear now, the teardown
174
+ * runs in order behind anything already queued. A createAnalyticsClient issued
175
+ * right after (even without awaiting) queues a real init behind it.
176
+ */
177
+ function resetSession() {
178
+ if (!initializationStarted)
179
+ return Promise.resolve();
180
+ initializationStarted = false;
181
+ sessionRefused = false;
182
+ currentOptions = null;
183
+ const decision = ++decisionCount;
184
+ return enqueue(() => runReset(decision));
185
+ }
186
+ setResetHandler(resetSession);
187
+ // One processor for every WebView the host attaches, across sessions — like
188
+ // the native proxy's. The sink resolves the client per message: the props are
189
+ // handed out at the first render, long before a client binds, and must keep
190
+ // working across reset() and re-init. Before a bind, or during a teardown,
191
+ // messages are refused with not_ready.
192
+ const bridgeProcessor = new BridgeMessageProcessor((envelope) => { var _a; return (_a = activeClient === null || activeClient === void 0 ? void 0 : activeClient.enqueueBridgeEvent(envelope)) !== null && _a !== void 0 ? _a : false; });
193
+ const attachWebView = (webViewRef, allowedOrigins) => attachWebViewBridge(webViewRef, allowedOrigins, bridgeProcessor);
194
+ // The proxy routes every attachWebView here, bound or not.
195
+ setAttachWebViewHandler(attachWebView);
196
+ function bindClient(instance) {
197
+ return {
198
+ track: (event, props) => instance.track(event, props),
199
+ identify: (userId, traits) => instance.identify(userId, traits),
200
+ group: (groupId, traits) => instance.group(groupId, traits),
201
+ screen: (name, props) => instance.screen(name, props),
202
+ page: (name, props) => instance.page(name, props),
203
+ alias: (newUserId) => instance.alias(newUserId),
204
+ recordOpenedURL: (url, sourceApplication) => instance.recordOpenedURL(url, sourceApplication),
205
+ setAdvertisingId: (advertisingId) => instance.setAdvertisingId(advertisingId),
206
+ clearAdvertisingId: () => instance.clearAdvertisingId(),
207
+ setTracing: (enabled) => instance.setTracing(enabled),
208
+ enableDebugLogging: () => instance.enableDebugLogging(),
209
+ getDebugInfo: () => instance.getDebugInfo(),
210
+ getAnonymousId: () => instance.getAnonymousId(),
211
+ getSessionId: () => instance.getSessionId(),
212
+ attachWebView,
213
+ flush: () => instance.flush(),
214
+ reset: () => resetSession(),
215
+ };
216
+ }
@@ -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
+ }
@@ -1,5 +1,11 @@
1
1
  import type { AnalyticsInterface } from '../types';
2
2
  export declare const proxyClient: AnalyticsInterface;
3
+ /**
4
+ * Sets (or clears, with `null`) the client whose init() is in flight, so
5
+ * recordOpenedURL reaches it before the cold-launch Opened is emitted.
6
+ * Cleared as soon as init() settles, before binding.
7
+ */
8
+ export declare function setInitializingClient(client: Pick<AnalyticsInterface, 'recordOpenedURL'> | null): void;
3
9
  /**
4
10
  * Binds or unbinds the real analytics client to the proxy and manages queued calls.
5
11
  *
@@ -30,4 +36,29 @@ export declare const proxyClient: AnalyticsInterface;
30
36
  export declare function setRealClient(client: AnalyticsInterface | null, opts?: {
31
37
  dropPending?: boolean;
32
38
  }): void;
39
+ /** Registers init.ts's WebView bridge, used by `attachWebView()` in every state. */
40
+ export declare function setAttachWebViewHandler(handler: AnalyticsInterface['attachWebView'] | null): void;
41
+ /** Registers init.ts's session reset, used by `reset()` in every state. */
42
+ export declare function setResetHandler(handler: (() => Promise<void>) | null): void;
43
+ /**
44
+ * Refuses the session: unbinds, drops calls queued before the refusal (they
45
+ * belonged to a session that never bound), settles their promises with the
46
+ * degraded value instead of rejecting, and makes later async calls resolve
47
+ * degraded. Calls made after this point queue and replay on recovery.
48
+ */
49
+ export declare function markConfigDisabled(description: string): void;
50
+ /**
51
+ * Lifts a refusal before a valid init builds its client, so async calls made
52
+ * during that init wait for the incoming bind rather than resolving against
53
+ * the previous verdict.
54
+ */
55
+ export declare function clearConfigDisabled(): void;
56
+ /**
57
+ * Removes and returns queued recordOpenedURL calls, oldest first. The init that
58
+ * builds a client applies them before init() runs: createAnalyticsClient only
59
+ * queues that init, so a URL forwarded right after the call (the usual
60
+ * `Linking.getInitialURL()` wiring) is queued here before any client exists,
61
+ * and replaying it after bind would miss the cold-launch Opened.
62
+ */
63
+ export declare function takePendingOpenedURLs(): Parameters<AnalyticsInterface['recordOpenedURL']>[];
33
64
  //# sourceMappingURL=proxyClient.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"proxyClient.d.ts","sourceRoot":"","sources":["../../../src/analytics/proxy/proxyClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AA2InD,eAAO,MAAM,WAAW,EAAE,kBAkBzB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,kBAAkB,GAAG,IAAI,EACjC,IAAI,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,OAAO,CAAA;CAAE,QAqBjC"}
1
+ {"version":3,"file":"proxyClient.d.ts","sourceRoot":"","sources":["../../../src/analytics/proxy/proxyClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AA4PnD,eAAO,MAAM,WAAW,EAAE,kBAuBzB,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,IAAI,CAAC,kBAAkB,EAAE,iBAAiB,CAAC,GAAG,IAAI,QAG3D;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,kBAAkB,GAAG,IAAI,EACjC,IAAI,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,OAAO,CAAA;CAAE,QAuBjC;AAED,oFAAoF;AACpF,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,kBAAkB,CAAC,eAAe,CAAC,GAAG,IAAI,QAGpD;AAED,2EAA2E;AAC3E,wBAAgB,eAAe,CAAC,OAAO,EAAE,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,QAEpE;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,MAAM,QAMrD;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,SAElC;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,IAAI,UAAU,CACjD,kBAAkB,CAAC,iBAAiB,CAAC,CACtC,EAAE,CAYF"}
@@ -1,6 +1,25 @@
1
+ import { inertProps } from '../webview/webViewBridge';
1
2
  const pendingCalls = [];
2
3
  const MAX_PENDING_CALLS = 20;
3
4
  let realClient = null;
5
+ // Description of the config error that refused this session, or null. While
6
+ // set, calls still queue (and replay if a valid init recovers the session),
7
+ // but nothing that returns a promise may wait for a bind that is not coming.
8
+ let configDisabledError = null;
9
+ // Owned by init.ts: reset must work before a bind (it is how a refused or
10
+ // still-initializing session is cleared), so the proxy cannot route it to the
11
+ // bound client alone.
12
+ let resetHandler = null;
13
+ // Owned by init.ts, which holds the session-wide bridge processor. Like reset,
14
+ // attachWebView must work before a bind: its props are needed at the first
15
+ // render, and queueing it would leave the WebView without a wrapper.
16
+ let attachWebViewHandler = null;
17
+ // The client whose init() is still running. recordOpenedURL only fills a
18
+ // one-slot buffer that the cold-launch Application Opened reads during
19
+ // init(), and the proxy binds only after init() resolves — so a cold-launch
20
+ // URL queued for replay would always miss its own Opened and ride on the
21
+ // next resume instead. Routing it here lets it land before that emit.
22
+ let initializingClient = null;
4
23
  const ASYNC_METHODS = {
5
24
  flush: true,
6
25
  getDebugInfo: true,
@@ -9,6 +28,26 @@ const ASYNC_METHODS = {
9
28
  clearAdvertisingId: true,
10
29
  };
11
30
  const isAsyncMethod = (m) => ASYNC_METHODS[m] === true;
31
+ /**
32
+ * What an async call resolves to on a config-refused session. getAnonymousId
33
+ * resolves "" promptly, like iOS and Android: a permanent hang on a
34
+ * misconfigured SDK would be worse than the crash this contract replaces.
35
+ */
36
+ function degradedResult(methodName) {
37
+ switch (methodName) {
38
+ case 'getAnonymousId':
39
+ return '';
40
+ case 'getDebugInfo':
41
+ return {
42
+ lifecycle: 'disabled',
43
+ proxy: true,
44
+ pendingCalls: pendingCalls.length,
45
+ configError: configDisabledError,
46
+ };
47
+ default:
48
+ return undefined;
49
+ }
50
+ }
12
51
  // One in-flight flush at a time
13
52
  let flushInFlight = null;
14
53
  /**
@@ -36,8 +75,19 @@ let flushInFlight = null;
36
75
  */
37
76
  function handleMethodCall(methodName, ...args) {
38
77
  var _a;
78
+ // Bound or not: the props are stateless and the shared processor resolves
79
+ // the client per message.
80
+ if (methodName === 'attachWebView') {
81
+ if (attachWebViewHandler) {
82
+ return attachWebViewHandler(...args);
83
+ }
84
+ // Only reachable when init.ts was never loaded (a deep import). Queueing
85
+ // would hand the render undefined; inert props keep it rendering.
86
+ console.warn('[MetaRouter] attachWebView called before the SDK loaded — ignoring.');
87
+ return inertProps();
88
+ }
39
89
  // Real client bound
40
- if (realClient) {
90
+ if (realClient && methodName !== 'reset') {
41
91
  if (methodName === 'flush') {
42
92
  if (flushInFlight)
43
93
  return flushInFlight;
@@ -49,22 +99,51 @@ function handleMethodCall(methodName, ...args) {
49
99
  }
50
100
  return realClient[methodName](...args);
51
101
  }
52
- // No real client bound yet
102
+ if (methodName === 'reset') {
103
+ if (resetHandler) {
104
+ return resetHandler();
105
+ }
106
+ return (realClient ? realClient.reset() : Promise.resolve());
107
+ }
108
+ // No real client bound yet. No queueing and no waiting for a bind, unlike
109
+ // getAnonymousId: sessions are minted by events, so before a bind "null — no
110
+ // session yet" is the true answer, refused sessions included.
111
+ if (methodName === 'getSessionId') {
112
+ return Promise.resolve(null);
113
+ }
114
+ if (methodName === 'recordOpenedURL' && initializingClient) {
115
+ initializingClient.recordOpenedURL(...args);
116
+ return undefined;
117
+ }
118
+ // Refused session: queries answer now and never take a queue slot.
119
+ if (configDisabledError !== null &&
120
+ (methodName === 'getAnonymousId' || methodName === 'getDebugInfo')) {
121
+ return Promise.resolve(degradedResult(methodName));
122
+ }
53
123
  if (pendingCalls.length >= MAX_PENDING_CALLS) {
54
124
  const dropped = pendingCalls.shift();
55
125
  (_a = dropped === null || dropped === void 0 ? void 0 : dropped.reject) === null || _a === void 0 ? void 0 : _a.call(dropped, new Error(`[MetaRouter] Dropped oldest call (queue cap ${MAX_PENDING_CALLS})`));
56
126
  console.warn(`[MetaRouter] Oldest call dropped (queue cap ${MAX_PENDING_CALLS})`);
57
127
  }
58
- // Special-cases while unbound:
59
- if (methodName === 'reset') {
60
- // Nothing to reset pre-bind; resolve immediately
61
- return Promise.resolve();
128
+ if (isAsyncMethod(methodName) && configDisabledError !== null) {
129
+ // Refused session: commands (flush, advertising id) still queue so a
130
+ // recovering valid init replays them like any other call, but their
131
+ // promise resolves now instead of waiting for a bind.
132
+ pendingCalls.push({
133
+ fn: () => {
134
+ if (!realClient)
135
+ return;
136
+ return Promise.resolve(realClient[methodName](...args)).then(() => undefined);
137
+ },
138
+ });
139
+ return Promise.resolve(undefined);
62
140
  }
63
141
  if (isAsyncMethod(methodName)) {
64
142
  // Queue async call and return a promise that resolves after bind+run
65
143
  return new Promise((resolve, reject) => {
66
144
  pendingCalls.push({
67
145
  reject, // keep a handle for dropPending
146
+ degrade: () => resolve(degradedResult(methodName)),
68
147
  fn: async () => {
69
148
  try {
70
149
  if (!realClient) {
@@ -96,6 +175,9 @@ function handleMethodCall(methodName, ...args) {
96
175
  return;
97
176
  realClient[methodName](...args);
98
177
  },
178
+ ...(methodName === 'recordOpenedURL' && {
179
+ openedURL: args,
180
+ }),
99
181
  });
100
182
  return undefined;
101
183
  }
@@ -106,6 +188,7 @@ export const proxyClient = {
106
188
  screen: (name, props) => handleMethodCall('screen', name, props),
107
189
  page: (name, props) => handleMethodCall('page', name, props),
108
190
  alias: (newUserId) => handleMethodCall('alias', newUserId),
191
+ recordOpenedURL: (url, sourceApplication) => handleMethodCall('recordOpenedURL', url, sourceApplication),
109
192
  setAdvertisingId: (advertisingId) => handleMethodCall('setAdvertisingId', advertisingId),
110
193
  clearAdvertisingId: () => handleMethodCall('clearAdvertisingId'),
111
194
  setTracing: (enabled) => handleMethodCall('setTracing', enabled),
@@ -114,7 +197,17 @@ export const proxyClient = {
114
197
  enableDebugLogging: () => handleMethodCall('enableDebugLogging'),
115
198
  getDebugInfo: () => handleMethodCall('getDebugInfo'),
116
199
  getAnonymousId: () => handleMethodCall('getAnonymousId'),
200
+ getSessionId: () => handleMethodCall('getSessionId'),
201
+ attachWebView: (webViewRef, allowedOrigins) => handleMethodCall('attachWebView', webViewRef, allowedOrigins),
117
202
  };
203
+ /**
204
+ * Sets (or clears, with `null`) the client whose init() is in flight, so
205
+ * recordOpenedURL reaches it before the cold-launch Opened is emitted.
206
+ * Cleared as soon as init() settles, before binding.
207
+ */
208
+ export function setInitializingClient(client) {
209
+ initializingClient = client;
210
+ }
118
211
  /**
119
212
  * Binds or unbinds the real analytics client to the proxy and manages queued calls.
120
213
  *
@@ -145,6 +238,8 @@ export const proxyClient = {
145
238
  export function setRealClient(client, opts) {
146
239
  var _a;
147
240
  realClient = client;
241
+ // Binding a client, or a reset's unbind, ends any refusal.
242
+ configDisabledError = null;
148
243
  if (client) {
149
244
  const items = pendingCalls.splice(0, pendingCalls.length);
150
245
  for (const { fn } of items) {
@@ -165,3 +260,55 @@ export function setRealClient(client, opts) {
165
260
  flushInFlight = null; // reset coalescer
166
261
  }
167
262
  }
263
+ /** Registers init.ts's WebView bridge, used by `attachWebView()` in every state. */
264
+ export function setAttachWebViewHandler(handler) {
265
+ attachWebViewHandler = handler;
266
+ }
267
+ /** Registers init.ts's session reset, used by `reset()` in every state. */
268
+ export function setResetHandler(handler) {
269
+ resetHandler = handler;
270
+ }
271
+ /**
272
+ * Refuses the session: unbinds, drops calls queued before the refusal (they
273
+ * belonged to a session that never bound), settles their promises with the
274
+ * degraded value instead of rejecting, and makes later async calls resolve
275
+ * degraded. Calls made after this point queue and replay on recovery.
276
+ */
277
+ export function markConfigDisabled(description) {
278
+ var _a;
279
+ realClient = null;
280
+ flushInFlight = null;
281
+ configDisabledError = description;
282
+ const items = pendingCalls.splice(0, pendingCalls.length);
283
+ for (const it of items)
284
+ (_a = it.degrade) === null || _a === void 0 ? void 0 : _a.call(it);
285
+ }
286
+ /**
287
+ * Lifts a refusal before a valid init builds its client, so async calls made
288
+ * during that init wait for the incoming bind rather than resolving against
289
+ * the previous verdict.
290
+ */
291
+ export function clearConfigDisabled() {
292
+ configDisabledError = null;
293
+ }
294
+ /**
295
+ * Removes and returns queued recordOpenedURL calls, oldest first. The init that
296
+ * builds a client applies them before init() runs: createAnalyticsClient only
297
+ * queues that init, so a URL forwarded right after the call (the usual
298
+ * `Linking.getInitialURL()` wiring) is queued here before any client exists,
299
+ * and replaying it after bind would miss the cold-launch Opened.
300
+ */
301
+ export function takePendingOpenedURLs() {
302
+ const taken = [];
303
+ for (let i = 0; i < pendingCalls.length;) {
304
+ const args = pendingCalls[i].openedURL;
305
+ if (args) {
306
+ taken.push(args);
307
+ pendingCalls.splice(i, 1);
308
+ }
309
+ else {
310
+ i++;
311
+ }
312
+ }
313
+ return taken;
314
+ }