@metarouter/react-native-sdk 1.8.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 (54) hide show
  1. package/README.md +139 -6
  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 +21 -0
  8. package/lib/analytics/MetaRouterAnalyticsClient.d.ts.map +1 -1
  9. package/lib/analytics/MetaRouterAnalyticsClient.js +77 -10
  10. package/lib/analytics/init.d.ts.map +1 -1
  11. package/lib/analytics/init.js +14 -1
  12. package/lib/analytics/proxy/proxyClient.d.ts +2 -0
  13. package/lib/analytics/proxy/proxyClient.d.ts.map +1 -1
  14. package/lib/analytics/proxy/proxyClient.js +28 -1
  15. package/lib/analytics/session/sessionManager.d.ts +108 -0
  16. package/lib/analytics/session/sessionManager.d.ts.map +1 -0
  17. package/lib/analytics/session/sessionManager.js +193 -0
  18. package/lib/analytics/types.d.ts +58 -0
  19. package/lib/analytics/types.d.ts.map +1 -1
  20. package/lib/analytics/utils/appContext.d.ts +5 -3
  21. package/lib/analytics/utils/appContext.d.ts.map +1 -1
  22. package/lib/analytics/utils/appContext.js +9 -8
  23. package/lib/analytics/utils/enrichEvent.d.ts +6 -2
  24. package/lib/analytics/utils/enrichEvent.d.ts.map +1 -1
  25. package/lib/analytics/utils/enrichEvent.js +20 -3
  26. package/lib/analytics/utils/initOptions.d.ts.map +1 -1
  27. package/lib/analytics/utils/initOptions.js +7 -0
  28. package/lib/analytics/utils/monotonicClock.d.ts +15 -0
  29. package/lib/analytics/utils/monotonicClock.d.ts.map +1 -0
  30. package/lib/analytics/utils/monotonicClock.js +52 -0
  31. package/lib/analytics/utils/sessionStorage.d.ts +27 -0
  32. package/lib/analytics/utils/sessionStorage.d.ts.map +1 -0
  33. package/lib/analytics/utils/sessionStorage.js +85 -0
  34. package/lib/analytics/webview/bridgeDedupStore.d.ts +37 -0
  35. package/lib/analytics/webview/bridgeDedupStore.d.ts.map +1 -0
  36. package/lib/analytics/webview/bridgeDedupStore.js +63 -0
  37. package/lib/analytics/webview/bridgeEnvelope.d.ts +68 -0
  38. package/lib/analytics/webview/bridgeEnvelope.d.ts.map +1 -0
  39. package/lib/analytics/webview/bridgeEnvelope.js +140 -0
  40. package/lib/analytics/webview/bridgeMessageProcessor.d.ts +38 -0
  41. package/lib/analytics/webview/bridgeMessageProcessor.d.ts.map +1 -0
  42. package/lib/analytics/webview/bridgeMessageProcessor.js +67 -0
  43. package/lib/analytics/webview/bridgeWrapperScript.d.ts +53 -0
  44. package/lib/analytics/webview/bridgeWrapperScript.d.ts.map +1 -0
  45. package/lib/analytics/webview/bridgeWrapperScript.js +161 -0
  46. package/lib/analytics/webview/webViewBridge.d.ts +39 -0
  47. package/lib/analytics/webview/webViewBridge.d.ts.map +1 -0
  48. package/lib/analytics/webview/webViewBridge.js +211 -0
  49. package/lib/analytics/webview/webViewSupport.d.ts +16 -0
  50. package/lib/analytics/webview/webViewSupport.d.ts.map +1 -0
  51. package/lib/analytics/webview/webViewSupport.js +52 -0
  52. package/lib/index.d.ts +1 -1
  53. package/lib/index.d.ts.map +1 -1
  54. package/package.json +11 -3
@@ -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"}
@@ -0,0 +1,140 @@
1
+ export const SUPPORTED_ENVELOPE_VERSION = 1;
2
+ /**
3
+ * Max envelope size accepted at the untrusted page→SDK boundary: a policy cap
4
+ * that bounds parse cost. 64 KiB sits well under the cluster's 250 KiB
5
+ * single-event ingest cap, leaving headroom for enrichment.
6
+ */
7
+ export const MAX_ENVELOPE_BYTES = 64 * 1024;
8
+ // UUIDs are 36 chars; the ceiling keeps the dedup store bounded in bytes, not
9
+ // just entries — 1000 retained near-64 KB ids would be ~64 MB.
10
+ export const MAX_MESSAGE_ID_CHARS = 256;
11
+ /** UTF-8 byte length without allocating an encoded copy. */
12
+ function utf8ByteLength(s) {
13
+ let bytes = 0;
14
+ for (let i = 0; i < s.length; i++) {
15
+ const c = s.charCodeAt(i);
16
+ if (c < 0x80)
17
+ bytes += 1;
18
+ else if (c < 0x800)
19
+ bytes += 2;
20
+ else if (c >= 0xd800 &&
21
+ c <= 0xdbff &&
22
+ i + 1 < s.length &&
23
+ s.charCodeAt(i + 1) >= 0xdc00 &&
24
+ s.charCodeAt(i + 1) <= 0xdfff) {
25
+ // A surrogate pair is one 4-byte code point.
26
+ bytes += 4;
27
+ i++;
28
+ }
29
+ else
30
+ bytes += 3; // includes a lone surrogate, encoded as U+FFFD
31
+ }
32
+ return bytes;
33
+ }
34
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
35
+ const stringOrUndefined = (v) => typeof v === 'string' ? v : undefined;
36
+ /**
37
+ * Parses and validates a raw bridge message, with the same rules and messages
38
+ * as the iOS and Android parsers.
39
+ *
40
+ * Validation order: size (before parsing, so an oversized payload is never
41
+ * deserialized) → JSON → messageId → version → type → name → properties.
42
+ * Unknown fields are ignored so the web side can add optional fields without a
43
+ * version bump; optional fields of an unexpected type read as absent — only
44
+ * `properties`, which the merge depends on, is strict.
45
+ */
46
+ export function parseBridgeEnvelope(raw) {
47
+ // A UTF-8 length is never below the UTF-16 length, so an over-length string
48
+ // is oversized without counting bytes.
49
+ if (raw.length > MAX_ENVELOPE_BYTES ||
50
+ utf8ByteLength(raw) > MAX_ENVELOPE_BYTES) {
51
+ return invalid('payload_too_large', `envelope exceeds ${MAX_ENVELOPE_BYTES} bytes`);
52
+ }
53
+ let root;
54
+ try {
55
+ root = JSON.parse(raw);
56
+ }
57
+ catch {
58
+ return invalid('malformed_json', 'envelope is not valid JSON');
59
+ }
60
+ if (!isObject(root)) {
61
+ return invalid('malformed_payload', 'envelope must be a JSON object');
62
+ }
63
+ // Extracted first so later rejections can echo it in the error reply.
64
+ const messageId = stringOrUndefined(root.messageId);
65
+ if (!messageId || messageId.trim() === '') {
66
+ return invalid('missing_field', 'messageId is required');
67
+ }
68
+ if (messageId.length > MAX_MESSAGE_ID_CHARS) {
69
+ // Not echoed: the reply would amplify the same bytes back to the page.
70
+ return invalid('malformed_payload', `messageId exceeds ${MAX_MESSAGE_ID_CHARS} chars`);
71
+ }
72
+ if (root.version === undefined) {
73
+ return invalid('missing_field', 'version is required', messageId);
74
+ }
75
+ const version = root.version;
76
+ if (typeof version !== 'number' || !Number.isSafeInteger(version)) {
77
+ return invalid('malformed_payload', 'version must be an integer', messageId);
78
+ }
79
+ if (version < 1) {
80
+ return invalid('malformed_payload', 'version must be >= 1', messageId);
81
+ }
82
+ if (version > SUPPORTED_ENVELOPE_VERSION) {
83
+ return {
84
+ ...invalid('unsupported_version', `envelope version ${version} > supported ${SUPPORTED_ENVELOPE_VERSION}`, messageId),
85
+ supportedVersion: SUPPORTED_ENVELOPE_VERSION,
86
+ };
87
+ }
88
+ const type = stringOrUndefined(root.type);
89
+ if (type === undefined) {
90
+ return invalid('missing_field', 'type is required', messageId);
91
+ }
92
+ if (type !== 'track' && type !== 'page') {
93
+ return invalid('unknown_type', `type must be "track" or "page", got "${type}"`, messageId);
94
+ }
95
+ const name = stringOrUndefined(root.name);
96
+ if (!name || name.trim() === '') {
97
+ return invalid('missing_field', 'name is required', messageId);
98
+ }
99
+ let properties;
100
+ if (root.properties === undefined || root.properties === null) {
101
+ properties = {};
102
+ }
103
+ else if (isObject(root.properties)) {
104
+ properties = root.properties;
105
+ }
106
+ else {
107
+ return invalid('malformed_payload', 'properties must be a JSON object', messageId);
108
+ }
109
+ const envelope = {
110
+ version,
111
+ messageId,
112
+ type,
113
+ name,
114
+ properties,
115
+ };
116
+ const sentAt = stringOrUndefined(root.sentAt);
117
+ if (sentAt !== undefined)
118
+ envelope.sentAt = sentAt;
119
+ if (isObject(root.page)) {
120
+ const page = {};
121
+ for (const key of ['url', 'path', 'search', 'title', 'referrer']) {
122
+ const value = stringOrUndefined(root.page[key]);
123
+ if (value !== undefined)
124
+ page[key] = value;
125
+ }
126
+ envelope.page = page;
127
+ }
128
+ if (isObject(root.source)) {
129
+ envelope.source = {
130
+ producer: stringOrUndefined(root.source.producer),
131
+ wrapperVersion: stringOrUndefined(root.source.wrapperVersion),
132
+ };
133
+ }
134
+ return { valid: true, envelope };
135
+ }
136
+ function invalid(code, message, messageId) {
137
+ return messageId === undefined
138
+ ? { valid: false, code, message }
139
+ : { valid: false, code, message, messageId };
140
+ }
@@ -0,0 +1,38 @@
1
+ import { BridgeDedupStore } from './bridgeDedupStore';
2
+ import { type BridgeEnvelope, type BridgeErrorCode } from './bridgeEnvelope';
3
+ /**
4
+ * Ack / error reply sent back to the wrapper. Wire shape (absent fields are
5
+ * omitted, as on iOS and Android):
6
+ * - ok: `{"status":"ok","messageId":"…"}`
7
+ * - error: `{"status":"error","messageId":"…","code":"…","message":"…","supportedVersion":1}`
8
+ */
9
+ export interface BridgeReply {
10
+ status: 'ok' | 'error';
11
+ messageId?: string;
12
+ code?: BridgeErrorCode;
13
+ message?: string;
14
+ supportedVersion?: number;
15
+ }
16
+ /**
17
+ * Receives validated, deduplicated envelopes. Returns whether the event
18
+ * actually entered the delivery path: an `ok` ack for an event that was
19
+ * silently dropped (SDK not ready) would lie to the producer.
20
+ */
21
+ export type BridgeEventSink = (envelope: BridgeEnvelope) => boolean;
22
+ /**
23
+ * The receive pipeline: raw message → parse/validate → dedup → sink, producing
24
+ * the reply for the wrapper. One processor serves every attached WebView of a
25
+ * session, like the native SDKs' one processor per client.
26
+ *
27
+ * Rejections are logged as well as replied — page consoles are rarely watched
28
+ * in production, so the app log is the primary debugging surface. JS is
29
+ * single-threaded, so the native "one confined thread" rule holds by
30
+ * construction.
31
+ */
32
+ export declare class BridgeMessageProcessor {
33
+ private readonly sink;
34
+ private readonly dedupStore;
35
+ constructor(sink: BridgeEventSink, dedupStore?: BridgeDedupStore);
36
+ process(raw: string): BridgeReply;
37
+ }
38
+ //# sourceMappingURL=bridgeMessageProcessor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bridgeMessageProcessor.d.ts","sourceRoot":"","sources":["../../../src/analytics/webview/bridgeMessageProcessor.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAEL,KAAK,cAAc,EACnB,KAAK,eAAe,EACrB,MAAM,kBAAkB,CAAC;AAE1B;;;;;GAKG;AACH,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,IAAI,GAAG,OAAO,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,eAAe,CAAC;IACvB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;;GAIG;AACH,MAAM,MAAM,eAAe,GAAG,CAAC,QAAQ,EAAE,cAAc,KAAK,OAAO,CAAC;AAEpE;;;;;;;;;GASG;AACH,qBAAa,sBAAsB;IAE/B,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,UAAU;gBADV,IAAI,EAAE,eAAe,EACrB,UAAU,GAAE,gBAAyC;IAGxE,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW;CAkDlC"}
@@ -0,0 +1,67 @@
1
+ import { log, warn } from '../utils/logger';
2
+ import { BridgeDedupStore } from './bridgeDedupStore';
3
+ import { parseBridgeEnvelope, } from './bridgeEnvelope';
4
+ /**
5
+ * The receive pipeline: raw message → parse/validate → dedup → sink, producing
6
+ * the reply for the wrapper. One processor serves every attached WebView of a
7
+ * session, like the native SDKs' one processor per client.
8
+ *
9
+ * Rejections are logged as well as replied — page consoles are rarely watched
10
+ * in production, so the app log is the primary debugging surface. JS is
11
+ * single-threaded, so the native "one confined thread" rule holds by
12
+ * construction.
13
+ */
14
+ export class BridgeMessageProcessor {
15
+ constructor(sink, dedupStore = new BridgeDedupStore()) {
16
+ this.sink = sink;
17
+ this.dedupStore = dedupStore;
18
+ }
19
+ process(raw) {
20
+ const result = parseBridgeEnvelope(raw);
21
+ if (!result.valid) {
22
+ // Truncated: for unknown_type the message embeds page-controlled text,
23
+ // and a page could otherwise write 64 KB lines into the app log.
24
+ warn(`WebView bridge message rejected (${result.code}): ${result.message.slice(0, 200)}`);
25
+ // Key order matches the native serializers, so the wire form is
26
+ // byte-identical across platforms.
27
+ return {
28
+ status: 'error',
29
+ ...(result.messageId !== undefined && { messageId: result.messageId }),
30
+ code: result.code,
31
+ message: result.message,
32
+ ...(result.supportedVersion !== undefined && {
33
+ supportedVersion: result.supportedVersion,
34
+ }),
35
+ };
36
+ }
37
+ const { envelope } = result;
38
+ if (!this.dedupStore.markIfNew(envelope.messageId)) {
39
+ // Acked ok, not errored: the producer's goal — exactly-once enqueue —
40
+ // was already met by the first delivery.
41
+ log(`WebView bridge duplicate dropped (messageId=${envelope.messageId})`);
42
+ return { status: 'ok', messageId: envelope.messageId };
43
+ }
44
+ let accepted = false;
45
+ try {
46
+ accepted = this.sink(envelope);
47
+ }
48
+ catch (err) {
49
+ warn('WebView bridge event enqueue failed:', err);
50
+ }
51
+ if (accepted) {
52
+ return { status: 'ok', messageId: envelope.messageId };
53
+ }
54
+ // Never entered the delivery path — un-record the id so a producer retry
55
+ // is not misread as a duplicate of a message that was in fact lost.
56
+ this.dedupStore.forget(envelope.messageId);
57
+ // Debug-level, as on iOS: expected while the SDK initializes or resets,
58
+ // and a page retrying in a loop must not flood the app log.
59
+ log(`WebView bridge event not accepted (messageId=${envelope.messageId})`);
60
+ return {
61
+ status: 'error',
62
+ messageId: envelope.messageId,
63
+ code: 'not_ready',
64
+ message: 'SDK not ready to accept events',
65
+ };
66
+ }
67
+ }
@@ -0,0 +1,53 @@
1
+ export declare const DEFAULT_BRIDGE_OBJECT_NAME = "metarouterBridge";
2
+ /**
3
+ * Name of the `window` channel object the wrapper posts through and whose
4
+ * `onmessage` receives replies — the same name, and the same page-visible
5
+ * surface, as the iOS and Android SDKs.
6
+ */
7
+ export declare const NATIVE_CHANNEL_NAME = "__metaRouterNativeChannel";
8
+ /**
9
+ * Prefix on every bridge message. `window.ReactNativeWebView.postMessage` is
10
+ * one channel shared with the host's own page→app messages (native has a
11
+ * dedicated one), so the prefix is what lets the SDK claim its messages and
12
+ * pass everything else through to the host untouched. The wrapper appends a
13
+ * per-session token after it (see attachWebViewBridge).
14
+ */
15
+ export declare const BRIDGE_MESSAGE_PREFIX = "__metaRouterBridge:";
16
+ export declare const WRAPPER_VERSION = "1.0.0";
17
+ /**
18
+ * Builds the wrapper injected via `injectedJavaScriptBeforeContentLoaded`:
19
+ * at document start on iOS, at `onPageStarted` on Android (so a page's
20
+ * earliest inline scripts can run before it exists). Identical to the iOS and Android
21
+ * wrapper except for the channel shim:
22
+ *
23
+ * - Defines `window.metarouterBridge` with `track`/`page`, wraps each call in
24
+ * an envelope — minting `messageId` and stamping the page facts at call time
25
+ * — and posts it as a JSON string. `messageId` must be minted here: an id
26
+ * assigned at receipt would give two deliveries of one message two ids.
27
+ * - Self-checks `location.origin` against the allowlist and defines nothing on
28
+ * other pages. `react-native-webview` has no origin-scoped channel, so this
29
+ * check plus the SDK's check of the sending frame's URL carry the security
30
+ * model together, as on iOS.
31
+ * - The channel shim posts through `window.ReactNativeWebView`, resolved at
32
+ * call time, and exposes a settable `onmessage` that replies are delivered to.
33
+ * - `properties` may be an object or a JSON string; a string that fails to
34
+ * parse is forwarded as-is so the SDK rejects it with `malformed_payload`.
35
+ * - JSON.stringify is guarded: unstringifiable properties (circular, BigInt)
36
+ * are coerced to a string and re-posted, so the page gets a coded error
37
+ * reply, never a TypeError thrown into its own calling code.
38
+ */
39
+ export declare function buildBridgeWrapperScript(allowedOrigins: readonly string[], bridgeObjectName?: string, messagePrefix?: string): string;
40
+ /**
41
+ * Reply delivery script, run in the page with the WebView ref's
42
+ * `injectJavaScript`. The reply JSON rides as a JS string literal, so the
43
+ * page-visible shape matches iOS and Android: `onmessage` receives an
44
+ * event-like object whose `data` is the reply string. The trailing `true;` is
45
+ * what react-native-webview asks injected scripts to end with.
46
+ *
47
+ * `injectJavaScript` runs in whatever page is in the main frame when the reply
48
+ * is sent, not in the frame that sent the message (iOS and Android reply to the
49
+ * source frame). The origin guard keeps a reply from reaching a page the
50
+ * WebView navigated to in between.
51
+ */
52
+ export declare function buildReplyScript(replyJson: string, allowedOrigins: readonly string[]): string;
53
+ //# sourceMappingURL=bridgeWrapperScript.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bridgeWrapperScript.d.ts","sourceRoot":"","sources":["../../../src/analytics/webview/bridgeWrapperScript.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,0BAA0B,qBAAqB,CAAC;AAE7D;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,8BAA8B,CAAC;AAE/D;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,wBAAwB,CAAC;AAE3D,eAAO,MAAM,eAAe,UAAU,CAAC;AAEvC;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,wBAAwB,CACtC,cAAc,EAAE,SAAS,MAAM,EAAE,EACjC,gBAAgB,GAAE,MAAmC,EACrD,aAAa,GAAE,MAA8B,GAC5C,MAAM,CA+FR;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAC9B,SAAS,EAAE,MAAM,EACjB,cAAc,EAAE,SAAS,MAAM,EAAE,GAChC,MAAM,CAKR"}