@eventra_dev/eventra-sdk 2.0.10 → 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.mjs CHANGED
@@ -167,7 +167,7 @@ var Diagnostics = class {
167
167
  // src/client.ts
168
168
  var SDK_NAME = "@eventra_dev/eventra-sdk";
169
169
  var DEFAULT_ENDPOINT = "https://api.eventra.dev/api/v1/ingest/batch";
170
- var SDK_VERSION = "2.0.10";
170
+ var SDK_VERSION = "2.0.12";
171
171
  var LEADER_KEY = "__eventra_leader__";
172
172
  var LEADER_TTL_MS = 4e3;
173
173
  var QUEUE_KEY = "__eventra_q__";
@@ -187,6 +187,7 @@ var RETRY_AFTER_MAX_MS = 3e4;
187
187
  var PERSIST_DEBOUNCE_MS = 50;
188
188
  var PERSISTED_EVENT_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1e3;
189
189
  var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
190
+ var KEEPALIVE_MAX_BYTES = 6e4;
190
191
  var DELIVERED_KEYS_MAX = 1e4;
191
192
  var activeInstances = 0;
192
193
  function detectRuntime() {
@@ -202,27 +203,97 @@ function uuidV4() {
202
203
  return crypto.randomUUID();
203
204
  }
204
205
  if (typeof crypto !== "undefined" && crypto.getRandomValues) {
205
- const bytes = new Uint8Array(16);
206
- crypto.getRandomValues(bytes);
207
- bytes[6] = bytes[6] & 15 | 64;
208
- bytes[8] = bytes[8] & 63 | 128;
209
- const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
210
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
211
- }
212
- throw new Error("Eventra: crypto API unavailable \u2014 cannot generate idempotencyKey");
206
+ const bytes2 = new Uint8Array(16);
207
+ crypto.getRandomValues(bytes2);
208
+ bytes2[6] = bytes2[6] & 15 | 64;
209
+ bytes2[8] = bytes2[8] & 63 | 128;
210
+ const hex2 = [...bytes2].map((b) => b.toString(16).padStart(2, "0")).join("");
211
+ return `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20)}`;
212
+ }
213
+ const bytes = new Uint8Array(16);
214
+ for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
215
+ let t = Date.now();
216
+ for (let i = 0; i < 6; i++) {
217
+ bytes[i] ^= t & 255;
218
+ t = Math.floor(t / 256);
219
+ }
220
+ bytes[6] = bytes[6] & 15 | 64;
221
+ bytes[8] = bytes[8] & 63 | 128;
222
+ const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
223
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
224
+ }
225
+ var MAX_TIMER_MS = 2147483647;
226
+ var MAX_RETRIES = 20;
227
+ function isUrl(value) {
228
+ try {
229
+ new URL(value);
230
+ return true;
231
+ } catch {
232
+ return false;
233
+ }
234
+ }
235
+ function warnOption(name, value, fallback) {
236
+ if (typeof console !== "undefined") {
237
+ console.warn(`Eventra: option "${name}" is invalid (${String(value)}), using ${String(fallback)}`);
238
+ }
239
+ }
240
+ function numberOption(name, value, fallback, min, max = Number.MAX_SAFE_INTEGER) {
241
+ if (value === void 0) return fallback;
242
+ if (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max) return value;
243
+ warnOption(name, value, fallback);
244
+ return fallback;
245
+ }
246
+ function callSafely(callback, ...args) {
247
+ if (!callback) return;
248
+ try {
249
+ const result = callback(...args);
250
+ if (result && typeof result.catch === "function") {
251
+ result.catch(() => void 0);
252
+ }
253
+ } catch {
254
+ }
255
+ }
256
+ function raceAbort(request, signal) {
257
+ return new Promise((resolve, reject) => {
258
+ const onAbort = () => reject(Object.assign(new Error("Eventra: request timed out"), { name: "AbortError" }));
259
+ signal.addEventListener("abort", onAbort, { once: true });
260
+ request.then(
261
+ (value) => {
262
+ signal.removeEventListener("abort", onAbort);
263
+ resolve(value);
264
+ },
265
+ (error) => {
266
+ signal.removeEventListener("abort", onAbort);
267
+ reject(error);
268
+ }
269
+ );
270
+ });
271
+ }
272
+ function discardBody(res) {
273
+ try {
274
+ const closing = res.body?.cancel?.();
275
+ if (closing && typeof closing.catch === "function") closing.catch(() => void 0);
276
+ } catch {
277
+ }
213
278
  }
214
279
  function sleep(ms) {
215
280
  return new Promise((r) => setTimeout(r, ms));
216
281
  }
217
- function truncate(value, max) {
218
- if (value === void 0) return void 0;
219
- return value.length > max ? value.slice(0, max) : value;
282
+ function cut(value, max) {
283
+ if (value.length <= max) return value;
284
+ const end = value.charCodeAt(max - 1) >= 55296 && value.charCodeAt(max - 1) <= 56319 ? max - 1 : max;
285
+ return value.slice(0, end);
286
+ }
287
+ function normalizeUserId(value, max) {
288
+ if (typeof value === "bigint" || typeof value === "number" && Number.isFinite(value)) return cut(String(value), max);
289
+ if (typeof value !== "string") return void 0;
290
+ return cut(value, max);
220
291
  }
221
292
  function normalizeEventName(name) {
222
293
  if (typeof name !== "string") return null;
223
294
  const trimmed = name.trim();
224
295
  if (!trimmed) return null;
225
- return trimmed.length > MAX_EVENT_NAME ? trimmed.slice(0, MAX_EVENT_NAME) : trimmed;
296
+ return cut(trimmed, MAX_EVENT_NAME).trimEnd();
226
297
  }
227
298
  function backoffMs(attempt, base) {
228
299
  const exp = Math.min(DEFAULT_MAX_RETRY_DELAY_MS, base * 2 ** attempt);
@@ -241,46 +312,65 @@ function utf8ByteLength(value) {
241
312
  }
242
313
  return value.length;
243
314
  }
315
+ function isStoredEvent(e) {
316
+ if (e === null || typeof e !== "object") return false;
317
+ const ev = e;
318
+ 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));
319
+ }
244
320
  function mergeQueues(...queues) {
245
321
  const seen = /* @__PURE__ */ new Set();
246
322
  const out = [];
247
323
  for (const q of queues) {
248
324
  for (const e of q) {
325
+ if (!isStoredEvent(e)) continue;
249
326
  if (seen.has(e.idempotencyKey)) continue;
250
327
  seen.add(e.idempotencyKey);
251
- out.push(e);
328
+ out.push(Number.isNaN(Date.parse(e.timestamp)) ? { ...e, timestamp: (/* @__PURE__ */ new Date()).toISOString() } : e);
252
329
  }
253
330
  }
254
331
  return out;
255
332
  }
333
+ var MAX_PROPERTIES_NODES = 5e4;
256
334
  function validateProperties(properties) {
335
+ 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
336
+ Object.prototype.toString.call(properties) !== "[object Object]") {
337
+ throw new Error("Eventra: properties must be an object");
338
+ }
257
339
  let hasKeys = false;
258
340
  for (const _ in properties) {
259
341
  hasKeys = true;
260
342
  break;
261
343
  }
262
- if (!hasKeys) return properties;
344
+ if (!hasKeys) return {};
345
+ let visited = 0;
263
346
  const depth = (obj, level) => {
264
347
  if (level > MAX_PROPERTIES_DEPTH) {
265
348
  throw new Error(`Eventra: properties exceed max depth (${MAX_PROPERTIES_DEPTH})`);
266
349
  }
350
+ if (++visited > MAX_PROPERTIES_NODES) {
351
+ throw new Error("Eventra: properties are too large to check");
352
+ }
267
353
  if (obj === null || typeof obj !== "object") return;
268
354
  if (Array.isArray(obj)) {
269
355
  for (const item of obj) depth(item, level + 1);
270
356
  return;
271
357
  }
272
- for (const value of Object.values(obj)) {
273
- depth(value, level + 1);
358
+ for (const key in obj) {
359
+ if (Object.prototype.hasOwnProperty.call(obj, key)) depth(obj[key], level + 1);
274
360
  }
275
361
  };
276
362
  depth(properties, 0);
277
363
  const json = JSON.stringify(properties);
278
- if (utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
364
+ if (json === void 0 || utf8ByteLength(json) > MAX_PROPERTIES_JSON_BYTES) {
279
365
  throw new Error(
280
366
  `Eventra: properties exceed max size (${MAX_PROPERTIES_JSON_BYTES} bytes)`
281
367
  );
282
368
  }
283
- return properties;
369
+ const copy = JSON.parse(json);
370
+ if (copy === null || typeof copy !== "object" || Array.isArray(copy)) {
371
+ throw new Error("Eventra: properties must be an object");
372
+ }
373
+ return copy;
284
374
  }
285
375
  function parseRetryAfterMs(value) {
286
376
  if (!value) return void 0;
@@ -345,12 +435,19 @@ var Storage = class {
345
435
  }
346
436
  /* v8 ignore stop */
347
437
  };
438
+ function storageAvailable() {
439
+ try {
440
+ return typeof localStorage !== "undefined" && localStorage !== null;
441
+ } catch {
442
+ return false;
443
+ }
444
+ }
348
445
  var Leader = class {
349
446
  constructor(onLeadershipChange) {
350
447
  this.onLeadershipChange = onLeadershipChange;
351
448
  this.tabId = uuidV4();
352
449
  this.isLeader = false;
353
- if (typeof localStorage === "undefined") {
450
+ if (!storageAvailable()) {
354
451
  this.isLeader = true;
355
452
  return;
356
453
  }
@@ -437,7 +534,7 @@ var Leader = class {
437
534
  if (this.onStorage && typeof window !== "undefined") {
438
535
  window.removeEventListener("storage", this.onStorage);
439
536
  }
440
- if (this.isLeader && typeof localStorage !== "undefined") {
537
+ if (this.isLeader && storageAvailable()) {
441
538
  try {
442
539
  const raw = localStorage.getItem(LEADER_KEY);
443
540
  if (raw) {
@@ -464,6 +561,14 @@ function warnIfInsecureEndpoint(endpoint) {
464
561
  } catch {
465
562
  }
466
563
  }
564
+ function isRedirectError(err) {
565
+ let current = err;
566
+ for (let depth = 0; depth < 3 && current instanceof Error; depth++) {
567
+ if (/redirect/i.test(current.message)) return true;
568
+ current = current.cause;
569
+ }
570
+ return false;
571
+ }
467
572
  var Eventra = class {
468
573
  constructor(options) {
469
574
  this.queue = [];
@@ -474,6 +579,7 @@ var Eventra = class {
474
579
  this.storage = new Storage();
475
580
  this.leader = null;
476
581
  this.failureCount = 0;
582
+ this.warnedRedirect = false;
477
583
  this.circuitOpenUntil = 0;
478
584
  this.circuitHalfOpen = false;
479
585
  // consecutive times the circuit opened without a success in between; drives
@@ -487,70 +593,128 @@ var Eventra = class {
487
593
  this.nextFlushAt = 0;
488
594
  // 0 = no limit; set by shutdown() so retries and sleeps cannot overrun it
489
595
  this.shutdownDeadline = 0;
596
+ this.shutdownBudget = DEFAULT_SHUTDOWN_TIMEOUT_MS;
597
+ // the page is being left (`pagehide`)
598
+ this.leaving = false;
490
599
  this.exitHandlers = [];
491
- if (!options.apiKey) throw new Error("Eventra: apiKey required");
600
+ if (!options || typeof options !== "object" || typeof options.apiKey !== "string" || !options.apiKey) {
601
+ throw new Error('Eventra: apiKey required - new Eventra({ apiKey: "..." })');
602
+ }
603
+ if (/[^\u0020-\u00ff]/.test(options.apiKey)) {
604
+ throw new Error("Eventra: apiKey has characters that cannot be sent in a header - copy it again from the dashboard");
605
+ }
606
+ if (options.fetchImpl !== void 0 && typeof options.fetchImpl !== "function") {
607
+ throw new Error("Eventra: fetchImpl must be a function");
608
+ }
492
609
  activeInstances++;
493
610
  if (activeInstances > 1 && typeof console !== "undefined") {
494
611
  console.warn(
495
- "Eventra: multiple SDK instances detected \u2014 duplicate timers and sends are possible"
612
+ "Eventra: multiple SDK instances detected - duplicate timers and sends are possible"
496
613
  );
497
614
  }
498
- this.options = options;
499
- this.apiKey = options.apiKey;
500
- this.endpoint = options.endpoint ?? DEFAULT_ENDPOINT;
501
- this.runtime = detectRuntime();
502
- warnIfInsecureEndpoint(this.endpoint);
503
- this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
504
- if (!this.fetch) {
505
- throw new Error("Eventra: fetch not available \u2014 provide fetchImpl");
506
- }
507
- this.maxBatch = options.maxBatchSize ?? 50;
508
- this.maxQueue = options.maxQueueSize ?? 1e4;
509
- this.maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
510
- this.flushInterval = options.flushInterval ?? 2e3;
511
- this.retries = options.maxRetries ?? 3;
512
- this.retryDelay = options.retryBaseDelayMs ?? 300;
513
- this.persistQueue = options.persistQueue ?? true;
514
- this.diagnosticsEnabled = options.diagnostics !== false;
515
- const shared = this.runtime === "browser" && this.persistQueue;
516
- this.diagnostics = new Diagnostics(
517
- shared ? new SharedStore(this.storage) : new MemoryStore(),
518
- DIAGNOSTICS_KEY,
519
- uuidV4,
520
- shared ? () => this.scheduleDiagnosticsSync() : void 0
521
- );
522
- this.sdkInfo = {
523
- name: SDK_NAME,
524
- version: SDK_VERSION,
525
- runtime: this.runtime
526
- };
527
- if (this.runtime === "browser") {
528
- if (this.persistQueue) {
529
- this.loadAndMergeQueue();
615
+ try {
616
+ this.options = options;
617
+ this.apiKey = options.apiKey;
618
+ if (options.endpoint !== void 0 && (typeof options.endpoint !== "string" || !options.endpoint.trim())) {
619
+ warnOption("endpoint", options.endpoint, DEFAULT_ENDPOINT);
530
620
  }
531
- this.setupQueueSync();
532
- }
533
- if (this.runtime === "browser" && options.multiTabMode === "leader") {
534
- this.leader = new Leader((isLeader) => {
535
- if (isLeader) void this.flush();
536
- });
537
- }
538
- if (!options.disableTimer) {
539
- this.startTimer();
540
- }
541
- if (this.runtime === "browser") {
542
- this.setupBrowserExit();
543
- }
544
- if (options.autoFlushOnExit !== false && this.runtime !== "browser") {
545
- this.setupProcessExit();
621
+ this.endpoint = typeof options.endpoint === "string" && options.endpoint.trim() ? options.endpoint.trim() : DEFAULT_ENDPOINT;
622
+ if (this.endpoint !== DEFAULT_ENDPOINT && !isUrl(this.endpoint)) {
623
+ warnOption("endpoint", this.endpoint, DEFAULT_ENDPOINT);
624
+ this.endpoint = DEFAULT_ENDPOINT;
625
+ }
626
+ if (options.multiTabMode !== void 0 && options.multiTabMode !== "independent" && options.multiTabMode !== "leader") {
627
+ warnOption("multiTabMode", options.multiTabMode, "independent");
628
+ }
629
+ if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") {
630
+ warnOption("diagnostics", options.diagnostics, "true");
631
+ }
632
+ for (const name of ["maxBatchSize", "maxQueueSize"]) {
633
+ const value = options[name];
634
+ if (typeof value === "number" && Number.isFinite(value) && value >= 1 && !Number.isInteger(value)) {
635
+ warnOption(name, value, Math.floor(value));
636
+ }
637
+ }
638
+ this.runtime = detectRuntime();
639
+ warnIfInsecureEndpoint(this.endpoint);
640
+ this.fetch = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
641
+ if (!this.fetch) {
642
+ throw new Error("Eventra: fetch not available - provide fetchImpl");
643
+ }
644
+ this.maxBatch = Math.floor(numberOption("maxBatchSize", options.maxBatchSize, 50, 1));
645
+ this.maxQueue = Math.floor(numberOption("maxQueueSize", options.maxQueueSize, 1e4, 1));
646
+ this.maxPayloadBytes = numberOption("maxPayloadBytes", options.maxPayloadBytes, DEFAULT_MAX_PAYLOAD_BYTES, 1);
647
+ this.flushInterval = numberOption("flushInterval", options.flushInterval, 2e3, 1, MAX_TIMER_MS);
648
+ this.retries = numberOption("maxRetries", options.maxRetries, 3, 0, MAX_RETRIES);
649
+ this.retryDelay = numberOption("retryBaseDelayMs", options.retryBaseDelayMs, 300, 0);
650
+ this.shutdownBudget = numberOption("shutdownTimeoutMs", options.shutdownTimeoutMs, DEFAULT_SHUTDOWN_TIMEOUT_MS, 0);
651
+ this.persistQueue = options.persistQueue ?? true;
652
+ this.diagnosticsEnabled = options.diagnostics !== false;
653
+ const shared = this.runtime === "browser" && this.persistQueue;
654
+ this.diagnostics = new Diagnostics(
655
+ shared ? new SharedStore(this.storage) : new MemoryStore(),
656
+ DIAGNOSTICS_KEY,
657
+ uuidV4,
658
+ shared ? () => this.scheduleDiagnosticsSync() : void 0
659
+ );
660
+ this.sdkInfo = {
661
+ name: SDK_NAME,
662
+ version: SDK_VERSION,
663
+ runtime: this.runtime
664
+ };
665
+ if (this.runtime === "browser") {
666
+ if (this.persistQueue) {
667
+ this.loadAndMergeQueue();
668
+ }
669
+ this.setupQueueSync();
670
+ }
671
+ if (this.runtime === "browser" && options.multiTabMode === "leader") {
672
+ this.leader = new Leader((isLeader) => {
673
+ if (isLeader) void this.flushNow(false);
674
+ });
675
+ }
676
+ if (!options.disableTimer) {
677
+ this.startTimer();
678
+ }
679
+ if (this.runtime === "browser") {
680
+ this.setupBrowserExit();
681
+ }
682
+ if (options.autoFlushOnExit !== false && this.runtime !== "browser") {
683
+ this.setupProcessExit();
684
+ }
685
+ Object.defineProperty(this, "apiKey", { enumerable: false });
686
+ Object.defineProperty(this, "options", { enumerable: false });
687
+ } catch (error) {
688
+ this.destroyed = true;
689
+ activeInstances = Math.max(0, activeInstances - 1);
690
+ for (const undo of [
691
+ () => clearInterval(this.timer),
692
+ () => this.leader?.destroy(),
693
+ () => this.channel?.close(),
694
+ () => this.exitHandlers.forEach((undoHandler) => undoHandler())
695
+ ]) {
696
+ try {
697
+ undo();
698
+ } catch {
699
+ }
700
+ }
701
+ throw error;
546
702
  }
547
703
  }
548
704
  track(name, options) {
705
+ try {
706
+ this.trackEvent(name, options);
707
+ } catch {
708
+ this.recordDiagnostic("invalid_event");
709
+ callSafely(this.options.onEventsDropped, 1);
710
+ }
711
+ }
712
+ trackEvent(name, options) {
549
713
  if (this.destroyed || this.shuttingDown) return;
550
714
  const eventName = normalizeEventName(name);
551
715
  if (eventName === null) {
552
716
  this.recordDiagnostic("invalid_event");
553
- this.options.onEventsDropped?.(1);
717
+ callSafely(this.options.onEventsDropped, 1);
554
718
  return;
555
719
  }
556
720
  let properties;
@@ -558,18 +722,18 @@ var Eventra = class {
558
722
  properties = validateProperties(options?.properties ?? {});
559
723
  } catch {
560
724
  this.recordDiagnostic("invalid_event");
561
- this.options.onEventsDropped?.(1);
725
+ callSafely(this.options.onEventsDropped, 1);
562
726
  return;
563
727
  }
564
728
  if (this.queue.length >= this.maxQueue) {
565
729
  this.recordDiagnostic("queue_full");
566
- this.options.onEventsDropped?.(1);
730
+ callSafely(this.options.onEventsDropped, 1);
567
731
  return;
568
732
  }
569
733
  const event = {
570
734
  idempotencyKey: uuidV4(),
571
735
  name: eventName,
572
- userId: truncate(options?.userId, MAX_USER_ID),
736
+ userId: normalizeUserId(options?.userId, MAX_USER_ID),
573
737
  properties,
574
738
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
575
739
  };
@@ -579,13 +743,14 @@ var Eventra = class {
579
743
  this.broadcast({ type: "queue-add", events: [event] });
580
744
  }
581
745
  if (this.queue.length >= this.maxBatch) {
582
- void this.flush();
746
+ void this.flushNow(false);
583
747
  }
584
748
  if (this.runtime === "serverless") {
585
- void this.flush();
749
+ void this.flushNow(false);
586
750
  }
587
751
  }
588
752
  async flush() {
753
+ if (this.flushPromise) await this.flushPromise.catch(() => void 0);
589
754
  return this.flushNow(false);
590
755
  }
591
756
  // `force` skips only the Retry-After delay (the last chance at shutdown);
@@ -612,7 +777,7 @@ var Eventra = class {
612
777
  }
613
778
  async runFlush() {
614
779
  try {
615
- while (this.queue.length > 0) {
780
+ while (this.queue.length > 0 && !this.destroyed) {
616
781
  const report = this.diagnosticsEnabled ? this.diagnostics.claim(this.queue.length, SDK_VERSION) : null;
617
782
  const batch = this.buildBatch(report);
618
783
  if (!batch.events.length) break;
@@ -661,10 +826,13 @@ var Eventra = class {
661
826
  * `shutdownTimeoutMs` (default 10 s) so a dead or rate-limited server cannot
662
827
  * hold a SIGTERM shutdown past a typical grace period.
663
828
  */
664
- async shutdown() {
665
- if (this.shuttingDown) return;
829
+ shutdown() {
830
+ this.shutdownPromise ??= this.runShutdown();
831
+ return this.shutdownPromise;
832
+ }
833
+ async runShutdown() {
666
834
  this.shuttingDown = true;
667
- const budget = this.options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
835
+ const budget = this.shutdownBudget;
668
836
  this.shutdownDeadline = Date.now() + Math.max(0, budget);
669
837
  let budgetTimer;
670
838
  const outOfTime = new Promise((resolve) => {
@@ -692,7 +860,10 @@ var Eventra = class {
692
860
  this.persistNow();
693
861
  this.leader?.destroy();
694
862
  if (this.channel) {
695
- this.channel.close();
863
+ try {
864
+ this.channel.close();
865
+ } catch {
866
+ }
696
867
  this.channel = void 0;
697
868
  }
698
869
  if (this.onStorageQueue && typeof window !== "undefined") {
@@ -719,7 +890,13 @@ var Eventra = class {
719
890
  let index = 0;
720
891
  while (index < this.queue.length && events.length < this.maxBatch) {
721
892
  const event = this.queue[index];
722
- const eventJson = JSON.stringify(event);
893
+ let eventJson;
894
+ try {
895
+ eventJson = JSON.stringify(event);
896
+ } catch {
897
+ this.dropPoisonEvent(event);
898
+ continue;
899
+ }
723
900
  const total2 = bytes + utf8ByteLength(eventJson) + (events.length ? 1 : 0);
724
901
  if (total2 > this.maxPayloadBytes) {
725
902
  if (events.length === 0) {
@@ -750,12 +927,13 @@ var Eventra = class {
750
927
  dropPoisonEvent(event) {
751
928
  this.recordDiagnostic("too_large");
752
929
  this.removeDelivered([event]);
753
- this.options.onEventsDropped?.(1);
754
- this.options.onDeliveryFailed?.({ status: 413, events: [event] });
930
+ callSafely(this.options.onEventsDropped, 1);
931
+ callSafely(this.options.onDeliveryFailed, { status: 413, events: [event] });
755
932
  }
756
933
  removeDelivered(batch) {
757
934
  const keys = new Set(batch.map((e) => e.idempotencyKey));
758
- this.queue = this.queue.filter((e) => !keys.has(e.idempotencyKey));
935
+ const head = batch.length <= this.queue.length && batch.every((event, index) => this.queue[index] === event);
936
+ this.queue = head ? this.queue.slice(batch.length) : this.queue.filter((e) => !keys.has(e.idempotencyKey));
759
937
  if (this.runtime === "browser") {
760
938
  this.rememberDelivered(keys);
761
939
  this.schedulePersist();
@@ -781,7 +959,8 @@ var Eventra = class {
781
959
  this.dropPoisonEvents(events);
782
960
  return false;
783
961
  }
784
- const useKeepalive = this.runtime === "browser" && typeof document !== "undefined" && document.visibilityState === "hidden" && payloadBytes <= this.maxPayloadBytes;
962
+ 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
963
+ payloadBytes <= Math.min(this.maxPayloadBytes, KEEPALIVE_MAX_BYTES);
785
964
  const maxAttempts = this.circuitHalfOpen ? 1 : Math.max(1, this.retries);
786
965
  let strippedDiagnostics = false;
787
966
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
@@ -789,20 +968,24 @@ var Eventra = class {
789
968
  const attemptTimeoutMs = this.shutdownDeadline > 0 ? Math.max(1, Math.min(FETCH_TIMEOUT_MS, this.shutdownDeadline - Date.now())) : FETCH_TIMEOUT_MS;
790
969
  const timeout = setTimeout(() => controller.abort(), attemptTimeoutMs);
791
970
  try {
792
- const res = await this.fetch(this.endpoint, {
793
- method: "POST",
794
- headers: {
795
- "Content-Type": "application/json",
796
- "x-api-key": this.apiKey
797
- },
798
- body: payload,
799
- signal: controller.signal,
800
- keepalive: useKeepalive,
801
- // never follow a redirect: x-api-key is a custom header, so fetch
802
- // would forward it to wherever a compromised or misconfigured
803
- // endpoint points
804
- redirect: "error"
805
- });
971
+ const res = await raceAbort(
972
+ this.fetch(this.endpoint, {
973
+ method: "POST",
974
+ headers: {
975
+ "Content-Type": "application/json",
976
+ "x-api-key": this.apiKey
977
+ },
978
+ body: payload,
979
+ signal: controller.signal,
980
+ keepalive: useKeepalive,
981
+ // never follow a redirect: x-api-key is a custom header, so fetch
982
+ // would forward it to wherever a compromised or misconfigured
983
+ // endpoint points
984
+ redirect: "error"
985
+ }),
986
+ controller.signal
987
+ );
988
+ discardBody(res);
806
989
  if (res.status === 429 || res.status >= 500) {
807
990
  throw new RetryableDeliveryError(
808
991
  "retryable delivery error",
@@ -819,7 +1002,7 @@ var Eventra = class {
819
1002
  continue;
820
1003
  }
821
1004
  this.recordDiagnostic("rejected", events.length);
822
- this.options.onDeliveryFailed?.({ status: res.status, events });
1005
+ callSafely(this.options.onDeliveryFailed, { status: res.status, events: [...events] });
823
1006
  this.removeDelivered(events);
824
1007
  return false;
825
1008
  }
@@ -832,6 +1015,12 @@ var Eventra = class {
832
1015
  }
833
1016
  return carriesDiagnostics;
834
1017
  } catch (err) {
1018
+ if (!this.warnedRedirect && isRedirectError(err) && typeof console !== "undefined") {
1019
+ this.warnedRedirect = true;
1020
+ console.warn(
1021
+ "Eventra: the endpoint answered with a redirect. It is not followed, so the API key is not forwarded, and events stay queued - check the endpoint URL (for example http instead of https)"
1022
+ );
1023
+ }
835
1024
  const isLast = attempt >= maxAttempts - 1;
836
1025
  const retryAfter = err instanceof RetryableDeliveryError ? err.retryAfterMs : void 0;
837
1026
  const wait = Math.max(backoffMs(attempt, this.retryDelay), retryAfter ?? 0);
@@ -886,7 +1075,7 @@ var Eventra = class {
886
1075
  }
887
1076
  withoutDelivered(events) {
888
1077
  if (!this.deliveredKeys.size) return events;
889
- return events.filter((e) => !this.deliveredKeys.has(e.idempotencyKey));
1078
+ return events.filter((e) => !this.deliveredKeys.has(e?.idempotencyKey));
890
1079
  }
891
1080
  rememberDelivered(keys) {
892
1081
  for (const key of keys) this.deliveredKeys.add(key);
@@ -929,7 +1118,7 @@ var Eventra = class {
929
1118
  if (queue.length <= this.maxQueue) return queue;
930
1119
  const dropped = queue.length - this.maxQueue;
931
1120
  this.recordDiagnostic("queue_full", dropped);
932
- this.options.onEventsDropped?.(dropped);
1121
+ callSafely(this.options.onEventsDropped, dropped);
933
1122
  return queue.slice(-this.maxQueue);
934
1123
  }
935
1124
  // Sends only what changed (a new event, or the keys just delivered) instead
@@ -942,7 +1131,13 @@ var Eventra = class {
942
1131
  }
943
1132
  setupQueueSync() {
944
1133
  if (typeof BroadcastChannel !== "undefined") {
945
- this.channel = new BroadcastChannel(CHANNEL_NAME);
1134
+ try {
1135
+ this.channel = new BroadcastChannel(CHANNEL_NAME);
1136
+ } catch {
1137
+ this.channel = void 0;
1138
+ }
1139
+ }
1140
+ if (this.channel) {
946
1141
  this.channel.onmessage = (e) => {
947
1142
  const data = e.data;
948
1143
  if (data?.type === "delivered" && Array.isArray(data.keys)) {
@@ -968,7 +1163,7 @@ var Eventra = class {
968
1163
  }
969
1164
  startTimer() {
970
1165
  this.timer = setInterval(() => {
971
- void this.flush();
1166
+ void this.flushNow(false);
972
1167
  }, this.flushInterval);
973
1168
  this.timer.unref?.();
974
1169
  }
@@ -980,6 +1175,7 @@ var Eventra = class {
980
1175
  }
981
1176
  };
982
1177
  const pageHide = () => {
1178
+ this.leaving = true;
983
1179
  this.persistNow();
984
1180
  void this.flush();
985
1181
  };
@@ -1008,8 +1204,20 @@ var Eventra = class {
1008
1204
  SIGINT: onSignal("SIGINT"),
1009
1205
  SIGTERM: onSignal("SIGTERM")
1010
1206
  };
1207
+ const listenAgain = () => {
1208
+ if (!this.destroyed) proc.once("beforeExit", onBeforeExit);
1209
+ };
1011
1210
  const onBeforeExit = () => {
1012
- if (this.queue.length) void this.flush();
1211
+ if (!this.queue.length) {
1212
+ listenAgain();
1213
+ return;
1214
+ }
1215
+ const own = this.shutdownDeadline === 0;
1216
+ if (own) this.shutdownDeadline = Date.now() + this.shutdownBudget;
1217
+ void this.flush().finally(() => {
1218
+ if (own && !this.shuttingDown && !this.queue.length) this.shutdownDeadline = 0;
1219
+ if (!this.queue.length) listenAgain();
1220
+ });
1013
1221
  };
1014
1222
  proc.once("SIGINT", handlers.SIGINT);
1015
1223
  proc.once("SIGTERM", handlers.SIGTERM);