@libo11y/react-native 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +68 -2
  3. package/dist/contracts/env.d.ts +38 -0
  4. package/dist/contracts/env.js +5 -0
  5. package/dist/contracts/storage.d.ts +18 -0
  6. package/dist/contracts/storage.js +4 -0
  7. package/dist/device-class.d.ts +7 -0
  8. package/dist/device-class.js +22 -0
  9. package/dist/env.d.ts +6 -0
  10. package/dist/env.js +39 -0
  11. package/dist/expo/app-info.d.ts +39 -0
  12. package/dist/expo/app-info.js +40 -0
  13. package/dist/expo/file-storage.d.ts +45 -0
  14. package/dist/expo/file-storage.js +93 -0
  15. package/dist/expo/options.d.ts +23 -0
  16. package/dist/expo/options.js +40 -0
  17. package/dist/expo.d.ts +38 -0
  18. package/dist/expo.js +57 -0
  19. package/dist/index.d.ts +24 -0
  20. package/dist/index.js +24 -0
  21. package/dist/instrumentation/network.d.ts +34 -0
  22. package/dist/instrumentation/network.js +69 -0
  23. package/dist/internal.d.ts +20 -0
  24. package/dist/internal.js +18 -0
  25. package/dist/lifecycle.d.ts +3 -0
  26. package/dist/lifecycle.js +51 -0
  27. package/dist/options.d.ts +109 -0
  28. package/dist/options.js +1 -0
  29. package/dist/platform.d.ts +32 -0
  30. package/dist/platform.js +47 -0
  31. package/dist/random.d.ts +8 -0
  32. package/dist/random.js +17 -0
  33. package/dist/resource.d.ts +18 -0
  34. package/dist/resource.js +22 -0
  35. package/dist/setup.d.ts +52 -0
  36. package/dist/setup.js +201 -0
  37. package/dist/storage/memory.d.ts +7 -0
  38. package/dist/storage/memory.js +19 -0
  39. package/dist/storage/queue.d.ts +23 -0
  40. package/dist/storage/queue.js +241 -0
  41. package/dist/version.d.ts +2 -0
  42. package/dist/version.js +2 -0
  43. package/package.json +73 -4
@@ -0,0 +1,18 @@
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
4
+ * native apps) and o11y.rum.device.class. fromEnv: OTEL_RESOURCE_ATTRIBUTES and OTEL_SERVICE_NAME
5
+ * from the options' env, parsed as the web platform parses them, and empty when hermetic. Nothing
6
+ * else, so the gateway drops and refuses nothing.
7
+ */
8
+ import type { ResourceLayers } from "@libo11y/core";
9
+ import type { ReactNativeEnv } from "./contracts/env.ts";
10
+ /** What detectReactNativeResource reads. */
11
+ export interface ReactNativeResourceOptions {
12
+ readonly env: ReactNativeEnv;
13
+ readonly hermetic: boolean;
14
+ /** The OTEL_* variables, as ReactNativeSetupOptions.env. */
15
+ readonly vars: Readonly<Record<string, string | undefined>>;
16
+ }
17
+ /** The detected and environment layers of the React Native resource. */
18
+ export declare function detectReactNativeResource(o: ReactNativeResourceOptions): Promise<ResourceLayers>;
@@ -0,0 +1,22 @@
1
+ import { ATTR_RUM_DEVICE_CLASS, ATTR_RUM_PLATFORM, RUM_PLATFORM_VALUE_REACT_NATIVE } from "@libo11y/spec";
2
+ import { parseResourceAttributes } from "@libo11y/web/portable";
3
+ import { SDK_INFO } from "@opentelemetry/core";
4
+ import { deviceClassOf } from "./device-class.js";
5
+ const OS_NAMES = new Set(["ios", "android"]);
6
+ /** The detected and environment layers of the React Native resource. */
7
+ export function detectReactNativeResource(o) {
8
+ const sdk = Object.fromEntries(Object.entries(SDK_INFO).filter(([k]) => k.startsWith("telemetry.sdk.")));
9
+ const detected = {
10
+ ...sdk,
11
+ [ATTR_RUM_PLATFORM]: RUM_PLATFORM_VALUE_REACT_NATIVE,
12
+ ...(OS_NAMES.has(o.env.os) ? { "os.name": o.env.os } : {}),
13
+ [ATTR_RUM_DEVICE_CLASS]: deviceClassOf(o.env),
14
+ };
15
+ if (o.hermetic)
16
+ return Promise.resolve({ detected, fromEnv: {} });
17
+ const fromEnv = parseResourceAttributes(o.vars.OTEL_RESOURCE_ATTRIBUTES);
18
+ const serviceName = o.vars.OTEL_SERVICE_NAME?.trim();
19
+ if (serviceName !== undefined && serviceName !== "")
20
+ fromEnv["service.name"] = serviceName;
21
+ return Promise.resolve({ detected, fromEnv });
22
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * setupReactNativeWith: React Native telemetry over its dependencies. setupReactNative, in
3
+ * index.ts, passes the real ones from env.ts, the only module that loads react-native.
4
+ */
5
+ import { type Platform } from "@libo11y/core";
6
+ import { type ConsentController, type ConsentControllerOptions, type createExporterSet, type Delivery, type DeliveryOptions, type HttpTransportOptions, type PersistentQueue, type SignalEndpoints, type Transport } from "@libo11y/web/portable";
7
+ import type { AppLifecycle, ReactNativeEnv } from "./contracts/env.ts";
8
+ import type { NetworkInstrumentation, NetworkInstrumentationOptions } from "./instrumentation/network.ts";
9
+ import type { ReactNativeSetupOptions, ReactNativeTelemetry } from "./options.ts";
10
+ import type { StorageQueueOptions } from "./storage/queue.ts";
11
+ /**
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
14
+ * or wrap any of them.
15
+ */
16
+ export interface ReactNativeDeps {
17
+ readonly env: ReactNativeEnv;
18
+ /** When the app is in the foreground. */
19
+ readonly lifecycle: AppLifecycle;
20
+ readonly createConsentController: (opts: ConsentControllerOptions) => ConsentController;
21
+ readonly openQueue: (opts: StorageQueueOptions) => Promise<PersistentQueue>;
22
+ readonly createHttpTransport: (opts: HttpTransportOptions) => Transport;
23
+ readonly createDelivery: (opts: DeliveryOptions) => Delivery;
24
+ readonly createExporterSet: typeof createExporterSet;
25
+ readonly installNetworkInstrumentation: (opts: NetworkInstrumentationOptions) => NetworkInstrumentation;
26
+ /**
27
+ * Observes the platform before core builds on it, with the delivery, the endpoints and the
28
+ * OTEL_* variables it reports, as RUM's binding needs them.
29
+ */
30
+ readonly onPlatform?: (platform: Platform, info: {
31
+ readonly delivery: Delivery;
32
+ readonly endpoints: SignalEndpoints;
33
+ readonly env: Readonly<Record<string, string>>;
34
+ }) => void;
35
+ }
36
+ /**
37
+ * Builds React Native telemetry, installing it globally (providers, propagator, context manager,
38
+ * and the fetch and XHR patches) when install is true. In order: the consent controller (initial
39
+ * state only), the retry queue on options.storage (default memoryStorage(); opening only
40
+ * reads), the endpoints (every endpoint given, in the options or the env, must be an absolute http
41
+ * or https URL, else INVALID_OPTION), the HTTP
42
+ * transport (the pristine fetch, no beacon), the delivery (every batch saved before it is sent,
43
+ * always online), reactNativePlatform, then core with console defaulting to false. The handle is
44
+ * core's Telemetry extended in place with consent and traceFetch.
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.
51
+ */
52
+ export declare function setupReactNativeWith(options: ReactNativeSetupOptions, deps: ReactNativeDeps, install: boolean): Promise<ReactNativeTelemetry>;
package/dist/setup.js ADDED
@@ -0,0 +1,201 @@
1
+ /**
2
+ * setupReactNativeWith: React Native telemetry over its dependencies. setupReactNative, in
3
+ * index.ts, passes the real ones from env.ts, the only module that loads react-native.
4
+ */
5
+ import { createTelemetryWith, O11yError, setupWith, } from "@libo11y/core";
6
+ import { flushInBackground, OTLP_SIGNALS, pristineFetch, resolveEndpoints, } from "@libo11y/web/portable";
7
+ import { diag } from "@opentelemetry/api";
8
+ import { reactNativePlatform } from "./platform.js";
9
+ import { memoryStorage } from "./storage/memory.js";
10
+ /** The retry queue's mobile bounds: smaller than the browser's 5 MiB and 1000 batches. */
11
+ const QUEUE_DEFAULTS = { maxBytes: 2_097_152, maxEntries: 500, maxAgeMillis: 86_400_000 };
12
+ /** The lease web's delivery uses for a timeout: three times it, never under 30 seconds. */
13
+ const leaseFor = (timeoutMillis) => Math.max(30_000, 3 * timeoutMillis);
14
+ /**
15
+ * Refuses an endpoint, from the options or (unless hermetic) the env, that is not an absolute http
16
+ * or https URL: an app has no page to resolve a relative one against.
17
+ */
18
+ function requireAbsoluteEndpoints(options, hermetic) {
19
+ const env = hermetic ? {} : (options.env ?? {});
20
+ const candidates = [
21
+ options.endpoint,
22
+ options.tracesEndpoint,
23
+ options.metricsEndpoint,
24
+ options.logsEndpoint,
25
+ env.OTEL_EXPORTER_OTLP_ENDPOINT,
26
+ ...OTLP_SIGNALS.map((s) => env[`OTEL_EXPORTER_OTLP_${s.toUpperCase()}_ENDPOINT`]),
27
+ ];
28
+ for (const raw of candidates) {
29
+ const value = raw?.trim();
30
+ if (value === undefined || value === "")
31
+ continue;
32
+ let protocol;
33
+ try {
34
+ protocol = new URL(value).protocol;
35
+ }
36
+ catch {
37
+ protocol = undefined;
38
+ }
39
+ if (protocol !== "http:" && protocol !== "https:") {
40
+ throw new O11yError("INVALID_OPTION", `o11y: react-native: endpoint must be an absolute http(s) URL, got ${JSON.stringify(value)}`);
41
+ }
42
+ }
43
+ }
44
+ /** Runs each cleanup step, reporting a failure through diag and going on. */
45
+ async function cleanup(steps) {
46
+ for (const step of steps) {
47
+ try {
48
+ await step();
49
+ }
50
+ catch (err) {
51
+ diag.warn("libo11y: react-native: shutdown step failed", err);
52
+ }
53
+ }
54
+ }
55
+ /**
56
+ * Builds React Native telemetry, installing it globally (providers, propagator, context manager,
57
+ * and the fetch and XHR patches) when install is true. In order: the consent controller (initial
58
+ * state only), the retry queue on options.storage (default memoryStorage(); opening only
59
+ * reads), the endpoints (every endpoint given, in the options or the env, must be an absolute http
60
+ * or https URL, else INVALID_OPTION), the HTTP
61
+ * transport (the pristine fetch, no beacon), the delivery (every batch saved before it is sent,
62
+ * always online), reactNativePlatform, then core with console defaulting to false. The handle is
63
+ * core's Telemetry extended in place with consent and traceFetch.
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.
70
+ */
71
+ export async function setupReactNativeWith(options, deps, install) {
72
+ const hermetic = options.hermetic === true;
73
+ requireAbsoluteEndpoints(options, hermetic);
74
+ const t = options.transport ?? {};
75
+ // Only the initial state: respectDoNotTrack and respectGlobalPrivacyControl stay off, because a
76
+ // React Native runtime has no such signals.
77
+ const controller = deps.createConsentController(options.consent?.initial === undefined ? {} : { initial: options.consent.initial });
78
+ const queue = await deps.openQueue({
79
+ storage: options.storage ?? memoryStorage(),
80
+ databaseName: "libo11y",
81
+ maxBytes: t.maxQueueBytes ?? QUEUE_DEFAULTS.maxBytes,
82
+ maxEntries: t.maxQueueEntries ?? QUEUE_DEFAULTS.maxEntries,
83
+ maxAgeMillis: t.maxQueueAgeMillis ?? QUEUE_DEFAULTS.maxAgeMillis,
84
+ });
85
+ const listeners = [];
86
+ let delivery;
87
+ let endpoints;
88
+ let telemetry;
89
+ let built;
90
+ try {
91
+ endpoints = resolveEndpoints(options, hermetic);
92
+ const transport = deps.createHttpTransport({
93
+ endpoints,
94
+ ...(options.headers === undefined ? {} : { headers: options.headers }),
95
+ ...(t.timeoutMillis === undefined ? {} : { timeoutMillis: t.timeoutMillis }),
96
+ ...(pristineFetch === undefined ? {} : { fetch: pristineFetch }),
97
+ sendBeacon: undefined,
98
+ isOnline: () => true,
99
+ });
100
+ delivery = deps.createDelivery({
101
+ transport,
102
+ queue,
103
+ gate: controller,
104
+ persistFirst: true,
105
+ mode: () => "normal",
106
+ isOnline: () => true,
107
+ ...(t.initialBackoffMillis === undefined ? {} : { initialBackoffMillis: t.initialBackoffMillis }),
108
+ ...(t.maxBackoffMillis === undefined ? {} : { maxBackoffMillis: t.maxBackoffMillis }),
109
+ ...(t.timeoutMillis === undefined ? {} : { leaseMillis: leaseFor(t.timeoutMillis) }),
110
+ });
111
+ const platform = reactNativePlatform({
112
+ exportOptions: options,
113
+ endpoints,
114
+ delivery,
115
+ gate: controller,
116
+ env: deps.env,
117
+ createExporterSet: deps.createExporterSet,
118
+ });
119
+ deps.onPlatform?.(platform, {
120
+ delivery,
121
+ endpoints,
122
+ env: platform.env(),
123
+ });
124
+ const coreOptions = { ...options, console: options.console ?? false };
125
+ telemetry = install
126
+ ? await setupWith(coreOptions, platform)
127
+ : await createTelemetryWith(coreOptions, platform);
128
+ built = telemetry;
129
+ const d = delivery;
130
+ listeners.push(deps.lifecycle.subscribe((visible) => {
131
+ if (visible)
132
+ void d.drain();
133
+ // flushInBackground never rejects, and says a flush that lost telemetry.
134
+ else
135
+ void flushInBackground(telemetry, "react-native: flush on background");
136
+ }));
137
+ }
138
+ catch (err) {
139
+ const d = delivery;
140
+ const b = built;
141
+ // Core first, so a failure after setupWith also releases its globals and ALREADY_SETUP guard.
142
+ await cleanup([() => b?.shutdown(), ...listeners, () => d?.shutdown(), () => queue.close()]);
143
+ throw err;
144
+ }
145
+ 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.
148
+ // Revoking while still pending clears too: it deletes only what an earlier launch left.
149
+ const unregisterRevoke = controller.onRevoke(async () => {
150
+ try {
151
+ await telemetry.forceFlush();
152
+ }
153
+ finally {
154
+ await activeDelivery.clear();
155
+ }
156
+ });
157
+ const uninstalls = [];
158
+ // Core's handle extended in place, so identity-keyed lookups such as exemplarStoreOf still work.
159
+ const handle = telemetry;
160
+ Object.defineProperty(handle, "consent", { value: controller.consent, enumerable: true });
161
+ handle.traceFetch = (f) => f;
162
+ const coreShutdown = telemetry.shutdown.bind(telemetry);
163
+ let shutdownPromise;
164
+ handle.shutdown = (opts) => {
165
+ shutdownPromise ??= (async () => {
166
+ const report = await coreShutdown(opts);
167
+ await cleanup([
168
+ ...uninstalls,
169
+ ...listeners,
170
+ unregisterRevoke,
171
+ () => activeDelivery.shutdown(),
172
+ () => queue.close(),
173
+ ]);
174
+ return report;
175
+ })();
176
+ return shutdownPromise;
177
+ };
178
+ if (install) {
179
+ try {
180
+ const instr = options.instrumentations ?? {};
181
+ const net = deps.installNetworkInstrumentation({
182
+ telemetry: handle,
183
+ propagateTo: instr.propagateTo ?? [],
184
+ ignoreUrls: [
185
+ ...(instr.ignoreUrls ?? []),
186
+ ...OTLP_SIGNALS.flatMap((s) => (endpoints[s] === undefined ? [] : [endpoints[s]])),
187
+ ],
188
+ fetch: instr.fetch !== false,
189
+ xhr: instr.xhr !== false,
190
+ });
191
+ uninstalls.push(() => net.uninstall());
192
+ handle.traceFetch = net.traceFetch;
193
+ }
194
+ catch (err) {
195
+ await handle.shutdown();
196
+ throw err;
197
+ }
198
+ }
199
+ void activeDelivery.drain();
200
+ return handle;
201
+ }
@@ -0,0 +1,7 @@
1
+ /** The default KeyValueStorage: a Map, lost when the app stops. */
2
+ import type { KeyValueStorage } from "../contracts/storage.ts";
3
+ /**
4
+ * A KeyValueStorage in memory. setupReactNative uses one when no storage is given, so batches still
5
+ * retry while the app runs, but nothing outlives the process.
6
+ */
7
+ export declare function memoryStorage(): KeyValueStorage;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * A KeyValueStorage in memory. setupReactNative uses one when no storage is given, so batches still
3
+ * retry while the app runs, but nothing outlives the process.
4
+ */
5
+ export function memoryStorage() {
6
+ const map = new Map();
7
+ return {
8
+ getItem: (k) => Promise.resolve(map.get(k) ?? null),
9
+ setItem: (k, v) => {
10
+ map.set(k, v);
11
+ return Promise.resolve();
12
+ },
13
+ removeItem: (k) => {
14
+ map.delete(k);
15
+ return Promise.resolve();
16
+ },
17
+ getAllKeys: () => Promise.resolve([...map.keys()]),
18
+ };
19
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The PersistentQueue over a KeyValueStorage, for React Native. One index key holds every entry's
3
+ * metadata, and each body has a key of its own, read only when the entry is claimed, so the queue
4
+ * holds no bodies in memory. A put resolves after the body and then the index are saved, so a batch
5
+ * the delivery sends after its put survives a crash or a stop mid-send. Leases live in memory,
6
+ * because one JavaScript context is the only consumer, and die with it. Bounds, eviction, expiry
7
+ * and order are the web queues' (the shared bounds helpers and conformance suite).
8
+ *
9
+ * Opening reads only. Orphan bodies, left by a stop between a body and its index, are removed
10
+ * inside the first mutating call, which the delivery makes only while consent is granted. An index
11
+ * entry whose body is gone is dropped when claimed; one whose body fails to read is skipped, and
12
+ * dropped after three failed reads. Every method runs on one chain and never rejects: a storage
13
+ * failure is reported through diag and the call resolves as if the change were dropped. After
14
+ * close, calls behave as on an empty queue, and an operation still running writes nothing more.
15
+ */
16
+ import { type PersistentQueue, type QueueOptions } from "@libo11y/web/portable";
17
+ import type { KeyValueStorage } from "../contracts/storage.ts";
18
+ /** Options for openStorageQueue: the web queue's bounds, and the storage. */
19
+ export interface StorageQueueOptions extends QueueOptions {
20
+ readonly storage: KeyValueStorage;
21
+ }
22
+ /** Opens the queue under `libo11y/<databaseName>/` in storage (databaseName default "libo11y"). */
23
+ export declare function openStorageQueue(opts: StorageQueueOptions): Promise<PersistentQueue>;
@@ -0,0 +1,241 @@
1
+ /**
2
+ * The PersistentQueue over a KeyValueStorage, for React Native. One index key holds every entry's
3
+ * metadata, and each body has a key of its own, read only when the entry is claimed, so the queue
4
+ * holds no bodies in memory. A put resolves after the body and then the index are saved, so a batch
5
+ * the delivery sends after its put survives a crash or a stop mid-send. Leases live in memory,
6
+ * because one JavaScript context is the only consumer, and die with it. Bounds, eviction, expiry
7
+ * and order are the web queues' (the shared bounds helpers and conformance suite).
8
+ *
9
+ * Opening reads only. Orphan bodies, left by a stop between a body and its index, are removed
10
+ * inside the first mutating call, which the delivery makes only while consent is granted. An index
11
+ * entry whose body is gone is dropped when claimed; one whose body fails to read is skipped, and
12
+ * dropped after three failed reads. Every method runs on one chain and never rejects: a storage
13
+ * failure is reported through diag and the call resolves as if the change were dropped. After
14
+ * close, calls behave as on an empty queue, and an operation still running writes nothing more.
15
+ */
16
+ import { buildEntry, byAge, dueAt, evictionPlan, isDue, isExpired, resolveBounds, } from "@libo11y/web/portable";
17
+ import { diag } from "@opentelemetry/api";
18
+ const INDEX_VERSION = 1;
19
+ /** Failed reads of one body after which claim drops the entry. */
20
+ const MAX_READ_FAILURES = 3;
21
+ const SIGNALS = new Set(["traces", "metrics", "logs"]);
22
+ function isMeta(e) {
23
+ if (typeof e !== "object" || e === null)
24
+ return false;
25
+ const m = e;
26
+ return (typeof m.id === "string" &&
27
+ SIGNALS.has(m.signal) &&
28
+ typeof m.bytes === "number" &&
29
+ typeof m.enqueuedAt === "number" &&
30
+ typeof m.attempts === "number" &&
31
+ typeof m.notBefore === "number");
32
+ }
33
+ /** The entries of a stored index; an index this version did not write, or cannot parse, is empty. */
34
+ function parseIndex(raw) {
35
+ if (raw === null)
36
+ return [];
37
+ try {
38
+ const v = JSON.parse(raw);
39
+ return v.v === INDEX_VERSION && Array.isArray(v.entries) ? v.entries.filter(isMeta) : [];
40
+ }
41
+ catch {
42
+ return [];
43
+ }
44
+ }
45
+ /** Opens the queue under `libo11y/<databaseName>/` in storage (databaseName default "libo11y"). */
46
+ export async function openStorageQueue(opts) {
47
+ const bounds = resolveBounds(opts);
48
+ const { storage } = opts;
49
+ const prefix = `libo11y/${opts.databaseName ?? "libo11y"}/`;
50
+ const indexKey = `${prefix}index`;
51
+ const bodyPrefix = `${prefix}b/`;
52
+ // Every entry with an empty body: bodies stay in storage until claimed.
53
+ const entries = new Map();
54
+ try {
55
+ for (const m of parseIndex(await storage.getItem(indexKey))) {
56
+ entries.set(m.id, { ...m, body: "", leaseUntil: 0 });
57
+ }
58
+ }
59
+ catch (err) {
60
+ diag.warn("libo11y: react-native: reading the retry queue failed; it starts empty", err);
61
+ }
62
+ let closed = false;
63
+ let cleaned = false;
64
+ // Failed body reads per entry: a body that keeps failing (too large for the storage to return,
65
+ // say) is dropped after MAX_READ_FAILURES, so it cannot hold the queue up for its whole age.
66
+ const readFailures = new Map();
67
+ let chain = Promise.resolve();
68
+ const serial = (fallback, fn) => {
69
+ const run = async () => {
70
+ if (closed)
71
+ return fallback;
72
+ try {
73
+ return await fn();
74
+ }
75
+ catch (err) {
76
+ diag.warn("libo11y: react-native: a retry queue operation failed", err);
77
+ return fallback;
78
+ }
79
+ };
80
+ const p = chain.then(run, run);
81
+ chain = p;
82
+ return p;
83
+ };
84
+ const ordered = () => [...entries.values()].sort(byAge);
85
+ // Once closed, an operation still running writes nothing more, so it cannot overwrite what is
86
+ // stored with a partial view.
87
+ const writeIndex = async () => {
88
+ if (closed)
89
+ return;
90
+ await storage.setItem(indexKey, JSON.stringify({
91
+ v: INDEX_VERSION,
92
+ entries: ordered().map(({ id, signal, bytes, enqueuedAt, attempts, notBefore }) => ({
93
+ id,
94
+ signal,
95
+ bytes,
96
+ enqueuedAt,
97
+ attempts,
98
+ notBefore,
99
+ })),
100
+ }));
101
+ };
102
+ // Removes the bodies no entry owns, once per queue (and again after clear). Best effort: an
103
+ // orphan that cannot be listed or removed waits for the next launch, and never fails the put or
104
+ // claim that ran the cleanup.
105
+ const cleanup = async () => {
106
+ if (cleaned || closed)
107
+ return;
108
+ cleaned = true;
109
+ let keys;
110
+ try {
111
+ keys = await storage.getAllKeys();
112
+ }
113
+ catch (err) {
114
+ diag.warn("libo11y: react-native: listing the retry queue's orphans failed", err);
115
+ return;
116
+ }
117
+ for (const key of keys) {
118
+ if (key.startsWith(bodyPrefix) && !entries.has(key.slice(bodyPrefix.length))) {
119
+ await storage.removeItem(key).catch((err) => {
120
+ diag.warn("libo11y: react-native: removing an orphan of the retry queue failed", err);
121
+ });
122
+ }
123
+ }
124
+ };
125
+ const drop = async (ids) => {
126
+ for (const id of ids) {
127
+ entries.delete(id);
128
+ readFailures.delete(id);
129
+ if (!closed)
130
+ await storage.removeItem(bodyPrefix + id);
131
+ }
132
+ };
133
+ return {
134
+ kind: "storage",
135
+ put: (batch) => serial(undefined, async () => {
136
+ await cleanup();
137
+ const now = bounds.now();
138
+ const entry = buildEntry(batch, now);
139
+ if (entry.bytes > bounds.maxBytes)
140
+ return undefined;
141
+ const evict = evictionPlan(ordered(), entry, now, bounds);
142
+ await drop(evict);
143
+ try {
144
+ await storage.setItem(bodyPrefix + entry.id, entry.body);
145
+ entries.set(entry.id, { ...entry, body: "" });
146
+ await writeIndex();
147
+ }
148
+ catch (err) {
149
+ // Not saved: keep nothing of it, so the caller's one direct attempt is the only send, and
150
+ // store the index without it and without what was evicted for it.
151
+ entries.delete(entry.id);
152
+ await storage.removeItem(bodyPrefix + entry.id).catch(() => { });
153
+ await writeIndex().catch(() => { });
154
+ throw err;
155
+ }
156
+ return entry;
157
+ }),
158
+ claim: (now, limit, leaseMillis) => serial([], async () => {
159
+ await cleanup();
160
+ const out = [];
161
+ const gone = [];
162
+ for (const e of ordered()) {
163
+ if (isExpired(e, now, bounds)) {
164
+ gone.push(e.id);
165
+ continue;
166
+ }
167
+ if (out.length >= limit)
168
+ break;
169
+ if (!isDue(e, now))
170
+ continue;
171
+ let body;
172
+ try {
173
+ body = await storage.getItem(bodyPrefix + e.id);
174
+ }
175
+ catch (err) {
176
+ const failures = (readFailures.get(e.id) ?? 0) + 1;
177
+ readFailures.set(e.id, failures);
178
+ diag.warn("libo11y: react-native: reading a queued batch failed", err);
179
+ if (failures >= MAX_READ_FAILURES)
180
+ gone.push(e.id);
181
+ continue;
182
+ }
183
+ readFailures.delete(e.id);
184
+ if (body === null) {
185
+ gone.push(e.id);
186
+ continue;
187
+ }
188
+ const leased = { ...e, leaseUntil: now + leaseMillis };
189
+ entries.set(e.id, leased);
190
+ out.push({ ...leased, body });
191
+ }
192
+ if (gone.length > 0) {
193
+ await drop(gone);
194
+ await writeIndex();
195
+ }
196
+ return out;
197
+ }),
198
+ reschedule: (id, notBefore) => serial(undefined, async () => {
199
+ const e = entries.get(id);
200
+ if (e === undefined)
201
+ return;
202
+ entries.set(id, { ...e, attempts: e.attempts + 1, notBefore, leaseUntil: 0 });
203
+ await writeIndex();
204
+ }),
205
+ remove: (ids) => serial(undefined, async () => {
206
+ const known = ids.filter((id) => entries.has(id));
207
+ if (known.length === 0)
208
+ return;
209
+ await drop(known);
210
+ await writeIndex();
211
+ }),
212
+ clear: () => serial(undefined, async () => {
213
+ entries.clear();
214
+ readFailures.clear();
215
+ cleaned = false;
216
+ await storage.removeItem(indexKey);
217
+ await cleanup();
218
+ }),
219
+ releaseLeases: () => serial(undefined, async () => {
220
+ for (const [id, e] of entries)
221
+ if (e.leaseUntil !== 0)
222
+ entries.set(id, { ...e, leaseUntil: 0 });
223
+ }),
224
+ nextDue: () => serial(undefined, async () => {
225
+ let next;
226
+ for (const e of entries.values())
227
+ next = next === undefined ? dueAt(e) : Math.min(next, dueAt(e));
228
+ return next;
229
+ }),
230
+ size: () => serial({ entries: 0, bytes: 0 }, async () => {
231
+ let bytes = 0;
232
+ for (const e of entries.values())
233
+ bytes += e.bytes;
234
+ return { entries: entries.size, bytes };
235
+ }),
236
+ close() {
237
+ // entries stay for an operation still running; every later call returns its empty fallback.
238
+ closed = true;
239
+ },
240
+ };
241
+ }
@@ -0,0 +1,2 @@
1
+ /** The `@libo11y/react-native` package version. scripts/release.ts keeps it equal to package.json. */
2
+ export declare const VERSION = "0.4.0";
@@ -0,0 +1,2 @@
1
+ /** The `@libo11y/react-native` package version. scripts/release.ts keeps it equal to package.json. */
2
+ export const VERSION = "0.4.0";
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "@libo11y/react-native",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0",
4
+ "description": "The libo11y React Native platform for TypeScript: setup over the OpenTelemetry JS 3.x providers on Hermes, the mobile resource, an OTLP/HTTP transport with a persistent retry queue on device storage, AppState flushing, the consent gate, and fetch and XHR spans.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./expo": {
14
+ "types": "./dist/expo.d.ts",
15
+ "default": "./dist/expo.js"
16
+ },
17
+ "./env": {
18
+ "types": "./dist/env.d.ts",
19
+ "default": "./dist/env.js"
20
+ },
21
+ "./internal": {
22
+ "types": "./dist/internal.d.ts",
23
+ "default": "./dist/internal.js"
24
+ }
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/jamesainslie/libo11y.git",
29
+ "directory": "ts/packages/react-native"
30
+ },
31
+ "dependencies": {
32
+ "@libo11y/core": "0.4.0",
33
+ "@libo11y/spec": "0.4.0",
34
+ "@libo11y/web": "0.4.0",
35
+ "@opentelemetry/api": "1.10.0",
36
+ "@opentelemetry/core": "3.1.1"
37
+ },
38
+ "peerDependencies": {
39
+ "expo-application": ">=58.0.0",
40
+ "expo-device": ">=58.0.0",
41
+ "expo-file-system": ">=58.0.0",
42
+ "expo-updates": ">=58.0.0",
43
+ "react-native": ">=0.88.0"
44
+ },
45
+ "peerDependenciesMeta": {
46
+ "expo-application": {
47
+ "optional": true
48
+ },
49
+ "expo-device": {
50
+ "optional": true
51
+ },
52
+ "expo-file-system": {
53
+ "optional": true
54
+ },
55
+ "expo-updates": {
56
+ "optional": true
57
+ }
58
+ },
59
+ "devDependencies": {
60
+ "@libo11y/test": "0.4.0",
61
+ "@opentelemetry/sdk-trace": "3.1.1",
62
+ "@types/react": "19.3.0",
63
+ "react": "19.3.1",
64
+ "react-native": "0.88.1"
65
+ },
66
+ "files": [
67
+ "dist",
68
+ "README.md",
69
+ "LICENSE"
70
+ ],
71
+ "publishConfig": {
72
+ "access": "public",
73
+ "provenance": true
74
+ }
75
+ }