@nagoorkani/session-capture-core 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.
@@ -0,0 +1,510 @@
1
+ /**
2
+ * Network capture.
3
+ *
4
+ * This module monkey-patches `XMLHttpRequest` inside someone else's
5
+ * application. It is the most dangerous code in the SDK, so the rules from
6
+ * section 24 are non-negotiable:
7
+ *
8
+ * - patch once, idempotently — double-wrapping doubles every event
9
+ * - always call through to the original
10
+ * - never swallow an error the app expects to receive
11
+ * - never capture bodies by default
12
+ * - apply the header deny-list at capture time, not later
13
+ * - skip requests to the ingestion endpoint itself
14
+ *
15
+ * That last rule is not optional: without it the SDK observes its own uploads
16
+ * and generates telemetry about generating telemetry, forever.
17
+ *
18
+ * ## Both, because there is no single choke point
19
+ *
20
+ * Bare React Native's `fetch` is `whatwg-fetch`, which runs on top of
21
+ * `XMLHttpRequest` — so an XHR patch sees it. Expo replaces `globalThis.fetch`
22
+ * with a native implementation (`expo/src/winter/runtime.native.ts` installs
23
+ * `expo/fetch` unless `EXPO_PUBLIC_USE_RN_FETCH=1`), and that one never
24
+ * touches XHR. Patching only XHR makes every `fetch()` in an Expo app
25
+ * invisible; patching only `fetch` makes axios and every other XHR client
26
+ * invisible. Both get patched.
27
+ *
28
+ * The two hand off so nothing is reported twice. `whatwg-fetch` calls
29
+ * `xhr.open`/`xhr.send` synchronously inside the Promise executor, so the
30
+ * moment `fetch` returns its promise we already know whether an XHR served it.
31
+ * If one did, the XHR side reports — it has response headers and a buffered
32
+ * body — and the fetch side stays quiet. If none did, the request was native
33
+ * and the fetch side reports.
34
+ *
35
+ * A fetch polyfill that reached XHR *asynchronously* would defeat that and be
36
+ * counted twice. `whatwg-fetch` does not, and it is the only XHR-backed fetch
37
+ * in play.
38
+ */
39
+ import { redact } from "./redact.js";
40
+ const PATCH_MARKER = '__sessionCapturePatched';
41
+ /** Strip query strings before capture: they routinely carry tokens. */
42
+ export function sanitizeUrl(url) {
43
+ const queryStart = url.indexOf('?');
44
+ return queryStart === -1 ? url : `${url.slice(0, queryStart)}?<redacted>`;
45
+ }
46
+ export function shouldCapture(url, ingestEndpoint, denyList) {
47
+ // The SDK's own uploads. Capturing them is an infinite loop.
48
+ if (ingestEndpoint && url.startsWith(ingestEndpoint)) {
49
+ return false;
50
+ }
51
+ return !denyList.some((pattern) => pattern && url.includes(pattern));
52
+ }
53
+ function headersToObject(init) {
54
+ if (!init)
55
+ return undefined;
56
+ const out = {};
57
+ try {
58
+ if (Array.isArray(init)) {
59
+ for (const [k, v] of init)
60
+ out[k] = v;
61
+ }
62
+ else if (typeof init.forEach === 'function') {
63
+ init.forEach((v, k) => {
64
+ out[k] = v;
65
+ });
66
+ }
67
+ else {
68
+ Object.assign(out, init);
69
+ }
70
+ }
71
+ catch {
72
+ return undefined;
73
+ }
74
+ // No headers is `undefined`, not `{}` — an empty object on every event is
75
+ // bytes in every batch for nothing.
76
+ return Object.keys(out).length > 0 ? out : undefined;
77
+ }
78
+ /**
79
+ * Install network capture.
80
+ *
81
+ * XHR when the host has it, which in React Native it always does. The `fetch`
82
+ * path is the fallback for a host that does not, and the two are never
83
+ * installed together — see the note at the top of this file.
84
+ *
85
+ * Returns a function that restores the originals.
86
+ */
87
+ export function installNetworkCapture(options) {
88
+ const xhr = globalThis.XMLHttpRequest;
89
+ const undo = [];
90
+ if (typeof xhr === 'function' && xhr.prototype) {
91
+ undo.push(installXhrCapture(xhr, options));
92
+ }
93
+ undo.push(installFetchCapture(options));
94
+ return () => {
95
+ for (const teardown of undo)
96
+ teardown();
97
+ };
98
+ }
99
+ /**
100
+ * Set for the synchronous portion of a patched `fetch` call, which is exactly
101
+ * when an XHR-backed fetch does its `open`/`send`.
102
+ *
103
+ * Module-level rather than per-install because there is only ever one of each
104
+ * global to patch, and JavaScript is single-threaded: no two fetch calls can
105
+ * be inside their synchronous portion at once.
106
+ */
107
+ let insideFetch = false;
108
+ /** Set by the XHR patch when it recognises the call it is serving as a fetch. */
109
+ let servedByXhr = false;
110
+ function installXhrCapture(xhr, options) {
111
+ const now = options.now ?? Date.now;
112
+ const proto = xhr.prototype;
113
+ if (proto[PATCH_MARKER]) {
114
+ // Already patched. Re-wrapping would double every event and stack
115
+ // wrappers that can never be unwound.
116
+ return () => { };
117
+ }
118
+ const originalOpen = proto.open;
119
+ const originalSend = proto.send;
120
+ const originalSetHeader = proto.setRequestHeader;
121
+ // Per-request state, keyed by the request. A WeakMap so an abandoned xhr
122
+ // takes its entry with it — this runs for the lifetime of the host app.
123
+ const pending = new WeakMap();
124
+ function patchedOpen(method, url, ...rest) {
125
+ try {
126
+ pending.set(this, {
127
+ method: String(method ?? 'GET').toUpperCase(),
128
+ url: String(url ?? ''),
129
+ headers: {},
130
+ started: 0,
131
+ });
132
+ }
133
+ catch {
134
+ // Capture must never affect the request it observed.
135
+ }
136
+ return originalOpen.call(this, method, url, ...rest);
137
+ }
138
+ function patchedSetHeader(name, value) {
139
+ try {
140
+ const state = pending.get(this);
141
+ // Redacted at report time, not here: the deny-list is remote config and
142
+ // may change between this call and the flush.
143
+ if (state)
144
+ state.headers[name] = value;
145
+ }
146
+ catch {
147
+ // As above.
148
+ }
149
+ return originalSetHeader.call(this, name, value);
150
+ }
151
+ function patchedSend(body) {
152
+ try {
153
+ const state = pending.get(this);
154
+ if (state && shouldCapture(state.url, options.ingestEndpoint, options.urlDenyList)) {
155
+ // Tell the fetch patch to stand down: this side has response headers
156
+ // and a buffered body, so it is the better of the two reports.
157
+ if (insideFetch)
158
+ servedByXhr = true;
159
+ state.started = now();
160
+ if (options.captureBodies) {
161
+ state.body = captureBody(body, headerValue(state.headers, 'content-type'), options.maskedKeys);
162
+ }
163
+ for (const reason of ['error', 'timeout', 'abort']) {
164
+ this.addEventListener(reason, () => {
165
+ const current = pending.get(this);
166
+ if (current)
167
+ current.reason = reason;
168
+ });
169
+ }
170
+ // `loadend` fires for success and every kind of failure alike, so one
171
+ // listener covers what the fetch path needs a try/catch pair for.
172
+ this.addEventListener('loadend', () => finish(this));
173
+ }
174
+ }
175
+ catch {
176
+ // As above.
177
+ }
178
+ return originalSend.call(this, body);
179
+ }
180
+ function finish(request) {
181
+ const state = pending.get(request);
182
+ if (!state)
183
+ return;
184
+ pending.delete(request);
185
+ try {
186
+ const status = request.status;
187
+ const event = {
188
+ url: sanitizeUrl(state.url),
189
+ method: state.method,
190
+ durationMs: now() - state.started,
191
+ requestHeaders: redactHeaders(state.headers, options.maskedKeys),
192
+ };
193
+ // Status 0 is "never got a response" — a connection failure, a timeout
194
+ // or an abort. It is not an HTTP status and must not be reported as one.
195
+ if (state.body !== undefined) {
196
+ event.requestBody = state.body;
197
+ }
198
+ if (status > 0) {
199
+ event.status = status;
200
+ const responseHeaders = parseResponseHeaders(request.getAllResponseHeaders());
201
+ event.responseHeaders = redactHeaders(responseHeaders, options.maskedKeys);
202
+ if (options.captureBodies) {
203
+ event.responseBody = readResponseBody(request, headerValue(responseHeaders ?? {}, 'content-type'), options.maskedKeys);
204
+ }
205
+ }
206
+ else {
207
+ event.error = FAILURE_TEXT[state.reason ?? 'error'];
208
+ }
209
+ report(options, event);
210
+ }
211
+ catch {
212
+ // As above.
213
+ }
214
+ }
215
+ proto.open = patchedOpen;
216
+ proto.setRequestHeader = patchedSetHeader;
217
+ proto.send = patchedSend;
218
+ proto[PATCH_MARKER] = true;
219
+ return () => {
220
+ // Only restore what is still ours — clobbering another library's wrapper
221
+ // would silently break its instrumentation.
222
+ if (proto.open === patchedOpen)
223
+ proto.open = originalOpen;
224
+ if (proto.setRequestHeader === patchedSetHeader)
225
+ proto.setRequestHeader = originalSetHeader;
226
+ if (proto.send === patchedSend)
227
+ proto.send = originalSend;
228
+ delete proto[PATCH_MARKER];
229
+ };
230
+ }
231
+ const FAILURE_TEXT = {
232
+ error: 'network error',
233
+ timeout: 'timeout',
234
+ abort: 'aborted',
235
+ };
236
+ /**
237
+ * Body capture cap, applied *after* redaction.
238
+ *
239
+ * Ingestion rejects any single event over 64 KB, and a rejected batch is
240
+ * indistinguishable from no traffic at all. Two bodies this size plus headers
241
+ * and a URL stay far inside that.
242
+ */
243
+ const MAX_BODY_CHARS = 4096;
244
+ function truncate(text) {
245
+ return text.length <= MAX_BODY_CHARS ? text : `${text.slice(0, MAX_BODY_CHARS)}…[truncated]`;
246
+ }
247
+ /** Header names are case-insensitive; whatever the caller typed is what we got. */
248
+ function headerValue(headers, name) {
249
+ const wanted = name.toLowerCase();
250
+ for (const key of Object.keys(headers)) {
251
+ if (key.toLowerCase() === wanted)
252
+ return String(headers[key] ?? '');
253
+ }
254
+ return '';
255
+ }
256
+ /** `application/json; charset=utf-8` → `application/json`. */
257
+ function mediaType(contentType) {
258
+ return (contentType.split(';')[0] ?? '').trim().toLowerCase();
259
+ }
260
+ /**
261
+ * Shape a body for storage, or say why it was not stored.
262
+ *
263
+ * JSON and form-encoded only, and that is the whole privacy argument: they are
264
+ * the two shapes `redact()` can walk by key. XML, protobuf, multipart and
265
+ * anything else cannot be key-redacted, and storing one raw is precisely the
266
+ * leak section 36 exists to prevent — so it is recorded by type and dropped.
267
+ *
268
+ * The limit worth stating plainly, because it does not go away: redaction
269
+ * matches *keys*, never values. `{"note": "my card is 4111…"}` ships intact.
270
+ * Body capture is a debugging tool for a project that has decided its bodies
271
+ * are safe to store. It is not a PII filter.
272
+ */
273
+ function captureBody(raw, contentType, maskedKeys) {
274
+ if (raw === undefined || raw === null || raw === '')
275
+ return undefined;
276
+ if (typeof raw !== 'string') {
277
+ // FormData, Blob, ArrayBuffer, a stream. Never read: reading one can
278
+ // consume it out from under the request, and none can be redacted by key.
279
+ return `[not captured: ${describeBody(raw)}]`;
280
+ }
281
+ const type = mediaType(contentType);
282
+ if (type === 'application/json' || type.endsWith('+json')) {
283
+ try {
284
+ return truncate(JSON.stringify(redact(JSON.parse(raw), maskedKeys)));
285
+ }
286
+ catch {
287
+ // Never fall back to the raw text: a body that does not parse is a body
288
+ // that cannot be redacted.
289
+ return '[not captured: malformed json]';
290
+ }
291
+ }
292
+ if (type === 'application/x-www-form-urlencoded') {
293
+ try {
294
+ const fields = {};
295
+ // `forEach` rather than iteration: React Native supplies its own
296
+ // URLSearchParams, and forEach is the part of it least likely to differ.
297
+ new URLSearchParams(raw).forEach((value, key) => {
298
+ fields[key] = value;
299
+ });
300
+ const out = new URLSearchParams();
301
+ for (const [key, value] of Object.entries(redact(fields, maskedKeys))) {
302
+ out.append(key, value);
303
+ }
304
+ return truncate(out.toString());
305
+ }
306
+ catch {
307
+ return '[not captured: malformed form data]';
308
+ }
309
+ }
310
+ return `[not captured: ${type || 'unknown content type'}]`;
311
+ }
312
+ /** Headers off a Response, before redaction, so content-type stays readable. */
313
+ function readHeaders(response) {
314
+ const headers = response.headers;
315
+ if (!headers || typeof headers.forEach !== 'function')
316
+ return undefined;
317
+ const out = {};
318
+ try {
319
+ headers.forEach((value, key) => {
320
+ out[key] = value;
321
+ });
322
+ }
323
+ catch {
324
+ return undefined;
325
+ }
326
+ return Object.keys(out).length > 0 ? out : undefined;
327
+ }
328
+ /**
329
+ * How large a response may be before its body is left alone.
330
+ *
331
+ * `clone()` buffers a second copy in the host app's memory, so this is not
332
+ * about our 4 KB storage cap — it is about not doubling a download nobody
333
+ * asked us to hold.
334
+ */
335
+ const MAX_CLONE_BYTES = 256 * 1024;
336
+ /**
337
+ * A promise for the response text, or null when the body should not be read.
338
+ *
339
+ * Only shapes `captureBody` can actually redact are worth cloning; everything
340
+ * else would cost the memory and then be replaced by a marker anyway.
341
+ */
342
+ function cloneForReading(response) {
343
+ if (typeof response.clone !== 'function')
344
+ return null;
345
+ const headers = readHeaders(response) ?? {};
346
+ const type = mediaType(headerValue(headers, 'content-type'));
347
+ const redactable = type === 'application/json' ||
348
+ type.endsWith('+json') ||
349
+ type === 'application/x-www-form-urlencoded';
350
+ if (!redactable)
351
+ return null;
352
+ const declared = Number(headerValue(headers, 'content-length'));
353
+ if (Number.isFinite(declared) && declared > MAX_CLONE_BYTES)
354
+ return null;
355
+ try {
356
+ return response.clone().text();
357
+ }
358
+ catch {
359
+ return null;
360
+ }
361
+ }
362
+ function describeBody(body) {
363
+ const name = body?.constructor?.name;
364
+ return name ? name.toLowerCase() : typeof body;
365
+ }
366
+ /**
367
+ * Read the response body, when it is readable at all.
368
+ *
369
+ * ponytail: text responses only. `responseText` throws unless `responseType`
370
+ * is `''` or `'text'`, and React Native's `fetch` sets it to `'blob'` — so
371
+ * axios and direct XHR give up their response bodies here and `fetch()` does
372
+ * not. Getting a blob would mean an async FileReader round-trip that delays
373
+ * the event past `loadend`; that is the upgrade path if it turns out to
374
+ * matter.
375
+ */
376
+ function readResponseBody(request, contentType, maskedKeys) {
377
+ // A host XHR that does not implement responseType at all reads as text,
378
+ // rather than as `[not captured: undefined response]`.
379
+ const type = request.responseType ?? '';
380
+ if (type !== '' && type !== 'text') {
381
+ return `[not captured: ${type} response]`;
382
+ }
383
+ try {
384
+ return captureBody(request.responseText, contentType, maskedKeys);
385
+ }
386
+ catch {
387
+ // The getter can still throw on a request that never reached LOADING.
388
+ return undefined;
389
+ }
390
+ }
391
+ /** `getAllResponseHeaders()` returns CRLF-delimited `name: value` lines. */
392
+ function parseResponseHeaders(raw) {
393
+ if (!raw)
394
+ return undefined;
395
+ const out = {};
396
+ for (const line of raw.split('\r\n')) {
397
+ const colon = line.indexOf(':');
398
+ if (colon === -1)
399
+ continue;
400
+ out[line.slice(0, colon).trim()] = line.slice(colon + 1).trim();
401
+ }
402
+ return Object.keys(out).length > 0 ? out : undefined;
403
+ }
404
+ /**
405
+ * Patch `fetch`.
406
+ *
407
+ * Reports only the requests the XHR patch did not already claim — in practice
408
+ * a native `fetch`, which is what Expo installs.
409
+ */
410
+ function installFetchCapture(options) {
411
+ const now = options.now ?? Date.now;
412
+ const target = globalThis;
413
+ const original = target.fetch;
414
+ if (typeof original !== 'function' || original[PATCH_MARKER]) {
415
+ // No fetch, or already patched. Re-wrapping would double-report and stack
416
+ // wrappers that can never be unwound.
417
+ return () => { };
418
+ }
419
+ const patched = async function patchedFetch(input, init) {
420
+ const url = typeof input === 'string' ? input : String(input);
421
+ const method = (init?.method ?? 'GET').toUpperCase();
422
+ if (!shouldCapture(url, options.ingestEndpoint, options.urlDenyList)) {
423
+ return original(input, init);
424
+ }
425
+ const started = now();
426
+ // An XHR-backed fetch does its open/send inside this call, synchronously,
427
+ // so `servedByXhr` is settled by the time the promise comes back.
428
+ let pending;
429
+ insideFetch = true;
430
+ servedByXhr = false;
431
+ try {
432
+ pending = original(input, init);
433
+ }
434
+ finally {
435
+ insideFetch = false;
436
+ }
437
+ const claimed = servedByXhr;
438
+ const requestBody = options.captureBodies
439
+ ? captureBody(init?.body, headerValue(headersToObject(init?.headers) ?? {}, 'content-type'), options.maskedKeys)
440
+ : undefined;
441
+ try {
442
+ const response = await pending;
443
+ if (claimed)
444
+ return response;
445
+ const event = {
446
+ url: sanitizeUrl(url),
447
+ method,
448
+ status: response.status,
449
+ durationMs: now() - started,
450
+ requestHeaders: redactHeaders(init?.headers, options.maskedKeys),
451
+ responseHeaders: redactHeaders(readHeaders(response), options.maskedKeys),
452
+ };
453
+ if (requestBody !== undefined)
454
+ event.requestBody = requestBody;
455
+ // Reading headers does not consume the body; reading the body does, so
456
+ // that goes through a clone and is reported when it resolves. The app
457
+ // gets its response either way, now, untouched.
458
+ const copy = options.captureBodies ? cloneForReading(response) : null;
459
+ if (copy) {
460
+ copy.then((text) => {
461
+ event.responseBody = captureBody(text, headerValue(readHeaders(response) ?? {}, 'content-type'), options.maskedKeys);
462
+ report(options, event);
463
+ }, () => report(options, event));
464
+ }
465
+ else {
466
+ report(options, event);
467
+ }
468
+ return response;
469
+ }
470
+ catch (error) {
471
+ if (!claimed) {
472
+ const event = {
473
+ url: sanitizeUrl(url),
474
+ method,
475
+ durationMs: now() - started,
476
+ error: error instanceof Error ? error.message : 'network error',
477
+ requestHeaders: redactHeaders(init?.headers, options.maskedKeys),
478
+ };
479
+ if (requestBody !== undefined)
480
+ event.requestBody = requestBody;
481
+ report(options, event);
482
+ }
483
+ // Rethrow untouched. The app's own error handling depends on it.
484
+ throw error;
485
+ }
486
+ };
487
+ patched[PATCH_MARKER] = true;
488
+ target.fetch = patched;
489
+ return () => {
490
+ // Only restore if nothing else patched on top of us — clobbering another
491
+ // library's wrapper would silently break its instrumentation.
492
+ if (target.fetch === patched) {
493
+ target.fetch = original;
494
+ }
495
+ };
496
+ }
497
+ function redactHeaders(headers, maskedKeys) {
498
+ const raw = headersToObject(headers);
499
+ if (!raw)
500
+ return undefined;
501
+ return redact(raw, maskedKeys);
502
+ }
503
+ function report(options, event) {
504
+ try {
505
+ options.onEvent(event);
506
+ }
507
+ catch {
508
+ // Capture must never affect the request it observed.
509
+ }
510
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Performance marks.
3
+ *
4
+ * ponytail: no native module. Real frame timing and startup instrumentation
5
+ * need one, which costs bundle size and breaks the Expo managed workflow for a
6
+ * signal most apps never look at (section 26).
7
+ *
8
+ * What is free and genuinely useful: how long the app took to become
9
+ * interactive, and durations the app chooses to measure itself.
10
+ */
11
+ export interface PerformanceMeasure {
12
+ name: string;
13
+ durationMs: number;
14
+ }
15
+ export declare function mark(name: string, now?: number): void;
16
+ /**
17
+ * Close a mark and return its duration.
18
+ *
19
+ * Returns null for an unknown mark rather than throwing or inventing a
20
+ * measurement — a mistyped name should lose a metric, not crash a screen.
21
+ */
22
+ export declare function measure(name: string, now?: number): PerformanceMeasure | null;
23
+ /**
24
+ * Time from SDK load to the moment the app declares itself ready.
25
+ *
26
+ * Measured from module load rather than process start, which is the earliest
27
+ * point reachable without a native module. It undercounts by however long the
28
+ * JS bundle took to reach this import — worth knowing when reading the number.
29
+ */
30
+ export declare function timeToReady(now?: number): PerformanceMeasure;
31
+ /** Test-only. */
32
+ export declare function resetMarks(): void;
33
+ export declare function openMarkCount(): number;
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Performance marks.
3
+ *
4
+ * ponytail: no native module. Real frame timing and startup instrumentation
5
+ * need one, which costs bundle size and breaks the Expo managed workflow for a
6
+ * signal most apps never look at (section 26).
7
+ *
8
+ * What is free and genuinely useful: how long the app took to become
9
+ * interactive, and durations the app chooses to measure itself.
10
+ */
11
+ /** Module load time, the earliest point the SDK can observe. */
12
+ const moduleLoadedAt = Date.now();
13
+ const marks = new Map();
14
+ /** Guard against an app that marks in a loop and never measures. */
15
+ const MAX_OPEN_MARKS = 100;
16
+ export function mark(name, now = Date.now()) {
17
+ if (marks.size >= MAX_OPEN_MARKS && !marks.has(name)) {
18
+ // Unbounded growth here would be the SDK leaking memory in someone else's
19
+ // app, which is exactly the failure mode we refuse to have.
20
+ return;
21
+ }
22
+ marks.set(name, now);
23
+ }
24
+ /**
25
+ * Close a mark and return its duration.
26
+ *
27
+ * Returns null for an unknown mark rather than throwing or inventing a
28
+ * measurement — a mistyped name should lose a metric, not crash a screen.
29
+ */
30
+ export function measure(name, now = Date.now()) {
31
+ const started = marks.get(name);
32
+ if (started === undefined) {
33
+ return null;
34
+ }
35
+ marks.delete(name);
36
+ return { name, durationMs: now - started };
37
+ }
38
+ /**
39
+ * Time from SDK load to the moment the app declares itself ready.
40
+ *
41
+ * Measured from module load rather than process start, which is the earliest
42
+ * point reachable without a native module. It undercounts by however long the
43
+ * JS bundle took to reach this import — worth knowing when reading the number.
44
+ */
45
+ export function timeToReady(now = Date.now()) {
46
+ return { name: 'app_ready', durationMs: now - moduleLoadedAt };
47
+ }
48
+ /** Test-only. */
49
+ export function resetMarks() {
50
+ marks.clear();
51
+ }
52
+ export function openMarkCount() {
53
+ return marks.size;
54
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Durable send queue.
3
+ *
4
+ * One file per batch, not one append-only log. A batch is therefore written
5
+ * and deleted atomically: a process killed mid-write leaves one unparseable
6
+ * file rather than a truncated line that corrupts everything after it in a
7
+ * shared log.
8
+ *
9
+ * Names sort oldest-first, so ordering falls out of `list()` without tracking
10
+ * an index that could disagree with what is on disk.
11
+ */
12
+ import type { EventBatch } from './types.ts';
13
+ import type { FileStore } from './store.ts';
14
+ export interface QueuedBatch {
15
+ name: string;
16
+ batch: EventBatch;
17
+ /** Send attempts so far. Used to give up on a batch nothing will accept. */
18
+ attempts: number;
19
+ }
20
+ export interface QueueOptions {
21
+ store: FileStore;
22
+ /**
23
+ * Ceiling on queued batches.
24
+ *
25
+ * An app offline for a week must not fill the user's storage. When full the
26
+ * oldest are dropped: recent events are closer to whatever the user is about
27
+ * to report, so they are worth more than the backlog.
28
+ */
29
+ maxBatches?: number;
30
+ /**
31
+ * Attempts before a batch is abandoned.
32
+ *
33
+ * Without this, one batch the server will never accept blocks the queue
34
+ * forever — the client-side version of a poison message (section 30).
35
+ */
36
+ maxAttempts?: number;
37
+ }
38
+ export declare class SendQueue {
39
+ private readonly store;
40
+ private readonly maxBatches;
41
+ private readonly maxAttempts;
42
+ private counter;
43
+ private droppedCount;
44
+ private abandonedCount;
45
+ constructor(options: QueueOptions);
46
+ /** Batches dropped because the queue was full. */
47
+ get dropped(): number;
48
+ /** Batches abandoned after exhausting their attempts. */
49
+ get abandoned(): number;
50
+ size(): Promise<number>;
51
+ /**
52
+ * Persist a batch for sending.
53
+ *
54
+ * Called before any network attempt, so a crash between capture and delivery
55
+ * loses nothing.
56
+ */
57
+ enqueue(batch: EventBatch, now?: number): Promise<string>;
58
+ /** Oldest queued batches, oldest first. */
59
+ peek(limit?: number): Promise<QueuedBatch[]>;
60
+ remove(name: string): Promise<void>;
61
+ /**
62
+ * Record a failed attempt.
63
+ *
64
+ * Returns false when the batch has been abandoned, so the caller knows it is
65
+ * gone rather than merely deferred.
66
+ */
67
+ recordFailure(entry: QueuedBatch): Promise<boolean>;
68
+ /** Drop oldest batches until the queue is under its ceiling. */
69
+ private prune;
70
+ }