@eventra_dev/eventra-sdk 2.0.5 → 2.0.6

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 CHANGED
@@ -1,10 +1,177 @@
1
+ // src/diagnostics.ts
2
+ var DROPPED_REASONS = /* @__PURE__ */ new Set([
3
+ "queue_full",
4
+ "invalid_event",
5
+ "too_large",
6
+ "rejected"
7
+ ]);
8
+ var FAILED_REASONS = /* @__PURE__ */ new Set([
9
+ "network",
10
+ "server_error",
11
+ "rate_limited",
12
+ "circuit_open"
13
+ ]);
14
+ var COUNT_MAX = 1e9;
15
+ var MemoryStore = class {
16
+ constructor() {
17
+ this.data = /* @__PURE__ */ new Map();
18
+ }
19
+ get(key) {
20
+ return this.data.get(key) ?? null;
21
+ }
22
+ set(key, value) {
23
+ this.data.set(key, value);
24
+ }
25
+ };
26
+ var SharedStore = class {
27
+ constructor(storage) {
28
+ this.storage = storage;
29
+ this.memory = new MemoryStore();
30
+ }
31
+ get(key) {
32
+ return this.storage.get(key) ?? this.memory.get(key);
33
+ }
34
+ set(key, value) {
35
+ this.memory.set(key, value);
36
+ this.storage.set(key, value);
37
+ }
38
+ };
39
+ function emptyCounts() {
40
+ return { dropped: 0, failed: 0, byReason: {} };
41
+ }
42
+ function isCount(value) {
43
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= COUNT_MAX;
44
+ }
45
+ function parseCounts(value) {
46
+ if (typeof value !== "object" || value === null) return null;
47
+ const v = value;
48
+ if (!isCount(v.dropped) || !isCount(v.failed)) return null;
49
+ const byReason = {};
50
+ const raw = v.byReason;
51
+ if (typeof raw === "object" && raw !== null) {
52
+ for (const [reason, count] of Object.entries(raw)) {
53
+ if ((DROPPED_REASONS.has(reason) || FAILED_REASONS.has(reason)) && isCount(count)) {
54
+ byReason[reason] = count;
55
+ }
56
+ }
57
+ }
58
+ const since = typeof v.since === "string" && !Number.isNaN(Date.parse(v.since)) ? v.since : void 0;
59
+ return { dropped: v.dropped, failed: v.failed, byReason, since };
60
+ }
61
+ function parseRecord(value) {
62
+ if (typeof value !== "object" || value === null) {
63
+ return { counts: emptyCounts() };
64
+ }
65
+ const v = value;
66
+ const counts = parseCounts(v.counts) ?? emptyCounts();
67
+ let pending;
68
+ const p = v.pending;
69
+ if (typeof p === "object" && p !== null && typeof p.reportId === "string") {
70
+ const pendingCounts = parseCounts(p.counts);
71
+ if (pendingCounts) pending = { reportId: p.reportId, counts: pendingCounts };
72
+ }
73
+ return { counts, pending };
74
+ }
75
+ function total(counts) {
76
+ return counts.dropped + counts.failed;
77
+ }
78
+ function add(into, from) {
79
+ into.dropped = Math.min(COUNT_MAX, into.dropped + from.dropped);
80
+ into.failed = Math.min(COUNT_MAX, into.failed + from.failed);
81
+ for (const [reason, count] of Object.entries(from.byReason)) {
82
+ into.byReason[reason] = Math.min(
83
+ COUNT_MAX,
84
+ (into.byReason[reason] ?? 0) + count
85
+ );
86
+ }
87
+ if (from.since && (!into.since || from.since < into.since)) {
88
+ into.since = from.since;
89
+ }
90
+ }
91
+ var Diagnostics = class {
92
+ constructor(store, key, newId, onChange = () => {
93
+ }) {
94
+ this.store = store;
95
+ this.key = key;
96
+ this.newId = newId;
97
+ this.onChange = onChange;
98
+ // not yet merged into the (possibly shared) record
99
+ this.local = emptyCounts();
100
+ this.dirty = false;
101
+ }
102
+ record(reason, n = 1) {
103
+ if (!(n > 0)) return;
104
+ const isDropped = DROPPED_REASONS.has(reason);
105
+ if (isDropped) {
106
+ this.local.dropped = Math.min(COUNT_MAX, this.local.dropped + n);
107
+ } else if (reason !== "circuit_open") {
108
+ this.local.failed = Math.min(COUNT_MAX, this.local.failed + n);
109
+ }
110
+ this.local.byReason[reason] = Math.min(
111
+ COUNT_MAX,
112
+ (this.local.byReason[reason] ?? 0) + n
113
+ );
114
+ this.local.since ??= (/* @__PURE__ */ new Date()).toISOString();
115
+ this.dirty = true;
116
+ this.onChange();
117
+ }
118
+ // writes the local counters into the shared record (debounced by the client,
119
+ // immediate on pagehide/destroy); a no-op when nothing changed
120
+ sync() {
121
+ if (!this.dirty) return;
122
+ const record = this.read();
123
+ add(record.counts, this.local);
124
+ this.local = emptyCounts();
125
+ this.dirty = false;
126
+ this.store.set(this.key, record);
127
+ }
128
+ // Moves the counters into a pending report and returns it; an unacknowledged
129
+ // pending report is returned again as it is. null when there is nothing to
130
+ // report or another tab claimed the same counters first.
131
+ claim(queued, sdkVersion) {
132
+ this.dirty = this.dirty || total(this.local) > 0;
133
+ this.sync();
134
+ const record = this.read();
135
+ if (!record.pending) {
136
+ if (total(record.counts) === 0) return null;
137
+ const reportId2 = this.newId();
138
+ record.pending = { reportId: reportId2, counts: record.counts };
139
+ record.counts = emptyCounts();
140
+ this.store.set(this.key, record);
141
+ const stored = this.read();
142
+ if (stored.pending?.reportId !== reportId2) return null;
143
+ }
144
+ const { reportId, counts } = record.pending;
145
+ return {
146
+ reportId,
147
+ since: counts.since ?? (/* @__PURE__ */ new Date()).toISOString(),
148
+ droppedTotal: counts.dropped,
149
+ failedTotal: counts.failed,
150
+ byReason: { ...counts.byReason },
151
+ queued,
152
+ sdkVersion
153
+ };
154
+ }
155
+ // the server accepted the batch the report travelled with
156
+ ack(reportId) {
157
+ const record = this.read();
158
+ if (record.pending?.reportId !== reportId) return;
159
+ record.pending = void 0;
160
+ this.store.set(this.key, record);
161
+ }
162
+ read() {
163
+ return parseRecord(this.store.get(this.key));
164
+ }
165
+ };
166
+
1
167
  // src/client.ts
2
168
  var SDK_NAME = "@eventra_dev/eventra-sdk";
3
169
  var DEFAULT_ENDPOINT = "https://api.eventra.dev/api/v1/ingest/batch";
4
- var SDK_VERSION = "2.0.5";
170
+ var SDK_VERSION = "2.0.6";
5
171
  var LEADER_KEY = "__eventra_leader__";
6
172
  var LEADER_TTL_MS = 4e3;
7
173
  var QUEUE_KEY = "__eventra_q__";
174
+ var DIAGNOSTICS_KEY = "__eventra_d__";
8
175
  var CHANNEL_NAME = "eventra-sdk";
9
176
  var MAX_EVENT_NAME = 64;
10
177
  var MAX_USER_ID = 120;
@@ -15,6 +182,12 @@ var DEFAULT_MAX_RETRY_DELAY_MS = 3e4;
15
182
  var FETCH_TIMEOUT_MS = 5e3;
16
183
  var CIRCUIT_FAILURE_THRESHOLD = 5;
17
184
  var CIRCUIT_COOLDOWN_MS = 5e3;
185
+ var CIRCUIT_COOLDOWN_MAX_MS = 6e4;
186
+ var RETRY_AFTER_MAX_MS = 3e4;
187
+ var PERSIST_DEBOUNCE_MS = 50;
188
+ var PERSISTED_EVENT_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1e3;
189
+ var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
190
+ var DELIVERED_KEYS_MAX = 1e4;
18
191
  var activeInstances = 0;
19
192
  function detectRuntime() {
20
193
  const g = globalThis;
@@ -56,9 +229,11 @@ function backoffMs(attempt, base) {
56
229
  const jitter = exp * (0.5 + Math.random() * 0.5);
57
230
  return jitter;
58
231
  }
232
+ var textEncoder;
59
233
  function utf8ByteLength(value) {
60
234
  if (typeof TextEncoder !== "undefined") {
61
- return new TextEncoder().encode(value).length;
235
+ textEncoder ??= new TextEncoder();
236
+ return textEncoder.encode(value).length;
62
237
  }
63
238
  const g = globalThis;
64
239
  if (g.Buffer) {
@@ -79,6 +254,12 @@ function mergeQueues(...queues) {
79
254
  return out;
80
255
  }
81
256
  function validateProperties(properties) {
257
+ let hasKeys = false;
258
+ for (const _ in properties) {
259
+ hasKeys = true;
260
+ break;
261
+ }
262
+ if (!hasKeys) return properties;
82
263
  const depth = (obj, level) => {
83
264
  if (level > MAX_PROPERTIES_DEPTH) {
84
265
  throw new Error(`Eventra: properties exceed max depth (${MAX_PROPERTIES_DEPTH})`);
@@ -101,18 +282,25 @@ function validateProperties(properties) {
101
282
  }
102
283
  return properties;
103
284
  }
104
- function estimateEnvelopeBytes(events, sdk, sentAt) {
105
- return utf8ByteLength(
106
- JSON.stringify({
107
- sentAt,
108
- sdk,
109
- events
110
- })
111
- );
285
+ function parseRetryAfterMs(value) {
286
+ if (!value) return void 0;
287
+ const trimmed = value.trim();
288
+ let ms;
289
+ if (/^\d+$/.test(trimmed)) {
290
+ ms = Number(trimmed) * 1e3;
291
+ } else {
292
+ const at = Date.parse(trimmed);
293
+ if (Number.isNaN(at)) return void 0;
294
+ ms = at - Date.now();
295
+ }
296
+ if (!(ms > 0)) return void 0;
297
+ return Math.min(ms, RETRY_AFTER_MAX_MS);
112
298
  }
113
299
  var RetryableDeliveryError = class extends Error {
114
- constructor(message = "retryable delivery error") {
300
+ constructor(message = "retryable delivery error", retryAfterMs, reason = "server_error") {
115
301
  super(message);
302
+ this.retryAfterMs = retryAfterMs;
303
+ this.reason = reason;
116
304
  this.name = "RetryableDeliveryError";
117
305
  }
118
306
  };
@@ -275,6 +463,17 @@ var Eventra = class {
275
463
  this.failureCount = 0;
276
464
  this.circuitOpenUntil = 0;
277
465
  this.circuitHalfOpen = false;
466
+ // consecutive times the circuit opened without a success in between; drives
467
+ // the exponential cooldown
468
+ this.circuitOpenCount = 0;
469
+ this.flushPromise = null;
470
+ this.persistDirty = false;
471
+ this.deliveredKeys = /* @__PURE__ */ new Set();
472
+ // a 429/5xx Retry-After that outlives the last attempt also delays the next
473
+ // flush (timer, size trigger, manual); shutdown() ignores it
474
+ this.nextFlushAt = 0;
475
+ // 0 = no limit; set by shutdown() so retries and sleeps cannot overrun it
476
+ this.shutdownDeadline = 0;
278
477
  this.exitHandlers = [];
279
478
  if (!options.apiKey) throw new Error("Eventra: apiKey required");
280
479
  activeInstances++;
@@ -298,6 +497,14 @@ var Eventra = class {
298
497
  this.retries = options.maxRetries ?? 3;
299
498
  this.retryDelay = options.retryBaseDelayMs ?? 300;
300
499
  this.persistQueue = options.persistQueue ?? true;
500
+ this.diagnosticsEnabled = options.diagnostics !== false;
501
+ const shared = this.runtime === "browser" && this.persistQueue;
502
+ this.diagnostics = new Diagnostics(
503
+ shared ? new SharedStore(this.storage) : new MemoryStore(),
504
+ DIAGNOSTICS_KEY,
505
+ uuidV4,
506
+ shared ? () => this.scheduleDiagnosticsSync() : void 0
507
+ );
301
508
  this.sdkInfo = {
302
509
  name: SDK_NAME,
303
510
  version: SDK_VERSION,
@@ -328,6 +535,7 @@ var Eventra = class {
328
535
  if (this.destroyed || this.shuttingDown) return;
329
536
  const eventName = normalizeEventName(name);
330
537
  if (eventName === null) {
538
+ this.recordDiagnostic("invalid_event");
331
539
  this.options.onEventsDropped?.(1);
332
540
  return;
333
541
  }
@@ -335,10 +543,12 @@ var Eventra = class {
335
543
  try {
336
544
  properties = validateProperties(options?.properties ?? {});
337
545
  } catch {
546
+ this.recordDiagnostic("invalid_event");
338
547
  this.options.onEventsDropped?.(1);
339
548
  return;
340
549
  }
341
550
  if (this.queue.length >= this.maxQueue) {
551
+ this.recordDiagnostic("queue_full");
342
552
  this.options.onEventsDropped?.(1);
343
553
  return;
344
554
  }
@@ -351,7 +561,8 @@ var Eventra = class {
351
561
  };
352
562
  this.queue.push(event);
353
563
  if (this.runtime === "browser") {
354
- this.syncQueue();
564
+ this.schedulePersist();
565
+ this.broadcast({ type: "queue-add", events: [event] });
355
566
  }
356
567
  if (this.queue.length >= this.maxBatch) {
357
568
  void this.flush();
@@ -361,8 +572,14 @@ var Eventra = class {
361
572
  }
362
573
  }
363
574
  async flush() {
575
+ return this.flushNow(false);
576
+ }
577
+ // `force` skips only the Retry-After delay (the last chance at shutdown);
578
+ // the circuit breaker still applies
579
+ async flushNow(force) {
364
580
  if (this.inFlight || this.destroyed) return;
365
581
  if (!this.queue.length && !this.sending?.length) return;
582
+ if (!force && Date.now() < this.nextFlushAt) return;
366
583
  if (this.leader && !this.leader.canSend()) return;
367
584
  const now = Date.now();
368
585
  if (now < this.circuitOpenUntil) return;
@@ -371,21 +588,46 @@ var Eventra = class {
371
588
  this.circuitOpenUntil = 0;
372
589
  }
373
590
  this.inFlight = true;
591
+ const run = this.runFlush();
592
+ this.flushPromise = run;
593
+ try {
594
+ await run;
595
+ } finally {
596
+ this.flushPromise = null;
597
+ }
598
+ }
599
+ async runFlush() {
374
600
  try {
375
601
  while (this.queue.length > 0) {
376
- const batch = this.buildBatch();
377
- if (!batch.length) break;
378
- this.sending = batch;
602
+ const report = this.diagnosticsEnabled ? this.diagnostics.claim(this.queue.length, SDK_VERSION) : null;
603
+ const batch = this.buildBatch(report);
604
+ if (!batch.events.length) break;
605
+ this.sending = batch.events;
379
606
  try {
380
- await this.send(batch);
381
- this.removeDelivered(batch);
607
+ const accepted = await this.send(batch);
608
+ if (accepted && batch.diagnostics) {
609
+ this.diagnostics.ack(batch.diagnostics.reportId);
610
+ }
611
+ this.removeDelivered(batch.events);
612
+ this.nextFlushAt = 0;
382
613
  this.failureCount = 0;
383
614
  this.circuitHalfOpen = false;
615
+ this.circuitOpenCount = 0;
384
616
  } catch (err) {
385
617
  if (err instanceof RetryableDeliveryError) {
618
+ this.recordDiagnostic(err.reason);
619
+ if (err.retryAfterMs) {
620
+ this.nextFlushAt = Date.now() + err.retryAfterMs;
621
+ }
386
622
  this.failureCount++;
387
623
  if (this.circuitHalfOpen || this.failureCount >= CIRCUIT_FAILURE_THRESHOLD) {
388
- this.circuitOpenUntil = Date.now() + CIRCUIT_COOLDOWN_MS;
624
+ this.recordDiagnostic("circuit_open");
625
+ const cooldown = Math.min(
626
+ CIRCUIT_COOLDOWN_MAX_MS,
627
+ CIRCUIT_COOLDOWN_MS * 2 ** this.circuitOpenCount
628
+ );
629
+ this.circuitOpenCount++;
630
+ this.circuitOpenUntil = Date.now() + Math.max(cooldown, err.retryAfterMs ?? 0);
389
631
  this.circuitHalfOpen = false;
390
632
  }
391
633
  break;
@@ -396,28 +638,44 @@ var Eventra = class {
396
638
  }
397
639
  if (this.circuitOpenUntil > Date.now()) break;
398
640
  }
399
- if (this.runtime === "browser") {
400
- this.syncQueue();
401
- }
402
641
  } finally {
403
642
  this.inFlight = false;
404
643
  }
405
644
  }
406
- /** Flush pending events, then tear down timers and listeners */
645
+ /**
646
+ * Flush pending events, then tear down timers and listeners. Gives up after
647
+ * `shutdownTimeoutMs` (default 10 s) so a dead or rate-limited server cannot
648
+ * hold a SIGTERM shutdown past a typical grace period.
649
+ */
407
650
  async shutdown() {
408
651
  if (this.shuttingDown) return;
409
652
  this.shuttingDown = true;
653
+ const budget = this.options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
654
+ this.shutdownDeadline = Date.now() + Math.max(0, budget);
655
+ let budgetTimer;
656
+ const outOfTime = new Promise((resolve) => {
657
+ budgetTimer = setTimeout(resolve, Math.max(0, budget));
658
+ budgetTimer.unref?.();
659
+ });
410
660
  try {
411
- await this.flush();
661
+ await Promise.race([this.flushEverything(), outOfTime]);
412
662
  } finally {
663
+ clearTimeout(budgetTimer);
413
664
  this.destroy();
414
665
  }
415
666
  }
667
+ async flushEverything() {
668
+ if (this.flushPromise) {
669
+ await this.flushPromise;
670
+ }
671
+ await this.flushNow(true);
672
+ }
416
673
  destroy() {
417
674
  if (this.destroyed) return;
418
675
  this.destroyed = true;
419
676
  activeInstances = Math.max(0, activeInstances - 1);
420
677
  if (this.timer) clearInterval(this.timer);
678
+ this.persistNow();
421
679
  this.leader?.destroy();
422
680
  if (this.channel) {
423
681
  this.channel.close();
@@ -430,65 +688,92 @@ var Eventra = class {
430
688
  off();
431
689
  }
432
690
  }
433
- buildBatch() {
434
- const batch = [];
691
+ buildBatch(report) {
692
+ const events = [];
693
+ const json = [];
435
694
  const sentAt = (/* @__PURE__ */ new Date()).toISOString();
695
+ const envelopeBytes = (withReport2) => utf8ByteLength(
696
+ JSON.stringify({
697
+ sentAt,
698
+ sdk: this.sdkInfo,
699
+ ...withReport2 && report ? { diagnostics: report } : {},
700
+ events: []
701
+ })
702
+ );
703
+ let withReport = report !== null;
704
+ let bytes = envelopeBytes(withReport);
436
705
  let index = 0;
437
- while (index < this.queue.length && batch.length < this.maxBatch) {
706
+ while (index < this.queue.length && events.length < this.maxBatch) {
438
707
  const event = this.queue[index];
439
- const candidate = [...batch, event];
440
- const bytes = estimateEnvelopeBytes(candidate, this.sdkInfo, sentAt);
441
- if (bytes > this.maxPayloadBytes) {
442
- if (batch.length === 0) {
443
- const poisonKey = event.idempotencyKey;
444
- this.dropPoisonEvent(event);
445
- if (this.queue[index]?.idempotencyKey === poisonKey) {
446
- index++;
708
+ const eventJson = JSON.stringify(event);
709
+ const total2 = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);
710
+ if (total2 > this.maxPayloadBytes) {
711
+ if (events.length === 0) {
712
+ if (withReport) {
713
+ withReport = false;
714
+ bytes = envelopeBytes(false);
715
+ continue;
447
716
  }
717
+ this.dropPoisonEvent(event);
718
+ withReport = report !== null;
719
+ bytes = envelopeBytes(withReport);
448
720
  continue;
449
721
  }
450
722
  break;
451
723
  }
452
- batch.push(event);
724
+ events.push(event);
725
+ json.push(eventJson);
726
+ bytes = total2;
453
727
  index++;
454
728
  }
455
- return batch;
729
+ return {
730
+ events,
731
+ json,
732
+ bytes,
733
+ diagnostics: withReport && report ? report : void 0
734
+ };
456
735
  }
457
736
  dropPoisonEvent(event) {
737
+ this.recordDiagnostic("too_large");
458
738
  this.removeDelivered([event]);
459
739
  this.options.onEventsDropped?.(1);
460
740
  this.options.onDeliveryFailed?.({ status: 413, events: [event] });
461
- if (this.runtime === "browser") {
462
- this.syncQueue();
463
- }
464
741
  }
465
742
  removeDelivered(batch) {
466
743
  const keys = new Set(batch.map((e) => e.idempotencyKey));
467
744
  this.queue = this.queue.filter((e) => !keys.has(e.idempotencyKey));
468
- }
469
- async send(events) {
470
- let payload;
471
- try {
472
- payload = JSON.stringify({
745
+ if (this.runtime === "browser") {
746
+ this.rememberDelivered(keys);
747
+ this.schedulePersist();
748
+ this.broadcast({ type: "delivered", keys: [...keys] });
749
+ }
750
+ }
751
+ // Resolves true only when the server answered 2xx for a payload that
752
+ // carried the diagnostics report (the only case that acknowledges it).
753
+ async send(batch) {
754
+ const { events } = batch;
755
+ let carriesDiagnostics = batch.diagnostics !== void 0;
756
+ const buildPayload = (withDiagnostics) => {
757
+ const head = JSON.stringify({
473
758
  sentAt: (/* @__PURE__ */ new Date()).toISOString(),
474
759
  sdk: this.sdkInfo,
475
- events
760
+ ...withDiagnostics && batch.diagnostics ? { diagnostics: batch.diagnostics } : {}
476
761
  });
477
- } catch {
478
- this.options.onDeliveryFailed?.({ status: 0, events });
479
- this.removeDelivered(events);
480
- return;
481
- }
482
- const payloadBytes = utf8ByteLength(payload);
762
+ return `${head.slice(0, -1)},"events":[${batch.json.join(",")}]}`;
763
+ };
764
+ let payload = buildPayload(carriesDiagnostics);
765
+ const payloadBytes = batch.bytes;
483
766
  if (payloadBytes > this.maxPayloadBytes) {
484
767
  this.dropPoisonEvents(events);
485
- return;
768
+ return false;
486
769
  }
487
770
  const useKeepalive = this.runtime === "browser" && typeof document !== "undefined" && document.visibilityState === "hidden" && payloadBytes <= this.maxPayloadBytes;
488
- const maxAttempts = Math.max(1, this.retries);
771
+ const maxAttempts = this.circuitHalfOpen ? 1 : Math.max(1, this.retries);
772
+ let strippedDiagnostics = false;
489
773
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
490
774
  const controller = new AbortController();
491
- const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
775
+ const attemptTimeoutMs = this.shutdownDeadline > 0 ? Math.max(1, Math.min(FETCH_TIMEOUT_MS, this.shutdownDeadline - Date.now())) : FETCH_TIMEOUT_MS;
776
+ const timeout = setTimeout(() => controller.abort(), attemptTimeoutMs);
492
777
  try {
493
778
  const res = await this.fetch(this.endpoint, {
494
779
  method: "POST",
@@ -501,27 +786,47 @@ var Eventra = class {
501
786
  keepalive: useKeepalive
502
787
  });
503
788
  if (res.status === 429 || res.status >= 500) {
504
- throw new RetryableDeliveryError();
789
+ throw new RetryableDeliveryError(
790
+ "retryable delivery error",
791
+ parseRetryAfterMs(res.headers?.get?.("retry-after")),
792
+ res.status === 429 ? "rate_limited" : "server_error"
793
+ );
505
794
  }
506
795
  if (res.status >= 400 && res.status < 500) {
796
+ if (carriesDiagnostics && (res.status === 400 || res.status === 422)) {
797
+ carriesDiagnostics = false;
798
+ strippedDiagnostics = true;
799
+ payload = buildPayload(false);
800
+ attempt--;
801
+ continue;
802
+ }
803
+ this.recordDiagnostic("rejected", events.length);
507
804
  this.options.onDeliveryFailed?.({ status: res.status, events });
508
805
  this.removeDelivered(events);
509
- return;
806
+ return false;
510
807
  }
511
808
  if (!res.ok) {
512
809
  throw new RetryableDeliveryError();
513
810
  }
514
- return;
811
+ if (strippedDiagnostics) {
812
+ this.diagnosticsEnabled = false;
813
+ return false;
814
+ }
815
+ return carriesDiagnostics;
515
816
  } catch (err) {
516
817
  const isLast = attempt >= maxAttempts - 1;
517
- if (isLast) {
518
- throw err instanceof RetryableDeliveryError ? err : new RetryableDeliveryError();
818
+ const retryAfter = err instanceof RetryableDeliveryError ? err.retryAfterMs : void 0;
819
+ const wait = Math.max(backoffMs(attempt, this.retryDelay), retryAfter ?? 0);
820
+ const outOfBudget = this.shutdownDeadline > 0 && Date.now() + wait >= this.shutdownDeadline;
821
+ if (isLast || outOfBudget) {
822
+ throw err instanceof RetryableDeliveryError ? err : new RetryableDeliveryError("retryable delivery error", void 0, "network");
519
823
  }
520
- await sleep(backoffMs(attempt + 1, this.retryDelay));
824
+ await sleep(wait);
521
825
  } finally {
522
826
  clearTimeout(timeout);
523
827
  }
524
828
  }
829
+ return false;
525
830
  }
526
831
  // Only caller is the defensive re-check in send() above, which is itself
527
832
  // unreachable in practice (see comment there) — see the same file's
@@ -533,39 +838,87 @@ var Eventra = class {
533
838
  }
534
839
  }
535
840
  /* v8 ignore stop */
841
+ recordDiagnostic(reason, n = 1) {
842
+ if (this.diagnosticsEnabled) this.diagnostics.record(reason, n);
843
+ }
844
+ // counters reach localStorage on the same debounce as the queue
845
+ scheduleDiagnosticsSync() {
846
+ if (this.persistTimer !== void 0) return;
847
+ this.persistTimer = setTimeout(() => {
848
+ this.persistTimer = void 0;
849
+ this.persistNow();
850
+ }, PERSIST_DEBOUNCE_MS);
851
+ }
536
852
  loadAndMergeQueue() {
537
853
  const remote = this.storage.get(QUEUE_KEY);
538
854
  if (Array.isArray(remote)) {
539
- this.queue = mergeQueues(this.queue, remote);
540
- }
541
- this.trimQueue();
855
+ const fresh = this.withoutExpired(remote);
856
+ if (fresh.length !== remote.length) this.persistDirty = true;
857
+ this.queue = mergeQueues(this.queue, this.withoutDelivered(fresh));
858
+ }
859
+ this.queue = this.trimQueue();
860
+ }
861
+ // events whose timestamp is unreadable are kept: their age cannot be judged
862
+ withoutExpired(events) {
863
+ const oldest = Date.now() - PERSISTED_EVENT_MAX_AGE_MS;
864
+ return events.filter((e) => {
865
+ const at = Date.parse(e?.timestamp);
866
+ return Number.isNaN(at) || at >= oldest;
867
+ });
542
868
  }
543
- syncQueue() {
544
- if (this.persistQueue) {
545
- const remote = this.storage.get(QUEUE_KEY);
546
- const merged = mergeQueues(
547
- Array.isArray(remote) ? remote : [],
548
- this.queue
549
- );
550
- this.queue = this.trimQueue(merged);
551
- this.storage.set(QUEUE_KEY, this.queue);
552
- } else {
553
- this.queue = this.trimQueue();
554
- }
555
- this.broadcastQueue();
869
+ withoutDelivered(events) {
870
+ if (!this.deliveredKeys.size) return events;
871
+ return events.filter((e) => !this.deliveredKeys.has(e.idempotencyKey));
872
+ }
873
+ rememberDelivered(keys) {
874
+ for (const key of keys) this.deliveredKeys.add(key);
875
+ for (const key of this.deliveredKeys) {
876
+ if (this.deliveredKeys.size <= DELIVERED_KEYS_MAX) break;
877
+ this.deliveredKeys.delete(key);
878
+ }
879
+ }
880
+ // Burst of track() calls = one write. Reading, merging and rewriting the
881
+ // whole queue on every call made each call cost O(queue size).
882
+ schedulePersist() {
883
+ if (!this.persistQueue) return;
884
+ this.persistDirty = true;
885
+ if (this.persistTimer !== void 0) return;
886
+ this.persistTimer = setTimeout(() => {
887
+ this.persistTimer = void 0;
888
+ this.persistNow();
889
+ }, PERSIST_DEBOUNCE_MS);
890
+ }
891
+ // Immediate write of the pending state (pagehide, tab hidden, destroy).
892
+ // Merges what other tabs wrote first, so concurrent tabs never overwrite
893
+ // each other's events; delivered events are filtered out so they stay gone.
894
+ persistNow() {
895
+ if (this.persistTimer !== void 0) {
896
+ clearTimeout(this.persistTimer);
897
+ this.persistTimer = void 0;
898
+ }
899
+ this.diagnostics.sync();
900
+ if (!this.persistQueue || !this.persistDirty) return;
901
+ this.persistDirty = false;
902
+ const remote = this.storage.get(QUEUE_KEY);
903
+ const merged = mergeQueues(
904
+ Array.isArray(remote) ? this.withoutDelivered(this.withoutExpired(remote)) : [],
905
+ this.queue
906
+ );
907
+ this.queue = this.trimQueue(merged);
908
+ this.storage.set(QUEUE_KEY, this.queue);
556
909
  }
557
910
  trimQueue(queue = this.queue) {
558
911
  if (queue.length <= this.maxQueue) return queue;
559
912
  const dropped = queue.length - this.maxQueue;
913
+ this.recordDiagnostic("queue_full", dropped);
560
914
  this.options.onEventsDropped?.(dropped);
561
915
  return queue.slice(-this.maxQueue);
562
916
  }
563
- broadcastQueue() {
917
+ // Sends only what changed (a new event, or the keys just delivered) instead
918
+ // of structured-cloning the whole queue on every call.
919
+ broadcast(message) {
564
920
  try {
565
- this.channel?.postMessage({
566
- type: "queue-sync",
567
- events: this.queue
568
- });
921
+ this.channel?.postMessage(message);
569
922
  } catch {
570
923
  }
571
924
  }
@@ -573,8 +926,17 @@ var Eventra = class {
573
926
  if (typeof BroadcastChannel !== "undefined") {
574
927
  this.channel = new BroadcastChannel(CHANNEL_NAME);
575
928
  this.channel.onmessage = (e) => {
576
- if (e.data?.type !== "queue-sync" || !Array.isArray(e.data.events)) return;
577
- this.queue = mergeQueues(this.queue, e.data.events);
929
+ const data = e.data;
930
+ if (data?.type === "delivered" && Array.isArray(data.keys)) {
931
+ const keys = new Set(data.keys);
932
+ this.rememberDelivered(keys);
933
+ this.queue = this.queue.filter((ev) => !keys.has(ev.idempotencyKey));
934
+ return;
935
+ }
936
+ if (data?.type !== "queue-add" && data?.type !== "queue-sync" || !Array.isArray(data.events)) {
937
+ return;
938
+ }
939
+ this.queue = mergeQueues(this.queue, this.withoutDelivered(data.events));
578
940
  this.queue = this.trimQueue();
579
941
  };
580
942
  }
@@ -590,14 +952,17 @@ var Eventra = class {
590
952
  this.timer = setInterval(() => {
591
953
  void this.flush();
592
954
  }, this.flushInterval);
955
+ this.timer.unref?.();
593
956
  }
594
957
  setupBrowserExit() {
595
958
  const handler = () => {
596
959
  if (document.visibilityState === "hidden") {
960
+ this.persistNow();
597
961
  void this.flush();
598
962
  }
599
963
  };
600
964
  const pageHide = () => {
965
+ this.persistNow();
601
966
  void this.flush();
602
967
  };
603
968
  document.addEventListener("visibilitychange", handler);
@@ -610,14 +975,31 @@ var Eventra = class {
610
975
  setupProcessExit() {
611
976
  const proc = globalThis.process;
612
977
  if (!proc?.on) return;
613
- const onSignal = () => {
614
- void this.shutdown();
978
+ const exitOnSignal = this.options.exitOnSignal === true;
979
+ const onSignal = (signal) => () => {
980
+ void this.shutdown().finally(() => {
981
+ if (!exitOnSignal) return;
982
+ proc.off?.(signal, handlers[signal]);
983
+ const othersListening = (proc.listenerCount?.(signal) ?? 0) > 0;
984
+ if (!othersListening && proc.kill && proc.pid !== void 0) {
985
+ proc.kill(proc.pid, signal);
986
+ }
987
+ });
988
+ };
989
+ const handlers = {
990
+ SIGINT: onSignal("SIGINT"),
991
+ SIGTERM: onSignal("SIGTERM")
992
+ };
993
+ const onBeforeExit = () => {
994
+ if (this.queue.length) void this.flush();
615
995
  };
616
- proc.once("SIGINT", onSignal);
617
- proc.once("SIGTERM", onSignal);
996
+ proc.once("SIGINT", handlers.SIGINT);
997
+ proc.once("SIGTERM", handlers.SIGTERM);
998
+ proc.once("beforeExit", onBeforeExit);
618
999
  this.exitHandlers.push(() => {
619
- proc.off?.("SIGINT", onSignal);
620
- proc.off?.("SIGTERM", onSignal);
1000
+ proc.off?.("SIGINT", handlers.SIGINT);
1001
+ proc.off?.("SIGTERM", handlers.SIGTERM);
1002
+ proc.off?.("beforeExit", onBeforeExit);
621
1003
  });
622
1004
  }
623
1005
  };