@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
package/README.md CHANGED
@@ -15,6 +15,9 @@ A lightweight React Native analytics SDK that transmits events to your MetaRoute
15
15
  - [API Reference](#api-reference)
16
16
  - [Features](#features)
17
17
  - [Disk-Backed Queue Persistence](#disk-backed-queue-persistence)
18
+ - [Application Lifecycle Events](#application-lifecycle-events)
19
+ - [Session Tracking](#session-tracking)
20
+ - [WebView Bridge](#webview-bridge)
18
21
  - [Compatibility](#-compatibility)
19
22
  - [Debugging](#debugging)
20
23
  - [Identity Persistence](#identity-persistence)
@@ -37,11 +40,11 @@ After installing or upgrading, run `cd ios && pod install` and rebuild the nativ
37
40
  ```js
38
41
  import { createAnalyticsClient } from "@metarouter/react-native-sdk";
39
42
 
40
- // Initialize the analytics client
41
- const analytics = await createAnalyticsClient({
43
+ // Returns the client right away; initialization finishes in the background
44
+ const analytics = createAnalyticsClient({
42
45
  writeKey: "your-write-key",
43
46
  ingestionHost: "https://your-ingestion-endpoint.com",
44
- debug: true, // Optional: enable debug mode
47
+ debug: __DEV__, // Optional: verbose logs, never in a store release
45
48
  flushIntervalSeconds: 30, // Optional: flush events every 30 seconds
46
49
  });
47
50
  ```
@@ -49,43 +52,25 @@ const analytics = await createAnalyticsClient({
49
52
  ### React Context Usage
50
53
 
51
54
  ```jsx
52
- import React, { useEffect, useState } from "react";
55
+ import React from "react";
53
56
  import {
54
57
  createAnalyticsClient,
55
58
  MetaRouterProvider,
56
59
  useMetaRouter,
57
60
  } from "@metarouter/react-native-sdk";
58
61
 
59
- const App = () => {
60
- const [analyticsClient, setAnalyticsClient] = useState(null);
61
- const [isLoading, setIsLoading] = useState(true);
62
-
63
- useEffect(() => {
64
- const initializeAnalytics = async () => {
65
- try {
66
- // Initialize the analytics client
67
- const client = await createAnalyticsClient({
68
- writeKey: "your-write-key",
69
- ingestionHost: "https://your-ingestion-endpoint.com",
70
- });
71
- setAnalyticsClient(client);
72
- } catch (error) {
73
- console.error("Failed to initialize analytics:", error);
74
- } finally {
75
- setIsLoading(false);
76
- }
77
- };
78
- initializeAnalytics();
79
- }, []);
80
-
81
- if (isLoading) return null; // or a loading spinner
62
+ // Create the client once, outside any component. It is usable immediately:
63
+ // there is no promise to await, and nothing to catch in a release build.
64
+ const analytics = createAnalyticsClient({
65
+ writeKey: "your-write-key",
66
+ ingestionHost: "https://your-ingestion-endpoint.com",
67
+ });
82
68
 
83
- return (
84
- <MetaRouterProvider analyticsClient={analyticsClient}>
85
- <YourApp />
86
- </MetaRouterProvider>
87
- );
88
- };
69
+ const App = () => (
70
+ <MetaRouterProvider analyticsClient={analytics}>
71
+ <YourApp />
72
+ </MetaRouterProvider>
73
+ );
89
74
 
90
75
  // Use analytics in any component
91
76
  const MyComponent = () => {
@@ -107,9 +92,9 @@ const MyComponent = () => {
107
92
  ```js
108
93
  import { createAnalyticsClient } from "@metarouter/react-native-sdk";
109
94
 
110
- // Initialize the client (optionally await it), but you can use it at any time
111
- // with events transmitted when the client is ready.
112
- const analytics = await createAnalyticsClient({
95
+ // Usable immediately: calls made before initialization finishes are
96
+ // buffered and sent once the client is ready.
97
+ const analytics = createAnalyticsClient({
113
98
  writeKey: "your-write-key",
114
99
  ingestionHost: "https://your-ingestion-endpoint.com",
115
100
  });
@@ -156,7 +141,7 @@ await analytics.reset();
156
141
 
157
142
  ```js
158
143
  // Initial configuration
159
- const analytics = await createAnalyticsClient({
144
+ const analytics = createAnalyticsClient({
160
145
  writeKey: "key-1",
161
146
  ingestionHost: "https://endpoint-1.com",
162
147
  });
@@ -164,8 +149,9 @@ const analytics = await createAnalyticsClient({
164
149
  // Later, if you need to change configuration:
165
150
  await analytics.reset(); // Must reset first!
166
151
 
167
- // Now reconfigure with new options
168
- const analytics = await createAnalyticsClient({
152
+ // Now reconfigure with new options. The same client object is returned, so
153
+ // existing references (and MetaRouterProvider) keep working.
154
+ createAnalyticsClient({
169
155
  writeKey: "key-2",
170
156
  ingestionHost: "https://endpoint-2.com",
171
157
  });
@@ -181,27 +167,63 @@ If you call `createAnalyticsClient()` with different options without resetting f
181
167
 
182
168
  ### createAnalyticsClient(options)
183
169
 
184
- Initializes the analytics client and returns a **live proxy** to the client instance.
185
-
186
- ⚠️ `createAnalyticsClient()` is asynchronous, but you **do not** need to `await` it before using analytics methods.
170
+ Starts initialization and returns a **live proxy** to the client instance, synchronously. It does not return a Promise, so there is nothing to `await`, and in a release build nothing to `catch`: invalid options never throw there (development builds throw so the mistake surfaces at the call site). See [Invalid configuration](#invalid-configuration).
187
171
 
188
172
  Calls to `track`, `identify`, etc. are **buffered in-memory** by the proxy and replayed **in order** once the client is fully initialized.
189
173
 
190
174
  **Options:**
191
175
 
192
- - `writeKey` (string, required): Your write key
193
- - `ingestionHost` (string, required): Your MetaRouter ingestor host
194
- - `debug` (boolean, optional): Enable debug mode
195
- - `flushIntervalSeconds` (number, optional): Interval in seconds to flush events
196
- - `maxQueueBytes` (number, optional): max bytes (UTF-8) held in memory queue (default: 5MB)
176
+ - `writeKey` (string, required): Your MetaRouter write key. Trimmed; empty or whitespace-only is a config error.
177
+ - `ingestionHost` (string, required): Your MetaRouter ingestion endpoint: an `http`/`https` URL with a host. Trimmed, and trailing slashes are removed. Cleartext `http` logs a warning unless the host is `localhost`, `127.0.0.1` or `::1`.
178
+ - `flushIntervalSeconds` (number, optional, default: `10`): How often the SDK attempts to send queued events. Values below 1 are clamped to 1.
179
+ - `debug` (boolean, optional, default: `false`): Enables verbose SDK logging. Can also be toggled at runtime via `analytics.enableDebugLogging()`.
180
+ - `maxQueueEvents` (number, optional, default: `2000`): Maximum events held in the in-memory queue. Values below 1 are clamped to 1. The queue is also bounded by a 5 MB byte cap — whichever limit is reached first triggers drop-oldest eviction.
181
+ - `maxDiskEvents` (number, optional, default: `10000`): Maximum unsent events retained on disk for crash safety and offline recovery. Negative values are clamped to `0` with a warning. Set to `0` to disable disk persistence (events are lost on app kill).
182
+ - `trackLifecycleEvents` (boolean, optional, default: `false`): Opt-in. Set to `true` to emit `Application Installed`, `Application Updated`, `Application Opened`, and `Application Backgrounded` events automatically. See [Application Lifecycle Events](#application-lifecycle-events).
183
+ - `sessionTimeoutMinutes` (number, optional, default: `30`): Minutes of inactivity after which the next event starts a new session. Fractions are accepted (`1.5` is 90 seconds); values below 1 are clamped to 1. See [Session Tracking](#session-tracking).
184
+ - `fireSessionStarted` (boolean, optional, default: `false`): Emit a `Session Started` track event each time a new session starts. See [Session Tracking](#session-tracking).
185
+ - `onConfigError` (function, optional): Called with a `ConfigError` (`type`, `description`, and `raw` for a bad host) when the options are invalid in a release build. See [Invalid configuration](#invalid-configuration).
186
+
187
+ Out-of-range numbers are clamped and logged as a warning; they never fail initialization.
197
188
 
198
189
  **Proxy behavior (quick notes):**
199
190
 
200
191
  - Buffer is **in-memory only** (not persisted). Calls made before ready are lost if the process exits.
201
192
  - Ordering is preserved relative to other buffered calls; normal FIFO + batching applies after ready.
202
- - On fatal config errors (`401/403/404`), the client enters **disabled** state and drops subsequent calls.
193
+ - On fatal config errors from the ingestion host (`401/403/404`), the client enters **disabled** state and drops subsequent calls. This is separate from [invalid options](#invalid-configuration) and does not call `onConfigError`.
203
194
  - `sentAt` is stamped when the batch is prepared for transmission (just before network send). If you need the original occurrence time, pass your own `timestamp` on each event.
204
195
 
196
+ ### Invalid configuration
197
+
198
+ Invalid options (an empty `writeKey`, or an `ingestionHost` that is not an `http`/`https` URL with a host) never crash a release build. The same rules apply on iOS and Android.
199
+
200
+ | Build | What happens |
201
+ | ----- | ------------ |
202
+ | Development (`__DEV__`) | `createAnalyticsClient` throws `Invalid InitOptions: <reason>`, so the mistake shows up immediately at the call site. |
203
+ | Release | An always-on error is logged (`[MetaRouter] MetaRouter disabled for this session — <reason>`), `onConfigError` is called once, synchronously, and the SDK stays inert for the session: calls are accepted and nothing is sent. |
204
+
205
+ While the session is disabled:
206
+
207
+ - `getAnonymousId()` resolves `""` instead of waiting, and `flush()` resolves immediately.
208
+ - `getDebugInfo()` returns `lifecycle: "disabled"` and the reason as `configError`.
209
+ - Calls made while disabled are kept (up to the usual 20) and sent if the session recovers.
210
+
211
+ A later `createAnalyticsClient` with valid options recovers the session, and so does `reset()`. An invalid call made while a valid session is running disables that session too, rather than leaving the old configuration running unnoticed.
212
+
213
+ Disabling a running session resets its client, which clears the stored identity (anonymous ID, user ID, group ID, advertising ID), the same as the Android SDK. A single invalid call between two valid ones therefore starts the recovered session as a new anonymous user.
214
+
215
+ ```js
216
+ const analytics = createAnalyticsClient({
217
+ writeKey: remoteConfig.writeKey,
218
+ ingestionHost: remoteConfig.ingestionHost,
219
+ onConfigError: (error) => {
220
+ // error.type is "emptyWriteKey" or "invalidIngestionHost" (with error.raw);
221
+ // error.description is the same text the iOS and Android SDKs report.
222
+ reportToYourDiagnostics("MetaRouter config", error.description);
223
+ },
224
+ });
225
+ ```
226
+
205
227
  ### Analytics Interface
206
228
 
207
229
  The analytics client provides the following methods:
@@ -212,12 +234,15 @@ The analytics client provides the following methods:
212
234
  - `screen(name: string, properties?: Record<string, any>)`: Track screen views
213
235
  - `page(name: string, properties?: Record<string, any>)`: Track page views
214
236
  - `alias(newUserId: string)`: Connect anonymous users to known user IDs. See [Using the alias() Method](#using-the-alias-method) for details
237
+ - `recordOpenedURL(url: string, sourceApplication?: string)`: Forward a URL the host received (from `Linking.getInitialURL`, `Linking.addEventListener('url', ...)`, a UIScene URL handler, or an Android Intent) so it is attached to the next `Application Opened` event. The SDK does not read `Linking` itself, so only URLs passed here are recorded. One-shot — the buffer is cleared after the next Opened emit; last-write-wins if called multiple times. No-op (with a warning, always logged) when `trackLifecycleEvents` is disabled. See [Application Lifecycle Events](#application-lifecycle-events) for deep-link wiring details.
215
238
  - `setAdvertisingId(advertisingId: string)`: Set the advertising identifier (IDFA on iOS, GAID on Android) for ad tracking. See [Advertising ID](#advertising-id-idfagaid) section for usage and compliance requirements
216
239
  - `clearAdvertisingId()`: Clear the advertising identifier from storage and context. Useful for GDPR/CCPA compliance when users opt out of ad tracking
217
240
  - `getAnonymousId(): Promise<string>`: Returns the current anonymous ID. Async, never returns null — guaranteed to resolve a string after `init()`
241
+ - `attachWebView(webViewRef, allowedOrigins: string[])`: Bridge a `react-native-webview` WebView so its pages' events are sent through the SDK. Returns props to spread onto the `<WebView>`. See [WebView Bridge](#webview-bridge)
242
+ - `getSessionId(): Promise<string | null>`: Returns the current session ID, or `null` before the first event has been sent this launch. Never waits for initialization and never extends the session. See [Session Tracking](#session-tracking)
218
243
  - `setTracing(enabled: boolean)`: Enable or disable tracing headers on API requests. When enabled, includes a `Trace: true` header for debugging request flows
219
244
  - `flush()`: Flush events immediately
220
- - `reset()`: Reset analytics state and clear all stored data (includes clearing advertising ID)
245
+ - `reset()`: Reset analytics state and clear stored identity (includes clearing advertising ID). The analytics session survives, so a logout does not split it
221
246
  - `enableDebugLogging()`: Enable debug logging
222
247
  - `getDebugInfo()`: Get current debug information
223
248
 
@@ -236,19 +261,235 @@ The analytics client provides the following methods:
236
261
  - 🎣 **React Hooks**: Easy integration with React components
237
262
  - 🔧 **TypeScript Support**: Full TypeScript support included
238
263
  - 🚀 **Lightweight**: Minimal overhead and dependencies
239
- - 💾 **Best-Effort Queue Persistence**: Can persist queued events to native disk storage and rehydrate them on next launch
264
+ - 💾 **Best-Effort Queue Persistence**: Persists unsent events to native disk storage and delivers them on reconnect or next launch
265
+ - 🌐 **WebView Bridge**: Events from pages in a `react-native-webview` WebView arrive with the app's identity — see [WebView Bridge](#webview-bridge)
266
+ - ⏱️ **Session Tracking**: Every event carries a session ID and count — see [Session Tracking](#session-tracking)
267
+ - 📲 **Lifecycle Events (opt-in)**: Emit `Application Installed/Updated/Opened/Backgrounded` automatically when enabled — see [Application Lifecycle Events](#application-lifecycle-events)
240
268
  - 🔄 **Reset Capability**: Easily reset analytics state for testing or logout scenarios
241
269
  - 🐛 **Debug Support**: Built-in debugging tools for troubleshooting
242
270
 
243
271
  ## Disk-Backed Queue Persistence
244
272
 
245
- This release adds native iOS and Android storage for best-effort queue durability.
273
+ Native iOS and Android storage gives the queue best-effort durability.
246
274
 
247
- - If queued events remain buffered when the app backgrounds, the SDK may persist the remaining queue to disk.
248
- - If the in-memory queue grows past internal persistence thresholds, the SDK may snapshot the queue to disk as a fallback.
249
- - Persisted events are rehydrated during the next `init()`.
275
+ - Events still in memory when the app backgrounds are written to disk.
276
+ - Once 500 events or 2 MB are queued in memory, the queue is also written to disk as a crash-safety snapshot.
277
+ - When the in-memory queue reaches `maxQueueEvents`, or the device is offline, overflowing events go to disk instead of being dropped.
278
+ - Events on disk are sent straight to the network when connectivity returns or on the next launch, without being loaded back into the memory queue. Events older than 7 days are discarded.
279
+ - When disk storage reaches `maxDiskEvents`, the oldest events are dropped. `reset()` deletes everything on disk.
280
+ - Without the native modules (for example in Expo Go), persistence is disabled with a warning.
250
281
  - This is a durability baseline, not a full offline mode. The SDK still primarily uses in-memory batching and normal network delivery, and it does not guarantee zero-loss across every crash or termination window.
251
282
 
283
+ ## Application Lifecycle Events
284
+
285
+ Opt-in. When enabled, the SDK emits four lifecycle events that mirror the iOS and Android native SDKs. They are sent through the same enrichment + batching pipeline as user-emitted events.
286
+
287
+ | Event | When it fires | Properties |
288
+ | --------------------------- | ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
289
+ | `Application Installed` | First launch with no prior version stored and no prior identity state. | `version`, `build` |
290
+ | `Application Updated` | First launch where the stored version/build differs from the current. | `version`, `build`, `previous_version`, `previous_build` |
291
+ | `Application Opened` | Cold launch (foreground) and every return to the foreground after a background entry. | `from_background` (false on cold launch, true on resume), `version`, `build`, optional `url`, optional `referring_application` |
292
+ | `Application Backgrounded` | App enters background from the foreground. | _(none)_ |
293
+
294
+ ### Enabling lifecycle events
295
+
296
+ Lifecycle events are **opt-in** — existing customers upgrading the SDK do not begin emitting these events without explicitly setting the flag. To enable:
297
+
298
+ ```js
299
+ const analytics = createAnalyticsClient({
300
+ writeKey: "your-write-key",
301
+ ingestionHost: "https://your-ingestion-endpoint.com",
302
+ trackLifecycleEvents: true, // default: false
303
+ });
304
+ ```
305
+
306
+ ### Notes
307
+
308
+ - `active → inactive → active` blips (Control Center, a FaceID prompt, system alerts) are **suppressed**. `Application Opened` with `from_background: true` needs a real background entry first; a return that passes through `inactive` (e.g. a passcode prompt on resume) still counts.
309
+ - On iOS, React Native reports `active → inactive → background` when the app is left; `Application Backgrounded` fires on the `background` step. A process that settles straight into the background from `unknown` (headless task, push wake) does not emit `Application Backgrounded`. On iOS the launch state is `inactive`, so locking the device before the app first becomes active does emit one, the same as the native iOS SDK.
310
+ - Cold launches in a background process state (silent push, headless task) suppress the cold-launch `Application Opened`; the next `background → active` transition emits with `from_background: false` as the cold-launch bridge.
311
+ - Existing users upgrading from a pre-lifecycle SDK build receive `Application Updated` with `previous_version="unknown"` and `previous_build="unknown"` (instead of a spurious `Application Installed`).
312
+ - Lifecycle storage (`metarouter:lifecycle:version`, `metarouter:lifecycle:build`) is **not** cleared by `reset()` — install/update history survives logout.
313
+ - `Application Backgrounded` is emitted **before** the SDK's flush-to-disk pass on background entry, so the event is captured by the same drain that ships pending events.
314
+
315
+ ### Deep-link wiring
316
+
317
+ The SDK does **not** read `Linking` itself, the same as the iOS and Android SDKs: only URLs your app forwards through `recordOpenedURL` are attached to `Application Opened` (as `url`, plus `referring_application` when you pass one). Forward the cold-launch URL and runtime URL events:
318
+
319
+ ```js
320
+ import { Linking } from "react-native";
321
+
322
+ const analytics = createAnalyticsClient({ /* ... */ trackLifecycleEvents: true });
323
+
324
+ // Cold launch: safe to call right after createAnalyticsClient(). A URL
325
+ // forwarded while initialization is still running reaches the cold-launch
326
+ // Application Opened.
327
+ Linking.getInitialURL().then((url) => {
328
+ if (url) analytics.recordOpenedURL(url);
329
+ });
330
+
331
+ // Resume: attached to the next Application Opened.
332
+ Linking.addEventListener("url", ({ url }) => {
333
+ analytics.recordOpenedURL(url);
334
+ });
335
+
336
+ // With a referring application (typically forwarded from native):
337
+ analytics.recordOpenedURL("myapp://product/123", "com.example.referrer");
338
+ ```
339
+
340
+ URLs from outside `Linking` (a UIScene URL handler on iOS, an Android `Intent.ACTION_VIEW`, a deep-link library such as Branch) are forwarded the same way.
341
+
342
+ **Buffer semantics:**
343
+
344
+ - One-shot — the buffer is cleared after the next `Application Opened` emits.
345
+ - Last-write-wins — multiple `recordOpenedURL` calls before the next Opened keep only the most recent URL.
346
+ - No-op with an always-on warning when `trackLifecycleEvents` is disabled, so misconfigurations surface in logs instead of failing silently.
347
+
348
+ ### Privacy & sanitization
349
+
350
+ URLs can contain sensitive material (auth tokens, OTPs, magic-link secrets, PII in query strings). The SDK records the URL verbatim, and because it only records what you forward, sanitizing before the call is enough:
351
+
352
+ ```js
353
+ function sanitize(url) {
354
+ const u = new URL(url);
355
+ // Strip known sensitive query params before forwarding.
356
+ ["token", "otp", "auth"].forEach((k) => u.searchParams.delete(k));
357
+ return u.toString();
358
+ }
359
+
360
+ Linking.addEventListener("url", ({ url }) => {
361
+ analytics.recordOpenedURL(sanitize(url));
362
+ });
363
+ ```
364
+
365
+ ### Why the SDK does not auto-instrument deep links
366
+
367
+ - **Privacy.** Hosts often receive URLs that contain credentials. Capturing them automatically would record secrets before the app has a chance to strip them.
368
+ - **Host control.** Apps with custom URL routers or deep-link libraries (react-navigation linking, react-native-firebase dynamic links, Branch) need to decide *if* and *which* URLs reach analytics — `recordOpenedURL` is the explicit hand-off point.
369
+ - **Parity.** The iOS (`recordOpenedURL`) and Android (`recordOpenedUrl`) SDKs work the same way, so the same app behaves the same on every platform.
370
+
371
+ ## Session Tracking
372
+
373
+ Every event carries the analytics session it belongs to, stamped as:
374
+
375
+ ```json
376
+ "context": {
377
+ "providers": {
378
+ "metarouter": {
379
+ "sessionID": "1757400000000",
380
+ "sessionCount": 3
381
+ }
382
+ }
383
+ }
384
+ ```
385
+
386
+ This is the same path and shape the web SDK's MetaRouter session sync and the iOS and Android SDKs produce, so pipeline mappings (e.g. GA4 `session_id` / `session_number`) read one field from every platform. `sessionID` is the epoch-millisecond timestamp of the session's first activity, as a string; `sessionCount` is the lifetime session ordinal for the install.
387
+
388
+ Session stamping is **always on** — there is nothing to enable and no network cost. A session starts with the first event and ends after `sessionTimeoutMinutes` (default 30) of inactivity; the window slides, so steady activity keeps one session alive indefinitely. Any tracked or lifecycle event counts as activity. Sessions survive app restarts that happen inside the window, and survive `reset()` — a logout mid-session does not split the session. Session state (id, count and last activity) is kept in AsyncStorage as one JSON value under `metarouter:session`, separate from identity, which is why `reset()` leaves it alone.
389
+
390
+ While the app is running, inactivity is measured on a native clock that keeps counting while the device sleeps and ignores changes to the device time. Across an app restart only the device time is available, so changing it can start a new session. Without the SDK's native modules (for example in Expo Go), the SDK uses the device time throughout and logs a warning.
391
+
392
+ ### Session Started event
393
+
394
+ Optionally, the SDK emits a `Session Started` track event (no properties, matching web) each time a new session starts:
395
+
396
+ ```ts
397
+ const analytics = createAnalyticsClient({
398
+ writeKey: 'YOUR_WRITE_KEY',
399
+ ingestionHost: 'https://your-ingestion-host.com',
400
+ sessionTimeoutMinutes: 30, // default
401
+ fireSessionStarted: true, // default false
402
+ });
403
+ ```
404
+
405
+ `fireSessionStarted` is off by default so upgrading the SDK never changes an app's event volume. Turn it on when a downstream destination needs an explicit session-start signal (GA4's `session_start`, for example).
406
+
407
+ ## WebView Bridge
408
+
409
+ Hybrid apps render some screens as web content inside a WebView. Without extra work that activity is invisible to MetaRouter, or double-tracked by an in-page analytics setup on a separate identity. The WebView bridge captures events fired by page JavaScript and sends them through the SDK, so WebView and app activity arrive at your cluster as **one user, one pipeline**: the app's identity, device context and session, plus the page's own facts, on every event.
410
+
411
+ ### Attaching
412
+
413
+ The bridge works with [`react-native-webview`](https://github.com/react-native-webview/react-native-webview) 13.13.1 or newer, an optional peer dependency (earlier versions report the main page's URL for messages from iframes, which the origin check relies on). `attachWebView` returns the props that wire the bridge into a `<WebView>`:
414
+
415
+ ```tsx
416
+ import { useRef } from 'react';
417
+ import { WebView } from 'react-native-webview';
418
+
419
+ function CheckoutScreen() {
420
+ const webViewRef = useRef<WebView>(null);
421
+ const bridge = analytics.attachWebView(webViewRef, ['https://www.example.com']);
422
+
423
+ return (
424
+ <WebView
425
+ ref={webViewRef}
426
+ source={{ uri: 'https://www.example.com/checkout' }}
427
+ injectedJavaScriptBeforeContentLoaded={bridge.injectedJavaScriptBeforeContentLoaded}
428
+ onMessage={(event) => {
429
+ if (!bridge.onMessage(event)) {
430
+ // Not a bridge message — the app's own page messages arrive here.
431
+ }
432
+ }}
433
+ />
434
+ );
435
+ }
436
+ ```
437
+
438
+ - `bridge.onMessage` returns `true` when it handled a bridge message and `false` for anything else, so an app that already uses `onMessage` chains its own handler. Without one, pass `onMessage={bridge.onMessage}`.
439
+ - Pass the ref so the page receives an ack or error for each message. Without a ref, events are still captured.
440
+ - Calling `attachWebView` on every render is fine, and so is calling it before `createAnalyticsClient` has finished initializing: messages that arrive before then are answered `not_ready`. The bridge keeps working across `reset()` and re-initialization.
441
+ - If the app already sets `injectedJavaScriptBeforeContentLoaded`, join the two scripts (`bridge.injectedJavaScriptBeforeContentLoaded + yourScript`). When the attach is refused the bridge script is empty, so the join stays safe.
442
+
443
+ Origins must be explicit `scheme://host[:port]` rules — no wildcards, paths or trailing slashes. Scheme and host are case-insensitive and default ports are ignored. Invalid rules are refused with a warning, and the returned props then do nothing. Origin scoping is the bridge's security boundary: it keeps other pages loaded in the same WebView (ads, redirects) from injecting events. `react-native-webview` does not scope its message channel to origins, so the SDK enforces the allowlist in two places: the injected wrapper defines nothing on other pages, and every message's sending-frame URL is checked — a message from any other origin is ignored without a reply. Messages must also carry a random token that the injected wrapper holds, as a second layer against frames that never received the wrapper. The token is not a secret from scripts on an allowed page (they are trusted already, and can call the bridge directly). Cleartext `http` origins log a warning unless the host is loopback.
444
+
445
+ ### What the page sees
446
+
447
+ Pages loaded from an allowed origin get a `window.metarouterBridge` object with two methods. Properties may be a plain object or a JSON string of one:
448
+
449
+ ```js
450
+ window.metarouterBridge.page('page_view', { section: 'checkout' });
451
+ window.metarouterBridge.track('product_viewed', JSON.stringify({ sku: 'SKU-123' }));
452
+ ```
453
+
454
+ A typical integration is a small shim in the page's tag manager:
455
+
456
+ ```js
457
+ function logEvent(name, params) {
458
+ var value = JSON.stringify(params);
459
+ if (!window.metarouterBridge) return; // origin not allowed
460
+ if (name === 'page_view') {
461
+ window.metarouterBridge.page(name, value);
462
+ } else {
463
+ window.metarouterBridge.track(name, value);
464
+ }
465
+ }
466
+ ```
467
+
468
+ The page-visible surface is identical in the iOS, Android and React Native SDKs, so one tag-manager integration serves every app.
469
+
470
+ ### What arrives at the cluster
471
+
472
+ Bridged events go through the same enrichment as the app's own events. The page contributes only what the app cannot know:
473
+
474
+ | From the page (stamped at call time) | From the SDK (merged at receipt) |
475
+ |---|---|
476
+ | event type (`track`/`page`), name, properties | `anonymousId` / `userId`, device + app context, session |
477
+ | `context.page` — url, path, search, title, referrer | `messageId`, `timestamp` |
478
+
479
+ Each bridge message carries an ID minted by the page, used to drop duplicate deliveries within 5 minutes. Malformed input is rejected with a coded error, never silently dropped, and events arriving while the SDK cannot accept them are answered `not_ready` rather than acknowledged.
480
+
481
+ ### Limits
482
+
483
+ - **Main frame only.** `react-native-webview` injects scripts before content loads into the main frame only, so iframes do not get the bridge (the iOS and Android SDKs also bridge allowlisted iframes).
484
+ - **Injection timing.** On iOS the wrapper is injected at document start. On Android, `react-native-webview` injects it when the page starts loading, which is not guaranteed to happen before the page's own scripts: an inline script at the top of the page can run first, find no bridge, and lose its call. Calls made once the page has loaded (and user-triggered ones) see the bridge. Guard calls with `if (window.metarouterBridge)` as in the shim above. A page already loaded when the props were first set has no bridge until it reloads.
485
+ - **Android WebView 82 or newer.** On Android the bridge needs the device's WebView provider to support `WEB_MESSAGE_LISTENER`, which Android System WebView has had since version 82 (2020) and which updates through Google Play. Without it `react-native-webview` reports the main page's URL for messages from every frame, so the origin check could not keep an iframe out; the bridge then refuses to attach, with a warning, and `attachWebView` returns props that do nothing (the Android SDK does the same). The check is a native module, so the app must be rebuilt after upgrading; without the module (e.g. Expo Go) the bridge also stays off.
486
+ - **Replies go to the current page.** Replies are delivered to whatever page is in the main frame when they are sent, and only if its origin is allowed.
487
+
488
+ ### Debugging
489
+
490
+ - SDK logs (`debug: true` or `enableDebugLogging()`) show attach confirmations, rejected messages with their error codes, and duplicate drops.
491
+ - In Safari's Develop menu (iOS) or `chrome://inspect` (Android), check `typeof window.metarouterBridge` to verify injection, and read replies with `window.__metaRouterNativeChannel.onmessage = e => console.log(e.data)`.
492
+
252
493
  ## ✅ Compatibility
253
494
 
254
495
  | Component | Supported Versions |
@@ -268,7 +509,7 @@ If you're not seeing API calls being made, here are some steps to troubleshoot:
268
509
 
269
510
  ```js
270
511
  // Initialize with debug enabled
271
- const analytics = await createAnalyticsClient({
512
+ const analytics = createAnalyticsClient({
272
513
  writeKey: "your-write-key",
273
514
  ingestionHost: "https://your-ingestion-endpoint.com",
274
515
  debug: true, // This enables detailed logging
@@ -302,7 +543,7 @@ await analytics.flush();
302
543
 
303
544
  ### Delivery & Backoff (How events flow under failures)
304
545
 
305
- Queue capacity: The SDK caps the in-memory queue at 5MB by default. When the cap is reached, the oldest events are dropped first (drop-oldest). You can change this via maxQueueBytes in createAnalyticsClient(options)
546
+ Queue capacity: The SDK caps the in-memory queue at 5 MB (hardcoded). When either the 5 MB byte cap or the `maxQueueEvents` count cap is reached, the oldest events are dropped first (drop-oldest). Tune the event count via `maxQueueEvents` in `createAnalyticsClient(options)`.
306
547
 
307
548
  This SDK uses a circuit breaker around network I/O. It keeps ordering stable, avoids tight retry loops, and backs off cleanly when your cluster is unhealthy or throttling.
308
549
 
@@ -514,7 +755,7 @@ await analytics.reset();
514
755
 
515
756
  ```js
516
757
  // App starts - SDK initializes
517
- const analytics = await createAnalyticsClient({...});
758
+ const analytics = createAnalyticsClient({...});
518
759
  // anonymousId: "abc-123" (auto-generated and persisted)
519
760
 
520
761
  // User browses before login
@@ -574,7 +815,7 @@ This does two things:
574
815
 
575
816
  ```js
576
817
  // App starts - user is anonymous
577
- const analytics = await createAnalyticsClient({...});
818
+ const analytics = createAnalyticsClient({...});
578
819
  // anonymousId: "abc-123" (auto-generated)
579
820
 
580
821
  // User browses anonymously
@@ -646,7 +887,7 @@ The SDK supports including advertising identifiers (IDFA on iOS, GAID on Android
646
887
  Use the `setAdvertisingId()` method to set the advertising identifier after initializing the analytics client:
647
888
 
648
889
  ```js
649
- const analytics = await createAnalyticsClient({
890
+ const analytics = createAnalyticsClient({
650
891
  writeKey: "your-write-key",
651
892
  ingestionHost: "https://your-ingestion-endpoint.com",
652
893
  });
@@ -689,7 +930,7 @@ import { AppTrackingTransparency } from "react-native-tracking-transparency";
689
930
  import { getAdvertisingId } from "@react-native-community/google-advertiser-id"; // or similar library
690
931
 
691
932
  // Initialize analytics first
692
- const analytics = await createAnalyticsClient({
933
+ const analytics = createAnalyticsClient({
693
934
  writeKey: "your-write-key",
694
935
  ingestionHost: "https://your-ingestion-endpoint.com",
695
936
  });
@@ -711,7 +952,7 @@ if (trackingStatus === "authorized") {
711
952
  import { getAdvertisingId } from "@react-native-community/google-advertiser-id"; // or similar library
712
953
 
713
954
  // Initialize analytics first
714
- const analytics = await createAnalyticsClient({
955
+ const analytics = createAnalyticsClient({
715
956
  writeKey: "your-write-key",
716
957
  ingestionHost: "https://your-ingestion-endpoint.com",
717
958
  });
@@ -38,4 +38,6 @@ repositories {
38
38
 
39
39
  dependencies {
40
40
  implementation "com.facebook.react:react-android:+"
41
+ // Same version as the Android SDK; WebViewFeature for the bridge check.
42
+ implementation "androidx.webkit:webkit:1.12.1"
41
43
  }
@@ -0,0 +1,24 @@
1
+ package com.metarouter.reactnative
2
+
3
+ import android.os.SystemClock
4
+ import com.facebook.react.bridge.ReactApplicationContext
5
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
6
+ import com.facebook.react.bridge.ReactMethod
7
+
8
+ /**
9
+ * Synchronous monotonic clock for session inactivity. elapsedRealtime keeps
10
+ * counting through deep sleep; uptimeMillis (and the CLOCK_MONOTONIC behind
11
+ * React Native's performance.now) does not, so a phone left asleep for hours
12
+ * would resume into the same session. Same clock as the Android SDK's
13
+ * SessionManager.
14
+ */
15
+ class MetaRouterClockModule(
16
+ reactContext: ReactApplicationContext
17
+ ) : ReactContextBaseJavaModule(reactContext) {
18
+
19
+ override fun getName(): String = "MetaRouterClock"
20
+
21
+ // Double: the bridge has no Long, and ms since boot fits a double exactly.
22
+ @ReactMethod(isBlockingSynchronousMethod = true)
23
+ fun continuousMillis(): Double = SystemClock.elapsedRealtime().toDouble()
24
+ }
@@ -11,7 +11,9 @@ class MetaRouterPackage : ReactPackage {
11
11
  ): List<NativeModule> {
12
12
  return listOf(
13
13
  MetaRouterQueueStorageModule(reactContext),
14
- MetaRouterNetworkMonitorModule(reactContext)
14
+ MetaRouterNetworkMonitorModule(reactContext),
15
+ MetaRouterClockModule(reactContext),
16
+ MetaRouterWebViewSupportModule(reactContext)
15
17
  )
16
18
  }
17
19
 
@@ -0,0 +1,27 @@
1
+ package com.metarouter.reactnative
2
+
3
+ import androidx.webkit.WebViewFeature
4
+ import com.facebook.react.bridge.ReactApplicationContext
5
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
6
+ import com.facebook.react.bridge.ReactMethod
7
+
8
+ /**
9
+ * Whether this device's WebView provider supports WEB_MESSAGE_LISTENER. Without
10
+ * it react-native-webview falls back to addJavascriptInterface, which every
11
+ * frame can call and which reports the main page's URL for every message, so
12
+ * the bridge's origin check cannot tell an iframe from the page. The Android
13
+ * SDK refuses to attach there; the RN bridge does the same.
14
+ *
15
+ * DOCUMENT_START_SCRIPT, the Android SDK's other requirement, is not checked:
16
+ * react-native-webview never uses it, so it would refuse nothing extra.
17
+ */
18
+ class MetaRouterWebViewSupportModule(
19
+ reactContext: ReactApplicationContext
20
+ ) : ReactContextBaseJavaModule(reactContext) {
21
+
22
+ override fun getName(): String = "MetaRouterWebViewSupport"
23
+
24
+ @ReactMethod(isBlockingSynchronousMethod = true)
25
+ fun isWebMessageListenerSupported(): Boolean =
26
+ WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)
27
+ }
@@ -0,0 +1,31 @@
1
+ #import <React/RCTBridgeModule.h>
2
+ #include <mach/mach_time.h>
3
+
4
+ // Synchronous monotonic clock for session inactivity. mach_continuous_time
5
+ // keeps counting while the device sleeps; mach_absolute_time (and the
6
+ // CACurrentMediaTime behind React Native's performance.now) does not, so a
7
+ // phone locked for hours would resume into the same session. Same clock as
8
+ // the iOS SDK's MonotonicClock.
9
+ @interface MetaRouterClock : NSObject <RCTBridgeModule>
10
+ @end
11
+
12
+ @implementation MetaRouterClock
13
+
14
+ RCT_EXPORT_MODULE()
15
+
16
+ + (BOOL)requiresMainQueueSetup {
17
+ return NO;
18
+ }
19
+
20
+ RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(continuousMillis)
21
+ {
22
+ static mach_timebase_info_data_t timebase;
23
+ static dispatch_once_t once;
24
+ dispatch_once(&once, ^{
25
+ mach_timebase_info(&timebase);
26
+ });
27
+ uint64_t nanos = mach_continuous_time() * timebase.numer / timebase.denom;
28
+ return @((double)(nanos / NSEC_PER_MSEC));
29
+ }
30
+
31
+ @end