@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,161 @@
1
+ export 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 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 const BRIDGE_MESSAGE_PREFIX = '__metaRouterBridge:';
16
+ export 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 function buildBridgeWrapperScript(allowedOrigins, bridgeObjectName = DEFAULT_BRIDGE_OBJECT_NAME, messagePrefix = BRIDGE_MESSAGE_PREFIX) {
40
+ if (allowedOrigins.length === 0) {
41
+ throw new Error('allowedOrigins must not be empty');
42
+ }
43
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(bridgeObjectName)) {
44
+ throw new Error('bridgeObjectName must be a valid JS identifier');
45
+ }
46
+ // JSON-encoding the allowlist keeps a hostile origin string from breaking
47
+ // out of the script — quotes arrive escaped.
48
+ const originsJsArray = JSON.stringify(allowedOrigins);
49
+ const prefix = JSON.stringify(messagePrefix);
50
+ return `(function() {
51
+ 'use strict';
52
+ var ALLOWED_ORIGINS = ${originsJsArray};
53
+ // A plain loop, not indexOf: on Android the page's own scripts can run
54
+ // first, and a patched Array.prototype.indexOf would pass any origin.
55
+ var allowed = false;
56
+ for (var i = 0; i < ALLOWED_ORIGINS.length; i++) {
57
+ if (ALLOWED_ORIGINS[i] === location.origin) { allowed = true; }
58
+ }
59
+ if (!allowed) { return; }
60
+ if (window.${bridgeObjectName}) { return; }
61
+
62
+ if (!window.${NATIVE_CHANNEL_NAME}) {
63
+ window.${NATIVE_CHANNEL_NAME} = {
64
+ onmessage: null,
65
+ postMessage: function(data) {
66
+ if (window.ReactNativeWebView &&
67
+ typeof window.ReactNativeWebView.postMessage === 'function') {
68
+ window.ReactNativeWebView.postMessage(${prefix} + data);
69
+ }
70
+ }
71
+ };
72
+ }
73
+
74
+ function uuidv4() {
75
+ if (window.crypto && window.crypto.getRandomValues) {
76
+ var b = new Uint8Array(16);
77
+ window.crypto.getRandomValues(b);
78
+ b[6] = (b[6] & 0x0f) | 0x40;
79
+ b[8] = (b[8] & 0x3f) | 0x80;
80
+ var h = [];
81
+ for (var i = 0; i < 16; i++) { h.push((b[i] + 0x100).toString(16).slice(1)); }
82
+ return h.slice(0, 4).join('') + '-' + h.slice(4, 6).join('') + '-' +
83
+ h.slice(6, 8).join('') + '-' + h.slice(8, 10).join('') + '-' +
84
+ h.slice(10, 16).join('');
85
+ }
86
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
87
+ var r = Math.random() * 16 | 0;
88
+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
89
+ });
90
+ }
91
+
92
+ function post(type, name, properties) {
93
+ if (typeof name !== 'string' || name.length === 0) { return; }
94
+ var props = properties;
95
+ if (typeof props === 'string') {
96
+ try { props = JSON.parse(props); } catch (e) { /* forward as-is; native rejects */ }
97
+ }
98
+ if (props === undefined || props === null) { props = {}; }
99
+ var envelope = {
100
+ version: 1,
101
+ messageId: uuidv4(),
102
+ type: type,
103
+ name: name,
104
+ properties: props,
105
+ sentAt: new Date().toISOString(),
106
+ page: {
107
+ url: location.href,
108
+ path: location.pathname,
109
+ search: location.search,
110
+ title: document.title,
111
+ referrer: document.referrer
112
+ },
113
+ source: { producer: 'wrapper', wrapperVersion: '${WRAPPER_VERSION}' }
114
+ };
115
+ var channel = window.${NATIVE_CHANNEL_NAME};
116
+ if (!channel || typeof channel.postMessage !== 'function') { return; }
117
+ var payload;
118
+ try {
119
+ payload = JSON.stringify(envelope);
120
+ } catch (e) {
121
+ try { envelope.properties = String(props); } catch (e2) { envelope.properties = 'unserializable'; }
122
+ payload = JSON.stringify(envelope);
123
+ }
124
+ channel.postMessage(payload);
125
+ }
126
+
127
+ window.${bridgeObjectName} = {
128
+ track: function(name, properties) { post('track', name, properties); },
129
+ page: function(name, properties) { post('page', name, properties); }
130
+ };
131
+ })();
132
+ true;`;
133
+ }
134
+ /**
135
+ * Reply delivery script, run in the page with the WebView ref's
136
+ * `injectJavaScript`. The reply JSON rides as a JS string literal, so the
137
+ * page-visible shape matches iOS and Android: `onmessage` receives an
138
+ * event-like object whose `data` is the reply string. The trailing `true;` is
139
+ * what react-native-webview asks injected scripts to end with.
140
+ *
141
+ * `injectJavaScript` runs in whatever page is in the main frame when the reply
142
+ * is sent, not in the frame that sent the message (iOS and Android reply to the
143
+ * source frame). The origin guard keeps a reply from reaching a page the
144
+ * WebView navigated to in between.
145
+ */
146
+ export function buildReplyScript(replyJson, allowedOrigins) {
147
+ const channel = `window.${NATIVE_CHANNEL_NAME}`;
148
+ // A plain loop rather than indexOf, which the page can patch (see the
149
+ // wrapper).
150
+ return `(function() { var o = ${JSON.stringify(allowedOrigins)}; for (var i = 0; i < o.length; i++) { if (o[i] === location.origin) { if (${channel} && typeof ${channel}.onmessage === 'function') { ${channel}.onmessage({ data: ${jsStringLiteral(replyJson)} }); } return; } } })(); true;`;
151
+ }
152
+ /**
153
+ * JSON.stringify leaves U+2028/U+2029 unescaped; engines before ES2019 read
154
+ * them as line terminators, so page-controlled text echoed in a reply (a
155
+ * messageId, an unknown type) would turn the reply script into a SyntaxError.
156
+ */
157
+ function jsStringLiteral(value) {
158
+ return JSON.stringify(value)
159
+ .replace(/\u2028/g, '\\u2028')
160
+ .replace(/\u2029/g, '\\u2029');
161
+ }
@@ -0,0 +1,39 @@
1
+ import type { BridgeMessageProcessor } from './bridgeMessageProcessor';
2
+ import type { WebViewBridgeProps, WebViewRefLike } from '../types';
3
+ /**
4
+ * Scheme and host are case-insensitive and default ports are implied, but both
5
+ * origin checks compare exact canonical strings: "https://Shop.Example.com:443"
6
+ * would pass validation yet never match, leaving the bridge silently inert.
7
+ * Same normalization as iOS.
8
+ */
9
+ export declare function normalizeOrigin(origin: string): string;
10
+ /** Canonical origin of a URL or origin string, or null when it has none. */
11
+ export declare function originOf(url: string | undefined): string | null;
12
+ export declare const inertProps: () => WebViewBridgeProps;
13
+ /**
14
+ * Builds the props that bridge one `react-native-webview` WebView. Same
15
+ * validation and warnings as the native attachWebView; differences forced by
16
+ * react-native-webview:
17
+ *
18
+ * - There is no WebView object to register on, so the bridge is the returned
19
+ * props: the wrapper for `injectedJavaScriptBeforeContentLoaded` and an
20
+ * `onMessage` handler that returns true for the SDK's messages and false for
21
+ * the host's, so the host can chain its own handler.
22
+ * - The message channel is not origin-scoped, so each message's reported
23
+ * sending-frame URL is checked against the allowlist, and must carry the
24
+ * session token only the main-frame wrapper holds (see BridgeState). The
25
+ * wrapper's own origin self-check is the page half. Failing messages are
26
+ * dropped with no reply — a hostile frame gets silence, not an oracle.
27
+ * - The wrapper reaches the main frame only, and on Android
28
+ * react-native-webview runs it when the page starts loading rather than at
29
+ * document start, so page code that runs before it finds no bridge.
30
+ * - Replies need the WebView ref (`injectJavaScript`), and go to the page in
31
+ * the main frame at reply time. Without a ref, events still flow and the
32
+ * page receives no acks.
33
+ * - Calling it again (e.g. on every render) returns equivalent props; dedup
34
+ * lives in the shared processor.
35
+ */
36
+ export declare function attachWebViewBridge(webViewRef: WebViewRefLike | null | undefined, allowedOrigins: readonly string[], processor: BridgeMessageProcessor): WebViewBridgeProps;
37
+ /** The message prefix (with token) the processor's wrapper posts with. Tests only. */
38
+ export declare function bridgeMessagePrefixFor(processor: BridgeMessageProcessor): string;
39
+ //# sourceMappingURL=webViewBridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webViewBridge.d.ts","sourceRoot":"","sources":["../../../src/analytics/webview/webViewBridge.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAOvE,OAAO,KAAK,EACV,kBAAkB,EAElB,cAAc,EACf,MAAM,UAAU,CAAC;AAelB;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAQtD;AAED,4EAA4E;AAC5E,wBAAgB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAM/D;AAoED,eAAO,MAAM,UAAU,QAAO,kBAM5B,CAAC;AAsDH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,mBAAmB,CACjC,UAAU,EAAE,cAAc,GAAG,IAAI,GAAG,SAAS,EAC7C,cAAc,EAAE,SAAS,MAAM,EAAE,EACjC,SAAS,EAAE,sBAAsB,GAChC,kBAAkB,CA8EpB;AAED,sFAAsF;AACtF,wBAAgB,sBAAsB,CACpC,SAAS,EAAE,sBAAsB,GAChC,MAAM,CAER"}
@@ -0,0 +1,211 @@
1
+ import uuid from 'react-native-uuid';
2
+ import { log, warn } from '../utils/logger';
3
+ import { isBridgeSupported } from './webViewSupport';
4
+ import { isLoopbackHost } from '../utils/initOptions';
5
+ import { BRIDGE_MESSAGE_PREFIX, DEFAULT_BRIDGE_OBJECT_NAME, buildBridgeWrapperScript, buildReplyScript, } from './bridgeWrapperScript';
6
+ // Origin rules must be scheme://host[:port] — anything else (paths, trailing
7
+ // slashes, wildcards) silently never matches the exact-origin checks. The host
8
+ // alternation carries bracketed IPv6 literals so http://[::1]:3000 reaches the
9
+ // loopback check instead of being rejected as malformed.
10
+ const ORIGIN_RULE = /^https?:\/\/([A-Za-z0-9.-]+|\[[0-9A-Fa-f:]+\])(:\d+)?$/;
11
+ // Origin of a message's sending frame. react-native-webview reports a full URL
12
+ // on iOS (frameInfo.request.URL) and the origin on Android (sourceOrigin).
13
+ // Backslash ends the authority as it does for browsers in http(s) URLs, so
14
+ // "https://evil.com\@shop.example.com" reads as evil.com, not shop.example.com.
15
+ const URL_ORIGIN = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/(?:[^/?#@\\]*@)?(\[[^\]\\]*\]|[^/?#:@\\]*)(?::(\d*))?(?:[/?#\\]|$)/;
16
+ /**
17
+ * Scheme and host are case-insensitive and default ports are implied, but both
18
+ * origin checks compare exact canonical strings: "https://Shop.Example.com:443"
19
+ * would pass validation yet never match, leaving the bridge silently inert.
20
+ * Same normalization as iOS.
21
+ */
22
+ export function normalizeOrigin(origin) {
23
+ let normalized = origin.toLowerCase();
24
+ if (normalized.startsWith('https://') && normalized.endsWith(':443')) {
25
+ normalized = normalized.slice(0, -4);
26
+ }
27
+ else if (normalized.startsWith('http://') && normalized.endsWith(':80')) {
28
+ normalized = normalized.slice(0, -3);
29
+ }
30
+ return normalized;
31
+ }
32
+ /** Canonical origin of a URL or origin string, or null when it has none. */
33
+ export function originOf(url) {
34
+ if (typeof url !== 'string')
35
+ return null;
36
+ const match = URL_ORIGIN.exec(url);
37
+ if (!match || !match[2])
38
+ return null;
39
+ const port = match[3] ? `:${match[3]}` : '';
40
+ return normalizeOrigin(`${match[1]}://${match[2]}${port}`);
41
+ }
42
+ const MAX_CACHED_ATTACHMENTS = 8;
43
+ const states = new WeakMap();
44
+ function stateFor(processor) {
45
+ let state = states.get(processor);
46
+ if (!state) {
47
+ state = {
48
+ messagePrefix: `${BRIDGE_MESSAGE_PREFIX}${String(uuid.v4())}:`,
49
+ attachments: new Map(),
50
+ noRefLogged: false,
51
+ };
52
+ states.set(processor, state);
53
+ }
54
+ return state;
55
+ }
56
+ // Refused origin lists already warned about — attachWebView runs on every
57
+ // render, and the warning would otherwise repeat on each one.
58
+ const warnedRefusals = new Set();
59
+ function warnOnce(key, message) {
60
+ if (warnedRefusals.has(key))
61
+ return;
62
+ warnedRefusals.add(key);
63
+ warn(message);
64
+ }
65
+ // Returned when the attach is refused: the host's own messages keep flowing,
66
+ // and the empty script is safe to join with the host's own. Bridge messages
67
+ // are still claimed (and dropped): a page loaded under an earlier, valid
68
+ // attach keeps posting, and its envelopes must not reach the host's handler.
69
+ export const inertProps = () => ({
70
+ injectedJavaScriptBeforeContentLoaded: '',
71
+ onMessage: (event) => {
72
+ var _a;
73
+ const data = (_a = event === null || event === void 0 ? void 0 : event.nativeEvent) === null || _a === void 0 ? void 0 : _a.data;
74
+ return typeof data === 'string' && data.startsWith(BRIDGE_MESSAGE_PREFIX);
75
+ },
76
+ });
77
+ // Never throws: JSON.stringify does on a BigInt or a cyclic entry, which an
78
+ // untyped caller (remote config) can pass, and attachWebView runs in render.
79
+ function cacheKey(allowedOrigins) {
80
+ if (!Array.isArray(allowedOrigins))
81
+ return null;
82
+ try {
83
+ return JSON.stringify(allowedOrigins);
84
+ }
85
+ catch {
86
+ return null;
87
+ }
88
+ }
89
+ function validate(allowedOrigins) {
90
+ if (!Array.isArray(allowedOrigins) || allowedOrigins.length === 0) {
91
+ warnOnce('[]', 'attachWebView called with no allowed origins — ignoring.');
92
+ return null;
93
+ }
94
+ if (allowedOrigins.some((o) => typeof o !== 'string')) {
95
+ warnOnce('<non-string>', 'attachWebView rejects non-string origin rules — use explicit scheme://host[:port] strings.');
96
+ return null;
97
+ }
98
+ // Normalized before validating: the pattern is case-sensitive, so a
99
+ // case-variant scheme would otherwise be rejected for a problem the host
100
+ // does not have.
101
+ const origins = allowedOrigins.map(normalizeOrigin);
102
+ const key = JSON.stringify(origins);
103
+ const invalid = origins.filter((o) => !ORIGIN_RULE.test(o));
104
+ if (invalid.length > 0) {
105
+ // Origin scoping is the bridge's security boundary; a wildcard would let
106
+ // any page loaded in this WebView inject events into the queue.
107
+ warnOnce(key, `attachWebView rejects invalid origin rules ${JSON.stringify(invalid)} — use explicit scheme://host[:port] origins.`);
108
+ return null;
109
+ }
110
+ const insecure = origins.filter((o) => o.startsWith('http://') && !isLoopbackHost(ORIGIN_RULE.exec(o)[1]));
111
+ if (insecure.length > 0) {
112
+ // A cleartext origin is spoofable in transit and the origin check then
113
+ // trusts it — fine for local development, worth a warning elsewhere.
114
+ warnOnce(key, `attachWebView: cleartext origin rules ${JSON.stringify(insecure)} — use https origins outside local development.`);
115
+ }
116
+ return { script: '', origins, allowed: new Set(origins) };
117
+ }
118
+ /**
119
+ * Builds the props that bridge one `react-native-webview` WebView. Same
120
+ * validation and warnings as the native attachWebView; differences forced by
121
+ * react-native-webview:
122
+ *
123
+ * - There is no WebView object to register on, so the bridge is the returned
124
+ * props: the wrapper for `injectedJavaScriptBeforeContentLoaded` and an
125
+ * `onMessage` handler that returns true for the SDK's messages and false for
126
+ * the host's, so the host can chain its own handler.
127
+ * - The message channel is not origin-scoped, so each message's reported
128
+ * sending-frame URL is checked against the allowlist, and must carry the
129
+ * session token only the main-frame wrapper holds (see BridgeState). The
130
+ * wrapper's own origin self-check is the page half. Failing messages are
131
+ * dropped with no reply — a hostile frame gets silence, not an oracle.
132
+ * - The wrapper reaches the main frame only, and on Android
133
+ * react-native-webview runs it when the page starts loading rather than at
134
+ * document start, so page code that runs before it finds no bridge.
135
+ * - Replies need the WebView ref (`injectJavaScript`), and go to the page in
136
+ * the main frame at reply time. Without a ref, events still flow and the
137
+ * page receives no acks.
138
+ * - Calling it again (e.g. on every render) returns equivalent props; dedup
139
+ * lives in the shared processor.
140
+ */
141
+ export function attachWebViewBridge(webViewRef, allowedOrigins, processor) {
142
+ const state = stateFor(processor);
143
+ const key = cacheKey(allowedOrigins);
144
+ let attachment = key === null ? undefined : state.attachments.get(key);
145
+ if (attachment) {
146
+ // Re-inserted so eviction drops the least recently rendered list.
147
+ state.attachments.delete(key);
148
+ state.attachments.set(key, attachment);
149
+ }
150
+ else {
151
+ const validated = key === null ? null : validate(allowedOrigins);
152
+ if (!validated) {
153
+ if (key === null) {
154
+ warnOnce('<unserializable>', 'attachWebView rejects origin rules that are not an array of strings.');
155
+ }
156
+ return inertProps();
157
+ }
158
+ // After validation, so origin mistakes are reported even where the bridge
159
+ // cannot run (e.g. Expo Go); before caching, so a cache hit implies
160
+ // support. Warns once itself, and the answer is cached for the process.
161
+ if (!isBridgeSupported())
162
+ return inertProps();
163
+ validated.script = buildBridgeWrapperScript(validated.origins, DEFAULT_BRIDGE_OBJECT_NAME, state.messagePrefix);
164
+ attachment = validated;
165
+ if (state.attachments.size >= MAX_CACHED_ATTACHMENTS) {
166
+ state.attachments.delete(state.attachments.keys().next().value);
167
+ }
168
+ state.attachments.set(key, attachment);
169
+ log(`WebView bridge attached (origins=${JSON.stringify(attachment.origins)})`);
170
+ }
171
+ const { script, origins, allowed } = attachment;
172
+ const onMessage = (event) => {
173
+ var _a;
174
+ const data = (_a = event === null || event === void 0 ? void 0 : event.nativeEvent) === null || _a === void 0 ? void 0 : _a.data;
175
+ if (typeof data !== 'string' || !data.startsWith(BRIDGE_MESSAGE_PREFIX)) {
176
+ return false;
177
+ }
178
+ if (!data.startsWith(state.messagePrefix)) {
179
+ // A bridge-shaped message without the token: a frame that never
180
+ // received the wrapper. Debug-level — a hostile frame could spam this.
181
+ log('WebView bridge dropped a message without a valid token');
182
+ return true;
183
+ }
184
+ const origin = originOf(event.nativeEvent.url);
185
+ if (origin === null || !allowed.has(origin)) {
186
+ log(`WebView bridge dropped message from non-allowlisted origin ${origin}`);
187
+ return true;
188
+ }
189
+ const reply = processor.process(data.slice(state.messagePrefix.length));
190
+ const webView = webViewRef === null || webViewRef === void 0 ? void 0 : webViewRef.current;
191
+ if (webView && typeof webView.injectJavaScript === 'function') {
192
+ try {
193
+ webView.injectJavaScript(buildReplyScript(JSON.stringify(reply), origins));
194
+ }
195
+ catch (err) {
196
+ // A page that navigated away mid-ack fails here routinely.
197
+ log('WebView bridge reply delivery failed:', err);
198
+ }
199
+ }
200
+ else if (!state.noRefLogged) {
201
+ state.noRefLogged = true;
202
+ log('WebView bridge: no WebView ref passed to attachWebView — events are captured, replies are not delivered.');
203
+ }
204
+ return true;
205
+ };
206
+ return { injectedJavaScriptBeforeContentLoaded: script, onMessage };
207
+ }
208
+ /** The message prefix (with token) the processor's wrapper posts with. Tests only. */
209
+ export function bridgeMessagePrefixFor(processor) {
210
+ return stateFor(processor).messagePrefix;
211
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Whether the bridge can attach on this device. Always true on iOS, whose
3
+ * WKWebView reports each message's real sending frame. On
4
+ * Android it needs the WebView provider's WEB_MESSAGE_LISTENER (WebView 82+):
5
+ * without it react-native-webview reports the main page's URL for messages
6
+ * from every frame, and the origin check cannot keep a cross-origin iframe
7
+ * out. Same policy as the Android SDK, which refuses to attach there.
8
+ *
9
+ * Fails closed: other platforms (not checked), a missing native module (an
10
+ * app not rebuilt since upgrading, Expo Go) or a failing synchronous call also
11
+ * refuse, with the reason in the warning.
12
+ */
13
+ export declare function isBridgeSupported(): boolean;
14
+ /** Forgets the cached answer. Tests only. */
15
+ export declare function resetBridgeSupportForTests(): void;
16
+ //# sourceMappingURL=webViewSupport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webViewSupport.d.ts","sourceRoot":"","sources":["../../../src/analytics/webview/webViewSupport.ts"],"names":[],"mappings":"AAWA;;;;;;;;;;;GAWG;AACH,wBAAgB,iBAAiB,IAAI,OAAO,CAuC3C;AAED,6CAA6C;AAC7C,wBAAgB,0BAA0B,IAAI,IAAI,CAEjD"}
@@ -0,0 +1,52 @@
1
+ import { NativeModules, Platform } from 'react-native';
2
+ import { warn } from '../utils/logger';
3
+ // Resolved once: the WebView provider does not change while the app runs,
4
+ // and attachWebView asks on every render.
5
+ let supported;
6
+ /**
7
+ * Whether the bridge can attach on this device. Always true on iOS, whose
8
+ * WKWebView reports each message's real sending frame. On
9
+ * Android it needs the WebView provider's WEB_MESSAGE_LISTENER (WebView 82+):
10
+ * without it react-native-webview reports the main page's URL for messages
11
+ * from every frame, and the origin check cannot keep a cross-origin iframe
12
+ * out. Same policy as the Android SDK, which refuses to attach there.
13
+ *
14
+ * Fails closed: other platforms (not checked), a missing native module (an
15
+ * app not rebuilt since upgrading, Expo Go) or a failing synchronous call also
16
+ * refuse, with the reason in the warning.
17
+ */
18
+ export function isBridgeSupported() {
19
+ if (supported !== undefined)
20
+ return supported;
21
+ if (Platform.OS === 'ios') {
22
+ supported = true;
23
+ return supported;
24
+ }
25
+ if (Platform.OS !== 'android') {
26
+ warn(`WebView bridge unavailable on ${Platform.OS}: only iOS and Android are supported. WebView events will not be captured.`);
27
+ supported = false;
28
+ return supported;
29
+ }
30
+ const mod = NativeModules.MetaRouterWebViewSupport;
31
+ if (!mod) {
32
+ warn('WebView bridge unavailable: the MetaRouterWebViewSupport native module is missing (rebuild the app after upgrading). WebView events will not be captured.');
33
+ supported = false;
34
+ return supported;
35
+ }
36
+ try {
37
+ supported = mod.isWebMessageListenerSupported() === true;
38
+ }
39
+ catch (err) {
40
+ warn('WebView bridge unavailable: the WebView feature check failed. WebView events will not be captured.', err);
41
+ supported = false;
42
+ return supported;
43
+ }
44
+ if (!supported) {
45
+ warn("WebView bridge unavailable: this device's WebView provider lacks WEB_MESSAGE_LISTENER. WebView events will not be captured.");
46
+ }
47
+ return supported;
48
+ }
49
+ /** Forgets the cached answer. Tests only. */
50
+ export function resetBridgeSupportForTests() {
51
+ supported = undefined;
52
+ }
package/lib/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createAnalyticsClient } from './analytics/init';
2
2
  export { MetaRouterProvider } from './react/context';
3
3
  export { useMetaRouter } from './react/useMetaRouter';
4
- export type { InitOptions, AnalyticsInterface, ConfigError, } from './analytics/types';
4
+ export type { InitOptions, AnalyticsInterface, ConfigError, WebViewBridgeProps, WebViewMessageEventLike, WebViewRefLike, } from './analytics/types';
5
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,YAAY,EACV,WAAW,EACX,kBAAkB,EAClB,WAAW,GACZ,MAAM,mBAAmB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAEzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,YAAY,EACV,WAAW,EACX,kBAAkB,EAClB,WAAW,EACX,kBAAkB,EAClB,uBAAuB,EACvB,cAAc,GACf,MAAM,mBAAmB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metarouter/react-native-sdk",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "main": "./lib/index.js",
5
5
  "types": "./lib/index.d.ts",
6
6
  "exports": {
@@ -20,6 +20,7 @@
20
20
  "scripts": {
21
21
  "clean": "rm -rf lib",
22
22
  "build": "tsc --project tsconfig.build.json",
23
+ "typecheck": "tsc --project tsconfig.typecheck.json",
23
24
  "prepare": "husky",
24
25
  "prepublishOnly": "npm run clean && npm run build",
25
26
  "test": "jest"
@@ -42,10 +43,16 @@
42
43
  "react-native-uuid": "^2.0.3"
43
44
  },
44
45
  "peerDependencies": {
45
- "@react-native-async-storage/async-storage": ">=2.2.0",
46
+ "@react-native-async-storage/async-storage": ">=2.2.0 <4",
46
47
  "react": ">=16.8.0",
47
48
  "react-native": ">=0.73.0",
48
- "react-native-device-info": ">=14.0.4"
49
+ "react-native-device-info": ">=14.0.4",
50
+ "react-native-webview": ">=13.13.1"
51
+ },
52
+ "peerDependenciesMeta": {
53
+ "react-native-webview": {
54
+ "optional": true
55
+ }
49
56
  },
50
57
  "devDependencies": {
51
58
  "@commitlint/cli": "^20.3.0",
@@ -65,6 +72,7 @@
65
72
  "metro-react-native-babel-preset": "^0.77.0",
66
73
  "prettier": "^3.7.4",
67
74
  "react-native-device-info": "^15.0.1",
75
+ "react-native-webview": "13.15.0",
68
76
  "typescript": "^5.9.3"
69
77
  },
70
78
  "react-native": "./lib/index.js",