@libo11y/rum-react-native 0.0.0-stage → 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.
@@ -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
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * errors(): JavaScript errors on React Native.
3
+ *
4
+ * Sources. An error React Native's global handler receives (ErrorUtils.setGlobalHandler) is
5
+ * uncaught: the collector records it and hands it to the handler that was installed before it,
6
+ * always, so the red box, LogBox and the crash still happen. A fatal error in a release build is
7
+ * about to end the process, so the current screen's summary is emitted and the telemetry flushed
8
+ * (React Native telemetry saves every batch on device storage before it sends it) before the
9
+ * previous handler runs, for at most fatalFlushMillis. A fatal error while one is waiting is
10
+ * recorded and handed on after it, in order. When the previous handler throws there, the throw
11
+ * is raised again from a task, so it still ends the app; the crash path runs once, and fatal
12
+ * errors after it, the raised throw included (not recorded again), go straight to the previous
13
+ * handler. In development the previous handler runs at once.
14
+ *
15
+ * Hermes reports unhandled promise rejections only to the tracker HermesInternal's
16
+ * enablePromiseRejectionTracker sets, which React Native turns on in development alone, and a
17
+ * second call replaces the first. The collector sets one with allRejections: each unhandled
18
+ * rejection is unhandled_rejection, and in development the tracker also does what React Native's
19
+ * does, through the previous global handler (the red box path) and console.warn. Another engine
20
+ * reports no rejections.
21
+ *
22
+ * A request that ends without a status is network, type NetworkError, message "<METHOD> <host>
23
+ * failed", unless the app aborted it, as in the browser's errors().
24
+ *
25
+ * React renders errors through an error boundary, never this handler: `@libo11y/rum-react`'s
26
+ * RumErrorBoundary, or an app's own boundary calling rum.addError with source boundary.
27
+ *
28
+ * Stacks. In a release build Hermes names the bundle by its path on the device, sometimes after
29
+ * "address at ". Each frame of the app's bundle is rewritten to app:///main.jsbundle (iOS) or
30
+ * app:///index.android.bundle (Android), so the gateway finds the source map uploaded under that
31
+ * name for the app's service.version and o11y.rum.app.update_id, and no device path leaves the
32
+ * phone. Engine frames (native, InternalBytecode.js) are kept. Development stacks point at Metro
33
+ * and are kept as they are.
34
+ *
35
+ * Every error goes through recordError, so it counts in the screen's summary, retains an unsampled
36
+ * session, and carries the breadcrumbs. An error raised while one is being recorded is not recorded
37
+ * again. Stop restores the previous global handler while RUM's is still the installed one; a
38
+ * handler installed over RUM's keeps calling it, and it then only passes errors on.
39
+ */
40
+ import { type RumCollector } from "@libo11y/rum/core";
41
+ import type { ErrorsEnv } from "./contracts/env.ts";
42
+ /** How long a fatal error in a release build waits for the flush before it reaches the previous handler. */
43
+ export declare const FATAL_FLUSH_MILLIS = 2000;
44
+ /** Internal options of errorsWith, for tests. */
45
+ export interface ErrorsWithOptions {
46
+ /** Default FATAL_FLUSH_MILLIS. */
47
+ readonly fatalFlushMillis?: number;
48
+ }
49
+ /** The errors collector over env. */
50
+ export declare function errorsWith(env: ErrorsEnv, o?: ErrorsWithOptions): RumCollector;
package/dist/errors.js ADDED
@@ -0,0 +1,213 @@
1
+ /**
2
+ * errors(): JavaScript errors on React Native.
3
+ *
4
+ * Sources. An error React Native's global handler receives (ErrorUtils.setGlobalHandler) is
5
+ * uncaught: the collector records it and hands it to the handler that was installed before it,
6
+ * always, so the red box, LogBox and the crash still happen. A fatal error in a release build is
7
+ * about to end the process, so the current screen's summary is emitted and the telemetry flushed
8
+ * (React Native telemetry saves every batch on device storage before it sends it) before the
9
+ * previous handler runs, for at most fatalFlushMillis. A fatal error while one is waiting is
10
+ * recorded and handed on after it, in order. When the previous handler throws there, the throw
11
+ * is raised again from a task, so it still ends the app; the crash path runs once, and fatal
12
+ * errors after it, the raised throw included (not recorded again), go straight to the previous
13
+ * handler. In development the previous handler runs at once.
14
+ *
15
+ * Hermes reports unhandled promise rejections only to the tracker HermesInternal's
16
+ * enablePromiseRejectionTracker sets, which React Native turns on in development alone, and a
17
+ * second call replaces the first. The collector sets one with allRejections: each unhandled
18
+ * rejection is unhandled_rejection, and in development the tracker also does what React Native's
19
+ * does, through the previous global handler (the red box path) and console.warn. Another engine
20
+ * reports no rejections.
21
+ *
22
+ * A request that ends without a status is network, type NetworkError, message "<METHOD> <host>
23
+ * failed", unless the app aborted it, as in the browser's errors().
24
+ *
25
+ * React renders errors through an error boundary, never this handler: `@libo11y/rum-react`'s
26
+ * RumErrorBoundary, or an app's own boundary calling rum.addError with source boundary.
27
+ *
28
+ * Stacks. In a release build Hermes names the bundle by its path on the device, sometimes after
29
+ * "address at ". Each frame of the app's bundle is rewritten to app:///main.jsbundle (iOS) or
30
+ * app:///index.android.bundle (Android), so the gateway finds the source map uploaded under that
31
+ * name for the app's service.version and o11y.rum.app.update_id, and no device path leaves the
32
+ * phone. Engine frames (native, InternalBytecode.js) are kept. Development stacks point at Metro
33
+ * and are kept as they are.
34
+ *
35
+ * Every error goes through recordError, so it counts in the screen's summary, retains an unsampled
36
+ * session, and carries the breadcrumbs. An error raised while one is being recorded is not recorded
37
+ * again. Stop restores the previous global handler while RUM's is still the installed one; a
38
+ * handler installed over RUM's keeps calling it, and it then only passes errors on.
39
+ */
40
+ import { normalizeError, recordError } from "@libo11y/rum/core";
41
+ import { diag } from "@opentelemetry/api";
42
+ import { hermesStack } from "./hermes-stack.js";
43
+ /** How long a fatal error in a release build waits for the flush before it reaches the previous handler. */
44
+ export const FATAL_FLUSH_MILLIS = 2000;
45
+ /** The error.type values of a request the app aborted, which is not a failure. */
46
+ const ABORTED = new Set(["AbortError", "abort"]);
47
+ /** An Error-like value recordError reads as is, so the type and message are exactly these. */
48
+ class Described extends Error {
49
+ constructor(name, message, stack) {
50
+ super(message);
51
+ this.name = name;
52
+ this.stack = stack ?? "";
53
+ }
54
+ }
55
+ function host(raw) {
56
+ try {
57
+ return new URL(raw).hostname;
58
+ }
59
+ catch {
60
+ return "";
61
+ }
62
+ }
63
+ /** React Native's development report of an unhandled rejection (promiseRejectionTrackingOptions). */
64
+ function devRejection(id, rejection) {
65
+ let message;
66
+ if (rejection === undefined)
67
+ message = "";
68
+ else if (Object.prototype.toString.call(rejection) === "[object Error]") {
69
+ message = Error.prototype.toString.call(rejection);
70
+ }
71
+ else if (typeof rejection === "string")
72
+ message = rejection;
73
+ else {
74
+ try {
75
+ message = JSON.stringify(rejection) ?? String(rejection);
76
+ }
77
+ catch {
78
+ message = String(rejection);
79
+ }
80
+ }
81
+ return new Error(`Uncaught (in promise, id: ${id})${message === "" ? "" : `: "${message}"`}`, {
82
+ cause: rejection,
83
+ });
84
+ }
85
+ /** The errors collector over env. */
86
+ export function errorsWith(env, o = {}) {
87
+ const flushMillis = o.fatalFlushMillis ?? FATAL_FLUSH_MILLIS;
88
+ return {
89
+ name: "errors",
90
+ start(rt) {
91
+ let stopped = false;
92
+ let recording = false;
93
+ const describe = (error) => {
94
+ if (env.dev)
95
+ return error;
96
+ const n = normalizeError(error);
97
+ return n.stack === undefined ? error : new Described(n.type, n.message, hermesStack(n.stack, env.os));
98
+ };
99
+ const record = (source, error) => {
100
+ if (stopped || recording)
101
+ return;
102
+ recording = true;
103
+ try {
104
+ recordError(rt, source, describe(error));
105
+ }
106
+ catch (err) {
107
+ diag.warn("o11y: rum: recording an error failed", err);
108
+ }
109
+ finally {
110
+ recording = false;
111
+ }
112
+ };
113
+ const utils = env.errorUtils;
114
+ const found = utils?.getGlobalHandler();
115
+ const previous = typeof found === "function" ? found : undefined;
116
+ /** Fatal errors waiting for the flush, in order; undefined while none waits. */
117
+ let waiting;
118
+ /** The crash path ran: later fatal errors go straight to the previous handler. */
119
+ let crashed = false;
120
+ /** What the previous handler threw on the crash path, raised again from a task. */
121
+ const raised = new WeakSet();
122
+ const crash = () => {
123
+ const errors = waiting ?? [];
124
+ waiting = undefined;
125
+ crashed = true;
126
+ for (const e of errors) {
127
+ try {
128
+ previous?.(e, true);
129
+ }
130
+ catch (thrown) {
131
+ // A throw here would reject the flush's promise, which the rejection tracker records
132
+ // and the app survives. Raised from a task, it takes React Native's crash path.
133
+ if (typeof thrown === "object" && thrown !== null)
134
+ raised.add(thrown);
135
+ env.setTimeout(() => {
136
+ throw thrown;
137
+ }, 0);
138
+ }
139
+ }
140
+ };
141
+ const handler = (error, isFatal) => {
142
+ const again = typeof error === "object" && error !== null && raised.has(error);
143
+ if (!again)
144
+ record("uncaught", error);
145
+ if (isFatal !== true || env.dev || stopped || crashed) {
146
+ previous?.(error, isFatal);
147
+ return;
148
+ }
149
+ if (waiting !== undefined) {
150
+ waiting.push(error);
151
+ return;
152
+ }
153
+ waiting = [error];
154
+ let done = false;
155
+ let timer;
156
+ const go = () => {
157
+ if (done)
158
+ return;
159
+ done = true;
160
+ env.clearTimeout(timer);
161
+ crash();
162
+ };
163
+ timer = env.setTimeout(go, flushMillis);
164
+ try {
165
+ rt.summary.flush();
166
+ }
167
+ catch (err) {
168
+ diag.warn("o11y: rum: emitting the summary before a crash failed", err);
169
+ }
170
+ rt.telemetry.forceFlush().then(go, go);
171
+ };
172
+ if (utils !== undefined && previous !== undefined)
173
+ utils.setGlobalHandler(handler);
174
+ const tracker = env.hermes?.enablePromiseRejectionTracker;
175
+ if (typeof tracker === "function") {
176
+ tracker.call(env.hermes, {
177
+ allRejections: true,
178
+ onUnhandled: (id, rejection) => {
179
+ record("unhandled_rejection", rejection);
180
+ if (env.dev)
181
+ previous?.(devRejection(id, rejection), false);
182
+ },
183
+ onHandled: (id) => {
184
+ if (!env.dev)
185
+ return;
186
+ env.warn(`Promise rejection handled (id: ${id})\nThis means you can ignore any previous messages of the form "Uncaught (in promise, id: ${id})"`);
187
+ },
188
+ });
189
+ }
190
+ // Requests in flight, so a failed one can be described by its method and host.
191
+ const requests = new Map();
192
+ const offBus = rt.bus.subscribe((s) => {
193
+ if (s.type === "request-start")
194
+ requests.set(s.spanId, { method: s.method, url: s.url });
195
+ else if (s.type === "request-end") {
196
+ const r = requests.get(s.spanId);
197
+ requests.delete(s.spanId);
198
+ if (r !== undefined && s.status === undefined && !ABORTED.has(s.errorType ?? "")) {
199
+ record("network", new Described("NetworkError", `${r.method} ${host(r.url)} failed`, undefined));
200
+ }
201
+ }
202
+ });
203
+ return () => {
204
+ stopped = true;
205
+ if (utils !== undefined && previous !== undefined && utils.getGlobalHandler() === handler) {
206
+ utils.setGlobalHandler(previous);
207
+ }
208
+ offBus();
209
+ requests.clear();
210
+ };
211
+ },
212
+ };
213
+ }
package/dist/expo.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type { ReactNativeRumTelemetry, RumReactNativeSetupOptions } from "./options.ts";
2
+ export type { ReactNativeRumTelemetry, RumReactNativeOptions, RumReactNativeSetupOptions, } from "./options.ts";
3
+ /**
4
+ * setupRumReactNative with expoOptions() under the app's own options: an option the app sets
5
+ * wins, and resourceAttributes merge key by key with the app's winning, as setupExpo does.
6
+ */
7
+ export declare function setupRumExpo(options?: RumReactNativeSetupOptions): Promise<ReactNativeRumTelemetry>;
package/dist/expo.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * libo11y RUM for Expo apps: setupRumReactNative with the options `@libo11y/react-native/expo`
3
+ * fills in, the retry queue, the retention buffer, the session and the remote configuration
4
+ * cache in the app's documents (expo-file-system), the app version (expo-application), the ID of
5
+ * the over-the-air update the app runs (expo-updates) and the device class (expo-device).
6
+ */
7
+ import { expoOptions } from "@libo11y/react-native/expo";
8
+ import { withExpoOptions } from "@libo11y/react-native/internal";
9
+ import { setupRumReactNative } from "./index.js";
10
+ /**
11
+ * setupRumReactNative with expoOptions() under the app's own options: an option the app sets
12
+ * wins, and resourceAttributes merge key by key with the app's winning, as setupExpo does.
13
+ */
14
+ export function setupRumExpo(options = {}) {
15
+ return setupRumReactNative(withExpoOptions(expoOptions(), options));
16
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Hermes stacks in release builds name the app's bundle by its path on the device, sometimes after
3
+ * "address at ". hermesStack rewrites each frame of the app's bundle to app:///main.jsbundle (iOS)
4
+ * or app:///index.android.bundle (Android), the names its source map is uploaded under, and keeps
5
+ * engine frames. A frame "address at" a bundle carries a bytecode offset, which Hermes prints
6
+ * 0-based (React Native's parseHermesStack reads it as virtualOffset0Based); it becomes the
7
+ * 1-based column every other frame carries and the gateway reads. It imports nothing, so the
8
+ * gateway journey in `@libo11y/sourcemaps` can use it.
9
+ */
10
+ /** The name the app's bundle has in stack frames on platform os, and the name its source map is uploaded under. */
11
+ export declare function bundleName(os: string): string;
12
+ /** Rewrites each frame of the app's bundle in a Hermes stack to app:///bundleName(os), keeping engine frames. */
13
+ export declare function hermesStack(stack: string, os: string): string;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Hermes stacks in release builds name the app's bundle by its path on the device, sometimes after
3
+ * "address at ". hermesStack rewrites each frame of the app's bundle to app:///main.jsbundle (iOS)
4
+ * or app:///index.android.bundle (Android), the names its source map is uploaded under, and keeps
5
+ * engine frames. A frame "address at" a bundle carries a bytecode offset, which Hermes prints
6
+ * 0-based (React Native's parseHermesStack reads it as virtualOffset0Based); it becomes the
7
+ * 1-based column every other frame carries and the gateway reads. It imports nothing, so the
8
+ * gateway journey in `@libo11y/sourcemaps` can use it.
9
+ */
10
+ /** Frame locations that belong to the engine, not the app's bundle. */
11
+ const ENGINE = new Set(["native", "[native code]", "InternalBytecode.js"]);
12
+ const isDigits = (t) => t !== "" && [...t].every((c) => c >= "0" && c <= "9");
13
+ /**
14
+ * Splits "location:line:col" or "location:line" into the location and ":line:col", or undefined.
15
+ * It scans from the end without a regular expression, so a long line costs linear time.
16
+ */
17
+ function splitPosition(s) {
18
+ const last = s.lastIndexOf(":");
19
+ if (last <= 0 || !isDigits(s.slice(last + 1)))
20
+ return undefined;
21
+ const before = s.lastIndexOf(":", last - 1);
22
+ const cut = before > 0 && isDigits(s.slice(before + 1, last)) ? before : last;
23
+ return [s.slice(0, cut), s.slice(cut)];
24
+ }
25
+ /** ":line:offset" with the 0-based offset made a 1-based column. */
26
+ function oneBased(position) {
27
+ const last = position.lastIndexOf(":");
28
+ if (last <= 0)
29
+ return position;
30
+ return `${position.slice(0, last)}:${Number(position.slice(last + 1)) + 1}`;
31
+ }
32
+ /**
33
+ * The parts of a frame line: what comes before the location, the location, and what comes after
34
+ * it, with a bytecode offset made a 1-based column.
35
+ */
36
+ function frameParts(line) {
37
+ const body = line.trimStart();
38
+ if (!body.startsWith("at "))
39
+ return undefined;
40
+ const indent = line.slice(0, line.length - body.length);
41
+ let head;
42
+ let inner;
43
+ let tail;
44
+ if (body.endsWith(")")) {
45
+ const open = body.lastIndexOf("(");
46
+ if (open < 0)
47
+ return undefined;
48
+ head = body.slice(0, open + 1);
49
+ inner = body.slice(open + 1, -1);
50
+ tail = ")";
51
+ }
52
+ else {
53
+ head = "at ";
54
+ inner = body.slice(3);
55
+ tail = "";
56
+ if (inner.includes(" "))
57
+ return undefined;
58
+ }
59
+ const bytecode = inner.startsWith("address at ");
60
+ if (bytecode)
61
+ inner = inner.slice("address at ".length);
62
+ const split = splitPosition(inner);
63
+ if (split === undefined)
64
+ return undefined;
65
+ const position = bytecode ? oneBased(split[1]) : split[1];
66
+ return [`${indent}${head}`, split[0], `${position}${tail}`];
67
+ }
68
+ /** The name the app's bundle has in stack frames on platform os, and the name its source map is uploaded under. */
69
+ export function bundleName(os) {
70
+ return os === "android" ? "index.android.bundle" : "main.jsbundle";
71
+ }
72
+ /** Rewrites each frame of the app's bundle in a Hermes stack to app:///bundleName(os), keeping engine frames. */
73
+ export function hermesStack(stack, os) {
74
+ const app = `app:///${bundleName(os)}`;
75
+ return stack
76
+ .split("\n")
77
+ .map((line) => {
78
+ const parts = frameParts(line);
79
+ if (parts === undefined || ENGINE.has(parts[1]))
80
+ return line;
81
+ return `${parts[0]}${app}${parts[2]}`;
82
+ })
83
+ .join("\n");
84
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * libo11y RUM for React Native apps on Hermes: setupRumReactNative over `@libo11y/react-native`,
3
+ * the collectors it runs (screens, errors, taps), and RumTouchBoundary, which passes touches to
4
+ * taps(). telemetry.rum is the browser's Rum handle, so `@libo11y/rum-react` and
5
+ * `@libo11y/rum-connect` work with it as they are.
6
+ */
7
+ export type { KeyValueStorage, ReactNativeSetupOptions, ReactNativeTelemetry } from "@libo11y/react-native";
8
+ export type { AddErrorOptions, CollectorName, RemoteConfig, RemoteConfigOptions, RequestStartHook, Rum, RumCollector, RumOptions, RumRuntime, } from "@libo11y/rum";
9
+ import type { RemoteConfig, RemoteConfigOptions, RumCollector } from "@libo11y/rum";
10
+ import type { ReactNativeRumTelemetry, RumReactNativeSetupOptions } from "./options.ts";
11
+ import { type TapsOptions } from "./taps.ts";
12
+ export type { ReactNativeRumTelemetry, RumReactNativeOptions, RumReactNativeSetupOptions, } from "./options.ts";
13
+ export { RumName, type RumNameProps } from "./tap-target.ts";
14
+ export type { TapsOptions } from "./taps.ts";
15
+ export { RumTouchBoundary, type RumTouchBoundaryProps } from "./touch-boundary.ts";
16
+ export { VERSION } from "./version.ts";
17
+ /**
18
+ * Builds React Native telemetry with RUM and installs it globally, as setupReactNative does. Every
19
+ * view is a screen, and the first is named rum.initialViewName (default "app") until a router
20
+ * adapter or rum.setViewName names it. Nothing is recorded, stored or sent until consent is
21
+ * granted, unless consent.initial is "granted". options.storage holds the retry queue, the
22
+ * retention buffer, the session (a relaunch within the idle window continues it) and the remote
23
+ * configuration cache. The app_load span runs from the process start to the first screen's
24
+ * rum.viewRendered(), once per process, also when consent comes later. Calling it twice without a
25
+ * shutdown rejects with ALREADY_SETUP.
26
+ */
27
+ export declare function setupRumReactNative(options?: RumReactNativeSetupOptions): Promise<ReactNativeRumTelemetry>;
28
+ /**
29
+ * The screens collector: a view span per screen, ending at the first frame after
30
+ * rum.viewRendered() or 10 seconds after it started. The first screen's span is a child of
31
+ * app_load; a later screen's is a root linked to the action that caused it. Pass it in
32
+ * rum.collectors.
33
+ */
34
+ export declare function screens(): RumCollector;
35
+ /**
36
+ * Remote configuration from the RUM gateway, as `@libo11y/rum`'s remoteConfig, for rum.remoteConfig.
37
+ * It is fetched only once consent is granted, and cached in the app's storage.
38
+ */
39
+ export declare function remoteConfig(opts?: RemoteConfigOptions): RemoteConfig;
40
+ /**
41
+ * The errors collector: errors React Native's global handler receives (uncaught, handed on to the
42
+ * previous handler always; a fatal one in a release build after a flush of at most 2 seconds),
43
+ * unhandled promise rejections on Hermes, and requests that failed without a response. Release
44
+ * stacks name the app's bundle app:///main.jsbundle (iOS) or app:///index.android.bundle
45
+ * (Android), so the gateway finds the source maps uploaded under those names. Render errors reach
46
+ * RUM through an error boundary: `@libo11y/rum-react`'s RumErrorBoundary, or rum.addError with
47
+ * source boundary. Pass it in rum.collectors.
48
+ */
49
+ export declare function errors(): RumCollector;
50
+ /**
51
+ * The taps collector: taps and long presses as action spans, named from the closest o11yName prop
52
+ * or RumName, else the target's accessibilityLabel, never from text; and rage and error taps as
53
+ * frustration signals. It records the touches RumTouchBoundary passes it, so render the boundary
54
+ * around the app. Pass it in rum.collectors.
55
+ */
56
+ export declare function taps(opts?: TapsOptions): RumCollector;