@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,4 +1,4 @@
1
- import uuid from "react-native-uuid";
1
+ import uuid from 'react-native-uuid';
2
2
  /**
3
3
  * Generate a messageId with a timestamp prefix (ms since epoch + UUID).
4
4
  * This makes it easy to debug when events were created.
@@ -17,14 +17,31 @@ function generateMessageId() {
17
17
  * @param event The base event with identity information.
18
18
  * @param writeKey The write key for the analytics project.
19
19
  * @param context The context information (device, app, environment, etc.).
20
+ * @param session The session this event belongs to; stamped at
21
+ * `context.providers.metarouter`.
20
22
  * @returns The enriched event payload.
21
23
  */
22
- export function enrichEvent(event, writeKey, context) {
24
+ export function enrichEvent(event, writeKey, context, session, page) {
23
25
  const enriched = {
24
26
  ...event,
25
27
  writeKey,
26
28
  messageId: generateMessageId(),
27
- context,
29
+ // A copy per event: `context` is the client's shared cached object. Key
30
+ // names and the epoch-ms string mirror the web SDK's MetaRouter session,
31
+ // so pipeline mappings read one shape from every platform — renaming any
32
+ // side forks them.
33
+ context: {
34
+ ...context,
35
+ providers: {
36
+ metarouter: {
37
+ sessionID: session.sessionId,
38
+ sessionCount: session.sessionCount,
39
+ },
40
+ },
41
+ // Bridge events carry the page they happened on; native events leave
42
+ // context.page absent, matching web SDK output.
43
+ ...(page && { page }),
44
+ },
28
45
  };
29
46
  return enriched;
30
47
  }
@@ -0,0 +1,22 @@
1
+ import type { ConfigError, InitOptions } from '../types';
2
+ export interface ValidatedInitOptions {
3
+ /** Normalized copy: trimmed key/host, trailing slashes removed, numbers clamped. */
4
+ options: InitOptions;
5
+ /** First error found (writeKey before host), or null when valid. */
6
+ configError: ConfigError | null;
7
+ }
8
+ /** True for localhost / 127.0.0.1 / ::1 (IPv6 brackets stripped), exact match. */
9
+ export declare function isLoopbackHost(host: string): boolean;
10
+ /**
11
+ * Single validation funnel, run once per `createAnalyticsClient` call — the
12
+ * equivalent of the native InitOptions constructor. Never throws: records the
13
+ * first error and clamps every numeric bound with a warning (one policy for
14
+ * all fields, matching iOS and Android). Warnings are logged here and nowhere
15
+ * else, so they appear once per call.
16
+ */
17
+ export declare function validateInitOptions(raw: InitOptions, opts?: {
18
+ logWarnings?: boolean;
19
+ }): ValidatedInitOptions;
20
+ export declare const DEFAULT_MAX_QUEUE_EVENTS = 2000;
21
+ export declare const DEFAULT_MAX_DISK_EVENTS = 10000;
22
+ //# sourceMappingURL=initOptions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initOptions.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/initOptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAsBzD,MAAM,WAAW,oBAAoB;IACnC,oFAAoF;IACpF,OAAO,EAAE,WAAW,CAAC;IACrB,oEAAoE;IACpE,WAAW,EAAE,WAAW,GAAG,IAAI,CAAC;CACjC;AAYD,kFAAkF;AAClF,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAIpD;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,GAAG,EAAE,WAAW,EAChB,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,OAAO,CAAA;CAAO,GACnC,oBAAoB,CAuFtB;AAED,eAAO,MAAM,wBAAwB,OAAO,CAAC;AAC7C,eAAO,MAAM,uBAAuB,QAAS,CAAC"}
@@ -0,0 +1,107 @@
1
+ import { warn as logWarn } from './logger';
2
+ /*
3
+ * Why the options were invalid. Recorded instead of thrown: a throw from the
4
+ * synchronous `createAnalyticsClient` call would take down a host that sources
5
+ * its config remotely and forgot a try/catch — the crash this contract exists
6
+ * to prevent. Each error carries its description, as `ConfigError.description`
7
+ * does on iOS and Android, and the text is byte-identical with both SDKs so one
8
+ * support answer covers all three.
9
+ */
10
+ const emptyWriteKeyError = () => ({
11
+ type: 'emptyWriteKey',
12
+ description: 'writeKey must not be empty or whitespace-only',
13
+ });
14
+ const invalidIngestionHostError = (raw) => ({
15
+ type: 'invalidIngestionHost',
16
+ raw,
17
+ description: `ingestionHost must be an http(s) URL, got "${raw}"`,
18
+ });
19
+ // `http(s)://[userinfo@]host[:port][/path]`. Parsed by hand rather than with
20
+ // `URL`: React Native's `URL` polyfill does not implement `hostname`, so it
21
+ // cannot tell "https:" (no host) from a real origin. Accepts what Foundation
22
+ // and java.net.URL accept, so the same string passes on all three platforms:
23
+ // userinfo, an empty port ("host:"), and bracketed IPv6 hosts.
24
+ const HTTP_URL = /^(https?):\/\/(?:[^\s/?#@]*@)?(\[[^\]\s]+\]|[^\s/?#:@]+)(:\d*)?([/?#]\S*)?$/i;
25
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1']);
26
+ /** True for localhost / 127.0.0.1 / ::1 (IPv6 brackets stripped), exact match. */
27
+ export function isLoopbackHost(host) {
28
+ const bare = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;
29
+ return LOOPBACK_HOSTS.has(bare);
30
+ }
31
+ /**
32
+ * Single validation funnel, run once per `createAnalyticsClient` call — the
33
+ * equivalent of the native InitOptions constructor. Never throws: records the
34
+ * first error and clamps every numeric bound with a warning (one policy for
35
+ * all fields, matching iOS and Android). Warnings are logged here and nowhere
36
+ * else, so they appear once per call.
37
+ */
38
+ export function validateInitOptions(raw, opts = {}) {
39
+ const warn = opts.logWarnings === false ? () => { } : logWarn;
40
+ let configError = null;
41
+ const writeKey = typeof raw.writeKey === 'string' ? raw.writeKey.trim() : '';
42
+ if (writeKey === '') {
43
+ configError = emptyWriteKeyError();
44
+ }
45
+ const rawHost = typeof raw.ingestionHost === 'string' ? raw.ingestionHost : '';
46
+ const ingestionHost = rawHost.trim().replace(/\/+$/, '');
47
+ const match = HTTP_URL.exec(ingestionHost);
48
+ if (!match) {
49
+ if (configError === null) {
50
+ configError = invalidIngestionHostError(rawHost);
51
+ }
52
+ }
53
+ else if (match[1].toLowerCase() === 'http' && !isLoopbackHost(match[2])) {
54
+ // A cleartext origin is spoofable in transit — legitimate for local
55
+ // development, worth a warning anywhere else.
56
+ warn(`ingestionHost ${ingestionHost} is cleartext http — use https outside local development.`);
57
+ }
58
+ // NaN / Infinity (e.g. Number('') from remote config) would slip past every
59
+ // `<` check and reach the dispatcher as a 0ms flush loop or a silently
60
+ // disabled disk queue. Treated as unset, with a warning. Native integer
61
+ // options cannot hold these values, so only JS needs the check.
62
+ const finiteOrUnset = (name, value) => {
63
+ if (value == null || Number.isFinite(value))
64
+ return value;
65
+ warn(`${name} (${value}) is not a finite number — using the default`);
66
+ return undefined;
67
+ };
68
+ const flushIntervalSeconds = finiteOrUnset('flushIntervalSeconds', raw.flushIntervalSeconds);
69
+ if (flushIntervalSeconds != null && flushIntervalSeconds < 1) {
70
+ warn(`flushIntervalSeconds (${flushIntervalSeconds}) clamped to 1`);
71
+ }
72
+ const maxQueueEvents = finiteOrUnset('maxQueueEvents', raw.maxQueueEvents);
73
+ if (maxQueueEvents != null && maxQueueEvents < 1) {
74
+ warn(`maxQueueEvents (${maxQueueEvents}) clamped to 1`);
75
+ }
76
+ const maxDiskEvents = finiteOrUnset('maxDiskEvents', raw.maxDiskEvents);
77
+ if (maxDiskEvents != null && maxDiskEvents < 0) {
78
+ warn(`maxDiskEvents (${maxDiskEvents}) clamped to 0 — use 0 to disable disk persistence`);
79
+ }
80
+ const sessionTimeoutMinutes = finiteOrUnset('sessionTimeoutMinutes', raw.sessionTimeoutMinutes);
81
+ if (sessionTimeoutMinutes != null && sessionTimeoutMinutes < 1) {
82
+ warn(`sessionTimeoutMinutes (${sessionTimeoutMinutes}) clamped to 1`);
83
+ }
84
+ const clampedQueue = Math.max(1, maxQueueEvents !== null && maxQueueEvents !== void 0 ? maxQueueEvents : DEFAULT_MAX_QUEUE_EVENTS);
85
+ const clampedDisk = Math.max(0, maxDiskEvents !== null && maxDiskEvents !== void 0 ? maxDiskEvents : DEFAULT_MAX_DISK_EVENTS);
86
+ if (clampedDisk > 0 && clampedDisk < clampedQueue) {
87
+ warn(`maxDiskEvents (${clampedDisk}) is less than maxQueueEvents (${clampedQueue}) — memory can hold more events than disk can preserve; events may be dropped during background flush`);
88
+ }
89
+ return {
90
+ options: {
91
+ ...raw,
92
+ writeKey,
93
+ ingestionHost,
94
+ flushIntervalSeconds: flushIntervalSeconds != null
95
+ ? Math.max(1, flushIntervalSeconds)
96
+ : undefined,
97
+ maxQueueEvents: clampedQueue,
98
+ maxDiskEvents: clampedDisk,
99
+ sessionTimeoutMinutes: sessionTimeoutMinutes != null
100
+ ? Math.max(1, sessionTimeoutMinutes)
101
+ : undefined,
102
+ },
103
+ configError,
104
+ };
105
+ }
106
+ export const DEFAULT_MAX_QUEUE_EVENTS = 2000;
107
+ export const DEFAULT_MAX_DISK_EVENTS = 10000;
@@ -0,0 +1,13 @@
1
+ export declare const LIFECYCLE_VERSION_KEY = "metarouter:lifecycle:version";
2
+ export declare const LIFECYCLE_BUILD_KEY = "metarouter:lifecycle:build";
3
+ /**
4
+ * Storage for app lifecycle state (last-seen version + build). Lives in a
5
+ * dedicated module so neither IdentityManager.reset() nor the client's reset()
6
+ * can wipe install/update history. Errors are swallowed so missing or
7
+ * unavailable storage is treated as "no prior lifecycle state" — the caller
8
+ * decides whether that means install or update.
9
+ */
10
+ export declare function getLifecycleVersion(): Promise<string | null>;
11
+ export declare function getLifecycleBuild(): Promise<string | null>;
12
+ export declare function setLifecycleVersionBuild(version: string, build: string): Promise<void>;
13
+ //# sourceMappingURL=lifecycleStorage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycleStorage.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/lifecycleStorage.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,qBAAqB,iCAAiC,CAAC;AACpE,eAAO,MAAM,mBAAmB,+BAA+B,CAAC;AAEhE;;;;;;GAMG;AAEH,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAMlE;AAED,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAMhE;AAED,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CAOf"}
@@ -0,0 +1,35 @@
1
+ import AsyncStorage from '@react-native-async-storage/async-storage';
2
+ export const LIFECYCLE_VERSION_KEY = 'metarouter:lifecycle:version';
3
+ export const LIFECYCLE_BUILD_KEY = 'metarouter:lifecycle:build';
4
+ /**
5
+ * Storage for app lifecycle state (last-seen version + build). Lives in a
6
+ * dedicated module so neither IdentityManager.reset() nor the client's reset()
7
+ * can wipe install/update history. Errors are swallowed so missing or
8
+ * unavailable storage is treated as "no prior lifecycle state" — the caller
9
+ * decides whether that means install or update.
10
+ */
11
+ export async function getLifecycleVersion() {
12
+ try {
13
+ return await AsyncStorage.getItem(LIFECYCLE_VERSION_KEY);
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ export async function getLifecycleBuild() {
20
+ try {
21
+ return await AsyncStorage.getItem(LIFECYCLE_BUILD_KEY);
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
27
+ export async function setLifecycleVersionBuild(version, build) {
28
+ try {
29
+ await AsyncStorage.setItem(LIFECYCLE_VERSION_KEY, version);
30
+ await AsyncStorage.setItem(LIFECYCLE_BUILD_KEY, build);
31
+ }
32
+ catch {
33
+ // best-effort; cold-launch state will be re-derived on next run
34
+ }
35
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Milliseconds on a monotonic clock that keeps counting through device sleep —
3
+ * `mach_continuous_time` on iOS, `SystemClock.elapsedRealtime` on Android, the
4
+ * same clocks the native SDKs measure session inactivity with. Read
5
+ * synchronously from the MetaRouterClock native module.
6
+ *
7
+ * Not `performance.now()`: React Native backs it with clocks that stop while
8
+ * the device sleeps, so an app backgrounded on a phone locked for hours would
9
+ * resume into the same session. Without the native module (e.g. Expo Go), or
10
+ * once a synchronous call fails, this falls back to wall-clock for the rest of
11
+ * the process with a one-time warning: sleep is then measured, but a clock
12
+ * change can end or stretch a session.
13
+ */
14
+ export declare function continuousMillis(): number;
15
+ //# sourceMappingURL=monotonicClock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"monotonicClock.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/monotonicClock.ts"],"names":[],"mappings":"AAeA;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,CAiCzC"}
@@ -0,0 +1,52 @@
1
+ import { NativeModules } from 'react-native';
2
+ import { warn } from './logger';
3
+ // Resolved once: touch() reads the clock on every enriched event.
4
+ let nativeClock;
5
+ // Last good native reading and the wall time it was taken at. A fallback after
6
+ // native readings continues from here: switching straight to Date.now() would
7
+ // jump from boot-relative to epoch milliseconds, and the session manager would
8
+ // read that jump as decades of inactivity and roll the session over.
9
+ let lastNative = null;
10
+ /**
11
+ * Milliseconds on a monotonic clock that keeps counting through device sleep —
12
+ * `mach_continuous_time` on iOS, `SystemClock.elapsedRealtime` on Android, the
13
+ * same clocks the native SDKs measure session inactivity with. Read
14
+ * synchronously from the MetaRouterClock native module.
15
+ *
16
+ * Not `performance.now()`: React Native backs it with clocks that stop while
17
+ * the device sleeps, so an app backgrounded on a phone locked for hours would
18
+ * resume into the same session. Without the native module (e.g. Expo Go), or
19
+ * once a synchronous call fails, this falls back to wall-clock for the rest of
20
+ * the process with a one-time warning: sleep is then measured, but a clock
21
+ * change can end or stretch a session.
22
+ */
23
+ export function continuousMillis() {
24
+ if (nativeClock === undefined) {
25
+ const mod = NativeModules.MetaRouterClock;
26
+ nativeClock = mod !== null && mod !== void 0 ? mod : null;
27
+ if (!mod) {
28
+ warn('MetaRouterClock native module is not available. Session inactivity is measured on the wall clock.');
29
+ }
30
+ }
31
+ if (nativeClock) {
32
+ try {
33
+ const value = nativeClock.continuousMillis();
34
+ if (typeof value === 'number' && Number.isFinite(value)) {
35
+ lastNative = { value, wall: Date.now() };
36
+ return value;
37
+ }
38
+ throw new Error(`continuousMillis returned ${String(value)}`);
39
+ }
40
+ catch (err) {
41
+ // A sync native call can throw where blocking methods are unsupported
42
+ // (Chrome remote debugging, some interop setups). Every track() reads
43
+ // this clock, so the failure must not reach host code; fall back for the
44
+ // rest of the process rather than alternating between two clocks.
45
+ nativeClock = null;
46
+ warn('MetaRouterClock native call failed; session inactivity is measured on the wall clock from now on.', err);
47
+ }
48
+ }
49
+ return lastNative
50
+ ? lastNative.value + (Date.now() - lastNative.wall)
51
+ : Date.now();
52
+ }
@@ -0,0 +1,27 @@
1
+ export declare const SESSION_KEY = "metarouter:session";
2
+ /**
3
+ * Persisted session state. Lives in its own key, outside identityStorage, so
4
+ * neither IdentityManager.reset() nor the client's reset() can end a session as
5
+ * a side effect: a logout mid-session must not fragment the analytics session —
6
+ * session-scoped reporting downstream (e.g. GA4) counts the visit, not the
7
+ * login state.
8
+ *
9
+ * `lastActivityMs` is wall-clock epoch ms on purpose: a monotonic reading is
10
+ * meaningless across process restarts, the only reason it is persisted at all.
11
+ */
12
+ export interface StoredSession {
13
+ id: string | null;
14
+ count: number | null;
15
+ lastActivityMs: number | null;
16
+ }
17
+ /**
18
+ * Reads the stored session, retrying with a short backoff. If storage stays
19
+ * unreadable it reads as empty — what the native SDKs see after their
20
+ * preferences are cleared: the next event mints a session counted from 1 and
21
+ * persists it. That loses the lifetime count, once, with a warning; the
22
+ * alternative of not writing at all lets a later launch resume a session from
23
+ * before the failure and interleave two session ids downstream.
24
+ */
25
+ export declare function loadSession(delay?: (ms: number) => Promise<void>): Promise<StoredSession>;
26
+ export declare function saveSession(id: string, count: number, lastActivityMs: number): void;
27
+ //# sourceMappingURL=sessionStorage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sessionStorage.d.ts","sourceRoot":"","sources":["../../../src/analytics/utils/sessionStorage.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,WAAW,uBAAuB,CAAC;AAEhD;;;;;;;;;GASG;AACH,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,MAAM,GAAG,IAAI,CAAC;IAClB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B;AAoCD;;;;;;;GAOG;AACH,wBAAsB,WAAW,CAC/B,KAAK,GAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CACgB,GAClD,OAAO,CAAC,aAAa,CAAC,CAyBxB;AAMD,wBAAgB,WAAW,CACzB,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,MAAM,EACb,cAAc,EAAE,MAAM,GACrB,IAAI,CASN"}
@@ -0,0 +1,85 @@
1
+ import AsyncStorage from '@react-native-async-storage/async-storage';
2
+ import { warn } from './logger';
3
+ // One JSON value under one key, read and written with getItem/setItem, which
4
+ // AsyncStorage 2.x and 3.x both have (2.x's multiGet/multiSet became
5
+ // getMany/setMany in 3.x, so no batch call works on both). One setItem also
6
+ // keeps the id, count and last activity consistent if the app is killed
7
+ // mid-write. The iOS and Android SDKs keep the same three fields under
8
+ // separate keys.
9
+ export const SESSION_KEY = 'metarouter:session';
10
+ // A missing or corrupt field reads as absent, so a fresh install starts its
11
+ // counter at 1 instead of resuming a phantom count.
12
+ function integerAtLeast(value, min) {
13
+ return typeof value === 'number' &&
14
+ Number.isSafeInteger(value) &&
15
+ value >= min
16
+ ? value
17
+ : null;
18
+ }
19
+ // Waits before each retry of a failed read. A failure here is usually transient
20
+ // (storage busy at cold start); an immediate retry tends to fail the same way.
21
+ const RETRY_DELAYS_MS = [100, 400];
22
+ const EMPTY = { id: null, count: null, lastActivityMs: null };
23
+ // Null for a value that is not a JSON object: rereading the same bad value
24
+ // would fail the same way, so it is not retried like a failed read.
25
+ function parse(raw) {
26
+ let parsed;
27
+ try {
28
+ parsed = JSON.parse(raw);
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ if (typeof parsed !== 'object' || parsed === null)
34
+ return null;
35
+ const { id, count, lastActivityMs } = parsed;
36
+ return {
37
+ id: typeof id === 'string' && id !== '' ? id : null,
38
+ count: integerAtLeast(count, 1),
39
+ lastActivityMs: integerAtLeast(lastActivityMs, 0),
40
+ };
41
+ }
42
+ /**
43
+ * Reads the stored session, retrying with a short backoff. If storage stays
44
+ * unreadable it reads as empty — what the native SDKs see after their
45
+ * preferences are cleared: the next event mints a session counted from 1 and
46
+ * persists it. That loses the lifetime count, once, with a warning; the
47
+ * alternative of not writing at all lets a later launch resume a session from
48
+ * before the failure and interleave two session ids downstream.
49
+ */
50
+ export async function loadSession(delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) {
51
+ let lastError;
52
+ for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt++) {
53
+ if (attempt > 0)
54
+ await delay(RETRY_DELAYS_MS[attempt - 1]);
55
+ let raw;
56
+ try {
57
+ raw = await AsyncStorage.getItem(SESSION_KEY);
58
+ }
59
+ catch (err) {
60
+ lastError = err;
61
+ continue;
62
+ }
63
+ if (raw == null)
64
+ return EMPTY;
65
+ const session = parse(raw);
66
+ if (session)
67
+ return session;
68
+ warn('Stored session is corrupt — starting a new session counted from 1.', raw.slice(0, 100));
69
+ return EMPTY;
70
+ }
71
+ warn('Session storage unreadable — starting a new session counted from 1.', lastError);
72
+ return EMPTY;
73
+ }
74
+ // Fire-and-forget: called from synchronous enrichment, so it must not throw
75
+ // into the host's track() — not even synchronously, which a storage module
76
+ // that is missing or mismatched does before a promise exists. A lost write
77
+ // costs at most one extra session after the next restart.
78
+ export function saveSession(id, count, lastActivityMs) {
79
+ try {
80
+ AsyncStorage.setItem(SESSION_KEY, JSON.stringify({ id, count, lastActivityMs })).catch(() => { });
81
+ }
82
+ catch {
83
+ // Same outcome as a rejected write.
84
+ }
85
+ }
@@ -0,0 +1,37 @@
1
+ export declare const DEFAULT_DEDUP_MAX_ENTRIES = 1000;
2
+ export declare const DEFAULT_DEDUP_TTL_MS: number;
3
+ /**
4
+ * Bounded record of recently seen bridge `messageId`s, with the iOS and
5
+ * Android rules.
6
+ *
7
+ * Redelivery happens when the page re-posts after a lost ack, so a duplicate
8
+ * can only arrive shortly after the original — entries older than the TTL
9
+ * count as never seen. The size bound keeps a long-lived WebView from growing
10
+ * the store forever; when full, the oldest entry goes first, being the least
11
+ * likely to still be inside a redelivery window.
12
+ *
13
+ * In-memory only: a duplicate across a process restart is indistinguishable
14
+ * from a fresh event and too rare to justify storage I/O on the message path.
15
+ */
16
+ export declare class BridgeDedupStore {
17
+ private readonly maxEntries;
18
+ private readonly ttlMs;
19
+ private readonly clock;
20
+ private readonly seen;
21
+ constructor(maxEntries?: number, ttlMs?: number, clock?: () => number);
22
+ /**
23
+ * Records `messageId` and reports whether it was new: true when unseen (or
24
+ * seen only outside the TTL) — process it; false for a live duplicate — drop
25
+ * it. A duplicate does NOT refresh the original timestamp: refreshing would
26
+ * let a producer stuck in a re-post loop keep its entry alive forever.
27
+ */
28
+ markIfNew(messageId: string): boolean;
29
+ /**
30
+ * Removes a recorded id whose message never entered the delivery path —
31
+ * left recorded, a legitimate producer retry would read as a duplicate of an
32
+ * event that was actually lost.
33
+ */
34
+ forget(messageId: string): void;
35
+ size(): number;
36
+ }
37
+ //# sourceMappingURL=bridgeDedupStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bridgeDedupStore.d.ts","sourceRoot":"","sources":["../../../src/analytics/webview/bridgeDedupStore.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,yBAAyB,OAAQ,CAAC;AAC/C,eAAO,MAAM,oBAAoB,QAAgB,CAAC;AAElD;;;;;;;;;;;;GAYG;AACH,qBAAa,gBAAgB;IAKzB,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,KAAK;IAEtB,OAAO,CAAC,QAAQ,CAAC,KAAK;IANxB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA6B;gBAG/B,UAAU,GAAE,MAAkC,EAC9C,KAAK,GAAE,MAA6B,EAEpC,KAAK,GAAE,MAAM,MAAyB;IAMzD;;;;;OAKG;IACH,SAAS,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO;IAgBrC;;;;OAIG;IACH,MAAM,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IAI/B,IAAI,IAAI,MAAM;CAGf"}
@@ -0,0 +1,63 @@
1
+ import { continuousMillis } from '../utils/monotonicClock';
2
+ export const DEFAULT_DEDUP_MAX_ENTRIES = 1000;
3
+ export const DEFAULT_DEDUP_TTL_MS = 5 * 60 * 1000;
4
+ /**
5
+ * Bounded record of recently seen bridge `messageId`s, with the iOS and
6
+ * Android rules.
7
+ *
8
+ * Redelivery happens when the page re-posts after a lost ack, so a duplicate
9
+ * can only arrive shortly after the original — entries older than the TTL
10
+ * count as never seen. The size bound keeps a long-lived WebView from growing
11
+ * the store forever; when full, the oldest entry goes first, being the least
12
+ * likely to still be inside a redelivery window.
13
+ *
14
+ * In-memory only: a duplicate across a process restart is indistinguishable
15
+ * from a fresh event and too rare to justify storage I/O on the message path.
16
+ */
17
+ export class BridgeDedupStore {
18
+ constructor(maxEntries = DEFAULT_DEDUP_MAX_ENTRIES, ttlMs = DEFAULT_DEDUP_TTL_MS,
19
+ // Monotonic through sleep, so the window measures real elapsed time.
20
+ clock = continuousMillis) {
21
+ this.maxEntries = maxEntries;
22
+ this.ttlMs = ttlMs;
23
+ this.clock = clock;
24
+ // Map iterates in insertion order, so the first key is the oldest entry.
25
+ this.seen = new Map();
26
+ if (!(maxEntries > 0))
27
+ throw new Error('maxEntries must be > 0');
28
+ if (!(ttlMs > 0))
29
+ throw new Error('ttlMs must be > 0');
30
+ }
31
+ /**
32
+ * Records `messageId` and reports whether it was new: true when unseen (or
33
+ * seen only outside the TTL) — process it; false for a live duplicate — drop
34
+ * it. A duplicate does NOT refresh the original timestamp: refreshing would
35
+ * let a producer stuck in a re-post loop keep its entry alive forever.
36
+ */
37
+ markIfNew(messageId) {
38
+ const now = this.clock();
39
+ const firstSeenAt = this.seen.get(messageId);
40
+ if (firstSeenAt !== undefined && now - firstSeenAt < this.ttlMs) {
41
+ return false;
42
+ }
43
+ // Delete before set so an expired entry moves to the back of the eviction
44
+ // order instead of keeping its stale position.
45
+ this.seen.delete(messageId);
46
+ this.seen.set(messageId, now);
47
+ if (this.seen.size > this.maxEntries) {
48
+ this.seen.delete(this.seen.keys().next().value);
49
+ }
50
+ return true;
51
+ }
52
+ /**
53
+ * Removes a recorded id whose message never entered the delivery path —
54
+ * left recorded, a legitimate producer retry would read as a duplicate of an
55
+ * event that was actually lost.
56
+ */
57
+ forget(messageId) {
58
+ this.seen.delete(messageId);
59
+ }
60
+ size() {
61
+ return this.seen.size;
62
+ }
63
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Error codes returned to the web producer. Closed set — the web side may
3
+ * branch on these, so adding a code is a contract change. The strings are the
4
+ * exact wire values, identical on iOS and Android.
5
+ */
6
+ export type BridgeErrorCode = 'malformed_json' | 'malformed_payload' | 'missing_field' | 'unknown_type' | 'unsupported_version' | 'payload_too_large' | 'not_ready';
7
+ /** Point-in-time page facts stamped by the wrapper at call time. */
8
+ export interface PageContext {
9
+ url?: string;
10
+ path?: string;
11
+ search?: string;
12
+ title?: string;
13
+ referrer?: string;
14
+ }
15
+ /**
16
+ * A validated web→native bridge envelope (contract v1). Only produced by
17
+ * parseBridgeEnvelope, so downstream code (merge, dedup) never re-validates.
18
+ *
19
+ * `sentAt` is the producer's untrusted clock (the SDK sets the real timestamp
20
+ * at merge) and `source` distinguishes the injected wrapper from a future
21
+ * web-SDK producer; both are carried, not consumed.
22
+ */
23
+ export interface BridgeEnvelope {
24
+ version: number;
25
+ messageId: string;
26
+ /** "track" or "page" in contract v1. */
27
+ type: 'track' | 'page';
28
+ name: string;
29
+ properties: Record<string, unknown>;
30
+ sentAt?: string;
31
+ page?: PageContext;
32
+ source?: {
33
+ producer?: string;
34
+ wrapperVersion?: string;
35
+ };
36
+ }
37
+ export type BridgeParseResult = {
38
+ valid: true;
39
+ envelope: BridgeEnvelope;
40
+ } | {
41
+ valid: false;
42
+ code: BridgeErrorCode;
43
+ message: string;
44
+ /** Echoed when it could be extracted — absent for unparseable input. */
45
+ messageId?: string;
46
+ /** Set only for unsupported_version. */
47
+ supportedVersion?: number;
48
+ };
49
+ export declare const SUPPORTED_ENVELOPE_VERSION = 1;
50
+ /**
51
+ * Max envelope size accepted at the untrusted page→SDK boundary: a policy cap
52
+ * that bounds parse cost. 64 KiB sits well under the cluster's 250 KiB
53
+ * single-event ingest cap, leaving headroom for enrichment.
54
+ */
55
+ export declare const MAX_ENVELOPE_BYTES: number;
56
+ export declare const MAX_MESSAGE_ID_CHARS = 256;
57
+ /**
58
+ * Parses and validates a raw bridge message, with the same rules and messages
59
+ * as the iOS and Android parsers.
60
+ *
61
+ * Validation order: size (before parsing, so an oversized payload is never
62
+ * deserialized) → JSON → messageId → version → type → name → properties.
63
+ * Unknown fields are ignored so the web side can add optional fields without a
64
+ * version bump; optional fields of an unexpected type read as absent — only
65
+ * `properties`, which the merge depends on, is strict.
66
+ */
67
+ export declare function parseBridgeEnvelope(raw: string): BridgeParseResult;
68
+ //# sourceMappingURL=bridgeEnvelope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bridgeEnvelope.d.ts","sourceRoot":"","sources":["../../../src/analytics/webview/bridgeEnvelope.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,eAAe,GACvB,gBAAgB,GAChB,mBAAmB,GACnB,eAAe,GACf,cAAc,GACd,qBAAqB,GACrB,mBAAmB,GACnB,WAAW,CAAC;AAEhB,oEAAoE;AACpE,MAAM,WAAW,WAAW;IAC1B,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,wCAAwC;IACxC,IAAI,EAAE,OAAO,GAAG,MAAM,CAAC;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACpC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,WAAW,CAAC;IACnB,MAAM,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,cAAc,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CACzD;AAED,MAAM,MAAM,iBAAiB,GACzB;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,QAAQ,EAAE,cAAc,CAAA;CAAE,GACzC;IACE,KAAK,EAAE,KAAK,CAAC;IACb,IAAI,EAAE,eAAe,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,wEAAwE;IACxE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wCAAwC;IACxC,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B,CAAC;AAEN,eAAO,MAAM,0BAA0B,IAAI,CAAC;AAE5C;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,QAAY,CAAC;AAI5C,eAAO,MAAM,oBAAoB,MAAM,CAAC;AA8BxC;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,iBAAiB,CAmHlE"}