@eventra_dev/eventra-sdk 2.0.11 → 2.0.12

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.cjs CHANGED
@@ -193,7 +193,7 @@ var Diagnostics = class {
193
193
  // src/client.ts
194
194
  var SDK_NAME = "@eventra_dev/eventra-sdk";
195
195
  var DEFAULT_ENDPOINT = "https://api.eventra.dev/api/v1/ingest/batch";
196
- var SDK_VERSION = "2.0.11";
196
+ var SDK_VERSION = "2.0.12";
197
197
  var LEADER_KEY = "__eventra_leader__";
198
198
  var LEADER_TTL_MS = 4e3;
199
199
  var QUEUE_KEY = "__eventra_q__";
@@ -213,6 +213,7 @@ var RETRY_AFTER_MAX_MS = 3e4;
213
213
  var PERSIST_DEBOUNCE_MS = 50;
214
214
  var PERSISTED_EVENT_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1e3;
215
215
  var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
216
+ var KEEPALIVE_MAX_BYTES = 6e4;
216
217
  var DELIVERED_KEYS_MAX = 1e4;
217
218
  var activeInstances = 0;
218
219
  function detectRuntime() {
@@ -228,27 +229,97 @@ function uuidV4() {
228
229
  return crypto.randomUUID();
229
230
  }
230
231
  if (typeof crypto !== "undefined" && crypto.getRandomValues) {
231
- const bytes = new Uint8Array(16);
232
- crypto.getRandomValues(bytes);
233
- bytes[6] = bytes[6] & 15 | 64;
234
- bytes[8] = bytes[8] & 63 | 128;
235
- const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
236
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
237
- }
238
- throw new Error("Eventra: crypto API unavailable \u2014 cannot generate idempotencyKey");
232
+ const bytes2 = new Uint8Array(16);
233
+ crypto.getRandomValues(bytes2);
234
+ bytes2[6] = bytes2[6] & 15 | 64;
235
+ bytes2[8] = bytes2[8] & 63 | 128;
236
+ const hex2 = [...bytes2].map((b) => b.toString(16).padStart(2, "0")).join("");
237
+ return `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20)}`;
238
+ }
239
+ const bytes = new Uint8Array(16);
240
+ for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
241
+ let t = Date.now();
242
+ for (let i = 0; i < 6; i++) {
243
+ bytes[i] ^= t & 255;
244
+ t = Math.floor(t / 256);
245
+ }
246
+ bytes[6] = bytes[6] & 15 | 64;
247
+ bytes[8] = bytes[8] & 63 | 128;
248
+ const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
249
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
250
+ }
251
+ var MAX_TIMER_MS = 2147483647;
252
+ var MAX_RETRIES = 20;
253
+ function isUrl(value) {
254
+ try {
255
+ new URL(value);
256
+ return true;
257
+ } catch {
258
+ return false;
259
+ }
260
+ }
261
+ function warnOption(name, value, fallback) {
262
+ if (typeof console !== "undefined") {
263
+ console.warn(`Eventra: option "${name}" is invalid (${String(value)}), using ${String(fallback)}`);
264
+ }
265
+ }
266
+ function numberOption(name, value, fallback, min, max = Number.MAX_SAFE_INTEGER) {
267
+ if (value === void 0) return fallback;
268
+ if (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max) return value;
269
+ warnOption(name, value, fallback);
270
+ return fallback;
271
+ }
272
+ function callSafely(callback, ...args) {
273
+ if (!callback) return;
274
+ try {
275
+ const result = callback(...args);
276
+ if (result && typeof result.catch === "function") {
277
+ result.catch(() => void 0);
278
+ }
279
+ } catch {
280
+ }
281
+ }
282
+ function raceAbort(request, signal) {
283
+ return new Promise((resolve, reject) => {
284
+ const onAbort = () => reject(Object.assign(new Error("Eventra: request timed out"), { name: "AbortError" }));
285
+ signal.addEventListener("abort", onAbort, { once: true });
286
+ request.then(
287
+ (value) => {
288
+ signal.removeEventListener("abort", onAbort);
289
+ resolve(value);
290
+ },
291
+ (error) => {
292
+ signal.removeEventListener("abort", onAbort);
293
+ reject(error);
294
+ }
295
+ );
296
+ });
297
+ }
298
+ function discardBody(res) {
299
+ try {
300
+ const closing = res.body?.cancel?.();
301
+ if (closing && typeof closing.catch === "function") closing.catch(() => void 0);
302
+ } catch {
303
+ }
239
304
  }
240
305
  function sleep(ms) {
241
306
  return new Promise((r) => setTimeout(r, ms));
242
307
  }
243
- function truncate(value, max) {
244
- if (value === void 0) return void 0;
245
- return value.length > max ? value.slice(0, max) : value;
308
+ function cut(value, max) {
309
+ if (value.length <= max) return value;
310
+ const end = value.charCodeAt(max - 1) >= 55296 && value.charCodeAt(max - 1) <= 56319 ? max - 1 : max;
311
+ return value.slice(0, end);
312
+ }
313
+ function normalizeUserId(value, max) {
314
+ if (typeof value === "bigint" || typeof value === "number" && Number.isFinite(value)) return cut(String(value), max);
315
+ if (typeof value !== "string") return void 0;
316
+ return cut(value, max);
246
317
  }
247
318
  function normalizeEventName(name) {
248
319
  if (typeof name !== "string") return null;
249
320
  const trimmed = name.trim();
250
321
  if (!trimmed) return null;
251
- return trimmed.length > MAX_EVENT_NAME ? trimmed.slice(0, MAX_EVENT_NAME) : trimmed;
322
+ return cut(trimmed, MAX_EVENT_NAME).trimEnd();
252
323
  }
253
324
  function backoffMs(attempt, base) {
254
325
  const exp = Math.min(DEFAULT_MAX_RETRY_DELAY_MS, base * 2 ** attempt);
@@ -267,46 +338,65 @@ function utf8ByteLength(value) {
267
338
  }
268
339
  return value.length;
269
340
  }
341
+ function isStoredEvent(e) {
342
+ if (e === null || typeof e !== "object") return false;
343
+ const ev = e;
344
+ return typeof ev.idempotencyKey === "string" && ev.idempotencyKey.length > 0 && ev.idempotencyKey.length <= 100 && typeof ev.name === "string" && ev.name.length > 0 && ev.name.length <= MAX_EVENT_NAME && typeof ev.timestamp === "string" && (ev.userId === void 0 || typeof ev.userId === "string" && ev.userId.length <= MAX_USER_ID) && (ev.properties === void 0 || ev.properties !== null && typeof ev.properties === "object" && !Array.isArray(ev.properties));
345
+ }
270
346
  function mergeQueues(...queues) {
271
347
  const seen = /* @__PURE__ */ new Set();
272
348
  const out = [];
273
349
  for (const q of queues) {
274
350
  for (const e of q) {
351
+ if (!isStoredEvent(e)) continue;
275
352
  if (seen.has(e.idempotencyKey)) continue;
276
353
  seen.add(e.idempotencyKey);
277
- out.push(e);
354
+ out.push(Number.isNaN(Date.parse(e.timestamp)) ? { ...e, timestamp: (/* @__PURE__ */ new Date()).toISOString() } : e);
278
355
  }
279
356
  }
280
357
  return out;
281
358
  }
359
+ var MAX_PROPERTIES_NODES = 5e4;
282
360
  function validateProperties(properties) {
361
+ if (properties === null || typeof properties !== "object" || Array.isArray(properties) || // a Date, a Map, a Set, a RegExp: objects, but not a bag of named values
362
+ Object.prototype.toString.call(properties) !== "[object Object]") {
363
+ throw new Error("Eventra: properties must be an object");
364
+ }
283
365
  let hasKeys = false;
284
366
  for (const _ in properties) {
285
367
  hasKeys = true;
286
368
  break;
287
369
  }
288
- if (!hasKeys) return properties;
370
+ if (!hasKeys) return {};
371
+ let visited = 0;
289
372
  const depth = (obj, level) => {
290
373
  if (level > MAX_PROPERTIES_DEPTH) {
291
374
  throw new Error(`Eventra: properties exceed max depth (${MAX_PROPERTIES_DEPTH})`);
292
375
  }
376
+ if (++visited > MAX_PROPERTIES_NODES) {
377
+ throw new Error("Eventra: properties are too large to check");
378
+ }
293
379
  if (obj === null || typeof obj !== "object") return;
294
380
  if (Array.isArray(obj)) {
295
381
  for (const item of obj) depth(item, level + 1);
296
382
  return;
297
383
  }
298
- for (const value of Object.values(obj)) {
299
- depth(value, level + 1);
384
+ for (const key in obj) {
385
+ if (Object.prototype.hasOwnProperty.call(obj, key)) depth(obj[key], level + 1);
300
386
  }
301
387
  };
302
388
  depth(properties, 0);
303
389
  const json = JSON.stringify(properties);
304
- if (utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
390
+ if (json === void 0 || utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
305
391
  throw new Error(
306
392
  `Eventra: properties exceed max size (${MAX_PROPERTIES_JSON_BYTES} bytes)`
307
393
  );
308
394
  }
309
- return properties;
395
+ const copy = JSON.parse(json);
396
+ if (copy === null || typeof copy !== "object" || Array.isArray(copy)) {
397
+ throw new Error("Eventra: properties must be an object");
398
+ }
399
+ return copy;
310
400
  }
311
401
  function parseRetryAfterMs(value) {
312
402
  if (!value) return void 0;
@@ -371,12 +461,19 @@ var Storage = class {
371
461
  }
372
462
  /* v8 ignore stop */
373
463
  };
464
+ function storageAvailable() {
465
+ try {
466
+ return typeof localStorage !== "undefined" && localStorage !== null;
467
+ } catch {
468
+ return false;
469
+ }
470
+ }
374
471
  var Leader = class {
375
472
  constructor(onLeadershipChange) {
376
473
  this.onLeadershipChange = onLeadershipChange;
377
474
  this.tabId = uuidV4();
378
475
  this.isLeader = false;
379
- if (typeof localStorage === "undefined") {
476
+ if (!storageAvailable()) {
380
477
  this.isLeader = true;
381
478
  return;
382
479
  }
@@ -463,7 +560,7 @@ var Leader = class {
463
560
  if (this.onStorage && typeof window !== "undefined") {
464
561
  window.removeEventListener("storage", this.onStorage);
465
562
  }
466
- if (this.isLeader && typeof localStorage !== "undefined") {
563
+ if (this.isLeader && storageAvailable()) {
467
564
  try {
468
565
  const raw = localStorage.getItem(LEADER_KEY);
469
566
  if (raw) {
@@ -522,70 +619,128 @@ var Eventra = class {
522
619
  this.nextFlushAt = 0;
523
620
  // 0 = no limit; set by shutdown() so retries and sleeps cannot overrun it
524
621
  this.shutdownDeadline = 0;
622
+ this.shutdownBudget = DEFAULT_SHUTDOWN_TIMEOUT_MS;
623
+ // the page is being left (`pagehide`)
624
+ this.leaving = false;
525
625
  this.exitHandlers = [];
526
- if (!options.apiKey) throw new Error("Eventra: apiKey required");
626
+ if (!options || typeof options !== "object" || typeof options.apiKey !== "string" || !options.apiKey) {
627
+ throw new Error('Eventra: apiKey required - new Eventra({ apiKey: "..." })');
628
+ }
629
+ if (/[^\u0020-\u00ff]/.test(options.apiKey)) {
630
+ throw new Error("Eventra: apiKey has characters that cannot be sent in a header - copy it again from the dashboard");
631
+ }
632
+ if (options.fetchImpl !== void 0 && typeof options.fetchImpl !== "function") {
633
+ throw new Error("Eventra: fetchImpl must be a function");
634
+ }
527
635
  activeInstances++;
528
636
  if (activeInstances > 1 && typeof console !== "undefined") {
529
637
  console.warn(
530
- "Eventra: multiple SDK instances detected \u2014 duplicate timers and sends are possible"
638
+ "Eventra: multiple SDK instances detected - duplicate timers and sends are possible"
531
639
  );
532
640
  }
533
- this.options = options;
534
- this.apiKey = options.apiKey;
535
- this.endpoint = options.endpoint ?? DEFAULT_ENDPOINT;
536
- this.runtime = detectRuntime();
537
- warnIfInsecureEndpoint(this.endpoint);
538
- this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
539
- if (!this.fetch) {
540
- throw new Error("Eventra: fetch not available \u2014 provide fetchImpl");
541
- }
542
- this.maxBatch = options.maxBatchSize ?? 50;
543
- this.maxQueue = options.maxQueueSize ?? 1e4;
544
- this.maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
545
- this.flushInterval = options.flushInterval ?? 2e3;
546
- this.retries = options.maxRetries ?? 3;
547
- this.retryDelay = options.retryBaseDelayMs ?? 300;
548
- this.persistQueue = options.persistQueue ?? true;
549
- this.diagnosticsEnabled = options.diagnostics !== false;
550
- const shared = this.runtime === "browser" && this.persistQueue;
551
- this.diagnostics = new Diagnostics(
552
- shared ? new SharedStore(this.storage) : new MemoryStore(),
553
- DIAGNOSTICS_KEY,
554
- uuidV4,
555
- shared ? () => this.scheduleDiagnosticsSync() : void 0
556
- );
557
- this.sdkInfo = {
558
- name: SDK_NAME,
559
- version: SDK_VERSION,
560
- runtime: this.runtime
561
- };
562
- if (this.runtime === "browser") {
563
- if (this.persistQueue) {
564
- this.loadAndMergeQueue();
641
+ try {
642
+ this.options = options;
643
+ this.apiKey = options.apiKey;
644
+ if (options.endpoint !== void 0 && (typeof options.endpoint !== "string" || !options.endpoint.trim())) {
645
+ warnOption("endpoint", options.endpoint, DEFAULT_ENDPOINT);
565
646
  }
566
- this.setupQueueSync();
567
- }
568
- if (this.runtime === "browser" && options.multiTabMode === "leader") {
569
- this.leader = new Leader((isLeader) => {
570
- if (isLeader) void this.flush();
571
- });
572
- }
573
- if (!options.disableTimer) {
574
- this.startTimer();
575
- }
576
- if (this.runtime === "browser") {
577
- this.setupBrowserExit();
578
- }
579
- if (options.autoFlushOnExit !== false && this.runtime !== "browser") {
580
- this.setupProcessExit();
647
+ this.endpoint = typeof options.endpoint === "string" && options.endpoint.trim() ? options.endpoint.trim() : DEFAULT_ENDPOINT;
648
+ if (this.endpoint !== DEFAULT_ENDPOINT && !isUrl(this.endpoint)) {
649
+ warnOption("endpoint", this.endpoint, DEFAULT_ENDPOINT);
650
+ this.endpoint = DEFAULT_ENDPOINT;
651
+ }
652
+ if (options.multiTabMode !== void 0 && options.multiTabMode !== "independent" && options.multiTabMode !== "leader") {
653
+ warnOption("multiTabMode", options.multiTabMode, "independent");
654
+ }
655
+ if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") {
656
+ warnOption("diagnostics", options.diagnostics, "true");
657
+ }
658
+ for (const name of ["maxBatchSize", "maxQueueSize"]) {
659
+ const value = options[name];
660
+ if (typeof value === "number" && Number.isFinite(value) && value >= 1 && !Number.isInteger(value)) {
661
+ warnOption(name, value, Math.floor(value));
662
+ }
663
+ }
664
+ this.runtime = detectRuntime();
665
+ warnIfInsecureEndpoint(this.endpoint);
666
+ this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
667
+ if (!this.fetch) {
668
+ throw new Error("Eventra: fetch not available - provide fetchImpl");
669
+ }
670
+ this.maxBatch = Math.floor(numberOption("maxBatchSize", options.maxBatchSize, 50, 1));
671
+ this.maxQueue = Math.floor(numberOption("maxQueueSize", options.maxQueueSize, 1e4, 1));
672
+ this.maxPayloadBytes = numberOption("maxPayloadBytes", options.maxPayloadBytes, DEFAULT_MAX_PAYLOAD_BYTES, 1);
673
+ this.flushInterval = numberOption("flushInterval", options.flushInterval, 2e3, 1, MAX_TIMER_MS);
674
+ this.retries = numberOption("maxRetries", options.maxRetries, 3, 0, MAX_RETRIES);
675
+ this.retryDelay = numberOption("retryBaseDelayMs", options.retryBaseDelayMs, 300, 0);
676
+ this.shutdownBudget = numberOption("shutdownTimeoutMs", options.shutdownTimeoutMs, DEFAULT_SHUTDOWN_TIMEOUT_MS, 0);
677
+ this.persistQueue = options.persistQueue ?? true;
678
+ this.diagnosticsEnabled = options.diagnostics !== false;
679
+ const shared = this.runtime === "browser" && this.persistQueue;
680
+ this.diagnostics = new Diagnostics(
681
+ shared ? new SharedStore(this.storage) : new MemoryStore(),
682
+ DIAGNOSTICS_KEY,
683
+ uuidV4,
684
+ shared ? () => this.scheduleDiagnosticsSync() : void 0
685
+ );
686
+ this.sdkInfo = {
687
+ name: SDK_NAME,
688
+ version: SDK_VERSION,
689
+ runtime: this.runtime
690
+ };
691
+ if (this.runtime === "browser") {
692
+ if (this.persistQueue) {
693
+ this.loadAndMergeQueue();
694
+ }
695
+ this.setupQueueSync();
696
+ }
697
+ if (this.runtime === "browser" && options.multiTabMode === "leader") {
698
+ this.leader = new Leader((isLeader) => {
699
+ if (isLeader) void this.flushNow(false);
700
+ });
701
+ }
702
+ if (!options.disableTimer) {
703
+ this.startTimer();
704
+ }
705
+ if (this.runtime === "browser") {
706
+ this.setupBrowserExit();
707
+ }
708
+ if (options.autoFlushOnExit !== false && this.runtime !== "browser") {
709
+ this.setupProcessExit();
710
+ }
711
+ Object.defineProperty(this, "apiKey", { enumerable: false });
712
+ Object.defineProperty(this, "options", { enumerable: false });
713
+ } catch (error) {
714
+ this.destroyed = true;
715
+ activeInstances = Math.max(0, activeInstances - 1);
716
+ for (const undo of [
717
+ () => clearInterval(this.timer),
718
+ () => this.leader?.destroy(),
719
+ () => this.channel?.close(),
720
+ () => this.exitHandlers.forEach((undoHandler) => undoHandler())
721
+ ]) {
722
+ try {
723
+ undo();
724
+ } catch {
725
+ }
726
+ }
727
+ throw error;
581
728
  }
582
729
  }
583
730
  track(name, options) {
731
+ try {
732
+ this.trackEvent(name, options);
733
+ } catch {
734
+ this.recordDiagnostic("invalid_event");
735
+ callSafely(this.options.onEventsDropped, 1);
736
+ }
737
+ }
738
+ trackEvent(name, options) {
584
739
  if (this.destroyed || this.shuttingDown) return;
585
740
  const eventName = normalizeEventName(name);
586
741
  if (eventName === null) {
587
742
  this.recordDiagnostic("invalid_event");
588
- this.options.onEventsDropped?.(1);
743
+ callSafely(this.options.onEventsDropped, 1);
589
744
  return;
590
745
  }
591
746
  let properties;
@@ -593,18 +748,18 @@ var Eventra = class {
593
748
  properties = validateProperties(options?.properties ?? {});
594
749
  } catch {
595
750
  this.recordDiagnostic("invalid_event");
596
- this.options.onEventsDropped?.(1);
751
+ callSafely(this.options.onEventsDropped, 1);
597
752
  return;
598
753
  }
599
754
  if (this.queue.length >= this.maxQueue) {
600
755
  this.recordDiagnostic("queue_full");
601
- this.options.onEventsDropped?.(1);
756
+ callSafely(this.options.onEventsDropped, 1);
602
757
  return;
603
758
  }
604
759
  const event = {
605
760
  idempotencyKey: uuidV4(),
606
761
  name: eventName,
607
- userId: truncate(options?.userId, MAX_USER_ID),
762
+ userId: normalizeUserId(options?.userId, MAX_USER_ID),
608
763
  properties,
609
764
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
610
765
  };
@@ -614,13 +769,14 @@ var Eventra = class {
614
769
  this.broadcast({ type: "queue-add", events: [event] });
615
770
  }
616
771
  if (this.queue.length >= this.maxBatch) {
617
- void this.flush();
772
+ void this.flushNow(false);
618
773
  }
619
774
  if (this.runtime === "serverless") {
620
- void this.flush();
775
+ void this.flushNow(false);
621
776
  }
622
777
  }
623
778
  async flush() {
779
+ if (this.flushPromise) await this.flushPromise.catch(() => void 0);
624
780
  return this.flushNow(false);
625
781
  }
626
782
  // `force` skips only the Retry-After delay (the last chance at shutdown);
@@ -647,7 +803,7 @@ var Eventra = class {
647
803
  }
648
804
  async runFlush() {
649
805
  try {
650
- while (this.queue.length > 0) {
806
+ while (this.queue.length > 0 && !this.destroyed) {
651
807
  const report = this.diagnosticsEnabled ? this.diagnostics.claim(this.queue.length, SDK_VERSION) : null;
652
808
  const batch = this.buildBatch(report);
653
809
  if (!batch.events.length) break;
@@ -696,10 +852,13 @@ var Eventra = class {
696
852
  * `shutdownTimeoutMs` (default 10 s) so a dead or rate-limited server cannot
697
853
  * hold a SIGTERM shutdown past a typical grace period.
698
854
  */
699
- async shutdown() {
700
- if (this.shuttingDown) return;
855
+ shutdown() {
856
+ this.shutdownPromise ??= this.runShutdown();
857
+ return this.shutdownPromise;
858
+ }
859
+ async runShutdown() {
701
860
  this.shuttingDown = true;
702
- const budget = this.options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
861
+ const budget = this.shutdownBudget;
703
862
  this.shutdownDeadline = Date.now() + Math.max(0, budget);
704
863
  let budgetTimer;
705
864
  const outOfTime = new Promise((resolve) => {
@@ -727,7 +886,10 @@ var Eventra = class {
727
886
  this.persistNow();
728
887
  this.leader?.destroy();
729
888
  if (this.channel) {
730
- this.channel.close();
889
+ try {
890
+ this.channel.close();
891
+ } catch {
892
+ }
731
893
  this.channel = void 0;
732
894
  }
733
895
  if (this.onStorageQueue && typeof window !== "undefined") {
@@ -754,7 +916,13 @@ var Eventra = class {
754
916
  let index = 0;
755
917
  while (index < this.queue.length && events.length < this.maxBatch) {
756
918
  const event = this.queue[index];
757
- const eventJson = JSON.stringify(event);
919
+ let eventJson;
920
+ try {
921
+ eventJson = JSON.stringify(event);
922
+ } catch {
923
+ this.dropPoisonEvent(event);
924
+ continue;
925
+ }
758
926
  const total2 = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);
759
927
  if (total2 > this.maxPayloadBytes) {
760
928
  if (events.length === 0) {
@@ -785,12 +953,13 @@ var Eventra = class {
785
953
  dropPoisonEvent(event) {
786
954
  this.recordDiagnostic("too_large");
787
955
  this.removeDelivered([event]);
788
- this.options.onEventsDropped?.(1);
789
- this.options.onDeliveryFailed?.({ status: 413, events: [event] });
956
+ callSafely(this.options.onEventsDropped, 1);
957
+ callSafely(this.options.onDeliveryFailed, { status: 413, events: [event] });
790
958
  }
791
959
  removeDelivered(batch) {
792
960
  const keys = new Set(batch.map((e) => e.idempotencyKey));
793
- this.queue = this.queue.filter((e) => !keys.has(e.idempotencyKey));
961
+ const head = batch.length <= this.queue.length && batch.every((event, index) => this.queue[index] === event);
962
+ this.queue = head ? this.queue.slice(batch.length) : this.queue.filter((e) => !keys.has(e.idempotencyKey));
794
963
  if (this.runtime === "browser") {
795
964
  this.rememberDelivered(keys);
796
965
  this.schedulePersist();
@@ -816,7 +985,8 @@ var Eventra = class {
816
985
  this.dropPoisonEvents(events);
817
986
  return false;
818
987
  }
819
- const useKeepalive = this.runtime === "browser" && typeof document !== "undefined" && document.visibilityState === "hidden" && payloadBytes <= this.maxPayloadBytes;
988
+ const useKeepalive = this.runtime === "browser" && typeof document !== "undefined" && (document.visibilityState === "hidden" || this.leaving) && // browsers refuse a keepalive body above 64 KiB (the whole request fails), whatever maxPayloadBytes allows
989
+ payloadBytes <= Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);
820
990
  const maxAttempts = this.circuitHalfOpen ? 1 : Math.max(1, this.retries);
821
991
  let strippedDiagnostics = false;
822
992
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
@@ -824,20 +994,24 @@ var Eventra = class {
824
994
  const attemptTimeoutMs = this.shutdownDeadline > 0 ? Math.max(1, Math.min(FETCH_TIMEOUT_MS, this.shutdownDeadline - Date.now())) : FETCH_TIMEOUT_MS;
825
995
  const timeout = setTimeout(() => controller.abort(), attemptTimeoutMs);
826
996
  try {
827
- const res = await this.fetch(this.endpoint, {
828
- method: "POST",
829
- headers: {
830
- "Content-Type": "application/json",
831
- "x-api-key": this.apiKey
832
- },
833
- body: payload,
834
- signal: controller.signal,
835
- keepalive: useKeepalive,
836
- // never follow a redirect: x-api-key is a custom header, so fetch
837
- // would forward it to wherever a compromised or misconfigured
838
- // endpoint points
839
- redirect: "error"
840
- });
997
+ const res = await raceAbort(
998
+ this.fetch(this.endpoint, {
999
+ method: "POST",
1000
+ headers: {
1001
+ "Content-Type": "application/json",
1002
+ "x-api-key": this.apiKey
1003
+ },
1004
+ body: payload,
1005
+ signal: controller.signal,
1006
+ keepalive: useKeepalive,
1007
+ // never follow a redirect: x-api-key is a custom header, so fetch
1008
+ // would forward it to wherever a compromised or misconfigured
1009
+ // endpoint points
1010
+ redirect: "error"
1011
+ }),
1012
+ controller.signal
1013
+ );
1014
+ discardBody(res);
841
1015
  if (res.status === 429 || res.status >= 500) {
842
1016
  throw new RetryableDeliveryError(
843
1017
  "retryable delivery error",
@@ -854,7 +1028,7 @@ var Eventra = class {
854
1028
  continue;
855
1029
  }
856
1030
  this.recordDiagnostic("rejected", events.length);
857
- this.options.onDeliveryFailed?.({ status: res.status, events });
1031
+ callSafely(this.options.onDeliveryFailed, { status: res.status, events: [...events] });
858
1032
  this.removeDelivered(events);
859
1033
  return false;
860
1034
  }
@@ -927,7 +1101,7 @@ var Eventra = class {
927
1101
  }
928
1102
  withoutDelivered(events) {
929
1103
  if (!this.deliveredKeys.size) return events;
930
- return events.filter((e) => !this.deliveredKeys.has(e.idempotencyKey));
1104
+ return events.filter((e) => !this.deliveredKeys.has(e?.idempotencyKey));
931
1105
  }
932
1106
  rememberDelivered(keys) {
933
1107
  for (const key of keys) this.deliveredKeys.add(key);
@@ -970,7 +1144,7 @@ var Eventra = class {
970
1144
  if (queue.length <= this.maxQueue) return queue;
971
1145
  const dropped = queue.length - this.maxQueue;
972
1146
  this.recordDiagnostic("queue_full", dropped);
973
- this.options.onEventsDropped?.(dropped);
1147
+ callSafely(this.options.onEventsDropped, dropped);
974
1148
  return queue.slice(-this.maxQueue);
975
1149
  }
976
1150
  // Sends only what changed (a new event, or the keys just delivered) instead
@@ -983,7 +1157,13 @@ var Eventra = class {
983
1157
  }
984
1158
  setupQueueSync() {
985
1159
  if (typeof BroadcastChannel !== "undefined") {
986
- this.channel = new BroadcastChannel(CHANNEL_NAME);
1160
+ try {
1161
+ this.channel = new BroadcastChannel(CHANNEL_NAME);
1162
+ } catch {
1163
+ this.channel = void 0;
1164
+ }
1165
+ }
1166
+ if (this.channel) {
987
1167
  this.channel.onmessage = (e) => {
988
1168
  const data = e.data;
989
1169
  if (data?.type === "delivered" && Array.isArray(data.keys)) {
@@ -1009,7 +1189,7 @@ var Eventra = class {
1009
1189
  }
1010
1190
  startTimer() {
1011
1191
  this.timer = setInterval(() => {
1012
- void this.flush();
1192
+ void this.flushNow(false);
1013
1193
  }, this.flushInterval);
1014
1194
  this.timer.unref?.();
1015
1195
  }
@@ -1021,6 +1201,7 @@ var Eventra = class {
1021
1201
  }
1022
1202
  };
1023
1203
  const pageHide = () => {
1204
+ this.leaving = true;
1024
1205
  this.persistNow();
1025
1206
  void this.flush();
1026
1207
  };
@@ -1049,8 +1230,20 @@ var Eventra = class {
1049
1230
  SIGINT: onSignal("SIGINT"),
1050
1231
  SIGTERM: onSignal("SIGTERM")
1051
1232
  };
1233
+ const listenAgain = () => {
1234
+ if (!this.destroyed) proc.once("beforeExit", onBeforeExit);
1235
+ };
1052
1236
  const onBeforeExit = () => {
1053
- if (this.queue.length) void this.flush();
1237
+ if (!this.queue.length) {
1238
+ listenAgain();
1239
+ return;
1240
+ }
1241
+ const own = this.shutdownDeadline === 0;
1242
+ if (own) this.shutdownDeadline = Date.now() + this.shutdownBudget;
1243
+ void this.flush().finally(() => {
1244
+ if (own && !this.shuttingDown && !this.queue.length) this.shutdownDeadline = 0;
1245
+ if (!this.queue.length) listenAgain();
1246
+ });
1054
1247
  };
1055
1248
  proc.once("SIGINT", handlers.SIGINT);
1056
1249
  proc.once("SIGTERM", handlers.SIGTERM);