@libo11y/react-native 0.4.0 → 0.7.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
@@ -54,16 +54,62 @@ and `expo-updates`. They are optional peer dependencies: an app that
54
54
  imports `./expo` installs them, at Expo SDK 58 or later. The main entry
55
55
  imports none of them. Tested on Expo SDK 58 only.
56
56
 
57
+ ## Native module (iOS)
58
+
59
+ The package ships an Expo module, `Libo11yNative`, written in Swift, for
60
+ iOS only. Expo's autolinking adds it to an app that lists
61
+ `@libo11y/react-native` in its own `dependencies`, at the next native
62
+ build (`npx expo prebuild` or EAS Build, then `pod install`). It needs no
63
+ config plugin. It needs iOS 16.4 or later, the minimum of Expo SDK 58's
64
+ modules.
65
+
66
+ - It reads the process start time from the kernel (`sysctl`
67
+ `kinfo_proc`), so `@libo11y/rum-react-native`'s `app_load` starts when
68
+ the process did, unless iOS prewarmed the process. The context history
69
+ records the start of every process, prewarmed or not.
70
+ - It subscribes to MetricKit and keeps each crash and hang report on disk
71
+ while RUM records under consent, at most 32 and none older than 7 days,
72
+ until `@libo11y/rum-react-native`'s `errors()` turns it into a record.
73
+ It keeps a report only when the report names its process (iOS 17 and
74
+ later) and that process wrote context by the time the report's payload
75
+ began, which it does only while RUM records under consent, so consent
76
+ covered the whole time the report may have happened in. It drops any other report, and one from before
77
+ recording was switched on. It remembers handled reports for 8 days, so
78
+ a report delivered again is not kept twice. Two reports alike, such as
79
+ two identical hangs, are kept apart by where they are in MetricKit's
80
+ payloads.
81
+ - A report keeps only the stack of the thread MetricKit attributes it to.
82
+ MetricKit's earlier payloads are read off the module's creating thread,
83
+ and JavaScript reads the reports and the history through async
84
+ functions, at most 512 KiB of reports at a time, so the JavaScript
85
+ thread never waits on the disk.
86
+ - It keeps the last 64 session and screen entries JavaScript writes, with
87
+ the process ID and start time, so a report from an earlier launch maps
88
+ to the session and screen it happened in. Every entry also carries when
89
+ its process first wrote under consent, so that time outlasts the entry
90
+ that set it.
91
+
92
+ Everything lives under the app's `Application Support/libo11y`, which is
93
+ excluded from backups. Revoking consent deletes the reports and the
94
+ history, and the revoke returns once they are gone. A file it cannot
95
+ delete is reported to JavaScript. The cleanup then stays pending on
96
+ disk, or, when even that mark cannot be written, the recording flag is
97
+ invalidated: the module keeps and reads back nothing, and recording
98
+ cannot be switched on again until a retried cleanup deletes everything.
99
+
100
+ The JavaScript looks the module up without importing anything native.
101
+ An app binary built before the module, an Android build, a bare React
102
+ Native app without Expo modules, and tests have no module, and the
103
+ packages then work exactly as before, JavaScript only. That is what an
104
+ over-the-air update running on an older binary gets.
105
+
57
106
  ## Status
58
107
 
59
- A preview. The package first ships in `ts/v0.4.0`, and its API can change
60
- in a minor release until the RUM package for React Native,
61
- `@libo11y/rum-react-native`, ships on top of it. It is not on npm yet.
62
- Until its first npm publish, install it from the tarball attached to the
63
- [`ts/v0.4.0` GitHub Release](https://github.com/jamesainslie/libo11y/releases/tag/ts/v0.4.0),
64
- whose notes list the exact URL:
108
+ A preview. The package first ships in `ts/v0.4.0`, is published on npm at
109
+ `0.7.0` (and attached as a tarball to the
110
+ [`ts/v0.7.0` GitHub Release](https://github.com/libo11y/libo11y/releases/tag/ts/v0.7.0)),
111
+ and its API can change in a minor release:
65
112
 
66
113
  ```sh
67
- npm install \
68
- https://github.com/jamesainslie/libo11y/releases/download/ts/v0.4.0/libo11y-react-native-0.4.0.tgz
114
+ npm install @libo11y/react-native
69
115
  ```
package/dist/env.d.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  import type { ReactNativeEnv } from "./contracts/env.ts";
2
2
  import type { ReactNativeDeps } from "./setup.ts";
3
+ export type { AppLifecycle, AppStateLike, ReactNativeEnv } from "./contracts/env.ts";
4
+ export type { KeyValueStorage } from "./contracts/storage.ts";
5
+ export type { NetworkInstrumentation, NetworkInstrumentationOptions } from "./instrumentation/network.ts";
6
+ export type { ReactNativeDeps } from "./setup.ts";
7
+ export type { StorageQueueOptions } from "./storage/queue.ts";
3
8
  /** React Native's AppState, Platform and Dimensions, read when called. */
4
9
  export declare function defaultReactNativeEnv(): ReactNativeEnv;
5
10
  /** The real dependencies of setupReactNativeWith over env. */
package/dist/env.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * @libo11y/react-native/env: the real React Native dependencies, for @libo11y/rum-react-native's
3
- * binding, which wraps them. For libo11y packages only: it follows the package version, carries no
4
- * compatibility promise and has no API report. The only module of this package that imports a
5
- * value from react-native, so node tests never load it (boundary.test.ts enforces that).
3
+ * binding, which wraps them. For libo11y packages only: it follows the package version and carries
4
+ * no compatibility promise. The only module of this package that imports a value from react-native,
5
+ * so node tests never load it (boundary.test.ts enforces that).
6
6
  */
7
7
  import { createConsentController, createDelivery, createExporterSet, createHttpTransport, } from "@libo11y/web/portable";
8
8
  import { AppState, Dimensions, Platform } from "react-native";
package/dist/expo.d.ts CHANGED
@@ -10,7 +10,7 @@ import { type ExpoAppInfo } from "./expo/app-info.ts";
10
10
  import { type ExpoOptions } from "./expo/options.ts";
11
11
  import type { ReactNativeSetupOptions, ReactNativeTelemetry } from "./options.ts";
12
12
  export type { KeyValueStorage } from "./contracts/storage.ts";
13
- export type { ReactNativeSetupOptions, ReactNativeTelemetry } from "./options.ts";
13
+ export type { ReactNativeConsentOptions, ReactNativeInstrumentationOptions, ReactNativeSetupOptions, ReactNativeTelemetry, ReactNativeTransportOptions, } from "./options.ts";
14
14
  export type { ExpoAppInfo, ExpoOptions };
15
15
  /**
16
16
  * A KeyValueStorage with one file per key in the libo11y directory of the app's documents
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * @libo11y/react-native/internal: the platform's building blocks, for @libo11y/rum-react-native.
3
- * For libo11y packages only: it follows the package version, carries no compatibility promise and
4
- * has no API report. Nothing reachable from here imports react-native or Expo (boundary.test.ts
5
- * enforces that), so node tests can load it; the binding takes the real env from ./env.
3
+ * For libo11y packages only: it follows the package version and carries no compatibility promise.
4
+ * Nothing reachable from here imports react-native or Expo (boundary.test.ts enforces that), so
5
+ * node tests can load it; the binding takes the real env from ./env.
6
6
  */
7
7
  export type { AppLifecycle, AppStateLike, ReactNativeEnv } from "./contracts/env.ts";
8
8
  export type { KeyValueStorage } from "./contracts/storage.ts";
@@ -12,6 +12,8 @@ export { expoFileStorageWith, type FileLike, type FileSystemLike } from "./expo/
12
12
  export { type ExpoOptions, expoOptionsFrom, withExpoOptions } from "./expo/options.ts";
13
13
  export { installNetworkInstrumentation, type NetworkInstrumentation, type NetworkInstrumentationOptions, RN_SCOPE, } from "./instrumentation/network.ts";
14
14
  export { appStateLifecycle } from "./lifecycle.ts";
15
+ export { type Libo11yNative, libo11yNative, libo11yNativeFrom, NATIVE_ABI, NATIVE_MODULE_NAME, type NativeContextEntry, type NativeDiagnostic, } from "./native.ts";
16
+ export type { ReactNativeConsentOptions, ReactNativeInstrumentationOptions, ReactNativeSetupOptions, ReactNativeTelemetry, ReactNativeTransportOptions, } from "./options.ts";
15
17
  export { MOBILE_ENV_DEFAULTS, type ReactNativePlatformOptions, reactNativePlatform } from "./platform.ts";
16
18
  export { uuidCrypto } from "./random.ts";
17
19
  export { detectReactNativeResource, type ReactNativeResourceOptions } from "./resource.ts";
package/dist/internal.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * @libo11y/react-native/internal: the platform's building blocks, for @libo11y/rum-react-native.
3
- * For libo11y packages only: it follows the package version, carries no compatibility promise and
4
- * has no API report. Nothing reachable from here imports react-native or Expo (boundary.test.ts
5
- * enforces that), so node tests can load it; the binding takes the real env from ./env.
3
+ * For libo11y packages only: it follows the package version and carries no compatibility promise.
4
+ * Nothing reachable from here imports react-native or Expo (boundary.test.ts enforces that), so
5
+ * node tests can load it; the binding takes the real env from ./env.
6
6
  */
7
7
  export { deviceClassOf } from "./device-class.js";
8
8
  export { expoAppInfoFrom } from "./expo/app-info.js";
@@ -10,6 +10,7 @@ export { expoFileStorageWith } from "./expo/file-storage.js";
10
10
  export { expoOptionsFrom, withExpoOptions } from "./expo/options.js";
11
11
  export { installNetworkInstrumentation, RN_SCOPE, } from "./instrumentation/network.js";
12
12
  export { appStateLifecycle } from "./lifecycle.js";
13
+ export { libo11yNative, libo11yNativeFrom, NATIVE_ABI, NATIVE_MODULE_NAME, } from "./native.js";
13
14
  export { MOBILE_ENV_DEFAULTS, reactNativePlatform } from "./platform.js";
14
15
  export { uuidCrypto } from "./random.js";
15
16
  export { detectReactNativeResource } from "./resource.js";
@@ -0,0 +1,110 @@
1
+ /** The name the module registers with Expo. */
2
+ export declare const NATIVE_MODULE_NAME = "Libo11yNative";
3
+ /** The interface version of the module this package speaks. */
4
+ export declare const NATIVE_ABI = 1;
5
+ /** One entry of the context history: what was current at `at`, as JavaScript wrote it. */
6
+ export interface NativeContextEntry {
7
+ /** Epoch milliseconds when this became current. */
8
+ readonly at: number;
9
+ readonly sessionId: string;
10
+ readonly viewId: string;
11
+ readonly viewName: string;
12
+ readonly viewKind: string;
13
+ /** The seq the view's next summary would have had. */
14
+ readonly seq: number;
15
+ /** service.version. */
16
+ readonly version?: string;
17
+ /** o11y.rum.app.update_id. */
18
+ readonly updateId?: string;
19
+ /** The writing process's ID, which the module adds. */
20
+ readonly pid?: number;
21
+ /** The writing process's start, epoch milliseconds, which the module adds. */
22
+ readonly processStart?: number;
23
+ /**
24
+ * When the writing process first wrote under consent, epoch milliseconds, which the module adds
25
+ * to every entry, so it outlasts the entry that set it.
26
+ */
27
+ readonly since?: number;
28
+ /** Written as a fatal JavaScript error ends the process, so its native crash is not reported again. */
29
+ readonly fatal?: boolean;
30
+ /** Whether the session was kept (sampled or retained) when this was written. */
31
+ readonly kept?: boolean;
32
+ /**
33
+ * Written when a later launch sent a late summary of the view: seq is the view's next seq then.
34
+ * It names no context of its own, and attribution skips it.
35
+ */
36
+ readonly late?: boolean;
37
+ /** On a late entry, the report it counted, so a report tried again is not counted twice. */
38
+ readonly report?: string;
39
+ }
40
+ /** A crash or hang report MetricKit delivered, as the module keeps it. */
41
+ export interface NativeDiagnostic {
42
+ /** Stable for one report, for acknowledgeDiagnostics. */
43
+ readonly id: string;
44
+ readonly kind: "crash" | "hang";
45
+ /** The delivering payload's time range, epoch milliseconds. */
46
+ readonly begin: number;
47
+ readonly end: number;
48
+ /** The process the report is about, when the operating system says (iOS 17 and later). */
49
+ readonly pid?: number;
50
+ readonly appVersion?: string;
51
+ readonly appBuild?: string;
52
+ readonly osVersion?: string;
53
+ /** The Mach exception type, such as 1 for EXC_BAD_ACCESS. */
54
+ readonly exceptionType?: number;
55
+ readonly exceptionCode?: number;
56
+ /** The POSIX signal number, such as 11 for SIGSEGV. */
57
+ readonly signal?: number;
58
+ readonly terminationReason?: string;
59
+ /** The Objective-C or Swift exception's name and message (iOS 17 and later). */
60
+ readonly objcName?: string;
61
+ readonly objcMessage?: string;
62
+ /** How long a hang lasted, in seconds. */
63
+ readonly hangSeconds?: number;
64
+ /** MetricKit's MXCallStackTree JSON. */
65
+ readonly callStackTree?: unknown;
66
+ }
67
+ /** The guarded bridge to the module. */
68
+ export interface Libo11yNative {
69
+ /**
70
+ * The process start time from the kernel (sysctl kinfo_proc), epoch milliseconds, also for a
71
+ * prewarmed process: the context history and attribution need it.
72
+ */
73
+ processStart(): number | undefined;
74
+ /**
75
+ * Whether iOS prewarmed this process before the person opened the app, so its process start is
76
+ * not when the app started.
77
+ */
78
+ prewarmed(): boolean;
79
+ /**
80
+ * Whether the module keeps MetricKit reports: on while RUM records under consent. Off also
81
+ * deletes the reports and the context history it holds. Resolves once the module did, off the
82
+ * JavaScript thread. Rejects when it could not: off then still stops the module recording in
83
+ * this process, and a later off (a denied start, a revoke) deletes again.
84
+ */
85
+ setRecording(on: boolean): Promise<void>;
86
+ /**
87
+ * Appends one context entry; the module adds the process ID and start and keeps the last 64.
88
+ * Resolves true once it kept it, false when it did not, as while recording is off.
89
+ */
90
+ recordContext(entry: NativeContextEntry): Promise<boolean>;
91
+ /** The context history. The module reads it off the JavaScript thread. */
92
+ contextHistory(): Promise<NativeContextEntry[]>;
93
+ /**
94
+ * The reports the module keeps, oldest first, as many as fit its batch bound; the rest come in
95
+ * a later call. The module reads them off the JavaScript thread.
96
+ */
97
+ pendingDiagnostics(): Promise<NativeDiagnostic[]>;
98
+ /** Deletes the reports with these IDs. */
99
+ acknowledgeDiagnostics(ids: readonly string[]): void;
100
+ }
101
+ /**
102
+ * The bridge over raw, the module object Expo installed, or undefined when raw is not the module
103
+ * this package speaks: missing, a function missing, or another ABI version.
104
+ */
105
+ export declare function libo11yNativeFrom(raw: unknown): Libo11yNative | undefined;
106
+ /**
107
+ * The module of this app binary, or undefined without one: an OTA update running on a binary built
108
+ * before the module, Android, or a runtime without Expo modules.
109
+ */
110
+ export declare function libo11yNative(): Libo11yNative | undefined;
package/dist/native.js ADDED
@@ -0,0 +1,169 @@
1
+ /**
2
+ * The optional libo11y native module (Libo11yNative), an Expo module for iOS that ships inside this
3
+ * package: it reads the process start time and keeps the crash and hang reports MetricKit delivers
4
+ * (ios/). An app binary built before the module was added, an Android build, a bare React Native
5
+ * app without Expo modules, and node tests have no module, so everything here works without it:
6
+ * libo11yNative() is then undefined and the JavaScript side runs alone.
7
+ *
8
+ * The lookup reads globalThis.expo.modules, the object Expo's requireOptionalNativeModule returns,
9
+ * so this file imports neither expo-modules-core nor react-native. A module of another ABI version
10
+ * is ignored. Every call but setRecording is guarded: a native failure becomes undefined, false
11
+ * or an empty list, never a throw into the app. setRecording rejects, so a failed cleanup is known. The two reads and setRecording are async functions, so the module reads and
12
+ * deletes its files off the JavaScript thread, and a caller can wait for the deletion.
13
+ */
14
+ import { diag } from "@opentelemetry/api";
15
+ /** The name the module registers with Expo. */
16
+ export const NATIVE_MODULE_NAME = "Libo11yNative";
17
+ /** The interface version of the module this package speaks. */
18
+ export const NATIVE_ABI = 1;
19
+ const FUNCTIONS = [
20
+ "abi",
21
+ "processStart",
22
+ "prewarmed",
23
+ "setRecording",
24
+ "recordContext",
25
+ "contextHistory",
26
+ "pendingDiagnostics",
27
+ "acknowledgeDiagnostics",
28
+ ];
29
+ let warned = false;
30
+ function warnOnce(what, err) {
31
+ if (warned)
32
+ return;
33
+ warned = true;
34
+ diag.warn(`o11y: the libo11y native module failed in ${what}`, err);
35
+ }
36
+ function guard(what, fallback, call) {
37
+ try {
38
+ return call();
39
+ }
40
+ catch (err) {
41
+ warnOnce(what, err);
42
+ return fallback;
43
+ }
44
+ }
45
+ async function guardAsync(what, fallback, call) {
46
+ try {
47
+ return await call();
48
+ }
49
+ catch (err) {
50
+ warnOnce(what, err);
51
+ return fallback;
52
+ }
53
+ }
54
+ const isObject = (v) => typeof v === "object" && v !== null;
55
+ const isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v);
56
+ const isString = (v) => typeof v === "string";
57
+ function parseList(raw) {
58
+ if (typeof raw !== "string")
59
+ return [];
60
+ try {
61
+ const v = JSON.parse(raw);
62
+ return Array.isArray(v) ? v : [];
63
+ }
64
+ catch {
65
+ return [];
66
+ }
67
+ }
68
+ /** Copies the optional fields of src that pass check. */
69
+ function optional(src, keys, check) {
70
+ const out = {};
71
+ for (const k of keys)
72
+ if (check(src[k]))
73
+ out[k] = src[k];
74
+ return out;
75
+ }
76
+ function contextEntry(v) {
77
+ if (!isObject(v))
78
+ return undefined;
79
+ const { at, sessionId, viewId, viewName, viewKind, seq } = v;
80
+ if (!isFiniteNumber(at) || !isString(sessionId) || !isString(viewId) || !isString(viewName))
81
+ return undefined;
82
+ if (!isString(viewKind) || !isFiniteNumber(seq))
83
+ return undefined;
84
+ return {
85
+ at,
86
+ sessionId,
87
+ viewId,
88
+ viewName,
89
+ viewKind,
90
+ seq,
91
+ ...optional(v, ["version", "updateId"], isString),
92
+ ...optional(v, ["pid", "processStart", "since"], isFiniteNumber),
93
+ ...(v.fatal === true ? { fatal: true } : {}),
94
+ ...(typeof v.kept === "boolean" ? { kept: v.kept } : {}),
95
+ ...(v.late === true ? { late: true } : {}),
96
+ ...(isString(v.report) ? { report: v.report } : {}),
97
+ };
98
+ }
99
+ function diagnostic(v) {
100
+ if (!isObject(v))
101
+ return undefined;
102
+ const { id, kind, begin, end } = v;
103
+ if (!isString(id) || id === "" || (kind !== "crash" && kind !== "hang"))
104
+ return undefined;
105
+ if (!isFiniteNumber(begin) || !isFiniteNumber(end))
106
+ return undefined;
107
+ return {
108
+ id,
109
+ kind,
110
+ begin,
111
+ end,
112
+ ...optional(v, ["pid", "exceptionType", "exceptionCode", "signal", "hangSeconds"], isFiniteNumber),
113
+ ...optional(v, ["appVersion", "appBuild", "osVersion", "terminationReason", "objcName", "objcMessage"], isString),
114
+ ...(isObject(v.callStackTree) ? { callStackTree: v.callStackTree } : {}),
115
+ };
116
+ }
117
+ function bridge(m) {
118
+ return {
119
+ processStart() {
120
+ return guard("processStart", undefined, () => {
121
+ const v = m.processStart();
122
+ return isFiniteNumber(v) && v > 0 ? v : undefined;
123
+ });
124
+ },
125
+ prewarmed() {
126
+ return guard("prewarmed", false, () => m.prewarmed() === true);
127
+ },
128
+ async setRecording(on) {
129
+ // Not guarded: a cleanup the module could not do is the caller's to know.
130
+ await m.setRecording(on);
131
+ },
132
+ recordContext(entry) {
133
+ return guardAsync("recordContext", false, async () => (await m.recordContext(JSON.stringify(entry))) === true);
134
+ },
135
+ contextHistory() {
136
+ return guardAsync("contextHistory", [], async () => parseList(await m.contextHistory()).flatMap((e) => contextEntry(e) ?? []));
137
+ },
138
+ pendingDiagnostics() {
139
+ return guardAsync("pendingDiagnostics", [], async () => parseList(await m.pendingDiagnostics()).flatMap((d) => diagnostic(d) ?? []));
140
+ },
141
+ acknowledgeDiagnostics(ids) {
142
+ if (ids.length === 0)
143
+ return;
144
+ guard("acknowledgeDiagnostics", undefined, () => m.acknowledgeDiagnostics([...ids]));
145
+ },
146
+ };
147
+ }
148
+ /**
149
+ * The bridge over raw, the module object Expo installed, or undefined when raw is not the module
150
+ * this package speaks: missing, a function missing, or another ABI version.
151
+ */
152
+ export function libo11yNativeFrom(raw) {
153
+ if (!isObject(raw) && typeof raw !== "function")
154
+ return undefined;
155
+ const m = raw;
156
+ if (FUNCTIONS.some((f) => typeof m[f] !== "function"))
157
+ return undefined;
158
+ const module = raw;
159
+ const abi = guard("abi", undefined, () => module.abi());
160
+ return abi === NATIVE_ABI ? bridge(module) : undefined;
161
+ }
162
+ /**
163
+ * The module of this app binary, or undefined without one: an OTA update running on a binary built
164
+ * before the module, Android, or a runtime without Expo modules.
165
+ */
166
+ export function libo11yNative() {
167
+ const modules = globalThis.expo?.modules;
168
+ return libo11yNativeFrom(guard("lookup", undefined, () => modules?.[NATIVE_MODULE_NAME]));
169
+ }
@@ -24,7 +24,8 @@ export interface ReactNativePlatformOptions {
24
24
  /**
25
25
  * A React Native Platform, named "react-native": env from browserEnv over MOBILE_ENV_DEFAULTS,
26
26
  * detectReactNativeResource, the options' context manager (default upstream's
27
- * StackContextManager), the exporter set over the delivery, console lines through the console
27
+ * StackContextManager), the exporter set over the delivery with the gate as its metric consent
28
+ * boundary, console lines through the console
28
29
  * methods captured when the platform is built (so captureConsole cannot recurse), core's own SHA-1
29
30
  * (Hermes has no Web Crypto), UUIDs from uuidCrypto, the global console for captureConsole, and
30
31
  * the gate. No runtime metrics.
package/dist/platform.js CHANGED
@@ -20,7 +20,8 @@ export const MOBILE_ENV_DEFAULTS = {
20
20
  /**
21
21
  * A React Native Platform, named "react-native": env from browserEnv over MOBILE_ENV_DEFAULTS,
22
22
  * detectReactNativeResource, the options' context manager (default upstream's
23
- * StackContextManager), the exporter set over the delivery, console lines through the console
23
+ * StackContextManager), the exporter set over the delivery with the gate as its metric consent
24
+ * boundary, console lines through the console
24
25
  * methods captured when the platform is built (so captureConsole cannot recurse), core's own SHA-1
25
26
  * (Hermes has no Web Crypto), UUIDs from uuidCrypto, the global console for captureConsole, and
26
27
  * the gate. No runtime metrics.
@@ -36,7 +37,7 @@ export function reactNativePlatform(o) {
36
37
  env: () => vars,
37
38
  detectResource: (hermetic) => detectReactNativeResource({ env: o.env, hermetic, vars }),
38
39
  contextManager: o.exportOptions.contextManager ?? createContextManager,
39
- buildExporters: (req) => o.createExporterSet(req, o.delivery, o.endpoints),
40
+ buildExporters: (req) => o.createExporterSet(req, o.delivery, o.endpoints, { gate: o.gate }),
40
41
  writeConsoleLine: (line) => log(line),
41
42
  writeDiagnosticLine: (line) => warn(line),
42
43
  sha1: async (data) => sha1(data),
@@ -1,6 +1,6 @@
1
1
  /**
2
- * The React Native resource, in the two layers core merges. Detected: upstream's telemetry.sdk.*,
3
- * o11y.rum.platform react_native, os.name (ios or android, the bounded set the gateway keeps for
2
+ * The React Native resource, in the two layers core merges. Detected: upstream's telemetry.sdk.*
3
+ * with telemetry.sdk.language javascript, o11y.rum.platform react_native, os.name (ios or android, the bounded set the gateway keeps for
4
4
  * native apps) and o11y.rum.device.class. fromEnv: OTEL_RESOURCE_ATTRIBUTES and OTEL_SERVICE_NAME
5
5
  * from the options' env, parsed as the web platform parses them, and empty when hermetic. Nothing
6
6
  * else, so the gateway drops and refuses nothing.
package/dist/resource.js CHANGED
@@ -3,11 +3,20 @@ import { parseResourceAttributes } from "@libo11y/web/portable";
3
3
  import { SDK_INFO } from "@opentelemetry/core";
4
4
  import { deviceClassOf } from "./device-class.js";
5
5
  const OS_NAMES = new Set(["ios", "android"]);
6
+ /**
7
+ * telemetry.sdk.language on React Native. Upstream's SDK_INFO depends on the bundler's conditions:
8
+ * Metro resolves OpenTelemetry's browser build (webjs), jest and Node its node build (nodejs), and
9
+ * neither names Hermes. Semantic conventions have no well-known value for React Native and allow
10
+ * another value when none applies, so this names the language. The gateway keeps it as a public
11
+ * resource attribute and classifies nothing by it.
12
+ */
13
+ const SDK_LANGUAGE = "javascript";
6
14
  /** The detected and environment layers of the React Native resource. */
7
15
  export function detectReactNativeResource(o) {
8
16
  const sdk = Object.fromEntries(Object.entries(SDK_INFO).filter(([k]) => k.startsWith("telemetry.sdk.")));
9
17
  const detected = {
10
18
  ...sdk,
19
+ "telemetry.sdk.language": SDK_LANGUAGE,
11
20
  [ATTR_RUM_PLATFORM]: RUM_PLATFORM_VALUE_REACT_NATIVE,
12
21
  ...(OS_NAMES.has(o.env.os) ? { "os.name": o.env.os } : {}),
13
22
  [ATTR_RUM_DEVICE_CLASS]: deviceClassOf(o.env),
package/dist/setup.d.ts CHANGED
@@ -10,7 +10,7 @@ import type { ReactNativeSetupOptions, ReactNativeTelemetry } from "./options.ts
10
10
  import type { StorageQueueOptions } from "./storage/queue.ts";
11
11
  /**
12
12
  * What setupReactNativeWith builds on. Internal: the default is the real modules and React
13
- * Native's AppState and Platform (env.ts); tests and @libo11y/rum-react-native's binding replace
13
+ * Native's AppState and Platform (env.ts); tests and `@libo11y/rum-react-native`'s binding replace
14
14
  * or wrap any of them.
15
15
  */
16
16
  export interface ReactNativeDeps {
@@ -43,10 +43,12 @@ export interface ReactNativeDeps {
43
43
  * always online), reactNativePlatform, then core with console defaulting to false. The handle is
44
44
  * core's Telemetry extended in place with consent and traceFetch.
45
45
  *
46
- * Going to the background flushes every provider; coming back drains the queue. Revoking consent
47
- * flushes into the closed gate and empties the queue, also when consent was never granted, which
48
- * deletes what an earlier launch left. Shutdown shuts core down, then removes the
49
- * patches and the lifecycle subscription, shuts the delivery down and closes the queue. After
50
- * setup the queue is drained once, so batches an earlier launch left go out once consent allows.
46
+ * Going to the background flushes every provider; coming back drains the queue. Starting denied
47
+ * empties the queue before the delivery is built. Revoking consent starts emptying the queue, then
48
+ * flushes into the closed gate, also when consent was never granted, which deletes what an earlier
49
+ * launch left. Shutdown shuts core down and then the delivery under the one timeoutMillis deadline,
50
+ * aborting a send still in flight at it and reporting that signal's deadline as missed, then removes
51
+ * the patches and the lifecycle subscription and closes the queue. After setup the queue is drained
52
+ * once, so batches an earlier launch left go out once consent allows.
51
53
  */
52
54
  export declare function setupReactNativeWith(options: ReactNativeSetupOptions, deps: ReactNativeDeps, install: boolean): Promise<ReactNativeTelemetry>;
package/dist/setup.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * index.ts, passes the real ones from env.ts, the only module that loads react-native.
4
4
  */
5
5
  import { createTelemetryWith, O11yError, setupWith, } from "@libo11y/core";
6
- import { flushInBackground, OTLP_SIGNALS, pristineFetch, resolveEndpoints, } from "@libo11y/web/portable";
6
+ import { flushInBackground, OTLP_SIGNALS, pristineFetch, resolveEndpoints, shutdownWithin, } from "@libo11y/web/portable";
7
7
  import { diag } from "@opentelemetry/api";
8
8
  import { reactNativePlatform } from "./platform.js";
9
9
  import { memoryStorage } from "./storage/memory.js";
@@ -62,14 +62,17 @@ async function cleanup(steps) {
62
62
  * always online), reactNativePlatform, then core with console defaulting to false. The handle is
63
63
  * core's Telemetry extended in place with consent and traceFetch.
64
64
  *
65
- * Going to the background flushes every provider; coming back drains the queue. Revoking consent
66
- * flushes into the closed gate and empties the queue, also when consent was never granted, which
67
- * deletes what an earlier launch left. Shutdown shuts core down, then removes the
68
- * patches and the lifecycle subscription, shuts the delivery down and closes the queue. After
69
- * setup the queue is drained once, so batches an earlier launch left go out once consent allows.
65
+ * Going to the background flushes every provider; coming back drains the queue. Starting denied
66
+ * empties the queue before the delivery is built. Revoking consent starts emptying the queue, then
67
+ * flushes into the closed gate, also when consent was never granted, which deletes what an earlier
68
+ * launch left. Shutdown shuts core down and then the delivery under the one timeoutMillis deadline,
69
+ * aborting a send still in flight at it and reporting that signal's deadline as missed, then removes
70
+ * the patches and the lifecycle subscription and closes the queue. After setup the queue is drained
71
+ * once, so batches an earlier launch left go out once consent allows.
70
72
  */
71
73
  export async function setupReactNativeWith(options, deps, install) {
72
74
  const hermetic = options.hermetic === true;
75
+ const sdkDisabled = !hermetic && (options.env?.OTEL_SDK_DISABLED ?? "").trim().toLowerCase() === "true";
73
76
  requireAbsoluteEndpoints(options, hermetic);
74
77
  const t = options.transport ?? {};
75
78
  // Only the initial state: respectDoNotTrack and respectGlobalPrivacyControl stay off, because a
@@ -88,6 +91,10 @@ export async function setupReactNativeWith(options, deps, install) {
88
91
  let telemetry;
89
92
  let built;
90
93
  try {
94
+ // A denied start deletes what an earlier launch left before a delivery exists to send it, so a
95
+ // grant later in this launch cannot send batches recorded before the denial. Pending keeps them.
96
+ if (controller.consent.state() === "denied")
97
+ await queue.clear();
91
98
  endpoints = resolveEndpoints(options, hermetic);
92
99
  const transport = deps.createHttpTransport({
93
100
  endpoints,
@@ -101,6 +108,7 @@ export async function setupReactNativeWith(options, deps, install) {
101
108
  transport,
102
109
  queue,
103
110
  gate: controller,
111
+ disabled: sdkDisabled,
104
112
  persistFirst: true,
105
113
  mode: () => "normal",
106
114
  isOnline: () => true,
@@ -143,15 +151,18 @@ export async function setupReactNativeWith(options, deps, install) {
143
151
  throw err;
144
152
  }
145
153
  const activeDelivery = delivery;
146
- // Revocation: the gate is already closed, so flushing drains the SDK buffers into it and they
147
- // are dropped; then the persistent queue is emptied.
154
+ // Revocation: the gate is already closed. The persistent queue is emptied first, whatever the
155
+ // flush does: a flush waits for exports in flight, up to its deadline, and an app killed in that
156
+ // time would otherwise keep the queue for a later grant to send. The flush then drains the SDK
157
+ // buffers into the closed gate, which drops them.
148
158
  // Revoking while still pending clears too: it deletes only what an earlier launch left.
149
159
  const unregisterRevoke = controller.onRevoke(async () => {
160
+ const cleared = activeDelivery.clear();
150
161
  try {
151
162
  await telemetry.forceFlush();
152
163
  }
153
164
  finally {
154
- await activeDelivery.clear();
165
+ await cleared;
155
166
  }
156
167
  });
157
168
  const uninstalls = [];
@@ -163,14 +174,9 @@ export async function setupReactNativeWith(options, deps, install) {
163
174
  let shutdownPromise;
164
175
  handle.shutdown = (opts) => {
165
176
  shutdownPromise ??= (async () => {
166
- const report = await coreShutdown(opts);
167
- await cleanup([
168
- ...uninstalls,
169
- ...listeners,
170
- unregisterRevoke,
171
- () => activeDelivery.shutdown(),
172
- () => queue.close(),
173
- ]);
177
+ // One deadline: core's providers, then the delivery's drain in what is left of it.
178
+ const report = await shutdownWithin(coreShutdown, activeDelivery, opts);
179
+ await cleanup([...uninstalls, ...listeners, unregisterRevoke, () => queue.close()]);
174
180
  return report;
175
181
  })();
176
182
  return shutdownPromise;