@libo11y/rum-react-native 0.0.0-bootstrap.0 → 0.6.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.
package/README.md CHANGED
@@ -1,3 +1,288 @@
1
- # `@libo11y/rum-react-native`
1
+ # @libo11y/rum-react-native
2
2
 
3
- Bootstrap placeholder reserving the `@libo11y/rum-react-native` package name on npm so GitHub Actions Trusted Publishing can publish the first release in the next `ts/v*` release.
3
+ Real user monitoring for React Native apps on Hermes, over
4
+ [`@libo11y/react-native`](../react-native). It records sessions, screens,
5
+ per-screen summaries, the app's start, JavaScript errors, taps and
6
+ frustration signals, gated on consent, and joins them to the backend
7
+ traces of the requests the app makes. The handle it returns is the same
8
+ `Rum` the browser's `@libo11y/rum` returns, so
9
+ [`@libo11y/rum-react`](../rum-react) and
10
+ [`@libo11y/rum-connect`](../rum-connect) work with it as they are.
11
+ [`@libo11y/rum-expo-router`](../rum-expo-router) names screens by Expo
12
+ Router route template.
13
+
14
+ ```sh
15
+ npm install @libo11y/react-native @libo11y/rum-react-native
16
+ ```
17
+
18
+ It needs React Native 0.88 or later and React 19 as peer dependencies. It
19
+ contains no native code, so adding it changes no native build.
20
+
21
+ ## Usage
22
+
23
+ An Expo app imports `setupRumExpo` from `@libo11y/rum-react-native/expo`,
24
+ which keeps everything RUM stores in the app's documents and fills in the
25
+ app version and the over-the-air update ID, as `setupExpo` does:
26
+
27
+ ```ts
28
+ import { errors, remoteConfig, screens, taps } from "@libo11y/rum-react-native";
29
+ import { setupRumExpo } from "@libo11y/rum-react-native/expo";
30
+
31
+ export const telemetryReady = setupRumExpo({
32
+ serviceName: "my-app",
33
+ environment: "production",
34
+ endpoint: "https://app.example.com/_o11y",
35
+ consent: { initial: "pending" },
36
+ instrumentations: { propagateTo: ["https://api.example.com"] },
37
+ rum: {
38
+ clientToken: "pub-my-app",
39
+ collectors: [screens(), errors(), taps()],
40
+ remoteConfig: remoteConfig(),
41
+ },
42
+ });
43
+ ```
44
+
45
+ A bare React Native app calls `setupRumReactNative` with the same options
46
+ and a `storage` of its own, such as AsyncStorage. Without one, RUM keeps
47
+ its state in memory and loses it when the app stops.
48
+
49
+ `telemetryReady` is a promise, because Metro bundles do not support
50
+ top-level `await`. The root component renders `RumTouchBoundary` around
51
+ the app, so `taps()` sees its touches, and an error boundary that reports
52
+ to RUM:
53
+
54
+ ```tsx
55
+ import { RumErrorBoundary, RumProvider } from "@libo11y/rum-react";
56
+ import { RumTouchBoundary } from "@libo11y/rum-react-native";
57
+
58
+ <RumTouchBoundary>
59
+ <RumProvider rum={telemetry.rum}>
60
+ <RumErrorBoundary fallback={<Oops />}>
61
+ <App />
62
+ </RumErrorBoundary>
63
+ </RumProvider>
64
+ </RumTouchBoundary>;
65
+ ```
66
+
67
+ An Expo Router app calls `useExpoRouterRum(telemetry?.rum)` from
68
+ [`@libo11y/rum-expo-router`](../rum-expo-router) in its root layout. Other
69
+ apps report screens themselves on the telemetry `telemetryReady` resolves
70
+ with:
71
+
72
+ ```ts
73
+ telemetry.rum.startView({ name: "/settings" }); // a new screen
74
+ telemetry.rum.setViewName("/"); // names the current screen
75
+ telemetry.rum.viewRendered(); // the screen's content is on screen
76
+ ```
77
+
78
+ Call `rum.viewRendered()` once the first screen is up, for example in an
79
+ effect of the root component. It ends the first screen's span and the
80
+ `app_load` span.
81
+
82
+ ## What it records
83
+
84
+ - **Sessions.** A session ends after 15 minutes without activity or 4
85
+ hours after it started. It is stored in the app's storage once consent
86
+ is granted, so a relaunch within the idle window continues it, and a
87
+ crash and relaunch stay in one session. A new screen (`rum.startView`),
88
+ a tap (with `taps()`) and coming back to the foreground count as
89
+ activity. Sampling, the retention buffer of sessions not yet kept and
90
+ the session events work as in `@libo11y/rum`; the buffer lives in the
91
+ app's storage.
92
+ - **Screens.** Every view has `o11y.rum.view.kind` `screen`. The first is
93
+ named `rum.initialViewName` (default `"app"`) until something names it.
94
+ It starts when the app started, as `app_load` does.
95
+ With `screens()` in `rum.collectors`, each screen gets a view span that
96
+ ends at the first frame after `rum.viewRendered()`, or 10 seconds after
97
+ it started. The first screen's span is a child of `app_load`; a later
98
+ screen's is a root linked to the action that caused it. Going to the
99
+ background (AppState `background`, or `inactive` on iOS) emits the
100
+ screen's `o11y.rum.view.summary` and flushes.
101
+ - **App start.** One `app_load` span per process, from
102
+ `performance.rnStartupTiming.startTime` (or, without it, when this
103
+ package was loaded) to the first screen's render, at most 60 seconds.
104
+ When consent is granted after the first screen rendered, even after
105
+ other screens, the span is still recorded, with the times remembered
106
+ from before the grant. An app that leaves its first screen before it
107
+ rendered records the 60-second cap.
108
+ - **Requests.** `@libo11y/react-native`'s fetch and XHR spans count
109
+ toward the screen's summary and leave breadcrumbs.
110
+ `rum.onRequestStart` hooks run on each of them, which is how
111
+ `connectRequestNaming` names Connect calls.
112
+ - **Errors**, with `errors()`. See [Errors](#errors).
113
+ - **Taps and frustration signals**, with `taps()` and `RumTouchBoundary`.
114
+ See [Taps](#taps).
115
+
116
+ Revoking consent removes the session, the retention buffer and the
117
+ remote configuration cache from the app's storage, also when only an
118
+ earlier launch had consent. An awaited `consent.revoke()` resolves once
119
+ storage holds none of them. A launch that starts with consent `denied`
120
+ removes them before setup resolves, so a later grant starts a new
121
+ session. A launch that starts `pending` leaves them in place.
122
+
123
+ The resource carries `o11y.rum.platform` `react_native`, and so do RUM's
124
+ own view spans, summaries and `o11y.rum.session.start`. App metrics export
125
+ with delta temporality, which the RUM gateway requires. Requests from an app carry no `Origin`, so the gateway's
126
+ entry for the app sets `allow_missing_origin` and a `client_token`.
127
+
128
+ Context does not carry across `await` on Hermes, which has no
129
+ `AsyncLocalStorage`. A request made after an `await` in a tap handler is
130
+ not that tap's child.
131
+
132
+ ## Errors
133
+
134
+ `errors()` records each error as `o11y.rum.error` with its breadcrumbs
135
+ (screens, taps and requests). It counts in the screen's summary, and it
136
+ keeps a session that sampling left out, which then sends the detail its
137
+ retention buffer held. It records only while consent is granted.
138
+
139
+ - **Uncaught errors** reach React Native's global handler
140
+ (`ErrorUtils.setGlobalHandler`). RUM records each one as `uncaught`
141
+ and then hands it to the handler installed before it, so the red box,
142
+ LogBox and the crash still happen. In a release build a fatal error
143
+ ends the app, so RUM first emits the screen's summary and flushes,
144
+ which saves the batches to the app's storage, and hands the error on
145
+ when the flush is done or after 2 seconds. A batch the app could not
146
+ send goes out on the next launch. In development the error is handed
147
+ on at once.
148
+ - **Unhandled promise rejections** on Hermes are `unhandled_rejection`.
149
+ Hermes reports them only to the tracker
150
+ `HermesInternal.enablePromiseRejectionTracker` sets, React Native sets
151
+ one in development only, and a new one replaces it. RUM sets its own
152
+ and, in development, reports each rejection to the red box as React
153
+ Native's does. Another library that sets a tracker after RUM replaces
154
+ RUM's.
155
+ - **Failed requests**, ended without a response, are `network`, unless
156
+ the app aborted them.
157
+ - **Render errors** never reach the global handler: React hands them to
158
+ an error boundary. Wrap the app in `@libo11y/rum-react`'s
159
+ `RumErrorBoundary`, or report from the app's own boundary:
160
+
161
+ ```ts
162
+ componentDidCatch(error: unknown, info: React.ErrorInfo): void {
163
+ rum.addError(error, { source: "boundary", componentStack: info.componentStack ?? undefined });
164
+ }
165
+ ```
166
+
167
+ A render error no boundary catches crashes the app without passing the
168
+ global handler, so RUM never sees it.
169
+
170
+ Release stacks reach the gateway readable. Hermes names the bundle by its
171
+ path on the device, so RUM rewrites each frame of the app's bundle to
172
+ `app:///main.jsbundle` on iOS and `app:///index.android.bundle` on
173
+ Android, and keeps engine frames (`native`, `InternalBytecode.js`). A
174
+ frame `address at` the bundle carries a bytecode offset, which Hermes
175
+ prints 0-based; RUM sends it as the 1-based column the gateway reads, so
176
+ offset 114 is sent as column 115. The gateway finds a stack's source map
177
+ by the resource's `service.version` and `o11y.rum.app.update_id` (which
178
+ `setupRumExpo` fills in) and that script path.
179
+
180
+ For an over-the-air update, `expo export --platform ios --source-maps`
181
+ writes the bytecode bundle `dist/_expo/static/js/ios/entry-<hash>.hbc`
182
+ and its map `dist/_expo/static/js/ios/entry-<hash>.hbc.map`, which Expo
183
+ has already composed from Metro's map and the Hermes compiler's, so it
184
+ maps bytecode offsets to your sources. Copy the map to
185
+ `main.jsbundle.map` and the bundle to `main.jsbundle` in a directory of
186
+ their own, and upload that directory under the iOS update's ID. Android
187
+ is the same with `android` in the path, `index.android.bundle` and the
188
+ Android update's ID:
189
+
190
+ ```sh
191
+ mkdir -p maps/ios
192
+ cp dist/_expo/static/js/ios/entry-*.hbc maps/ios/main.jsbundle
193
+ cp dist/_expo/static/js/ios/entry-*.hbc.map maps/ios/main.jsbundle.map
194
+ libo11y-sourcemaps upload --endpoint https://app.example.com --service my-app \
195
+ --release 1.1.0 --update-id "$IOS_UPDATE_ID" --url-prefix ~/ maps/ios
196
+ ```
197
+
198
+ The lookup key is `service.version` and the update ID together. One
199
+ update served to two native app versions (two `--release` values) needs
200
+ its map uploaded once for each version. A store build's embedded bundle
201
+ has no update ID: upload its composed map with `--release` and no
202
+ `--update-id`.
203
+
204
+ Development stacks point at Metro and are sent as they are.
205
+
206
+ ## Taps
207
+
208
+ `taps()` records the touches `RumTouchBoundary` passes it. A touch is a
209
+ tap when the finger moved at most 10 points and the touch was not
210
+ cancelled (a scroll view that takes it cancels it), and a long press when
211
+ it was held 500 ms or more. A gesture with a second finger is neither.
212
+ Each one is an action span, `action tap` or `action long_press`, with
213
+ `o11y.rum.element.selector` and, when there is a privacy-safe one, the
214
+ action name. The span ends when the work it caused settles, as a click's
215
+ does in the browser. A screen it opened links to it as its cause.
216
+
217
+ The name is the closest explicit name, from the touched element up:
218
+
219
+ ```tsx
220
+ <RumName name="save-project">
221
+ <Pressable onPress={save}>
222
+ <Text>Save</Text>
223
+ </Pressable>
224
+ </RumName>
225
+ <AppButton o11yName="open-project" onPress={open} /> {/* a component of the app that takes o11yName */}
226
+ ```
227
+
228
+ Without one, it is the tapped element's `aria-label` or
229
+ `accessibilityLabel`. An app whose labels can carry a person's data (a
230
+ contact's name on a row, say) sets `taps({ accessibilityNames: false })`,
231
+ and then only `o11yName` and `RumName` name taps. RUM never records text
232
+ a person typed or the text of an element. The tapped element is the closest one, from the touched
233
+ element up, with an `onPress`, `onLongPress` or `onClick` handler, a
234
+ button-like role, or a responder that is accessible, which is what
235
+ `Pressable`, the Touchables and a pressable `Text` render. The selector
236
+ is the element's type after the names of up to four components above it,
237
+ such as `ProjectRow > Pressable > RCTView`, or `unknown`. A minified build
238
+ leaves one-letter names, which the selector skips. With
239
+ `taps({ testIds: true })`, a `testID` (or `nativeID`) on the element is the
240
+ selector `#<testID>` when it looks like a fixed name in code: lowercase
241
+ letters, `_` and `-`, starting with a letter, at most 64 characters. IDs
242
+ with digits, capitals, spaces or an at sign, such as `client-${email}` or
243
+ a record's ID, never are, because the selector reaches the gateway's
244
+ storage. It is off by default.
245
+ `o11yName` is not in React Native's prop types, so a component of the app
246
+ declares it, or `RumName` names what it wraps.
247
+
248
+ Frustration signals: three taps on one element within a second are a
249
+ `rage` signal, and an error within a second of a tap, or while its action
250
+ is open, an `error` signal. Dead taps are not detected, because React
251
+ Native has no signal that a tap changed nothing on screen.
252
+ `taps({ frustration: false })` turns both off, and `rageTaps` sets the
253
+ count.
254
+
255
+ ### How taps are seen, and the trade-off
256
+
257
+ `RumTouchBoundary` is one plain `View` at the root with `onTouchStart`,
258
+ `onTouchEnd` and `onTouchCancel` handlers. Touch events bubble to it
259
+ whatever handles them, and it never asks to become the responder, so it
260
+ changes no press, gesture or scroll. It works with Fabric and React
261
+ Native 0.88's `EventTarget` event dispatch, and with the legacy dispatch.
262
+
263
+ - React Native runs the responder system, and so `onPress`, before the
264
+ touch events bubble. A tap is known only after its handler ran. The
265
+ tap's span starts then, the requests its handler started are not its
266
+ children (they started first), but the tap waits for them to finish
267
+ before it settles. A screen the handler navigated to starts after the
268
+ tap, so the link from the screen to the tap holds.
269
+ - React Native hands a touch handler only the touched host element. Its
270
+ props, and its parents', are reachable only through React's internal
271
+ instance handle (`__internalInstanceHandle` on Fabric, `_targetInst` on
272
+ the legacy dispatch). RUM reads them without changing anything, and a
273
+ React Native release that removes the handle leaves taps recorded
274
+ without a name.
275
+
276
+ The alternatives were wrapping every pressable, which needs code at each
277
+ element, and patching `React.createElement` or the JSX runtime to wrap
278
+ every `onPress`, which would put RUM inside every press of the app.
279
+
280
+ ## Status
281
+
282
+ A preview. The package first ships in `ts/v0.6.0`, is published on npm at
283
+ `0.6.0` (and attached as a tarball to the
284
+ [`ts/v0.6.0` GitHub Release](https://github.com/libo11y/libo11y/releases/tag/ts/v0.6.0)),
285
+ and its API can change in a minor release. Errors, taps and the Expo
286
+ Router adapter [`@libo11y/rum-expo-router`](../rum-expo-router) ship with
287
+ it. Native crashes, hangs and the native app start come with the native
288
+ module.
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The app_load span on React Native: once per process, the app's start until its
3
+ * first screen rendered. It starts at performance.rnStartupTiming.startTime when that is a finite
4
+ * time before setup (React Native's measure of the native process start), else when
5
+ * `@libo11y/rum-react-native` was first evaluated. The setup reports every rum.startView and
6
+ * rum.viewRendered here, consent or not, so the first screen's render is known even when consent
7
+ * comes later or after other screens. app_load is recorded when the first grant of the process
8
+ * begins the load view, with its session.id and view ID, and is the load view span's parent
9
+ * (appLoadStarted). It ends at the first screen's render, or capMillis after its start without one,
10
+ * as when the app moved to another screen before the first rendered.
11
+ */
12
+ import { type RumRuntime } from "@libo11y/rum/core";
13
+ import type { RumReactNativeEnv } from "./contracts/env.ts";
14
+ /** app_load ends this long after it started at the latest. */
15
+ export declare const APP_LOAD_CAP_MILLIS = 60000;
16
+ /** The app start recorder of one process. */
17
+ export interface AppStart {
18
+ /** The app's start, in performance.now() time: where app_load and the first screen begin. */
19
+ readonly start: number;
20
+ /** Records app_load on runtime when its first grant begins the load view. */
21
+ attach(runtime: RumRuntime): void;
22
+ /** rum.startView was called: the first screen is gone. */
23
+ screenStarted(): void;
24
+ /** rum.viewRendered was called at, in performance.now() time. */
25
+ rendered(at: number): void;
26
+ /** Ends an open app_load now (shutdown) and stops listening. */
27
+ close(): void;
28
+ }
29
+ export interface AppStartOptions {
30
+ readonly env: RumReactNativeEnv;
31
+ /** performance.now(). */
32
+ readonly now: () => number;
33
+ /** Default APP_LOAD_CAP_MILLIS. */
34
+ readonly capMillis?: number;
35
+ }
36
+ export declare function createAppStart(o: AppStartOptions): AppStart;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The app_load span on React Native: once per process, the app's start until its
3
+ * first screen rendered. It starts at performance.rnStartupTiming.startTime when that is a finite
4
+ * time before setup (React Native's measure of the native process start), else when
5
+ * `@libo11y/rum-react-native` was first evaluated. The setup reports every rum.startView and
6
+ * rum.viewRendered here, consent or not, so the first screen's render is known even when consent
7
+ * comes later or after other screens. app_load is recorded when the first grant of the process
8
+ * begins the load view, with its session.id and view ID, and is the load view span's parent
9
+ * (appLoadStarted). It ends at the first screen's render, or capMillis after its start without one,
10
+ * as when the app moved to another screen before the first rendered.
11
+ */
12
+ import { APP_LOAD_SPAN, ATTR_SESSION_ID } from "@libo11y/rum/core";
13
+ import { ATTR_RUM_PLATFORM, ATTR_RUM_SPAN_SHAPE, ATTR_RUM_VIEW_ID, RUM_SPAN_SHAPE_VALUE_APP_LOAD, } from "@libo11y/spec";
14
+ import { ROOT_CONTEXT, SpanKind } from "@opentelemetry/api";
15
+ /** app_load ends this long after it started at the latest. */
16
+ export const APP_LOAD_CAP_MILLIS = 60_000;
17
+ /** The app start, in performance.now() time: React Native's process start when it is usable. */
18
+ function startOf(env, now) {
19
+ const s = env.startupTiming?.startTime;
20
+ return typeof s === "number" && Number.isFinite(s) && s >= 0 && s < now ? s : env.loadedAt;
21
+ }
22
+ export function createAppStart(o) {
23
+ const start = startOf(o.env, o.now());
24
+ const capAt = start + (o.capMillis ?? APP_LOAD_CAP_MILLIS);
25
+ let recorded = false;
26
+ /** The first screen was left before it rendered. */
27
+ let left = false;
28
+ let firstRender;
29
+ let timer;
30
+ let off;
31
+ /** Ends the open app_load at a performance.now() time, within its start and cap. */
32
+ let end;
33
+ const record = (rt, viewId, sessionId) => {
34
+ recorded = true;
35
+ const span = rt.tracer.startSpan(APP_LOAD_SPAN, {
36
+ kind: SpanKind.INTERNAL,
37
+ startTime: rt.timeOrigin + start,
38
+ attributes: {
39
+ [ATTR_RUM_SPAN_SHAPE]: RUM_SPAN_SHAPE_VALUE_APP_LOAD,
40
+ [ATTR_RUM_PLATFORM]: rt.platform,
41
+ [ATTR_RUM_VIEW_ID]: viewId,
42
+ [ATTR_SESSION_ID]: sessionId,
43
+ },
44
+ }, ROOT_CONTEXT);
45
+ rt.views.appLoadStarted(span.spanContext());
46
+ end = (at) => {
47
+ end = undefined;
48
+ o.env.clearTimeout(timer);
49
+ span.end(rt.timeOrigin + Math.max(start, Math.min(at, capAt)));
50
+ };
51
+ if (firstRender !== undefined)
52
+ end(firstRender);
53
+ else
54
+ timer = o.env.setTimeout(() => end?.(capAt), Math.max(0, capAt - o.now()));
55
+ };
56
+ return {
57
+ start,
58
+ attach(rt) {
59
+ off?.();
60
+ off = rt.views.subscribe((e) => {
61
+ if (e.type !== "start" || recorded || e.view.id !== rt.views.loadView()?.id)
62
+ return;
63
+ record(rt, e.view.id, e.view.sessionId);
64
+ });
65
+ },
66
+ screenStarted() {
67
+ left = true;
68
+ },
69
+ rendered(at) {
70
+ if (left || firstRender !== undefined)
71
+ return;
72
+ firstRender = at;
73
+ end?.(at);
74
+ },
75
+ close() {
76
+ off?.();
77
+ off = undefined;
78
+ end?.(o.now());
79
+ },
80
+ };
81
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The React Native binding of the RUM core: setupRumCore hands it the setup options with
3
+ * RUM's span processor, context manager and forwarding span exporter in place, and the wrappers;
4
+ * it runs `@libo11y/react-native`'s setupReactNativeWith over deps with each wrapper applied. The
5
+ * lifecycle is the app's AppState: background, and inactive on iOS, hide the app; active shows it.
6
+ */
7
+ import type { ReactNativeSetupOptions, ReactNativeTelemetry } from "@libo11y/react-native";
8
+ import { type AppLifecycle, type ReactNativeDeps } from "@libo11y/react-native/internal";
9
+ import type { RumBind, RumLifecycle } from "@libo11y/rum/core";
10
+ /** A binding of React Native: its setup options and telemetry. */
11
+ export type ReactNativeRumBind = RumBind<ReactNativeSetupOptions, ReactNativeTelemetry>;
12
+ /** How the binding runs the platform. */
13
+ export interface ReactNativeBindingOptions {
14
+ /** Install the telemetry globally, as setupReactNative does. */
15
+ readonly install: boolean;
16
+ /** The fetch the OTLP transport sends with instead of the pristine global fetch, as in tests. */
17
+ readonly fetch?: typeof globalThis.fetch;
18
+ }
19
+ /** The React Native binding: setupReactNativeWith over deps with RUM's wrappers. */
20
+ export declare function reactNativeBinding(deps: ReactNativeDeps, o: ReactNativeBindingOptions): ReactNativeRumBind;
21
+ /**
22
+ * RUM's lifecycle over the app's: hide on going to the background, show on coming back. RUM
23
+ * subscribes before the binding runs the platform's setup, so on a hide the summaries are emitted
24
+ * before the platform's own listener flushes them. No restore: an app has no back/forward cache.
25
+ * The setup adds activity: a new screen, until the touch boundary records touches.
26
+ */
27
+ export declare function rumLifecycle(app: AppLifecycle): RumLifecycle;
@@ -0,0 +1,31 @@
1
+ import { setupReactNativeWith, } from "@libo11y/react-native/internal";
2
+ /** The React Native binding: setupReactNativeWith over deps with RUM's wrappers. */
3
+ export function reactNativeBinding(deps, o) {
4
+ const fetch = o.fetch;
5
+ return (options, w) => setupReactNativeWith(options, {
6
+ ...deps,
7
+ createConsentController: (co) => w.consentController(deps.createConsentController(co)),
8
+ createHttpTransport: (t) => deps.createHttpTransport(w.transportOptions(fetch === undefined ? t : { ...t, fetch })),
9
+ // Traces are injected, so the platform's span exporter goes unused; logs are routed by
10
+ // session. The gateway accepts only delta sums and histograms, so app metrics export with
11
+ // delta temporality.
12
+ createExporterSet: (req, d, endpoints, eo) => w.exporterSet(deps.createExporterSet(req, d, endpoints, { ...eo, metricTemporality: "delta" })),
13
+ installNetworkInstrumentation: (n) => deps.installNetworkInstrumentation({ ...n, onStart: w.onRequestStart }),
14
+ onPlatform: (platform, info) => {
15
+ w.platform({ delivery: info.delivery, endpoints: info.endpoints }, info.env);
16
+ deps.onPlatform?.(platform, info);
17
+ },
18
+ }, o.install);
19
+ }
20
+ /**
21
+ * RUM's lifecycle over the app's: hide on going to the background, show on coming back. RUM
22
+ * subscribes before the binding runs the platform's setup, so on a hide the summaries are emitted
23
+ * before the platform's own listener flushes them. No restore: an app has no back/forward cache.
24
+ * The setup adds activity: a new screen, until the touch boundary records touches.
25
+ */
26
+ export function rumLifecycle(app) {
27
+ return {
28
+ visible: () => app.visible(),
29
+ subscribe: (h) => app.subscribe((visible) => (visible ? h.show() : h.hide())),
30
+ };
31
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The remote configuration cache on device storage. The remote configuration client reads its
3
+ * cache synchronously (localStorage on the web), and device storage is asynchronous, so the cache
4
+ * reads the listed keys once, when RUM opens remote configuration on the first grant, and serves
5
+ * them from memory. Writes change memory at once and reach storage in the background, one after
6
+ * another in call order; a failed write keeps the value for this run only.
7
+ */
8
+ import type { KeyValueStorage } from "@libo11y/react-native";
9
+ import type { ConfigCacheStorage } from "@libo11y/rum/core";
10
+ /** The remote configuration cache over device storage, whose background writes can be awaited. */
11
+ export interface PreloadedStorage extends ConfigCacheStorage {
12
+ /**
13
+ * Resolves once every write already made has reached storage or failed. A failed write was
14
+ * reported through diag when it failed. Never rejects.
15
+ */
16
+ flush(): Promise<void>;
17
+ }
18
+ /** A synchronous cache of keys over storage, once their stored values are read. Never rejects. */
19
+ export declare function preloadedStorage(storage: KeyValueStorage, keys: readonly string[]): Promise<PreloadedStorage>;
@@ -0,0 +1,38 @@
1
+ import { diag } from "@opentelemetry/api";
2
+ /** A synchronous cache of keys over storage, once their stored values are read. Never rejects. */
3
+ export async function preloadedStorage(storage, keys) {
4
+ const allowed = new Set(keys);
5
+ const values = new Map();
6
+ for (const k of allowed) {
7
+ try {
8
+ const v = await storage.getItem(k);
9
+ if (v !== null)
10
+ values.set(k, v);
11
+ }
12
+ catch (err) {
13
+ diag.debug("o11y: rum: remote configuration cache unreadable", err);
14
+ }
15
+ }
16
+ let last = Promise.resolve();
17
+ const background = (write) => {
18
+ last = last
19
+ .then(write)
20
+ .catch((err) => diag.debug("o11y: rum: remote configuration cache write failed", err));
21
+ };
22
+ return {
23
+ getItem: (k) => (allowed.has(k) ? (values.get(k) ?? null) : null),
24
+ setItem(k, v) {
25
+ if (!allowed.has(k))
26
+ return;
27
+ values.set(k, v);
28
+ background(() => storage.setItem(k, v));
29
+ },
30
+ removeItem(k) {
31
+ if (!allowed.has(k))
32
+ return;
33
+ values.delete(k);
34
+ background(() => storage.removeItem(k));
35
+ },
36
+ flush: () => last,
37
+ };
38
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Contract. What the React Native RUM collectors read from the runtime. Internal: env.ts reads the
3
+ * real globals, and tests pass a fake, so no module a test imports loads react-native.
4
+ */
5
+ /** React Native's performance.rnStartupTiming, in performance.now() time. */
6
+ export interface StartupTimingLike {
7
+ /** When the native process started, as React Native measures it. */
8
+ readonly startTime?: number;
9
+ readonly endTime?: number;
10
+ }
11
+ /** What the React Native RUM collectors read from the runtime. */
12
+ export interface RumReactNativeEnv {
13
+ /** performance.rnStartupTiming, where the runtime has it. */
14
+ readonly startupTiming?: StartupTimingLike;
15
+ /** performance.now() when `@libo11y/rum-react-native` was first evaluated: the app start fallback. */
16
+ readonly loadedAt: number;
17
+ /** False while the app is in the background, or inactive on iOS. */
18
+ visible(): boolean;
19
+ requestAnimationFrame(cb: () => void): unknown;
20
+ setTimeout(cb: () => void, ms: number): unknown;
21
+ clearTimeout(handle: unknown): void;
22
+ }
23
+ /** React Native's global error handler, as ErrorUtils.setGlobalHandler takes it. */
24
+ export type GlobalErrorHandler = (error: unknown, isFatal?: boolean) => void;
25
+ /** The part of React Native's global ErrorUtils the errors collector uses. */
26
+ export interface ErrorUtilsLike {
27
+ /** The handler installed now. */
28
+ getGlobalHandler(): GlobalErrorHandler | undefined;
29
+ /** Replaces the installed handler. */
30
+ setGlobalHandler(handler: GlobalErrorHandler): void;
31
+ }
32
+ /** The options of Hermes' promise rejection tracker, as the promise library's rejection tracking takes them. */
33
+ export interface RejectionTrackerOptions {
34
+ /** Track every rejection, not only those of an Error. */
35
+ readonly allRejections: boolean;
36
+ /** A rejection had no handler when the engine checked. */
37
+ onUnhandled(id: number, rejection: unknown): void;
38
+ /** A rejection onUnhandled reported got a handler later. */
39
+ onHandled(id: number): void;
40
+ }
41
+ /** The part of the HermesInternal global the errors collector uses. */
42
+ export interface HermesInternalLike {
43
+ /** Replaces the tracker any earlier call set up, React Native's development one included. */
44
+ enablePromiseRejectionTracker?(options: RejectionTrackerOptions): void;
45
+ }
46
+ /** What the errors collector reads from the runtime. */
47
+ export interface ErrorsEnv {
48
+ /** The ErrorUtils global, absent outside React Native. */
49
+ readonly errorUtils?: ErrorUtilsLike;
50
+ /** The HermesInternal global, absent on another engine. */
51
+ readonly hermes?: HermesInternalLike;
52
+ /** Platform.OS: the bundle stack frames are named after. */
53
+ readonly os: string;
54
+ /** __DEV__: a development build, whose stacks point at Metro and whose fatal errors show the red box at once. */
55
+ readonly dev: boolean;
56
+ /** console.warn, for React Native's development note on a rejection handled late. */
57
+ warn(message: string): void;
58
+ /** The runtime's setTimeout, for the fatal error deadline. */
59
+ setTimeout(cb: () => void, ms: number): unknown;
60
+ /** The runtime's clearTimeout. */
61
+ clearTimeout(handle: unknown): void;
62
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Contract. What the React Native RUM collectors read from the runtime. Internal: env.ts reads the
3
+ * real globals, and tests pass a fake, so no module a test imports loads react-native.
4
+ */
5
+ export {};
package/dist/env.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import { type AppLifecycle } from "@libo11y/react-native/internal";
2
+ import type { SettleTimers } from "@libo11y/rum/core";
3
+ import type { ErrorsEnv, RumReactNativeEnv } from "./contracts/env.ts";
4
+ import type { RumReactNativeDeps } from "./setup.ts";
5
+ /** React Native's frames, timers and startup timing, with the app's lifecycle for visible. */
6
+ export declare function defaultRumEnv(lifecycle?: AppLifecycle): RumReactNativeEnv;
7
+ /** The runtime's timers. */
8
+ export declare const runtimeTimers: SettleTimers;
9
+ /** React Native's ErrorUtils and Hermes' HermesInternal globals, the platform and __DEV__, for errors(). */
10
+ export declare function defaultErrorsEnv(): ErrorsEnv;
11
+ /** The real dependencies of setupRumReactNativeWith. */
12
+ export declare function defaultRumReactNativeDeps(): RumReactNativeDeps;
package/dist/env.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The real React Native dependencies of setupRumReactNative and screens(). The only module of the
3
+ * main entry that reads React Native's globals and, through `@libo11y/react-native/env`, loads
4
+ * react-native, so node tests never load it (boundary.test.ts enforces that).
5
+ */
6
+ import { defaultReactNativeDeps, defaultReactNativeEnv } from "@libo11y/react-native/env";
7
+ import { appStateLifecycle } from "@libo11y/react-native/internal";
8
+ const perf = globalThis
9
+ .performance;
10
+ /** performance.now() when this module was first evaluated: the app start without rnStartupTiming. */
11
+ const LOADED_AT = perf?.now() ?? 0;
12
+ /** React Native's frames, timers and startup timing, with the app's lifecycle for visible. */
13
+ export function defaultRumEnv(lifecycle = appStateLifecycle(defaultReactNativeEnv().appState)) {
14
+ const startup = perf?.rnStartupTiming;
15
+ return {
16
+ ...(startup === undefined ? {} : { startupTiming: startup }),
17
+ loadedAt: LOADED_AT,
18
+ visible: () => lifecycle.visible(),
19
+ requestAnimationFrame: (cb) => requestAnimationFrame(cb),
20
+ setTimeout: (cb, ms) => setTimeout(cb, ms),
21
+ clearTimeout: (h) => clearTimeout(h),
22
+ };
23
+ }
24
+ /** The runtime's timers. */
25
+ export const runtimeTimers = {
26
+ setTimeout: (cb, ms) => setTimeout(cb, ms),
27
+ clearTimeout: (h) => clearTimeout(h),
28
+ };
29
+ /** React Native's ErrorUtils and Hermes' HermesInternal globals, the platform and __DEV__, for errors(). */
30
+ export function defaultErrorsEnv() {
31
+ const g = globalThis;
32
+ const rn = defaultReactNativeEnv();
33
+ return {
34
+ ...(g.ErrorUtils == null ? {} : { errorUtils: g.ErrorUtils }),
35
+ ...(g.HermesInternal == null ? {} : { hermes: g.HermesInternal }),
36
+ os: rn.os,
37
+ dev: rn.dev,
38
+ warn: (m) => console.warn(m),
39
+ ...runtimeTimers,
40
+ };
41
+ }
42
+ /** The real dependencies of setupRumReactNativeWith. */
43
+ export function defaultRumReactNativeDeps() {
44
+ const platform = defaultReactNativeDeps();
45
+ const now = () => perf?.now() ?? Date.now();
46
+ return {
47
+ platform,
48
+ env: defaultRumEnv(platform.lifecycle),
49
+ now: Date.now,
50
+ perfNow: now,
51
+ // React Native has performance.timeOrigin; a runtime without it counts from now.
52
+ timeOrigin: typeof perf?.timeOrigin === "number" ? perf.timeOrigin : Date.now() - now(),
53
+ };
54
+ }