@nagoorkani/session-capture-expo 0.1.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/dist/index.mjs ADDED
@@ -0,0 +1,1801 @@
1
+ // ../core/src/batcher.ts
2
+ var DEFAULT_MAX_BUFFERED = 1e3;
3
+ var Batcher = class {
4
+ constructor(options) {
5
+ this.buffer = [];
6
+ this.timer = null;
7
+ this.droppedCount = 0;
8
+ this.options = options;
9
+ this.maxBuffered = options.maxBuffered ?? DEFAULT_MAX_BUFFERED;
10
+ }
11
+ /** Events discarded due to the buffer ceiling. */
12
+ get dropped() {
13
+ return this.droppedCount;
14
+ }
15
+ get size() {
16
+ return this.buffer.length;
17
+ }
18
+ add(event) {
19
+ if (this.buffer.length >= this.maxBuffered) {
20
+ this.buffer.shift();
21
+ this.droppedCount += 1;
22
+ }
23
+ this.buffer.push(event);
24
+ if (this.buffer.length >= this.options.maxSize) {
25
+ void this.flush();
26
+ return;
27
+ }
28
+ this.scheduleFlush();
29
+ }
30
+ /** Send whatever is buffered. No-op when empty. */
31
+ async flush() {
32
+ this.clearTimer();
33
+ if (this.buffer.length === 0) {
34
+ return;
35
+ }
36
+ const events = this.buffer;
37
+ this.buffer = [];
38
+ await this.options.onFlush(events);
39
+ }
40
+ /**
41
+ * Adopt new batching parameters, e.g. from remote config.
42
+ *
43
+ * A pending timer is left alone deliberately: restarting it on every config
44
+ * fetch would let a short interval keep resetting itself and delay the flush
45
+ * indefinitely. The new interval applies from the next scheduled flush.
46
+ */
47
+ reconfigure(options) {
48
+ if (options.maxSize !== void 0) {
49
+ this.options.maxSize = options.maxSize;
50
+ }
51
+ if (options.flushIntervalMs !== void 0) {
52
+ this.options.flushIntervalMs = options.flushIntervalMs;
53
+ }
54
+ if (this.buffer.length >= this.options.maxSize) {
55
+ void this.flush();
56
+ }
57
+ }
58
+ /** Stop the timer. Call during teardown; does not flush. */
59
+ stop() {
60
+ this.clearTimer();
61
+ }
62
+ /**
63
+ * Discard everything buffered and stop the timer.
64
+ *
65
+ * For consent withdrawal and the remote kill switch, where the buffer must
66
+ * not merely go unsent — it must go. Returns how many events were dropped.
67
+ */
68
+ drop() {
69
+ this.clearTimer();
70
+ const dropped = this.buffer.length;
71
+ this.buffer = [];
72
+ return dropped;
73
+ }
74
+ scheduleFlush() {
75
+ if (this.timer !== null) {
76
+ return;
77
+ }
78
+ this.timer = setTimeout(() => {
79
+ this.timer = null;
80
+ void this.flush();
81
+ }, this.options.flushIntervalMs);
82
+ this.timer?.unref?.();
83
+ }
84
+ clearTimer() {
85
+ if (this.timer !== null) {
86
+ clearTimeout(this.timer);
87
+ this.timer = null;
88
+ }
89
+ }
90
+ };
91
+
92
+ // ../core/src/redact.ts
93
+ var DENIED_KEYS = /* @__PURE__ */ new Set([
94
+ "authorization",
95
+ "cookie",
96
+ "set-cookie",
97
+ "proxy-authorization"
98
+ ]);
99
+ var DENIED_PATTERN = /token|key|secret|password|passwd|auth|session|credential/i;
100
+ var REDACTED = "[redacted]";
101
+ var MAX_DEPTH = 8;
102
+ function isDenied(key, extraKeys) {
103
+ const lower = key.toLowerCase();
104
+ return DENIED_KEYS.has(lower) || extraKeys.has(lower) || DENIED_PATTERN.test(key);
105
+ }
106
+ function redact(value, maskedKeys = []) {
107
+ const extra = new Set(maskedKeys.map((k) => k.toLowerCase()));
108
+ return walk(value, extra, 0, /* @__PURE__ */ new WeakSet());
109
+ }
110
+ function walk(value, extra, depth, seen) {
111
+ if (value === null || typeof value !== "object") {
112
+ return value;
113
+ }
114
+ if (depth >= MAX_DEPTH) {
115
+ return REDACTED;
116
+ }
117
+ if (seen.has(value)) {
118
+ return REDACTED;
119
+ }
120
+ seen.add(value);
121
+ if (Array.isArray(value)) {
122
+ return value.map((item) => walk(item, extra, depth + 1, seen));
123
+ }
124
+ const out = {};
125
+ for (const [key, item] of Object.entries(value)) {
126
+ out[key] = isDenied(key, extra) ? REDACTED : walk(item, extra, depth + 1, seen);
127
+ }
128
+ return out;
129
+ }
130
+
131
+ // ../core/src/breadcrumbs.ts
132
+ var MAX_BREADCRUMBS = 20;
133
+ var MAX_MESSAGE_CHARS = 200;
134
+ var buffer = [];
135
+ function addBreadcrumb(type, message, data, maskedKeys = [], now = Date.now()) {
136
+ if (buffer.length >= MAX_BREADCRUMBS) {
137
+ buffer.shift();
138
+ }
139
+ const crumb = { timestamp: now, type };
140
+ if (message !== void 0) {
141
+ crumb.message = message.slice(0, MAX_MESSAGE_CHARS);
142
+ }
143
+ if (data !== void 0) {
144
+ crumb.data = redact(data, maskedKeys);
145
+ }
146
+ buffer.push(crumb);
147
+ }
148
+ function snapshotBreadcrumbs(now = Date.now()) {
149
+ return buffer.map(({ timestamp, ...rest }) => ({
150
+ t: now - timestamp,
151
+ ...rest
152
+ }));
153
+ }
154
+ function clearBreadcrumbs() {
155
+ buffer.length = 0;
156
+ }
157
+
158
+ // ../core/src/types.ts
159
+ var SCHEMA_VERSION = 1;
160
+ var DEFAULT_CONFIG = {
161
+ enabled: true,
162
+ sampleRate: 1,
163
+ batchSize: 50,
164
+ flushIntervalMs: 1e4,
165
+ maskedKeys: [],
166
+ urlDenyList: [],
167
+ captureBodies: false,
168
+ replayEnabled: false,
169
+ replaySampleRate: 0,
170
+ configVersion: 0
171
+ };
172
+
173
+ // ../core/src/config.ts
174
+ var FETCH_TIMEOUT_MS = 1e4;
175
+ var LIMITS = {
176
+ batchSize: { min: 1, max: 1e3 },
177
+ flushIntervalMs: { min: 1e3, max: 5 * 60 * 1e3 },
178
+ listEntries: 100
179
+ };
180
+ var CACHE_FILE = "remote-config.json";
181
+ function clamp(value, min, max) {
182
+ return Math.min(max, Math.max(min, value));
183
+ }
184
+ function asNumber(value, fallback, min, max) {
185
+ return typeof value === "number" && Number.isFinite(value) ? clamp(value, min, max) : fallback;
186
+ }
187
+ function asBoolean(value, fallback) {
188
+ return typeof value === "boolean" ? value : fallback;
189
+ }
190
+ function asStringList(value, fallback) {
191
+ if (!Array.isArray(value)) return [...fallback];
192
+ return value.filter((entry) => typeof entry === "string" && entry.length > 0).slice(0, LIMITS.listEntries);
193
+ }
194
+ function sanitizeConfig(raw, base = DEFAULT_CONFIG) {
195
+ if (typeof raw !== "object" || raw === null) {
196
+ return { ...base };
197
+ }
198
+ const input = raw;
199
+ return {
200
+ enabled: asBoolean(input.enabled, base.enabled),
201
+ sampleRate: asNumber(input.sampleRate, base.sampleRate, 0, 1),
202
+ batchSize: Math.round(
203
+ asNumber(input.batchSize, base.batchSize, LIMITS.batchSize.min, LIMITS.batchSize.max)
204
+ ),
205
+ flushIntervalMs: Math.round(
206
+ asNumber(
207
+ input.flushIntervalMs,
208
+ base.flushIntervalMs,
209
+ LIMITS.flushIntervalMs.min,
210
+ LIMITS.flushIntervalMs.max
211
+ )
212
+ ),
213
+ maskedKeys: asStringList(input.maskedKeys, base.maskedKeys),
214
+ urlDenyList: asStringList(input.urlDenyList, base.urlDenyList),
215
+ captureBodies: asBoolean(input.captureBodies, base.captureBodies),
216
+ replayEnabled: asBoolean(input.replayEnabled, base.replayEnabled),
217
+ replaySampleRate: asNumber(input.replaySampleRate, base.replaySampleRate, 0, 1),
218
+ configVersion: Math.round(
219
+ asNumber(input.configVersion, base.configVersion, 0, Number.MAX_SAFE_INTEGER)
220
+ )
221
+ };
222
+ }
223
+ async function fetchRemoteConfig(options) {
224
+ const doFetch = options.fetchImpl ?? fetch;
225
+ const base = options.endpoint.replace(/\/$/, "");
226
+ const url = `${base}/v1/config?projectId=${encodeURIComponent(options.projectId)}`;
227
+ const controller = new AbortController();
228
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? FETCH_TIMEOUT_MS);
229
+ try {
230
+ const response = await doFetch(url, {
231
+ method: "GET",
232
+ headers: {
233
+ accept: "application/json",
234
+ authorization: `Bearer ${options.apiKey}`
235
+ },
236
+ signal: controller.signal
237
+ });
238
+ if (!response.ok) {
239
+ return null;
240
+ }
241
+ return sanitizeConfig(await response.json());
242
+ } catch {
243
+ return null;
244
+ } finally {
245
+ clearTimeout(timer);
246
+ }
247
+ }
248
+ async function loadCachedConfig(store) {
249
+ try {
250
+ const raw = await store.read(CACHE_FILE);
251
+ if (raw === null) return null;
252
+ return sanitizeConfig(JSON.parse(raw));
253
+ } catch {
254
+ return null;
255
+ }
256
+ }
257
+ async function saveConfig(store, config) {
258
+ try {
259
+ await store.write(CACHE_FILE, JSON.stringify(config));
260
+ } catch {
261
+ }
262
+ }
263
+
264
+ // ../core/src/errors.ts
265
+ var MAX_STACK_CHARS = 8 * 1024;
266
+ var MAX_MESSAGE_CHARS2 = 1024;
267
+ function describeError(value, handled) {
268
+ if (value instanceof Error) {
269
+ return {
270
+ type: value.name || "Error",
271
+ message: (value.message || "").slice(0, MAX_MESSAGE_CHARS2),
272
+ stack: value.stack?.slice(0, MAX_STACK_CHARS),
273
+ handled
274
+ };
275
+ }
276
+ if (typeof value === "string") {
277
+ return {
278
+ type: "Error",
279
+ message: value.slice(0, MAX_MESSAGE_CHARS2),
280
+ handled
281
+ };
282
+ }
283
+ let message;
284
+ try {
285
+ message = typeof value === "object" && value !== null ? JSON.stringify(value) : String(value);
286
+ } catch {
287
+ message = "[unserializable]";
288
+ }
289
+ return {
290
+ type: "UnknownError",
291
+ message: (message ?? "undefined").slice(0, MAX_MESSAGE_CHARS2),
292
+ handled
293
+ };
294
+ }
295
+ var installed = false;
296
+ function installErrorHandlers(onError2) {
297
+ if (installed) {
298
+ return () => {
299
+ };
300
+ }
301
+ installed = true;
302
+ const uninstalls = [];
303
+ uninstalls.push(installGlobalErrorHandler(onError2));
304
+ uninstalls.push(installRejectionHandler(onError2));
305
+ return () => {
306
+ installed = false;
307
+ for (const fn of uninstalls) {
308
+ try {
309
+ fn();
310
+ } catch {
311
+ }
312
+ }
313
+ };
314
+ }
315
+ function installGlobalErrorHandler(onError2) {
316
+ const errorUtils = globalThis.ErrorUtils;
317
+ if (!errorUtils?.setGlobalHandler || !errorUtils.getGlobalHandler) {
318
+ return installErrorEventHandler(onError2);
319
+ }
320
+ const previous = errorUtils.getGlobalHandler();
321
+ errorUtils.setGlobalHandler((error, isFatal) => {
322
+ try {
323
+ const captured = describeError(error, false);
324
+ captured.fatal = isFatal ?? false;
325
+ onError2(captured);
326
+ } catch {
327
+ }
328
+ previous?.(error, isFatal);
329
+ });
330
+ return () => {
331
+ if (previous) errorUtils.setGlobalHandler?.(previous);
332
+ };
333
+ }
334
+ function installErrorEventHandler(onError2) {
335
+ const target = globalThis;
336
+ if (typeof target.addEventListener !== "function") {
337
+ return () => {
338
+ };
339
+ }
340
+ const handler = (event) => {
341
+ try {
342
+ const thrown = event?.error;
343
+ const value = thrown ?? event?.message ?? event;
344
+ onError2(describeError(value, false));
345
+ } catch {
346
+ }
347
+ };
348
+ try {
349
+ target.addEventListener("error", handler);
350
+ } catch {
351
+ return () => {
352
+ };
353
+ }
354
+ return () => {
355
+ try {
356
+ target.removeEventListener?.("error", handler);
357
+ } catch {
358
+ }
359
+ };
360
+ }
361
+ function installRejectionHandler(onError2) {
362
+ const target = globalThis;
363
+ if (typeof target.addEventListener !== "function") {
364
+ return () => {
365
+ };
366
+ }
367
+ const handler = (event) => {
368
+ try {
369
+ const reason = event?.reason ?? event;
370
+ const captured = describeError(reason, false);
371
+ captured.type = captured.type === "Error" ? "UnhandledRejection" : captured.type;
372
+ onError2(captured);
373
+ } catch {
374
+ }
375
+ };
376
+ try {
377
+ target.addEventListener("unhandledrejection", handler);
378
+ } catch {
379
+ return () => {
380
+ };
381
+ }
382
+ return () => {
383
+ try {
384
+ target.removeEventListener?.("unhandledrejection", handler);
385
+ } catch {
386
+ }
387
+ };
388
+ }
389
+
390
+ // ../core/src/ids.ts
391
+ function createId(prefix) {
392
+ const time = Date.now().toString(36);
393
+ const random = Math.random().toString(36).slice(2, 10);
394
+ return `${prefix}_${time}${random}`;
395
+ }
396
+ function hashString(input) {
397
+ let hash = 2166136261;
398
+ for (let i = 0; i < input.length; i += 1) {
399
+ hash ^= input.charCodeAt(i);
400
+ hash = Math.imul(hash, 16777619);
401
+ }
402
+ hash ^= hash >>> 16;
403
+ hash = Math.imul(hash, 2246822507);
404
+ hash ^= hash >>> 13;
405
+ hash = Math.imul(hash, 3266489909);
406
+ hash ^= hash >>> 16;
407
+ return hash >>> 0;
408
+ }
409
+ function isSampled(sessionId, sampleRate) {
410
+ if (sampleRate >= 1) return true;
411
+ if (sampleRate <= 0) return false;
412
+ return hashString(sessionId) / 4294967296 < sampleRate;
413
+ }
414
+
415
+ // ../core/src/performance.ts
416
+ var moduleLoadedAt = Date.now();
417
+ var marks = /* @__PURE__ */ new Map();
418
+ var MAX_OPEN_MARKS = 100;
419
+ function mark(name, now = Date.now()) {
420
+ if (marks.size >= MAX_OPEN_MARKS && !marks.has(name)) {
421
+ return;
422
+ }
423
+ marks.set(name, now);
424
+ }
425
+ function measure(name, now = Date.now()) {
426
+ const started = marks.get(name);
427
+ if (started === void 0) {
428
+ return null;
429
+ }
430
+ marks.delete(name);
431
+ return { name, durationMs: now - started };
432
+ }
433
+ function timeToReady(now = Date.now()) {
434
+ return { name: "app_ready", durationMs: now - moduleLoadedAt };
435
+ }
436
+
437
+ // ../core/src/session.ts
438
+ var SessionManager = class {
439
+ // Explicit fields rather than parameter properties: Node's strip-only
440
+ // TypeScript mode rejects the shorthand, and keeping these files runnable
441
+ // without a build step is worth more than the brevity.
442
+ constructor(options) {
443
+ this.state = null;
444
+ /** True only while `onEnd` runs. See `touch()`. */
445
+ this.rotating = false;
446
+ this.options = options;
447
+ this.now = options.now ?? Date.now;
448
+ this.state = options.initial ?? null;
449
+ }
450
+ current() {
451
+ return this.state;
452
+ }
453
+ /**
454
+ * Register activity, starting or rotating the session as needed.
455
+ *
456
+ * Returns the session the caller should attribute its event to.
457
+ */
458
+ touch() {
459
+ const now = this.now();
460
+ if (this.state && (this.rotating || !this.expired(now))) {
461
+ this.state.lastActivityAt = now;
462
+ return this.state;
463
+ }
464
+ const ending = this.state;
465
+ if (ending) {
466
+ this.rotating = true;
467
+ try {
468
+ this.options.onEnd?.(ending);
469
+ } catch {
470
+ } finally {
471
+ this.rotating = false;
472
+ }
473
+ }
474
+ return this.start(now);
475
+ }
476
+ /** Whether the current session is over after a period with no activity. */
477
+ expired(now) {
478
+ if (!this.state) return true;
479
+ return now - this.state.lastActivityAt > this.options.timeoutMs;
480
+ }
481
+ /**
482
+ * Take the next sequence number for a session already in hand.
483
+ *
484
+ * The caller has already decided which session this event belongs to —
485
+ * `touch()` for anything that keeps a session alive, `current()` for a
486
+ * goodbye. Taking the sequence must not make that decision a second time.
487
+ */
488
+ takeSequence(session) {
489
+ const sequence = session.sequence;
490
+ session.sequence += 1;
491
+ return sequence;
492
+ }
493
+ setScreen(name) {
494
+ this.touch().screen = name;
495
+ }
496
+ /** Explicit end, e.g. on an intentional logout. */
497
+ end() {
498
+ this.state = null;
499
+ }
500
+ /** Apply a new sample rate. Takes effect from the next session onward. */
501
+ setSampleRate(sampleRate) {
502
+ this.options = { ...this.options, sampleRate };
503
+ }
504
+ start(now) {
505
+ const sessionId = createId("sess");
506
+ this.state = {
507
+ sessionId,
508
+ startedAt: now,
509
+ lastActivityAt: now,
510
+ // Sequence restarts per session. Ordering is only ever meaningful
511
+ // within one session (section 14).
512
+ sequence: 0,
513
+ sampled: isSampled(sessionId, this.options.sampleRate),
514
+ screen: null
515
+ };
516
+ try {
517
+ this.options.onStart?.(this.state);
518
+ } catch {
519
+ }
520
+ return this.state;
521
+ }
522
+ };
523
+
524
+ // ../core/src/core.ts
525
+ var SDK_VERSION = "0.1.0";
526
+ var SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
527
+ var ALWAYS_CAPTURED = /* @__PURE__ */ new Set([
528
+ "error"
529
+ ]);
530
+ var SdkCore = class {
531
+ constructor(deps = {}) {
532
+ this.options = null;
533
+ this.config = DEFAULT_CONFIG;
534
+ this.sessions = null;
535
+ this.batcher = null;
536
+ this.enabled = false;
537
+ this.started = false;
538
+ /**
539
+ * Notified after an error is captured.
540
+ *
541
+ * The seam the optional replay package hangs off (section 23). Core does not
542
+ * know what replay is and must not: this is a list of callbacks, and if the
543
+ * package is not installed the list is empty.
544
+ */
545
+ this.errorListeners = /* @__PURE__ */ new Set();
546
+ /**
547
+ * Notified as each session begins.
548
+ *
549
+ * The same seam as `errorListeners`, for the thing replay cannot get from
550
+ * `onError`: continuous recording needs the session id at every flush, and
551
+ * needs the start boundary to decide whether this session is sampled.
552
+ */
553
+ this.sessionListeners = /* @__PURE__ */ new Set();
554
+ /** Events discarded because remote config disabled capture. Diagnostics. */
555
+ this.dropOnKill = 0;
556
+ this.now = deps.now ?? Date.now;
557
+ this.onFlush = deps.onFlush ?? (() => {
558
+ });
559
+ this.deviceContext = deps.deviceContext ?? (() => ({}));
560
+ this.restoreSession = deps.restoreSession ?? (() => null);
561
+ }
562
+ /**
563
+ * The live session, for a platform that has to persist it.
564
+ *
565
+ * Read-only by convention — it is the manager's own object, and mutating it
566
+ * from outside would desynchronize the sequence counter from the events
567
+ * already sent.
568
+ */
569
+ session() {
570
+ return this.sessions?.current() ?? null;
571
+ }
572
+ init(options) {
573
+ if (this.started) {
574
+ return;
575
+ }
576
+ this.options = options;
577
+ this.enabled = options.enabled ?? true;
578
+ this.started = true;
579
+ this.sessions = new SessionManager({
580
+ timeoutMs: SESSION_TIMEOUT_MS,
581
+ initial: this.restoreSession(),
582
+ sampleRate: this.config.sampleRate,
583
+ now: this.now,
584
+ onStart: (session) => this.announce(session.sessionId),
585
+ // Close the outgoing side of an inactivity rotation immediately. The
586
+ // backend finalizer remains the fallback for force-quits and OS kills.
587
+ onEnd: () => this.capture("session_end")
588
+ });
589
+ this.batcher = new Batcher({
590
+ maxSize: this.config.batchSize,
591
+ flushIntervalMs: this.config.flushIntervalMs,
592
+ onFlush: (events) => this.deliver(events)
593
+ });
594
+ this.startSessionIfNeeded();
595
+ }
596
+ /**
597
+ * Whether capture is currently active.
598
+ *
599
+ * Three independent gates: initialized, locally enabled (consent), and
600
+ * remotely enabled (the kill switch). Any one of them off means nothing is
601
+ * captured and nothing is buffered.
602
+ */
603
+ isEnabled() {
604
+ return this.started && this.enabled && this.config.enabled;
605
+ }
606
+ setEnabled(enabled) {
607
+ this.enabled = enabled;
608
+ if (enabled) {
609
+ this.startSessionIfNeeded();
610
+ return;
611
+ }
612
+ if (!enabled) {
613
+ this.batcher?.drop();
614
+ }
615
+ }
616
+ /**
617
+ * Apply remote configuration (section 39).
618
+ *
619
+ * Takes effect on a running SDK, not just at startup — that is the whole
620
+ * point of the kill switch. `isEnabled()` re-reads `config.enabled` on every
621
+ * capture, so `enabled: false` stops collection mid-session.
622
+ *
623
+ * Sampling is the one thing that cannot be retrofitted: it is decided once
624
+ * at session start and must stay that way, or a timeline ends up half
625
+ * captured while looking complete. A new rate therefore applies from the
626
+ * next session.
627
+ */
628
+ applyConfig(config) {
629
+ const wasEnabled = this.config.enabled;
630
+ this.config = config;
631
+ this.sessions?.setSampleRate(config.sampleRate);
632
+ if (wasEnabled && !config.enabled) {
633
+ const dropped = this.batcher?.drop() ?? 0;
634
+ if (dropped > 0) {
635
+ this.dropOnKill = dropped;
636
+ }
637
+ return;
638
+ }
639
+ this.batcher?.reconfigure({
640
+ maxSize: config.batchSize,
641
+ flushIntervalMs: config.flushIntervalMs
642
+ });
643
+ }
644
+ get droppedOnKill() {
645
+ return this.dropOnKill;
646
+ }
647
+ /** The config currently in force. */
648
+ get remoteConfig() {
649
+ return this.config;
650
+ }
651
+ capture(type, data) {
652
+ if (!this.isEnabled() || !this.sessions || !this.batcher) {
653
+ return null;
654
+ }
655
+ const session = type === "session_end" ? this.sessions.current() : this.sessions.touch();
656
+ if (!session) return null;
657
+ if (!session.sampled && !ALWAYS_CAPTURED.has(type)) {
658
+ return null;
659
+ }
660
+ const event = {
661
+ id: createId("evt"),
662
+ type,
663
+ sessionId: session.sessionId,
664
+ sequence: this.sessions.takeSequence(session),
665
+ timestamp: this.now(),
666
+ // Redact before the event reaches the buffer, never on the way out.
667
+ ...data ? { data: redact(data, this.config.maskedKeys) } : {}
668
+ };
669
+ this.batcher.add(event);
670
+ if (type !== "error") {
671
+ addBreadcrumb(type, void 0, data, this.config.maskedKeys, event.timestamp);
672
+ }
673
+ return event;
674
+ }
675
+ /**
676
+ * Capture an error with its breadcrumb trail.
677
+ *
678
+ * Bypasses sampling: errors are rare and are the reason people install this.
679
+ */
680
+ captureError(value, handled, extra) {
681
+ this.report(describeError(value, handled), extra);
682
+ }
683
+ /**
684
+ * Capture an error the global handler has already described.
685
+ *
686
+ * Separate from `captureError` because `describeError` cannot usefully
687
+ * re-describe its own output: a `CapturedError` is a plain object, so it
688
+ * took the object branch and came out as `UnknownError` with the real type,
689
+ * message and stack JSON-stringified inside the message. Every *uncaught*
690
+ * error — the ones that matter most — arrived that way, and the `fatal`
691
+ * flag was lost with them.
692
+ */
693
+ captureCrash(described) {
694
+ this.report(described);
695
+ }
696
+ report(described, extra) {
697
+ if (!this.isEnabled()) return;
698
+ this.capture("error", {
699
+ ...described,
700
+ ...extra,
701
+ breadcrumbs: snapshotBreadcrumbs(this.now())
702
+ });
703
+ const sessionId = this.sessions?.current()?.sessionId ?? "";
704
+ for (const listener of this.errorListeners) {
705
+ try {
706
+ listener(sessionId);
707
+ } catch {
708
+ }
709
+ }
710
+ if (described.fatal) {
711
+ this.capture("session_end", { reason: "crash" });
712
+ this.sessions?.end();
713
+ }
714
+ void this.batcher?.flush();
715
+ }
716
+ /**
717
+ * Subscribe to errors. Returns an unsubscribe.
718
+ *
719
+ * The session id is passed rather than left for the subscriber to look up:
720
+ * by the time a listener runs the session could have rolled over, and a
721
+ * recording filed against the wrong session is worse than none.
722
+ */
723
+ /**
724
+ * Count ongoing work as activity, without emitting an event for it.
725
+ *
726
+ * Recording is activity even when no analytics event happens, so replay
727
+ * calls this as it cuts segments. That keeps an actively recorded session
728
+ * alive; after thirty minutes without either kind of work, the next touch
729
+ * rotates through the ordinary inactivity boundary.
730
+ */
731
+ keepAlive() {
732
+ if (!this.isEnabled()) return;
733
+ this.sessions?.touch();
734
+ }
735
+ /** The config in force right now, including anything remote config changed. */
736
+ currentConfig() {
737
+ return this.config;
738
+ }
739
+ onSession(listener) {
740
+ this.sessionListeners.add(listener);
741
+ const open = this.sessions?.current();
742
+ if (open) {
743
+ try {
744
+ listener(open.sessionId);
745
+ } catch {
746
+ }
747
+ }
748
+ return () => {
749
+ this.sessionListeners.delete(listener);
750
+ };
751
+ }
752
+ onError(listener) {
753
+ this.errorListeners.add(listener);
754
+ return () => {
755
+ this.errorListeners.delete(listener);
756
+ };
757
+ }
758
+ captureNetwork(event) {
759
+ this.capture("network_request", { ...event });
760
+ }
761
+ /** Close a named mark and record its duration. */
762
+ measure(name) {
763
+ const result = measure(name, this.now());
764
+ if (result) {
765
+ this.capture("performance", { ...result });
766
+ }
767
+ }
768
+ mark(name) {
769
+ mark(name, this.now());
770
+ }
771
+ /** Record time from SDK load to app-ready. */
772
+ markReady() {
773
+ this.capture("performance", { ...timeToReady(this.now()) });
774
+ }
775
+ screen(name) {
776
+ if (!this.isEnabled() || !this.sessions) return;
777
+ this.sessions.setScreen(name);
778
+ this.capture("screen_view", { screen: name });
779
+ }
780
+ /** Called by the platform lifecycle glue. */
781
+ onAppStateChange(state) {
782
+ if (!this.isEnabled()) return;
783
+ if (state === "background") {
784
+ this.capture("lifecycle", { state: "background" });
785
+ void this.batcher?.flush();
786
+ return;
787
+ }
788
+ this.sessions?.touch();
789
+ this.capture("lifecycle", { state: "active" });
790
+ }
791
+ async flush() {
792
+ await this.batcher?.flush();
793
+ }
794
+ shutdown() {
795
+ clearBreadcrumbs();
796
+ if (this.isEnabled() && this.sessions?.current()) {
797
+ this.capture("session_end");
798
+ void this.batcher?.flush();
799
+ }
800
+ this.batcher?.stop();
801
+ this.sessions?.end();
802
+ this.started = false;
803
+ }
804
+ startSessionIfNeeded() {
805
+ if (!this.isEnabled() || !this.sessions) return;
806
+ if (this.sessions.current()) return;
807
+ this.sessions.touch();
808
+ }
809
+ /**
810
+ * Announce a session that has just begun.
811
+ *
812
+ * Called from inside `SessionManager.start()`, which is reachable from
813
+ * inside `capture()` — so this re-enters `capture()`. That is safe and is
814
+ * what gives the right ordering: `this.state` is already set, so the nested
815
+ * `touch()` finds a live session rather than rotating again, and
816
+ * `session_start` takes sequence 0 while the event that triggered the
817
+ * rotation takes 1.
818
+ */
819
+ announce(sessionId) {
820
+ this.capture("session_start", { ...this.deviceContext() });
821
+ for (const listener of this.sessionListeners) {
822
+ try {
823
+ listener(sessionId);
824
+ } catch {
825
+ }
826
+ }
827
+ }
828
+ /** Test accessors. */
829
+ get currentSession() {
830
+ return this.sessions?.current() ?? null;
831
+ }
832
+ get buffered() {
833
+ return this.batcher?.size ?? 0;
834
+ }
835
+ deliver(events) {
836
+ if (!this.options) return;
837
+ const batch = {
838
+ schemaVersion: SCHEMA_VERSION,
839
+ projectId: this.options.projectId,
840
+ sdkVersion: SDK_VERSION,
841
+ sentAt: this.now(),
842
+ events
843
+ };
844
+ return this.onFlush(batch);
845
+ }
846
+ };
847
+
848
+ // ../core/src/transport.ts
849
+ function classifyStatus(status) {
850
+ if (status >= 200 && status < 300) {
851
+ return { kind: "sent" };
852
+ }
853
+ if (status === 408 || status === 425 || status === 429 || status >= 500) {
854
+ return { kind: "retry", reason: `http ${status}` };
855
+ }
856
+ return { kind: "permanent", reason: `http ${status}` };
857
+ }
858
+ function parseRetryAfter(value, now = Date.now()) {
859
+ if (!value) return void 0;
860
+ const seconds = Number(value);
861
+ if (Number.isFinite(seconds)) {
862
+ return Math.max(0, seconds * 1e3);
863
+ }
864
+ const when = Date.parse(value);
865
+ return Number.isNaN(when) ? void 0 : Math.max(0, when - now);
866
+ }
867
+ var BASE_DELAY_MS = 1e3;
868
+ var MAX_DELAY_MS = 5 * 60 * 1e3;
869
+ function backoffDelay(attempts, random = Math.random) {
870
+ const exponential = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** Math.max(0, attempts));
871
+ return Math.floor(random() * exponential);
872
+ }
873
+ async function sendBatch(options, batch) {
874
+ const doFetch = options.fetchImpl ?? fetch;
875
+ const url = `${options.endpoint.replace(/\/$/, "")}/v1/mobile/events`;
876
+ let response;
877
+ try {
878
+ response = await doFetch(url, {
879
+ method: "POST",
880
+ headers: {
881
+ "content-type": "application/json",
882
+ authorization: `Bearer ${options.apiKey}`,
883
+ "x-sdk-version": options.sdkVersion
884
+ },
885
+ body: JSON.stringify(batch),
886
+ // Ignored by runtimes that do not know it, which is what makes it safe
887
+ // to send unconditionally from a shared transport.
888
+ keepalive: options.keepalive === true
889
+ });
890
+ } catch (err) {
891
+ return {
892
+ kind: "retry",
893
+ reason: err instanceof Error ? err.message : "network error"
894
+ };
895
+ }
896
+ const outcome = classifyStatus(response.status);
897
+ if (outcome.kind === "retry") {
898
+ const retryAfterMs = parseRetryAfter(
899
+ typeof response.headers?.get === "function" ? response.headers.get("retry-after") : null
900
+ );
901
+ return retryAfterMs === void 0 ? outcome : { ...outcome, retryAfterMs };
902
+ }
903
+ return outcome;
904
+ }
905
+
906
+ // ../core/src/dispatcher.ts
907
+ var Dispatcher = class {
908
+ constructor(options) {
909
+ this.draining = false;
910
+ /** Wall-clock time before which no send should be attempted. */
911
+ this.pausedUntil = 0;
912
+ this.queue = options.queue;
913
+ this.transport = options.transport;
914
+ this.batchesPerDrain = options.batchesPerDrain ?? 5;
915
+ this.now = options.now ?? Date.now;
916
+ this.onOutcome = options.onOutcome;
917
+ }
918
+ /** True while backpressure is in effect. */
919
+ get paused() {
920
+ return this.now() < this.pausedUntil;
921
+ }
922
+ get pausedForMs() {
923
+ return Math.max(0, this.pausedUntil - this.now());
924
+ }
925
+ /**
926
+ * Send what is queued.
927
+ *
928
+ * Returns the number of batches delivered. Stops early on the first batch
929
+ * that needs retrying: the queue is ordered, and a failure almost always
930
+ * means the network or the server is unavailable for the next one too.
931
+ * Continuing would just burn attempts on every queued batch at once.
932
+ */
933
+ async drain() {
934
+ if (this.draining || this.paused) return 0;
935
+ this.draining = true;
936
+ let sent = 0;
937
+ try {
938
+ const entries = await this.queue.peek(this.batchesPerDrain);
939
+ for (const entry of entries) {
940
+ const outcome = await sendBatch(this.transport, entry.batch);
941
+ this.onOutcome?.(outcome, entry);
942
+ if (outcome.kind === "sent") {
943
+ await this.queue.remove(entry.name);
944
+ sent += 1;
945
+ continue;
946
+ }
947
+ if (outcome.kind === "permanent") {
948
+ await this.queue.remove(entry.name);
949
+ continue;
950
+ }
951
+ const delay = outcome.retryAfterMs ?? backoffDelay(entry.attempts);
952
+ this.pausedUntil = this.now() + delay;
953
+ await this.queue.recordFailure(entry);
954
+ break;
955
+ }
956
+ } finally {
957
+ this.draining = false;
958
+ }
959
+ return sent;
960
+ }
961
+ /** Clear backpressure, e.g. when the app returns to the foreground. */
962
+ resume() {
963
+ this.pausedUntil = 0;
964
+ }
965
+ };
966
+
967
+ // ../core/src/network.ts
968
+ var PATCH_MARKER = "__sessionCapturePatched";
969
+ function sanitizeUrl(url) {
970
+ const queryStart = url.indexOf("?");
971
+ return queryStart === -1 ? url : `${url.slice(0, queryStart)}?<redacted>`;
972
+ }
973
+ function shouldCapture(url, ingestEndpoint, denyList) {
974
+ if (ingestEndpoint && url.startsWith(ingestEndpoint)) {
975
+ return false;
976
+ }
977
+ return !denyList.some((pattern) => pattern && url.includes(pattern));
978
+ }
979
+ function headersToObject(init2) {
980
+ if (!init2) return void 0;
981
+ const out = {};
982
+ try {
983
+ if (Array.isArray(init2)) {
984
+ for (const [k, v] of init2) out[k] = v;
985
+ } else if (typeof init2.forEach === "function") {
986
+ init2.forEach((v, k) => {
987
+ out[k] = v;
988
+ });
989
+ } else {
990
+ Object.assign(out, init2);
991
+ }
992
+ } catch {
993
+ return void 0;
994
+ }
995
+ return Object.keys(out).length > 0 ? out : void 0;
996
+ }
997
+ function installNetworkCapture(options) {
998
+ const xhr = globalThis.XMLHttpRequest;
999
+ const undo = [];
1000
+ if (typeof xhr === "function" && xhr.prototype) {
1001
+ undo.push(installXhrCapture(xhr, options));
1002
+ }
1003
+ undo.push(installFetchCapture(options));
1004
+ return () => {
1005
+ for (const teardown2 of undo) teardown2();
1006
+ };
1007
+ }
1008
+ var insideFetch = false;
1009
+ var servedByXhr = false;
1010
+ function installXhrCapture(xhr, options) {
1011
+ const now = options.now ?? Date.now;
1012
+ const proto = xhr.prototype;
1013
+ if (proto[PATCH_MARKER]) {
1014
+ return () => {
1015
+ };
1016
+ }
1017
+ const originalOpen = proto.open;
1018
+ const originalSend = proto.send;
1019
+ const originalSetHeader = proto.setRequestHeader;
1020
+ const pending = /* @__PURE__ */ new WeakMap();
1021
+ function patchedOpen(method, url, ...rest) {
1022
+ try {
1023
+ pending.set(this, {
1024
+ method: String(method ?? "GET").toUpperCase(),
1025
+ url: String(url ?? ""),
1026
+ headers: {},
1027
+ started: 0
1028
+ });
1029
+ } catch {
1030
+ }
1031
+ return originalOpen.call(this, method, url, ...rest);
1032
+ }
1033
+ function patchedSetHeader(name, value) {
1034
+ try {
1035
+ const state = pending.get(this);
1036
+ if (state) state.headers[name] = value;
1037
+ } catch {
1038
+ }
1039
+ return originalSetHeader.call(this, name, value);
1040
+ }
1041
+ function patchedSend(body) {
1042
+ try {
1043
+ const state = pending.get(this);
1044
+ if (state && shouldCapture(state.url, options.ingestEndpoint, options.urlDenyList)) {
1045
+ if (insideFetch) servedByXhr = true;
1046
+ state.started = now();
1047
+ if (options.captureBodies) {
1048
+ state.body = captureBody(
1049
+ body,
1050
+ headerValue(state.headers, "content-type"),
1051
+ options.maskedKeys
1052
+ );
1053
+ }
1054
+ for (const reason of ["error", "timeout", "abort"]) {
1055
+ this.addEventListener(reason, () => {
1056
+ const current = pending.get(this);
1057
+ if (current) current.reason = reason;
1058
+ });
1059
+ }
1060
+ this.addEventListener("loadend", () => finish(this));
1061
+ }
1062
+ } catch {
1063
+ }
1064
+ return originalSend.call(this, body);
1065
+ }
1066
+ function finish(request) {
1067
+ const state = pending.get(request);
1068
+ if (!state) return;
1069
+ pending.delete(request);
1070
+ try {
1071
+ const status = request.status;
1072
+ const event = {
1073
+ url: sanitizeUrl(state.url),
1074
+ method: state.method,
1075
+ durationMs: now() - state.started,
1076
+ requestHeaders: redactHeaders(state.headers, options.maskedKeys)
1077
+ };
1078
+ if (state.body !== void 0) {
1079
+ event.requestBody = state.body;
1080
+ }
1081
+ if (status > 0) {
1082
+ event.status = status;
1083
+ const responseHeaders = parseResponseHeaders(request.getAllResponseHeaders());
1084
+ event.responseHeaders = redactHeaders(responseHeaders, options.maskedKeys);
1085
+ if (options.captureBodies) {
1086
+ event.responseBody = readResponseBody(
1087
+ request,
1088
+ headerValue(responseHeaders ?? {}, "content-type"),
1089
+ options.maskedKeys
1090
+ );
1091
+ }
1092
+ } else {
1093
+ event.error = FAILURE_TEXT[state.reason ?? "error"];
1094
+ }
1095
+ report(options, event);
1096
+ } catch {
1097
+ }
1098
+ }
1099
+ proto.open = patchedOpen;
1100
+ proto.setRequestHeader = patchedSetHeader;
1101
+ proto.send = patchedSend;
1102
+ proto[PATCH_MARKER] = true;
1103
+ return () => {
1104
+ if (proto.open === patchedOpen) proto.open = originalOpen;
1105
+ if (proto.setRequestHeader === patchedSetHeader) proto.setRequestHeader = originalSetHeader;
1106
+ if (proto.send === patchedSend) proto.send = originalSend;
1107
+ delete proto[PATCH_MARKER];
1108
+ };
1109
+ }
1110
+ var FAILURE_TEXT = {
1111
+ error: "network error",
1112
+ timeout: "timeout",
1113
+ abort: "aborted"
1114
+ };
1115
+ var MAX_BODY_CHARS = 4096;
1116
+ function truncate(text) {
1117
+ return text.length <= MAX_BODY_CHARS ? text : `${text.slice(0, MAX_BODY_CHARS)}\u2026[truncated]`;
1118
+ }
1119
+ function headerValue(headers, name) {
1120
+ const wanted = name.toLowerCase();
1121
+ for (const key of Object.keys(headers)) {
1122
+ if (key.toLowerCase() === wanted) return String(headers[key] ?? "");
1123
+ }
1124
+ return "";
1125
+ }
1126
+ function mediaType(contentType) {
1127
+ return (contentType.split(";")[0] ?? "").trim().toLowerCase();
1128
+ }
1129
+ function captureBody(raw, contentType, maskedKeys) {
1130
+ if (raw === void 0 || raw === null || raw === "") return void 0;
1131
+ if (typeof raw !== "string") {
1132
+ return `[not captured: ${describeBody(raw)}]`;
1133
+ }
1134
+ const type = mediaType(contentType);
1135
+ if (type === "application/json" || type.endsWith("+json")) {
1136
+ try {
1137
+ return truncate(JSON.stringify(redact(JSON.parse(raw), maskedKeys)));
1138
+ } catch {
1139
+ return "[not captured: malformed json]";
1140
+ }
1141
+ }
1142
+ if (type === "application/x-www-form-urlencoded") {
1143
+ try {
1144
+ const fields = {};
1145
+ new URLSearchParams(raw).forEach((value, key) => {
1146
+ fields[key] = value;
1147
+ });
1148
+ const out = new URLSearchParams();
1149
+ for (const [key, value] of Object.entries(
1150
+ redact(fields, maskedKeys)
1151
+ )) {
1152
+ out.append(key, value);
1153
+ }
1154
+ return truncate(out.toString());
1155
+ } catch {
1156
+ return "[not captured: malformed form data]";
1157
+ }
1158
+ }
1159
+ return `[not captured: ${type || "unknown content type"}]`;
1160
+ }
1161
+ function readHeaders(response) {
1162
+ const headers = response.headers;
1163
+ if (!headers || typeof headers.forEach !== "function") return void 0;
1164
+ const out = {};
1165
+ try {
1166
+ headers.forEach((value, key) => {
1167
+ out[key] = value;
1168
+ });
1169
+ } catch {
1170
+ return void 0;
1171
+ }
1172
+ return Object.keys(out).length > 0 ? out : void 0;
1173
+ }
1174
+ var MAX_CLONE_BYTES = 256 * 1024;
1175
+ function cloneForReading(response) {
1176
+ if (typeof response.clone !== "function") return null;
1177
+ const headers = readHeaders(response) ?? {};
1178
+ const type = mediaType(headerValue(headers, "content-type"));
1179
+ const redactable = type === "application/json" || type.endsWith("+json") || type === "application/x-www-form-urlencoded";
1180
+ if (!redactable) return null;
1181
+ const declared = Number(headerValue(headers, "content-length"));
1182
+ if (Number.isFinite(declared) && declared > MAX_CLONE_BYTES) return null;
1183
+ try {
1184
+ return response.clone().text();
1185
+ } catch {
1186
+ return null;
1187
+ }
1188
+ }
1189
+ function describeBody(body) {
1190
+ const name = body?.constructor?.name;
1191
+ return name ? name.toLowerCase() : typeof body;
1192
+ }
1193
+ function readResponseBody(request, contentType, maskedKeys) {
1194
+ const type = request.responseType ?? "";
1195
+ if (type !== "" && type !== "text") {
1196
+ return `[not captured: ${type} response]`;
1197
+ }
1198
+ try {
1199
+ return captureBody(request.responseText, contentType, maskedKeys);
1200
+ } catch {
1201
+ return void 0;
1202
+ }
1203
+ }
1204
+ function parseResponseHeaders(raw) {
1205
+ if (!raw) return void 0;
1206
+ const out = {};
1207
+ for (const line of raw.split("\r\n")) {
1208
+ const colon = line.indexOf(":");
1209
+ if (colon === -1) continue;
1210
+ out[line.slice(0, colon).trim()] = line.slice(colon + 1).trim();
1211
+ }
1212
+ return Object.keys(out).length > 0 ? out : void 0;
1213
+ }
1214
+ function installFetchCapture(options) {
1215
+ const now = options.now ?? Date.now;
1216
+ const target = globalThis;
1217
+ const original = target.fetch;
1218
+ if (typeof original !== "function" || original[PATCH_MARKER]) {
1219
+ return () => {
1220
+ };
1221
+ }
1222
+ const patched = async function patchedFetch(input, init2) {
1223
+ const url = typeof input === "string" ? input : String(input);
1224
+ const method = (init2?.method ?? "GET").toUpperCase();
1225
+ if (!shouldCapture(url, options.ingestEndpoint, options.urlDenyList)) {
1226
+ return original(input, init2);
1227
+ }
1228
+ const started = now();
1229
+ let pending;
1230
+ insideFetch = true;
1231
+ servedByXhr = false;
1232
+ try {
1233
+ pending = original(input, init2);
1234
+ } finally {
1235
+ insideFetch = false;
1236
+ }
1237
+ const claimed = servedByXhr;
1238
+ const requestBody = options.captureBodies ? captureBody(init2?.body, headerValue(headersToObject(init2?.headers) ?? {}, "content-type"), options.maskedKeys) : void 0;
1239
+ try {
1240
+ const response = await pending;
1241
+ if (claimed) return response;
1242
+ const event = {
1243
+ url: sanitizeUrl(url),
1244
+ method,
1245
+ status: response.status,
1246
+ durationMs: now() - started,
1247
+ requestHeaders: redactHeaders(init2?.headers, options.maskedKeys),
1248
+ responseHeaders: redactHeaders(readHeaders(response), options.maskedKeys)
1249
+ };
1250
+ if (requestBody !== void 0) event.requestBody = requestBody;
1251
+ const copy = options.captureBodies ? cloneForReading(response) : null;
1252
+ if (copy) {
1253
+ copy.then(
1254
+ (text) => {
1255
+ event.responseBody = captureBody(
1256
+ text,
1257
+ headerValue(readHeaders(response) ?? {}, "content-type"),
1258
+ options.maskedKeys
1259
+ );
1260
+ report(options, event);
1261
+ },
1262
+ () => report(options, event)
1263
+ );
1264
+ } else {
1265
+ report(options, event);
1266
+ }
1267
+ return response;
1268
+ } catch (error) {
1269
+ if (!claimed) {
1270
+ const event = {
1271
+ url: sanitizeUrl(url),
1272
+ method,
1273
+ durationMs: now() - started,
1274
+ error: error instanceof Error ? error.message : "network error",
1275
+ requestHeaders: redactHeaders(init2?.headers, options.maskedKeys)
1276
+ };
1277
+ if (requestBody !== void 0) event.requestBody = requestBody;
1278
+ report(options, event);
1279
+ }
1280
+ throw error;
1281
+ }
1282
+ };
1283
+ patched[PATCH_MARKER] = true;
1284
+ target.fetch = patched;
1285
+ return () => {
1286
+ if (target.fetch === patched) {
1287
+ target.fetch = original;
1288
+ }
1289
+ };
1290
+ }
1291
+ function redactHeaders(headers, maskedKeys) {
1292
+ const raw = headersToObject(headers);
1293
+ if (!raw) return void 0;
1294
+ return redact(raw, maskedKeys);
1295
+ }
1296
+ function report(options, event) {
1297
+ try {
1298
+ options.onEvent(event);
1299
+ } catch {
1300
+ }
1301
+ }
1302
+
1303
+ // ../core/src/queue.ts
1304
+ var DEFAULT_MAX_BATCHES = 50;
1305
+ var DEFAULT_MAX_ATTEMPTS = 8;
1306
+ var SendQueue = class {
1307
+ constructor(options) {
1308
+ this.counter = 0;
1309
+ this.droppedCount = 0;
1310
+ this.abandonedCount = 0;
1311
+ this.store = options.store;
1312
+ this.maxBatches = options.maxBatches ?? DEFAULT_MAX_BATCHES;
1313
+ this.maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
1314
+ }
1315
+ /** Batches dropped because the queue was full. */
1316
+ get dropped() {
1317
+ return this.droppedCount;
1318
+ }
1319
+ /** Batches abandoned after exhausting their attempts. */
1320
+ get abandoned() {
1321
+ return this.abandonedCount;
1322
+ }
1323
+ async size() {
1324
+ return (await this.store.list()).length;
1325
+ }
1326
+ /**
1327
+ * Persist a batch for sending.
1328
+ *
1329
+ * Called before any network attempt, so a crash between capture and delivery
1330
+ * loses nothing.
1331
+ */
1332
+ async enqueue(batch, now = Date.now()) {
1333
+ await this.prune();
1334
+ this.counter = (this.counter + 1) % 1e6;
1335
+ const name = `${String(now).padStart(15, "0")}-${String(this.counter).padStart(6, "0")}.json`;
1336
+ const envelope = { batch, attempts: 0 };
1337
+ await this.store.write(name, JSON.stringify(envelope));
1338
+ return name;
1339
+ }
1340
+ /** Oldest queued batches, oldest first. */
1341
+ async peek(limit = 5) {
1342
+ const names = (await this.store.list()).sort().slice(0, limit);
1343
+ const out = [];
1344
+ for (const name of names) {
1345
+ const raw = await this.store.read(name);
1346
+ if (raw === null) continue;
1347
+ try {
1348
+ const envelope = JSON.parse(raw);
1349
+ if (!envelope?.batch?.events) throw new Error("missing events");
1350
+ out.push({ name, batch: envelope.batch, attempts: envelope.attempts ?? 0 });
1351
+ } catch {
1352
+ await this.store.remove(name);
1353
+ this.abandonedCount += 1;
1354
+ }
1355
+ }
1356
+ return out;
1357
+ }
1358
+ async remove(name) {
1359
+ await this.store.remove(name);
1360
+ }
1361
+ /**
1362
+ * Record a failed attempt.
1363
+ *
1364
+ * Returns false when the batch has been abandoned, so the caller knows it is
1365
+ * gone rather than merely deferred.
1366
+ */
1367
+ async recordFailure(entry) {
1368
+ const attempts = entry.attempts + 1;
1369
+ if (attempts >= this.maxAttempts) {
1370
+ await this.store.remove(entry.name);
1371
+ this.abandonedCount += 1;
1372
+ return false;
1373
+ }
1374
+ const envelope = { batch: entry.batch, attempts };
1375
+ await this.store.write(entry.name, JSON.stringify(envelope));
1376
+ return true;
1377
+ }
1378
+ /** Drop oldest batches until the queue is under its ceiling. */
1379
+ async prune() {
1380
+ const names = (await this.store.list()).sort();
1381
+ const excess = names.length - (this.maxBatches - 1);
1382
+ for (let i = 0; i < excess; i += 1) {
1383
+ const name = names[i];
1384
+ if (!name) break;
1385
+ await this.store.remove(name);
1386
+ this.droppedCount += 1;
1387
+ }
1388
+ }
1389
+ };
1390
+
1391
+ // ../core/src/safe.ts
1392
+ var FAILURE_THRESHOLD = 5;
1393
+ var consecutiveFailures = 0;
1394
+ var disabled = false;
1395
+ function isSelfDisabled() {
1396
+ return disabled;
1397
+ }
1398
+ function safe(fn, fallback, label = "sdk") {
1399
+ return (...args) => {
1400
+ if (disabled) return fallback;
1401
+ try {
1402
+ const result = fn(...args);
1403
+ consecutiveFailures = 0;
1404
+ return result;
1405
+ } catch (err) {
1406
+ recordFailure(label, err);
1407
+ return fallback;
1408
+ }
1409
+ };
1410
+ }
1411
+ function safeAsync(fn, fallback, label = "sdk") {
1412
+ return async (...args) => {
1413
+ if (disabled) return fallback;
1414
+ try {
1415
+ const result = await fn(...args);
1416
+ consecutiveFailures = 0;
1417
+ return result;
1418
+ } catch (err) {
1419
+ recordFailure(label, err);
1420
+ return fallback;
1421
+ }
1422
+ };
1423
+ }
1424
+ function recordFailure(label, err) {
1425
+ consecutiveFailures += 1;
1426
+ if (consecutiveFailures >= FAILURE_THRESHOLD) {
1427
+ disabled = true;
1428
+ console.warn(
1429
+ `[session-capture] disabled after ${FAILURE_THRESHOLD} consecutive internal errors (${label})`,
1430
+ err
1431
+ );
1432
+ return;
1433
+ }
1434
+ if (isDev()) {
1435
+ console.warn(`[session-capture] internal error in ${label}`, err);
1436
+ }
1437
+ }
1438
+ function isDev() {
1439
+ return typeof __DEV__ !== "undefined" && __DEV__ === true;
1440
+ }
1441
+
1442
+ // ../core/src/store.ts
1443
+ var QUEUE_DIR = "session-capture-queue";
1444
+ var CONFIG_DIR = "session-capture-config";
1445
+ var MemoryStore = class {
1446
+ constructor() {
1447
+ this.entries = /* @__PURE__ */ new Map();
1448
+ }
1449
+ async list() {
1450
+ return [...this.entries.keys()].sort();
1451
+ }
1452
+ async read(name) {
1453
+ return this.entries.get(name) ?? null;
1454
+ }
1455
+ async write(name, contents) {
1456
+ this.entries.set(name, contents);
1457
+ }
1458
+ async remove(name) {
1459
+ this.entries.delete(name);
1460
+ }
1461
+ /** Test helper. */
1462
+ get size() {
1463
+ return this.entries.size;
1464
+ }
1465
+ };
1466
+
1467
+ // src/device.ts
1468
+ import { Platform } from "react-native";
1469
+ function readDeviceContext(appVersion) {
1470
+ const context = {};
1471
+ if (appVersion) {
1472
+ context.appVersion = appVersion;
1473
+ }
1474
+ if (Platform.OS === "ios" || Platform.OS === "android") {
1475
+ context.platform = Platform.OS;
1476
+ }
1477
+ if (Platform.Version !== void 0 && Platform.Version !== null) {
1478
+ context.osVersion = String(Platform.Version);
1479
+ }
1480
+ return context;
1481
+ }
1482
+
1483
+ // src/store-expo.ts
1484
+ import { Directory, File, Paths } from "expo-file-system";
1485
+ var ExpoFileStore = class {
1486
+ /**
1487
+ * `directory` is a parameter because the queue and the remote-config cache
1488
+ * must not share one. `SendQueue.peek()` treats every file it can see as a
1489
+ * queued batch and *deletes* whatever fails to parse as one, so a config
1490
+ * file stored alongside the queue would vanish on the first drain.
1491
+ */
1492
+ constructor(directory = QUEUE_DIR) {
1493
+ this.dir = new Directory(Paths.document, directory);
1494
+ if (!this.dir.exists) {
1495
+ this.dir.create({ intermediates: true });
1496
+ }
1497
+ }
1498
+ async list() {
1499
+ return this.dir.list().filter((entry) => entry instanceof File).map((file) => file.name);
1500
+ }
1501
+ async read(name) {
1502
+ const file = new File(this.dir, name);
1503
+ return file.exists ? file.text() : null;
1504
+ }
1505
+ async write(name, contents) {
1506
+ const file = new File(this.dir, name);
1507
+ if (!file.exists) {
1508
+ file.create();
1509
+ }
1510
+ file.write(contents);
1511
+ }
1512
+ async remove(name) {
1513
+ const file = new File(this.dir, name);
1514
+ if (file.exists) {
1515
+ file.delete();
1516
+ }
1517
+ }
1518
+ };
1519
+ function createPersistentStore(directory = QUEUE_DIR) {
1520
+ try {
1521
+ return new ExpoFileStore(directory);
1522
+ } catch {
1523
+ return null;
1524
+ }
1525
+ }
1526
+
1527
+ // src/lifecycle.ts
1528
+ import { AppState } from "react-native";
1529
+ function installLifecycleListener(onChange) {
1530
+ try {
1531
+ const subscription = AppState.addEventListener(
1532
+ "change",
1533
+ (next) => {
1534
+ if (next === "active") onChange("active");
1535
+ else if (next === "background") onChange("background");
1536
+ }
1537
+ );
1538
+ return () => {
1539
+ try {
1540
+ subscription?.remove?.();
1541
+ } catch {
1542
+ }
1543
+ };
1544
+ } catch {
1545
+ return () => {
1546
+ };
1547
+ }
1548
+ }
1549
+
1550
+ // src/index.ts
1551
+ var DRAIN_INTERVAL_MS = 3e4;
1552
+ var CONFIG_REFRESH_MS = 6 * 60 * 60 * 1e3;
1553
+ var CONFIG_MIN_INTERVAL_MS = 15 * 60 * 1e3;
1554
+ var core = null;
1555
+ var dispatcher = null;
1556
+ var queue = null;
1557
+ var configStore = null;
1558
+ var drainTimer = null;
1559
+ var configTimer = null;
1560
+ var lastConfigFetch = 0;
1561
+ var teardown = [];
1562
+ var networkOptions = {
1563
+ maskedKeys: [],
1564
+ urlDenyList: [],
1565
+ // Off until a project says otherwise, and off again the moment it stops
1566
+ // saying so — including when a config fetch is what turned it on.
1567
+ captureBodies: false
1568
+ };
1569
+ function applyConfig(config) {
1570
+ core?.applyConfig(config);
1571
+ networkOptions.maskedKeys = config.maskedKeys;
1572
+ networkOptions.urlDenyList = config.urlDenyList;
1573
+ networkOptions.captureBodies = config.captureBodies;
1574
+ }
1575
+ async function refreshConfig(options, force = false) {
1576
+ const now = Date.now();
1577
+ if (!force && now - lastConfigFetch < CONFIG_MIN_INTERVAL_MS) {
1578
+ return;
1579
+ }
1580
+ lastConfigFetch = now;
1581
+ const config = await fetchRemoteConfig({
1582
+ endpoint: options.endpoint,
1583
+ apiKey: options.apiKey,
1584
+ projectId: options.projectId
1585
+ });
1586
+ if (!config || !core) {
1587
+ return;
1588
+ }
1589
+ applyConfig(config);
1590
+ if (configStore) {
1591
+ await saveConfig(configStore, config);
1592
+ }
1593
+ }
1594
+ async function bootstrapConfig(options) {
1595
+ if (configStore) {
1596
+ const cached = await loadCachedConfig(configStore);
1597
+ if (cached && core) {
1598
+ applyConfig(cached);
1599
+ }
1600
+ }
1601
+ await refreshConfig(options, true);
1602
+ }
1603
+ var init = safe((options) => {
1604
+ if (core) {
1605
+ return;
1606
+ }
1607
+ const store = createPersistentStore() ?? new MemoryStore();
1608
+ queue = new SendQueue({ store });
1609
+ configStore = createPersistentStore(CONFIG_DIR) ?? new MemoryStore();
1610
+ dispatcher = new Dispatcher({
1611
+ queue,
1612
+ transport: {
1613
+ endpoint: options.endpoint,
1614
+ apiKey: options.apiKey,
1615
+ sdkVersion: SDK_VERSION
1616
+ }
1617
+ });
1618
+ core = new SdkCore({
1619
+ onFlush: async (batch) => {
1620
+ await queue?.enqueue(batch);
1621
+ void dispatcher?.drain();
1622
+ },
1623
+ deviceContext: () => ({ ...readDeviceContext(options.appVersion) })
1624
+ });
1625
+ core.init(options);
1626
+ void bootstrapConfig(options).catch(() => {
1627
+ });
1628
+ teardown.push(
1629
+ installLifecycleListener((state) => {
1630
+ core?.onAppStateChange(state);
1631
+ if (state === "active") {
1632
+ void refreshConfig(options).catch(() => {
1633
+ });
1634
+ dispatcher?.resume();
1635
+ void dispatcher?.drain();
1636
+ }
1637
+ })
1638
+ );
1639
+ drainTimer = setInterval(() => {
1640
+ void dispatcher?.drain();
1641
+ }, DRAIN_INTERVAL_MS);
1642
+ drainTimer?.unref?.();
1643
+ configTimer = setInterval(() => {
1644
+ void refreshConfig(options).catch(() => {
1645
+ });
1646
+ }, CONFIG_REFRESH_MS);
1647
+ configTimer?.unref?.();
1648
+ teardown.push(
1649
+ installErrorHandlers((error) => core?.captureCrash(error))
1650
+ );
1651
+ if (options.captureNetwork !== false) {
1652
+ teardown.push(
1653
+ installNetworkCapture({
1654
+ ingestEndpoint: options.endpoint,
1655
+ get urlDenyList() {
1656
+ return networkOptions.urlDenyList;
1657
+ },
1658
+ get maskedKeys() {
1659
+ return networkOptions.maskedKeys;
1660
+ },
1661
+ get captureBodies() {
1662
+ return networkOptions.captureBodies;
1663
+ },
1664
+ onEvent: (event) => core?.captureNetwork(event)
1665
+ })
1666
+ );
1667
+ }
1668
+ }, void 0, "init");
1669
+ var setEnabled = safe((enabled) => {
1670
+ core?.setEnabled(enabled);
1671
+ }, void 0, "setEnabled");
1672
+ var isEnabled = safe(
1673
+ () => core?.isEnabled() ?? false,
1674
+ false,
1675
+ "isEnabled"
1676
+ );
1677
+ var track = safe(
1678
+ (name, properties) => {
1679
+ core?.capture("custom", { name, ...properties });
1680
+ },
1681
+ void 0,
1682
+ "track"
1683
+ );
1684
+ var screen = safe((name) => {
1685
+ core?.screen(name);
1686
+ }, void 0, "screen");
1687
+ var identify = safe(
1688
+ (userId, traits) => {
1689
+ core?.capture("user_action", { action: "identify", userId, ...traits });
1690
+ },
1691
+ void 0,
1692
+ "identify"
1693
+ );
1694
+ var flush = safeAsync(
1695
+ async () => {
1696
+ await core?.flush();
1697
+ await dispatcher?.drain();
1698
+ },
1699
+ void 0,
1700
+ "flush"
1701
+ );
1702
+ var pendingBatches = safeAsync(
1703
+ async () => await queue?.size() ?? 0,
1704
+ 0,
1705
+ "pendingBatches"
1706
+ );
1707
+ var currentConfig = safe(
1708
+ () => core?.currentConfig() ?? DEFAULT_CONFIG,
1709
+ DEFAULT_CONFIG,
1710
+ "currentConfig"
1711
+ );
1712
+ var keepSessionAlive = safe(() => {
1713
+ core?.keepAlive();
1714
+ }, void 0, "keepSessionAlive");
1715
+ var onSession = safe(
1716
+ (listener) => core?.onSession(listener) ?? (() => {
1717
+ }),
1718
+ () => {
1719
+ },
1720
+ "onSession"
1721
+ );
1722
+ var onError = safe(
1723
+ (listener) => core?.onError(listener) ?? (() => {
1724
+ }),
1725
+ () => {
1726
+ },
1727
+ "onError"
1728
+ );
1729
+ var captureException = safe(
1730
+ (error, extra) => {
1731
+ core?.captureError(error, true, extra);
1732
+ },
1733
+ void 0,
1734
+ "captureException"
1735
+ );
1736
+ var breadcrumb = safe(
1737
+ (message, data) => {
1738
+ addBreadcrumb("manual", message, data);
1739
+ },
1740
+ void 0,
1741
+ "breadcrumb"
1742
+ );
1743
+ var startMeasure = safe((name) => {
1744
+ core?.mark(name);
1745
+ }, void 0, "startMeasure");
1746
+ var endMeasure = safe((name) => {
1747
+ core?.measure(name);
1748
+ }, void 0, "endMeasure");
1749
+ var markAppReady = safe(() => {
1750
+ core?.markReady();
1751
+ }, void 0, "markAppReady");
1752
+ var shutdown = safe(() => {
1753
+ if (drainTimer) {
1754
+ clearInterval(drainTimer);
1755
+ drainTimer = null;
1756
+ }
1757
+ if (configTimer) {
1758
+ clearInterval(configTimer);
1759
+ configTimer = null;
1760
+ }
1761
+ while (teardown.length) {
1762
+ teardown.pop()?.();
1763
+ }
1764
+ core?.shutdown();
1765
+ core = null;
1766
+ dispatcher = null;
1767
+ queue = null;
1768
+ configStore = null;
1769
+ lastConfigFetch = 0;
1770
+ networkOptions.maskedKeys = [];
1771
+ networkOptions.urlDenyList = [];
1772
+ }, void 0, "shutdown");
1773
+ export {
1774
+ DEFAULT_CONFIG,
1775
+ MemoryStore,
1776
+ SCHEMA_VERSION,
1777
+ SDK_VERSION,
1778
+ breadcrumb,
1779
+ captureException,
1780
+ createPersistentStore,
1781
+ currentConfig,
1782
+ endMeasure,
1783
+ flush,
1784
+ identify,
1785
+ init,
1786
+ isEnabled,
1787
+ isSampled,
1788
+ isSelfDisabled,
1789
+ keepSessionAlive,
1790
+ markAppReady,
1791
+ onError,
1792
+ onSession,
1793
+ pendingBatches,
1794
+ safe,
1795
+ safeAsync,
1796
+ screen,
1797
+ setEnabled,
1798
+ shutdown,
1799
+ startMeasure,
1800
+ track
1801
+ };