@active-reach/web-sdk 1.48.0 → 1.50.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.
Files changed (55) hide show
  1. package/dist/aegis.min.js +1 -1
  2. package/dist/aegis.min.js.map +1 -1
  3. package/dist/{analytics-zA6ckfKP.mjs → analytics-DMY0Q0rI.mjs} +911 -312
  4. package/dist/analytics-DMY0Q0rI.mjs.map +1 -0
  5. package/dist/chat/AegisChat.d.ts +20 -0
  6. package/dist/chat/AegisChat.d.ts.map +1 -1
  7. package/dist/chat/index.d.ts +1 -1
  8. package/dist/chat/index.d.ts.map +1 -1
  9. package/dist/core/analytics.d.ts.map +1 -1
  10. package/dist/core/bootstrap.d.ts +2 -1
  11. package/dist/core/bootstrap.d.ts.map +1 -1
  12. package/dist/core/prefetch-bundle-client.d.ts.map +1 -1
  13. package/dist/core/purchase-backlog.d.ts +141 -0
  14. package/dist/core/purchase-backlog.d.ts.map +1 -0
  15. package/dist/core/purchase-events.d.ts +25 -0
  16. package/dist/core/purchase-events.d.ts.map +1 -0
  17. package/dist/core/queue.d.ts +39 -0
  18. package/dist/core/queue.d.ts.map +1 -1
  19. package/dist/core/sdk-config-poller.d.ts.map +1 -1
  20. package/dist/core/transport.d.ts +74 -1
  21. package/dist/core/transport.d.ts.map +1 -1
  22. package/dist/ecommerce/index.d.ts +1 -1
  23. package/dist/ecommerce/index.d.ts.map +1 -1
  24. package/dist/ecommerce/types.d.ts +10 -0
  25. package/dist/ecommerce/types.d.ts.map +1 -1
  26. package/dist/governance/trait-governor.d.ts +13 -6
  27. package/dist/governance/trait-governor.d.ts.map +1 -1
  28. package/dist/inapp/AegisInAppManager.d.ts +94 -6
  29. package/dist/inapp/AegisInAppManager.d.ts.map +1 -1
  30. package/dist/inapp/anon-claim.d.ts +36 -0
  31. package/dist/inapp/anon-claim.d.ts.map +1 -0
  32. package/dist/inapp/index.d.ts +1 -1
  33. package/dist/inapp/index.d.ts.map +1 -1
  34. package/dist/inapp/prize-retry.d.ts +51 -0
  35. package/dist/inapp/prize-retry.d.ts.map +1 -0
  36. package/dist/inapp/rail-fallback.d.ts +83 -0
  37. package/dist/inapp/rail-fallback.d.ts.map +1 -0
  38. package/dist/inapp/renderers/games.d.ts.map +1 -1
  39. package/dist/inapp/renderers/types.d.ts +12 -0
  40. package/dist/inapp/renderers/types.d.ts.map +1 -1
  41. package/dist/inapp/section-spot-lineup.d.ts +43 -0
  42. package/dist/inapp/section-spot-lineup.d.ts.map +1 -0
  43. package/dist/index.d.ts +4 -3
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +986 -145
  46. package/dist/index.js.map +1 -1
  47. package/dist/react.js +1 -1
  48. package/dist/runtime/AegisMessageRuntime.d.ts +17 -0
  49. package/dist/runtime/AegisMessageRuntime.d.ts.map +1 -1
  50. package/dist/utils/fetch-abort.d.ts +23 -0
  51. package/dist/utils/fetch-abort.d.ts.map +1 -0
  52. package/dist/utils/preview-as-of.d.ts +21 -0
  53. package/dist/utils/preview-as-of.d.ts.map +1 -0
  54. package/package.json +2 -2
  55. package/dist/analytics-zA6ckfKP.mjs.map +0 -1
@@ -472,208 +472,63 @@ function redactMetaCookies(event) {
472
472
  if (masked.fbp !== void 0) masked.fbp = "[redacted]";
473
473
  return { ...event, properties: masked };
474
474
  }
475
- class EventQueue {
476
- constructor(config, transport, storage) {
477
- this.buffer = [];
478
- this.flushInterval = null;
479
- this.isFlushing = false;
480
- this.offlineQueue = [];
481
- this.isOnline = navigator.onLine;
482
- this.config = config;
483
- this.transport = transport;
484
- this.storage = storage;
485
- if (config.enableOfflineMode) {
486
- this.loadOfflineQueue();
487
- this.setupOnlineListener();
488
- }
489
- this.startFlushTimer();
490
- this.setupUnloadHandlers();
491
- }
492
- loadOfflineQueue() {
493
- const offlineData = this.storage.get("offline_queue");
494
- if (!offlineData) {
495
- return;
496
- }
497
- try {
498
- const events = JSON.parse(offlineData);
499
- if (Array.isArray(events) && events.length > 0) {
500
- this.offlineQueue = events.slice(0, this.config.maxOfflineEvents);
501
- logger.info(`Loaded ${this.offlineQueue.length} offline events`);
502
- if (this.isOnline) {
503
- this.flushOfflineQueue();
504
- }
505
- }
506
- } catch (error) {
507
- logger.warn("Failed to load offline queue:", error);
508
- this.storage.remove("offline_queue");
509
- }
510
- }
511
- saveOfflineQueue() {
512
- if (this.offlineQueue.length === 0) {
513
- this.storage.remove("offline_queue");
514
- return;
515
- }
516
- try {
517
- const data = JSON.stringify(this.offlineQueue);
518
- this.storage.set("offline_queue", data);
519
- logger.debug(`Saved ${this.offlineQueue.length} events to offline queue`);
520
- } catch (error) {
521
- logger.warn("Failed to save offline queue:", error);
522
- }
523
- }
524
- setupOnlineListener() {
525
- window.addEventListener("online", () => {
526
- logger.info("Connection restored");
527
- this.isOnline = true;
528
- this.flushOfflineQueue();
529
- this.flush();
530
- });
531
- window.addEventListener("offline", () => {
532
- logger.warn("Connection lost, entering offline mode");
533
- this.isOnline = false;
534
- });
535
- }
536
- async flushOfflineQueue() {
537
- if (this.offlineQueue.length === 0) {
538
- return;
539
- }
540
- logger.info(`Flushing ${this.offlineQueue.length} offline events`);
541
- const events = [...this.offlineQueue];
542
- this.offlineQueue = [];
543
- this.storage.remove("offline_queue");
544
- const result = await this.transport.send(events);
545
- if (!result.success) {
546
- logger.warn("Failed to send offline events, re-queueing");
547
- this.offlineQueue = [...events, ...this.offlineQueue].slice(
548
- 0,
549
- this.config.maxOfflineEvents
550
- );
551
- this.saveOfflineQueue();
552
- } else {
553
- logger.info("Offline events sent successfully");
554
- }
555
- }
556
- push(event) {
557
- if (!this.isOnline && this.config.enableOfflineMode) {
558
- this.addToOfflineQueue(event);
559
- return;
560
- }
561
- this.buffer.push(event);
562
- logger.debug("Event queued:", event.type, redactMetaCookies(event));
563
- if (this.buffer.length >= this.config.batchSize) {
564
- this.flush();
565
- }
566
- }
567
- addToOfflineQueue(event) {
568
- if (this.offlineQueue.length >= this.config.maxOfflineEvents) {
569
- logger.warn("Offline queue full, dropping oldest event");
570
- this.offlineQueue.shift();
571
- }
572
- this.offlineQueue.push(event);
573
- this.saveOfflineQueue();
574
- logger.debug("Event added to offline queue");
575
- }
576
- async flush() {
577
- if (this.isFlushing) {
578
- logger.debug("Flush already in progress, skipping");
579
- return;
580
- }
581
- if (this.buffer.length === 0) {
582
- return;
583
- }
584
- this.isFlushing = true;
585
- const events = [...this.buffer];
586
- this.buffer = [];
587
- logger.info(`Flushing ${events.length} events`);
588
- try {
589
- const result = await this.transport.send(events);
590
- if (!result.success) {
591
- logger.error("Failed to send events:", result.error);
592
- if (this.config.enableOfflineMode) {
593
- this.offlineQueue = [...this.offlineQueue, ...events].slice(
594
- 0,
595
- this.config.maxOfflineEvents
596
- );
597
- this.saveOfflineQueue();
598
- logger.info("Events saved to offline queue");
599
- } else {
600
- this.buffer.unshift(...events);
601
- logger.warn("Events re-queued for retry");
602
- }
603
- } else {
604
- logger.info("Events sent successfully");
605
- }
606
- } catch (error) {
607
- logger.error("Flush error:", error);
608
- if (this.config.enableOfflineMode) {
609
- this.offlineQueue = [...this.offlineQueue, ...events].slice(
610
- 0,
611
- this.config.maxOfflineEvents
612
- );
613
- this.saveOfflineQueue();
614
- }
615
- } finally {
616
- this.isFlushing = false;
617
- }
618
- }
619
- startFlushTimer() {
620
- if (this.flushInterval) {
621
- clearInterval(this.flushInterval);
622
- }
623
- this.flushInterval = window.setInterval(() => {
624
- this.flush();
625
- }, this.config.batchInterval);
626
- logger.debug(
627
- `Flush timer started with interval: ${this.config.batchInterval}ms`
628
- );
629
- }
630
- setupUnloadHandlers() {
631
- const flushBeforeUnload = () => {
632
- if (this.buffer.length > 0 || this.offlineQueue.length > 0) {
633
- this.persistBufferToOfflineQueue();
634
- this.flush();
635
- }
636
- };
637
- document.addEventListener("visibilitychange", () => {
638
- if (document.visibilityState === "hidden") {
639
- flushBeforeUnload();
640
- }
641
- });
642
- window.addEventListener("beforeunload", flushBeforeUnload);
643
- window.addEventListener("pagehide", flushBeforeUnload);
644
- }
645
- persistBufferToOfflineQueue() {
646
- if (this.buffer.length === 0) {
647
- return;
648
- }
649
- if (this.config.enableOfflineMode) {
650
- this.offlineQueue = [...this.offlineQueue, ...this.buffer].slice(
651
- 0,
652
- this.config.maxOfflineEvents
653
- );
654
- this.saveOfflineQueue();
655
- logger.debug("Buffer persisted to offline queue before unload");
656
- }
657
- }
658
- getQueueSize() {
659
- return this.buffer.length;
660
- }
661
- getOfflineQueueSize() {
662
- return this.offlineQueue.length;
663
- }
664
- clear() {
665
- this.buffer = [];
666
- this.offlineQueue = [];
667
- this.storage.remove("offline_queue");
668
- logger.info("Queue cleared");
669
- }
670
- destroy() {
671
- if (this.flushInterval) {
672
- clearInterval(this.flushInterval);
673
- this.flushInterval = null;
674
- }
675
- this.flush();
676
- }
475
+ const PURCHASE_EVENT_NAMES = /* @__PURE__ */ new Set([
476
+ "transaction.purchase",
477
+ "transaction_purchase",
478
+ "bulk_order",
479
+ "historical_order",
480
+ "lookalike_first_purchase",
481
+ "offline_order",
482
+ "order.completed",
483
+ "order_completed",
484
+ "order_import",
485
+ "order_placed",
486
+ "order_placed_cod",
487
+ "orders_create",
488
+ "order_success",
489
+ "order_upload",
490
+ "pos_first_transaction",
491
+ "pos_transaction_completed",
492
+ "purchase",
493
+ "purchase.completed",
494
+ "purchase_completed",
495
+ "sales_order_place_after",
496
+ "transaction",
497
+ "woocommerce_order_completed",
498
+ "woocommerce_order_placed"
499
+ ]);
500
+ function normalise(raw) {
501
+ return raw.trim().toLowerCase().replace(/[./\-\s]+/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "");
502
+ }
503
+ function isPurchaseEventName(name) {
504
+ if (typeof name !== "string" || name.length === 0) return false;
505
+ const lower = name.toLowerCase();
506
+ return PURCHASE_EVENT_NAMES.has(lower) || PURCHASE_EVENT_NAMES.has(normalise(name));
507
+ }
508
+ function isPurchaseEvent(event) {
509
+ if (!event || event.type !== "track") return false;
510
+ return isPurchaseEventName(event.event);
511
+ }
512
+ const KEEPALIVE_BODY_MAX_BYTES = 6e4;
513
+ const KEEPALIVE_SPLIT_ON_ZERO_BYTES = 16e3;
514
+ function utf8Bytes(text) {
515
+ if (typeof TextEncoder !== "undefined") return new TextEncoder().encode(text).length;
516
+ return unescape(encodeURIComponent(text)).length;
517
+ }
518
+ const MAX_BATCH_EVENTS = 100;
519
+ function parseRetryAfterMs(value, now = Date.now()) {
520
+ if (!value) return void 0;
521
+ const trimmed = value.trim();
522
+ let ms;
523
+ if (/^\d+(\.\d+)?$/.test(trimmed)) {
524
+ ms = Number(trimmed) * 1e3;
525
+ } else {
526
+ const at = Date.parse(trimmed);
527
+ if (Number.isNaN(at)) return void 0;
528
+ ms = at - now;
529
+ }
530
+ if (!Number.isFinite(ms) || ms < 0) return void 0;
531
+ return Math.min(ms, 5 * 60 * 1e3);
677
532
  }
678
533
  class Transport {
679
534
  constructor(config, storage) {
@@ -818,138 +673,838 @@ class Transport {
818
673
  return false;
819
674
  }
820
675
  }
821
- async send(events) {
822
- if (events.length === 0) {
823
- return { success: true };
676
+ async send(events, options = {}) {
677
+ if (events.length === 0) {
678
+ return { success: true };
679
+ }
680
+ const endpoint = this.getActiveEndpoint();
681
+ if (events.length > MAX_BATCH_EVENTS) {
682
+ let last = { success: true, endpoint };
683
+ for (let i = 0; i < events.length; i += MAX_BATCH_EVENTS) {
684
+ const chunk = events.slice(i, i + MAX_BATCH_EVENTS);
685
+ last = await this.sendChunk(endpoint, chunk, options);
686
+ if (!last.success) {
687
+ const rejected = [...last.rejected ?? chunk, ...events.slice(i + MAX_BATCH_EVENTS)];
688
+ return { ...last, success: false, rejected };
689
+ }
690
+ }
691
+ return last;
692
+ }
693
+ return this.sendChunk(endpoint, events, options);
694
+ }
695
+ /**
696
+ * One request (<= MAX_BATCH_EVENTS). Halved, never dropped, when:
697
+ * - it is a keepalive request whose body is over KEEPALIVE_BODY_MAX_BYTES
698
+ * (split before sending; the browser would refuse it);
699
+ * - the gateway answers 413;
700
+ * - a keepalive request over KEEPALIVE_SPLIT_ON_ZERO_BYTES fails with
701
+ * status 0 (a browser quota refusal looks like a network error);
702
+ * - the gateway answers 400 and `splitOnBadRequest` is set.
703
+ */
704
+ async sendChunk(endpoint, events, options) {
705
+ const keepalive = options.keepalive !== false;
706
+ const bytes = keepalive ? utf8Bytes(JSON.stringify(this.buildPayload(events))) : 0;
707
+ const oversize = keepalive && bytes > KEEPALIVE_BODY_MAX_BYTES;
708
+ if (oversize && events.length > 1) {
709
+ return this.sendHalves(endpoint, events, options, "keepalive body over 60 KB");
710
+ }
711
+ const sendOpts = oversize ? { ...options, keepalive: false } : options;
712
+ const result = await this.sendOne(endpoint, events, sendOpts);
713
+ if (result.success) return result;
714
+ const status = result.status;
715
+ const splittable = status === 413 || status === 0 && sendOpts.keepalive !== false && bytes > KEEPALIVE_SPLIT_ON_ZERO_BYTES || status === 400 && options.splitOnBadRequest === true;
716
+ if (!splittable) return result;
717
+ if (events.length <= 1) {
718
+ if (status === 400 || status === 413) {
719
+ return { ...result, rejected: events, terminalEvent: events[0] };
720
+ }
721
+ return result;
722
+ }
723
+ return this.sendHalves(endpoint, events, options, `HTTP ${status}`);
724
+ }
725
+ async sendHalves(endpoint, events, options, why) {
726
+ const mid = Math.ceil(events.length / 2);
727
+ const head = events.slice(0, mid);
728
+ const tail = events.slice(mid);
729
+ logger.warn(`Batch of ${events.length} split (${why}); sending halves of ${head.length} and ${tail.length}`);
730
+ const first = await this.sendChunk(endpoint, head, options);
731
+ if (!first.success) {
732
+ return { ...first, success: false, rejected: [...first.rejected ?? head, ...tail] };
733
+ }
734
+ const second = await this.sendChunk(endpoint, tail, options);
735
+ if (!second.success) {
736
+ return { ...second, success: false, rejected: second.rejected ?? tail };
737
+ }
738
+ return second;
739
+ }
740
+ async sendOne(endpoint, events, options) {
741
+ const payload = this.buildPayload(events);
742
+ logger.debug("Sending batch:", { endpoint, eventCount: events.length });
743
+ const keepalive = options.keepalive !== false;
744
+ if (options.confirmDelivery) {
745
+ return this.sendViaFetch(endpoint, payload, this.config.maxRetries, keepalive);
746
+ }
747
+ if (!keepalive) {
748
+ return this.sendViaFetch(endpoint, payload, 1, false);
749
+ }
750
+ if (document.visibilityState === "hidden" && typeof navigator.sendBeacon === "function") {
751
+ const result = this.sendViaBeacon(endpoint, payload);
752
+ return Promise.resolve(result);
753
+ } else {
754
+ return this.sendViaFetch(endpoint, payload);
755
+ }
756
+ }
757
+ getActiveEndpoint() {
758
+ if (this.activeCell) {
759
+ return `${this.activeCell.url}/v1/batch`;
760
+ }
761
+ if (this.config.apiHost) {
762
+ return `${this.config.apiHost}/v1/batch`;
763
+ }
764
+ throw new Error("No active endpoint available");
765
+ }
766
+ buildPayload(events) {
767
+ return {
768
+ batch: events,
769
+ sentAt: (/* @__PURE__ */ new Date()).toISOString(),
770
+ writeKey: this.config.writeKey,
771
+ context: this.activeCell ? {
772
+ cell: {
773
+ region: this.activeCell.region,
774
+ endpoint: this.activeCell.url
775
+ }
776
+ } : void 0
777
+ };
778
+ }
779
+ sendViaBeacon(endpoint, payload) {
780
+ try {
781
+ const blob = new Blob([JSON.stringify(payload)], {
782
+ type: "application/json"
783
+ });
784
+ const sent = navigator.sendBeacon(endpoint, blob);
785
+ if (sent) {
786
+ logger.debug("Batch sent via Beacon");
787
+ return { success: true, endpoint };
788
+ } else {
789
+ logger.warn("Beacon send failed, falling back to fetch");
790
+ return this.sendViaFetch(endpoint, payload);
791
+ }
792
+ } catch (error) {
793
+ logger.error("Beacon send error:", error);
794
+ return {
795
+ success: false,
796
+ error,
797
+ endpoint
798
+ };
799
+ }
800
+ }
801
+ async sendViaFetch(endpoint, payload, attempt = 1, keepalive = true) {
802
+ var _a, _b;
803
+ try {
804
+ const controller = new AbortController();
805
+ const timeoutId = setTimeout(
806
+ () => controller.abort(),
807
+ this.config.requestTimeout
808
+ );
809
+ const response = await fetch(endpoint, {
810
+ method: "POST",
811
+ headers: {
812
+ "Content-Type": "application/json",
813
+ Authorization: `Bearer ${this.config.writeKey}`
814
+ },
815
+ body: JSON.stringify(payload),
816
+ keepalive,
817
+ signal: controller.signal
818
+ });
819
+ clearTimeout(timeoutId);
820
+ if (response.ok) {
821
+ const result = await response.json();
822
+ logger.debug("Batch sent successfully:", result);
823
+ return { success: true, response: result, endpoint };
824
+ } else {
825
+ const errorText = await response.text();
826
+ const error = new Error(
827
+ `HTTP ${response.status}: ${errorText || response.statusText}`
828
+ );
829
+ logger.error("Batch send failed:", error);
830
+ const retryAfterMs = parseRetryAfterMs((_b = (_a = response.headers) == null ? void 0 : _a.get) == null ? void 0 : _b.call(_a, "Retry-After"));
831
+ if (this.shouldRetry(response.status, attempt)) {
832
+ return this.retryRequest(endpoint, payload, attempt, retryAfterMs, keepalive);
833
+ }
834
+ return {
835
+ success: false,
836
+ error,
837
+ endpoint,
838
+ status: response.status,
839
+ retryAfterMs
840
+ };
841
+ }
842
+ } catch (error) {
843
+ logger.error("Fetch error:", error);
844
+ if (this.shouldRetry(0, attempt)) {
845
+ return this.retryRequest(endpoint, payload, attempt, void 0, keepalive);
846
+ }
847
+ return {
848
+ success: false,
849
+ error,
850
+ endpoint,
851
+ status: 0
852
+ };
853
+ }
854
+ }
855
+ shouldRetry(statusCode, attempt) {
856
+ if (!this.config.retryFailedRequests) {
857
+ return false;
858
+ }
859
+ if (attempt >= this.config.maxRetries) {
860
+ return false;
861
+ }
862
+ if (statusCode === 0) {
863
+ return true;
864
+ }
865
+ return statusCode >= 500 || statusCode === 429;
866
+ }
867
+ async retryRequest(endpoint, payload, attempt, retryAfterMs, keepalive = true) {
868
+ const delay = Math.max(
869
+ Math.pow(this.config.retryBackoffMultiplier, attempt) * 1e3,
870
+ retryAfterMs ?? 0
871
+ );
872
+ logger.info(`Retrying request in ${delay}ms (attempt ${attempt + 1})`);
873
+ await new Promise((resolve) => setTimeout(resolve, delay));
874
+ return this.sendViaFetch(endpoint, payload, attempt + 1, keepalive);
875
+ }
876
+ getActiveCell() {
877
+ return this.activeCell;
878
+ }
879
+ getRegionLatencies() {
880
+ return new Map(this.regionLatencyMap);
881
+ }
882
+ destroy() {
883
+ if (this.healthCheckInterval) {
884
+ clearInterval(this.healthCheckInterval);
885
+ this.healthCheckInterval = null;
886
+ }
887
+ }
888
+ }
889
+ const MAX_PURCHASE_BACKLOG = 200;
890
+ const MAX_PURCHASE_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
891
+ const PURCHASE_SEND_CHUNK = 50;
892
+ const PURCHASE_RETRY_BASE_MS = 1e3;
893
+ const PURCHASE_RETRY_MAX_MS = 6e4;
894
+ const SETTLED_RETENTION_MS = 8 * 24 * 60 * 60 * 1e3;
895
+ const SETTLED_MAX = 2e3;
896
+ const PURCHASE_BACKLOG_PREFIX = "aegis_purchase_backlog:v1:";
897
+ const ENVELOPE_BYTES = 2e3;
898
+ const AUTH_PAUSE_BASE_MS = 5 * 60 * 1e3;
899
+ const AUTH_PAUSE_MAX_MS = 60 * 60 * 1e3;
900
+ const MAX_TERMINAL_STREAK = 3;
901
+ function fnv1a(input) {
902
+ let h = 2166136261;
903
+ for (let i = 0; i < input.length; i++) {
904
+ h ^= input.charCodeAt(i);
905
+ h = Math.imul(h, 16777619) >>> 0;
906
+ }
907
+ return h.toString(16);
908
+ }
909
+ function purchaseBacklogKey(namespace) {
910
+ return PURCHASE_BACKLOG_PREFIX + (namespace ? fnv1a(namespace) : "default");
911
+ }
912
+ function idOf(e) {
913
+ return e.messageId || "";
914
+ }
915
+ function eventTime(e, now) {
916
+ const t = Date.parse(e.timestamp || "");
917
+ return Number.isNaN(t) ? now : t;
918
+ }
919
+ class PurchaseBacklog {
920
+ constructor(transport, namespace) {
921
+ var _a;
922
+ this.transport = transport;
923
+ this.events = [];
924
+ this.settled = /* @__PURE__ */ new Map();
925
+ this.inFlight = false;
926
+ this.attempt = 0;
927
+ this.timer = null;
928
+ this.destroyed = false;
929
+ this.dropped = { overBound: 0, expired: 0, terminal: 0 };
930
+ this.orphaned = 0;
931
+ this.authPaused = 0;
932
+ this.terminalStreak = 0;
933
+ this.bypassPauseOnce = false;
934
+ this.key = purchaseBacklogKey(namespace);
935
+ this.terminalStreak = ((_a = this.readAuthPause()) == null ? void 0 : _a.streak) ?? 0;
936
+ this.countOrphans();
937
+ this.persist();
938
+ if (this.events.length > 0) {
939
+ logger.info(`Loaded ${this.events.length} unsent purchase events`);
940
+ this.retryNow();
941
+ }
942
+ }
943
+ size() {
944
+ return this.events.length;
945
+ }
946
+ totalDropped() {
947
+ return this.dropped.overBound + this.dropped.expired + this.dropped.terminal;
948
+ }
949
+ add(event) {
950
+ const id = idOf(event);
951
+ if (id && (this.settled.has(id) || this.events.some((e) => idOf(e) === id))) return;
952
+ this.events.push(event);
953
+ this.persist();
954
+ this.bypassPauseOnce = true;
955
+ this.retryNow();
956
+ }
957
+ /** Cancel any pending backoff and try on the next tick (live page). */
958
+ retryNow() {
959
+ if (this.destroyed || this.events.length === 0) return;
960
+ this.clearTimer();
961
+ this.attempt = 0;
962
+ this.schedule(0);
963
+ }
964
+ /**
965
+ * Called SYNCHRONOUSLY from an unload handler: the keepalive fetch starts
966
+ * before this returns (timers do not run after pagehide). Sends only what
967
+ * fits in one keepalive body; the rest stay on disk for the next load.
968
+ */
969
+ flushOnUnload() {
970
+ if (this.events.length === 0) return;
971
+ void this.drain(true);
972
+ }
973
+ /** Forget every held purchase (an explicit embedder wipe). */
974
+ clear() {
975
+ for (const e of this.events) this.settle(idOf(e));
976
+ this.events = [];
977
+ this.clearTimer();
978
+ this.persist();
979
+ }
980
+ destroy() {
981
+ this.flushOnUnload();
982
+ this.clearTimer();
983
+ this.destroyed = true;
984
+ }
985
+ static retryDelayMs(attempt, retryAfterMs, jitter = Math.random()) {
986
+ const exp = Math.min(PURCHASE_RETRY_MAX_MS, PURCHASE_RETRY_BASE_MS * Math.pow(2, Math.max(0, attempt - 1)));
987
+ return Math.max(Math.round(exp * (0.8 + 0.4 * jitter)), retryAfterMs ?? 0);
988
+ }
989
+ /** Send one request's worth; keep every purchase until a 2xx accepts it. */
990
+ async drain(unloading = false) {
991
+ if (this.events.length === 0) return;
992
+ if (this.inFlight && !unloading) return;
993
+ const pause = this.readAuthPause();
994
+ const paused = !!pause && Date.now() < pause.until;
995
+ if (paused && !unloading && !this.bypassPauseOnce) {
996
+ this.schedule(pause.until - Date.now());
997
+ return;
998
+ }
999
+ if (!unloading) this.bypassPauseOnce = false;
1000
+ const chunk = unloading ? this.unloadChunk() : this.events.slice(0, PURCHASE_SEND_CHUNK);
1001
+ if (chunk.length === 0) return;
1002
+ if (!unloading) this.inFlight = true;
1003
+ let success = false;
1004
+ let retryAfterMs;
1005
+ let accepted = [];
1006
+ const terminal = [];
1007
+ let keyRefused = false;
1008
+ let streakPause = false;
1009
+ try {
1010
+ const result = await this.transport.send(chunk, {
1011
+ confirmDelivery: true,
1012
+ keepalive: unloading,
1013
+ splitOnBadRequest: true
1014
+ });
1015
+ success = result.success;
1016
+ retryAfterMs = result.retryAfterMs;
1017
+ if (success) {
1018
+ accepted = chunk;
1019
+ } else {
1020
+ const left = new Set((result.rejected ?? chunk).map(idOf));
1021
+ accepted = chunk.filter((e) => !left.has(idOf(e)));
1022
+ if (result.terminalEvent) {
1023
+ if (this.terminalStreak >= MAX_TERMINAL_STREAK) {
1024
+ streakPause = true;
1025
+ } else {
1026
+ terminal.push(result.terminalEvent);
1027
+ }
1028
+ } else if (result.status === 401 || result.status === 403) {
1029
+ keyRefused = true;
1030
+ }
1031
+ logger.warn(`Purchase send not accepted (status ${result.status ?? "n/a"}); kept for retry`, result.error);
1032
+ }
1033
+ } catch (error) {
1034
+ logger.warn("Purchase send error; kept for retry:", error);
1035
+ } finally {
1036
+ if (!unloading) this.inFlight = false;
1037
+ }
1038
+ for (const e of terminal) {
1039
+ this.dropped.terminal += 1;
1040
+ logger.error("Purchase refused by the gateway and cannot succeed on retry; evicted", redactMetaCookies(e));
1041
+ }
1042
+ const done = [...accepted, ...terminal];
1043
+ if (done.length > 0) {
1044
+ const ids = new Set(done.map(idOf));
1045
+ for (const id of ids) this.settle(id);
1046
+ this.events = this.events.filter((e) => !ids.has(idOf(e)));
1047
+ this.persist();
1048
+ }
1049
+ if (accepted.length > 0) this.terminalStreak = 0;
1050
+ this.terminalStreak += terminal.length;
1051
+ if (success) this.clearAuthPause();
1052
+ if (keyRefused || streakPause) {
1053
+ const prev = this.readAuthPause();
1054
+ let wait;
1055
+ if (prev && Date.now() < prev.until) {
1056
+ wait = prev.until - Date.now();
1057
+ } else {
1058
+ const level = prev ? prev.level + 1 : 0;
1059
+ wait = Math.min(AUTH_PAUSE_MAX_MS, AUTH_PAUSE_BASE_MS * Math.pow(2, level));
1060
+ this.writeAuthPause({ until: Date.now() + wait, level, streak: this.terminalStreak });
1061
+ }
1062
+ this.authPaused += 1;
1063
+ if (streakPause) {
1064
+ logger.error(
1065
+ `Purchase drain: ${MAX_TERMINAL_STREAK}+ events refused in a row (400/413); evicting stopped, pausing ${Math.round(wait / 6e4)} min`
1066
+ );
1067
+ } else {
1068
+ logger.warn(
1069
+ `Purchase drain refused (key rejected, 401/403); nothing evicted, pausing ${Math.round(wait / 6e4)} min`
1070
+ );
1071
+ }
1072
+ if (!unloading && !this.destroyed) this.schedule(wait);
1073
+ return;
1074
+ }
1075
+ if (unloading || this.destroyed) return;
1076
+ if (success || terminal.length > 0) {
1077
+ this.attempt = 0;
1078
+ if (this.events.length > 0) this.schedule(0);
1079
+ return;
1080
+ }
1081
+ this.attempt += 1;
1082
+ this.schedule(PurchaseBacklog.retryDelayMs(this.attempt, retryAfterMs));
1083
+ }
1084
+ // ── internals ───────────────────────────────────────────────────────────
1085
+ /** The oldest purchases whose batch body fits one keepalive request. */
1086
+ unloadChunk() {
1087
+ const out = [];
1088
+ let bytes = ENVELOPE_BYTES;
1089
+ for (const e of this.events) {
1090
+ const b = utf8Bytes(JSON.stringify(e)) + 1;
1091
+ if (bytes + b > KEEPALIVE_BODY_MAX_BYTES) break;
1092
+ out.push(e);
1093
+ bytes += b;
1094
+ if (out.length >= PURCHASE_SEND_CHUNK) break;
1095
+ }
1096
+ return out;
1097
+ }
1098
+ readAuthPause() {
1099
+ try {
1100
+ if (typeof localStorage === "undefined") return null;
1101
+ const raw = localStorage.getItem(`${this.key}:auth_pause`);
1102
+ if (!raw) return null;
1103
+ const p = JSON.parse(raw);
1104
+ return typeof p.until === "number" && typeof p.level === "number" ? p : null;
1105
+ } catch {
1106
+ return null;
1107
+ }
1108
+ }
1109
+ writeAuthPause(p) {
1110
+ try {
1111
+ if (typeof localStorage !== "undefined") localStorage.setItem(`${this.key}:auth_pause`, JSON.stringify(p));
1112
+ } catch {
1113
+ }
1114
+ }
1115
+ clearAuthPause() {
1116
+ try {
1117
+ if (typeof localStorage !== "undefined") localStorage.removeItem(`${this.key}:auth_pause`);
1118
+ } catch {
1119
+ }
1120
+ }
1121
+ schedule(delayMs) {
1122
+ if (this.destroyed || this.timer) return;
1123
+ this.timer = setTimeout(() => {
1124
+ this.timer = null;
1125
+ void this.drain(false);
1126
+ }, delayMs);
1127
+ }
1128
+ clearTimer() {
1129
+ if (this.timer) {
1130
+ clearTimeout(this.timer);
1131
+ this.timer = null;
1132
+ }
1133
+ }
1134
+ settle(id) {
1135
+ if (id) this.settled.set(id, Date.now());
1136
+ }
1137
+ read() {
1138
+ try {
1139
+ if (typeof localStorage === "undefined") return { events: [], settled: {} };
1140
+ const raw = localStorage.getItem(this.key);
1141
+ if (!raw) return { events: [], settled: {} };
1142
+ const parsed = JSON.parse(raw);
1143
+ if (Array.isArray(parsed)) return { events: parsed, settled: {} };
1144
+ const obj = parsed || {};
1145
+ return {
1146
+ events: Array.isArray(obj.events) ? obj.events : [],
1147
+ settled: obj.settled && typeof obj.settled === "object" ? obj.settled : {}
1148
+ };
1149
+ } catch (error) {
1150
+ logger.warn("Failed to read purchase backlog:", error);
1151
+ return { events: [], settled: {} };
1152
+ }
1153
+ }
1154
+ /**
1155
+ * Merge with what other tabs wrote, apply the bounds, write back. The
1156
+ * union of events by messageId, minus every id any tab has settled.
1157
+ */
1158
+ persist() {
1159
+ const now = Date.now();
1160
+ const stored = this.read();
1161
+ for (const [id, t] of Object.entries(stored.settled)) {
1162
+ if (typeof t === "number" && (this.settled.get(id) ?? 0) < t) this.settled.set(id, t);
1163
+ }
1164
+ for (const [id, t] of this.settled) {
1165
+ if (now - t > SETTLED_RETENTION_MS) this.settled.delete(id);
1166
+ }
1167
+ if (this.settled.size > SETTLED_MAX) {
1168
+ const newest = [...this.settled.entries()].sort((a, b) => b[1] - a[1]).slice(0, SETTLED_MAX);
1169
+ this.settled = new Map(newest);
1170
+ }
1171
+ const byId = /* @__PURE__ */ new Map();
1172
+ const anon = [];
1173
+ for (const e of [...this.events, ...stored.events]) {
1174
+ if (!e || typeof e !== "object") continue;
1175
+ const id = idOf(e);
1176
+ if (!id) {
1177
+ anon.push(e);
1178
+ continue;
1179
+ }
1180
+ if (this.settled.has(id) || byId.has(id)) continue;
1181
+ byId.set(id, e);
1182
+ }
1183
+ let merged = [...byId.values(), ...anon].sort((a, b) => eventTime(a, now) - eventTime(b, now));
1184
+ const fresh = [];
1185
+ for (const e of merged) {
1186
+ if (now - eventTime(e, now) > MAX_PURCHASE_AGE_MS) {
1187
+ this.dropped.expired += 1;
1188
+ this.settle(idOf(e));
1189
+ logger.error("Purchase older than 7 days never accepted; evicted", redactMetaCookies(e));
1190
+ } else {
1191
+ fresh.push(e);
1192
+ }
1193
+ }
1194
+ merged = fresh;
1195
+ while (merged.length > MAX_PURCHASE_BACKLOG) {
1196
+ const evicted = merged.shift();
1197
+ this.dropped.overBound += 1;
1198
+ this.settle(idOf(evicted));
1199
+ logger.error(
1200
+ `Purchase backlog past its bound (${MAX_PURCHASE_BACKLOG}); evicting the oldest purchase`,
1201
+ redactMetaCookies(evicted)
1202
+ );
1203
+ }
1204
+ this.events = merged;
1205
+ try {
1206
+ if (typeof localStorage === "undefined") return;
1207
+ if (this.events.length === 0 && this.settled.size === 0) {
1208
+ localStorage.removeItem(this.key);
1209
+ return;
1210
+ }
1211
+ const settled = {};
1212
+ for (const [id, t] of this.settled) settled[id] = t;
1213
+ localStorage.setItem(this.key, JSON.stringify({ events: this.events, settled }));
1214
+ } catch (error) {
1215
+ logger.warn("Failed to persist purchase backlog:", error);
1216
+ }
1217
+ }
1218
+ countOrphans() {
1219
+ try {
1220
+ if (typeof localStorage === "undefined") return;
1221
+ for (let i = 0; i < localStorage.length; i++) {
1222
+ const k = localStorage.key(i);
1223
+ if (!k || !k.startsWith(PURCHASE_BACKLOG_PREFIX) || k === this.key) continue;
1224
+ const raw = localStorage.getItem(k);
1225
+ const parsed = raw ? JSON.parse(raw) : null;
1226
+ const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed == null ? void 0 : parsed.events) ? parsed.events : [];
1227
+ this.orphaned += list.length;
1228
+ }
1229
+ if (this.orphaned > 0) {
1230
+ logger.warn(
1231
+ `${this.orphaned} unsent purchase(s) are held under another write key on this origin; they are sent only when that key loads again`
1232
+ );
1233
+ }
1234
+ } catch {
1235
+ }
1236
+ }
1237
+ }
1238
+ class EventQueue {
1239
+ constructor(config, transport, storage) {
1240
+ this.buffer = [];
1241
+ this.flushInterval = null;
1242
+ this.isFlushing = false;
1243
+ this.offlineQueue = [];
1244
+ this.isOnline = navigator.onLine;
1245
+ this.config = config;
1246
+ this.transport = transport;
1247
+ this.storage = storage;
1248
+ this.purchases = new PurchaseBacklog(transport, config.persistNamespace);
1249
+ if (config.enableOfflineMode) {
1250
+ this.loadOfflineQueue();
1251
+ this.setupOnlineListener();
1252
+ } else {
1253
+ this.setupPurchaseOnlineListener();
1254
+ }
1255
+ this.startFlushTimer();
1256
+ this.setupUnloadHandlers();
1257
+ }
1258
+ loadOfflineQueue() {
1259
+ const offlineData = this.storage.get("offline_queue");
1260
+ if (!offlineData) {
1261
+ return;
1262
+ }
1263
+ try {
1264
+ const events = JSON.parse(offlineData);
1265
+ if (Array.isArray(events) && events.length > 0) {
1266
+ const rest = this.takePurchases(events);
1267
+ this.offlineQueue = rest.slice(0, this.config.maxOfflineEvents);
1268
+ logger.info(`Loaded ${this.offlineQueue.length} offline events`);
1269
+ if (this.isOnline) {
1270
+ this.flushOfflineQueue();
1271
+ }
1272
+ }
1273
+ } catch (error) {
1274
+ logger.warn("Failed to load offline queue:", error);
1275
+ this.storage.remove("offline_queue");
1276
+ }
1277
+ }
1278
+ saveOfflineQueue() {
1279
+ if (this.offlineQueue.length === 0) {
1280
+ this.storage.remove("offline_queue");
1281
+ return;
1282
+ }
1283
+ try {
1284
+ const data = JSON.stringify(this.offlineQueue);
1285
+ this.storage.set("offline_queue", data);
1286
+ logger.debug(`Saved ${this.offlineQueue.length} events to offline queue`);
1287
+ } catch (error) {
1288
+ logger.warn("Failed to save offline queue:", error);
1289
+ }
1290
+ }
1291
+ setupOnlineListener() {
1292
+ window.addEventListener("online", () => {
1293
+ logger.info("Connection restored");
1294
+ this.isOnline = true;
1295
+ this.purchases.retryNow();
1296
+ this.flushOfflineQueue();
1297
+ this.flush();
1298
+ });
1299
+ window.addEventListener("offline", () => {
1300
+ logger.warn("Connection lost, entering offline mode");
1301
+ this.isOnline = false;
1302
+ });
1303
+ }
1304
+ async flushOfflineQueue() {
1305
+ if (this.offlineQueue.length === 0) {
1306
+ return;
824
1307
  }
825
- const endpoint = this.getActiveEndpoint();
826
- const payload = this.buildPayload(events);
827
- logger.debug("Sending batch:", { endpoint, eventCount: events.length });
828
- if (document.visibilityState === "hidden" && typeof navigator.sendBeacon === "function") {
829
- const result = this.sendViaBeacon(endpoint, payload);
830
- return Promise.resolve(result);
1308
+ logger.info(`Flushing ${this.offlineQueue.length} offline events`);
1309
+ const events = [...this.offlineQueue];
1310
+ this.offlineQueue = [];
1311
+ this.storage.remove("offline_queue");
1312
+ const result = await this.transport.send(events);
1313
+ if (!result.success) {
1314
+ logger.warn("Failed to send offline events, re-queueing");
1315
+ const unaccepted = this.takePurchases(result.rejected ?? events);
1316
+ this.offlineQueue = [...unaccepted, ...this.offlineQueue].slice(
1317
+ 0,
1318
+ this.config.maxOfflineEvents
1319
+ );
1320
+ this.saveOfflineQueue();
831
1321
  } else {
832
- return this.sendViaFetch(endpoint, payload);
1322
+ logger.info("Offline events sent successfully");
833
1323
  }
834
1324
  }
835
- getActiveEndpoint() {
836
- if (this.activeCell) {
837
- return `${this.activeCell.url}/v1/batch`;
1325
+ push(event) {
1326
+ if (isPurchaseEvent(event)) {
1327
+ this.purchases.add(event);
1328
+ logger.debug("Purchase queued:", event.type, redactMetaCookies(event));
1329
+ return;
838
1330
  }
839
- if (this.config.apiHost) {
840
- return `${this.config.apiHost}/v1/batch`;
1331
+ if (!this.isOnline && this.config.enableOfflineMode) {
1332
+ this.addToOfflineQueue(event);
1333
+ return;
1334
+ }
1335
+ this.buffer.push(event);
1336
+ logger.debug("Event queued:", event.type, redactMetaCookies(event));
1337
+ if (this.buffer.length >= this.config.batchSize) {
1338
+ this.flush();
841
1339
  }
842
- throw new Error("No active endpoint available");
843
1340
  }
844
- buildPayload(events) {
845
- return {
846
- batch: events,
847
- sentAt: (/* @__PURE__ */ new Date()).toISOString(),
848
- writeKey: this.config.writeKey,
849
- context: this.activeCell ? {
850
- cell: {
851
- region: this.activeCell.region,
852
- endpoint: this.activeCell.url
853
- }
854
- } : void 0
855
- };
1341
+ addToOfflineQueue(event) {
1342
+ if (isPurchaseEvent(event)) {
1343
+ this.purchases.add(event);
1344
+ return;
1345
+ }
1346
+ if (this.offlineQueue.length >= this.config.maxOfflineEvents) {
1347
+ logger.warn("Offline queue full, dropping oldest event");
1348
+ this.offlineQueue.shift();
1349
+ }
1350
+ this.offlineQueue.push(event);
1351
+ this.saveOfflineQueue();
1352
+ logger.debug("Event added to offline queue");
856
1353
  }
857
- sendViaBeacon(endpoint, payload) {
1354
+ async flush() {
1355
+ if (this.isFlushing) {
1356
+ logger.debug("Flush already in progress, skipping");
1357
+ return;
1358
+ }
1359
+ if (this.buffer.length === 0) {
1360
+ return;
1361
+ }
1362
+ this.isFlushing = true;
1363
+ const events = this.takePurchases([...this.buffer]);
1364
+ this.buffer = [];
1365
+ if (events.length === 0) {
1366
+ this.isFlushing = false;
1367
+ return;
1368
+ }
1369
+ logger.info(`Flushing ${events.length} events`);
858
1370
  try {
859
- const blob = new Blob([JSON.stringify(payload)], {
860
- type: "application/json"
861
- });
862
- const sent = navigator.sendBeacon(endpoint, blob);
863
- if (sent) {
864
- logger.debug("Batch sent via Beacon");
865
- return { success: true, endpoint };
1371
+ const result = await this.transport.send(events);
1372
+ if (!result.success) {
1373
+ logger.error("Failed to send events:", result.error);
1374
+ const unaccepted = result.rejected ?? events;
1375
+ if (this.config.enableOfflineMode) {
1376
+ this.offlineQueue = [...this.offlineQueue, ...unaccepted].slice(
1377
+ 0,
1378
+ this.config.maxOfflineEvents
1379
+ );
1380
+ this.saveOfflineQueue();
1381
+ logger.info("Events saved to offline queue");
1382
+ } else {
1383
+ this.buffer.unshift(...unaccepted);
1384
+ logger.warn("Events re-queued for retry");
1385
+ }
866
1386
  } else {
867
- logger.warn("Beacon send failed, falling back to fetch");
868
- return this.sendViaFetch(endpoint, payload);
1387
+ logger.info("Events sent successfully");
869
1388
  }
870
1389
  } catch (error) {
871
- logger.error("Beacon send error:", error);
872
- return {
873
- success: false,
874
- error,
875
- endpoint
876
- };
1390
+ logger.error("Flush error:", error);
1391
+ if (this.config.enableOfflineMode) {
1392
+ this.offlineQueue = [...this.offlineQueue, ...events].slice(
1393
+ 0,
1394
+ this.config.maxOfflineEvents
1395
+ );
1396
+ this.saveOfflineQueue();
1397
+ }
1398
+ } finally {
1399
+ this.isFlushing = false;
877
1400
  }
878
1401
  }
879
- async sendViaFetch(endpoint, payload, attempt = 1) {
880
- try {
881
- const controller = new AbortController();
882
- const timeoutId = setTimeout(
883
- () => controller.abort(),
884
- this.config.requestTimeout
885
- );
886
- const response = await fetch(endpoint, {
887
- method: "POST",
888
- headers: {
889
- "Content-Type": "application/json",
890
- Authorization: `Bearer ${this.config.writeKey}`
891
- },
892
- body: JSON.stringify(payload),
893
- keepalive: true,
894
- signal: controller.signal
895
- });
896
- clearTimeout(timeoutId);
897
- if (response.ok) {
898
- const result = await response.json();
899
- logger.debug("Batch sent successfully:", result);
900
- return { success: true, response: result, endpoint };
901
- } else {
902
- const errorText = await response.text();
903
- const error = new Error(
904
- `HTTP ${response.status}: ${errorText || response.statusText}`
905
- );
906
- logger.error("Batch send failed:", error);
907
- if (this.shouldRetry(response.status, attempt)) {
908
- return this.retryRequest(endpoint, payload, attempt);
909
- }
910
- return { success: false, error, endpoint };
1402
+ startFlushTimer() {
1403
+ if (this.flushInterval) {
1404
+ clearInterval(this.flushInterval);
1405
+ }
1406
+ this.flushInterval = window.setInterval(() => {
1407
+ this.flush();
1408
+ }, this.config.batchInterval);
1409
+ logger.debug(
1410
+ `Flush timer started with interval: ${this.config.batchInterval}ms`
1411
+ );
1412
+ }
1413
+ setupUnloadHandlers() {
1414
+ const flushBeforeUnload = () => {
1415
+ this.purchases.flushOnUnload();
1416
+ if (this.buffer.length > 0 || this.offlineQueue.length > 0) {
1417
+ this.persistBufferToOfflineQueue();
1418
+ this.flush();
911
1419
  }
912
- } catch (error) {
913
- logger.error("Fetch error:", error);
914
- if (this.shouldRetry(0, attempt)) {
915
- return this.retryRequest(endpoint, payload, attempt);
1420
+ };
1421
+ document.addEventListener("visibilitychange", () => {
1422
+ if (document.visibilityState === "hidden") {
1423
+ flushBeforeUnload();
916
1424
  }
917
- return {
918
- success: false,
919
- error,
920
- endpoint
921
- };
922
- }
1425
+ });
1426
+ window.addEventListener("beforeunload", flushBeforeUnload);
1427
+ window.addEventListener("pagehide", flushBeforeUnload);
923
1428
  }
924
- shouldRetry(statusCode, attempt) {
925
- if (!this.config.retryFailedRequests) {
926
- return false;
1429
+ persistBufferToOfflineQueue() {
1430
+ if (this.buffer.length === 0) {
1431
+ return;
927
1432
  }
928
- if (attempt >= this.config.maxRetries) {
929
- return false;
1433
+ if (this.config.enableOfflineMode) {
1434
+ const rest = this.takePurchases([...this.buffer]);
1435
+ this.offlineQueue = [...this.offlineQueue, ...rest].slice(
1436
+ 0,
1437
+ this.config.maxOfflineEvents
1438
+ );
1439
+ this.saveOfflineQueue();
1440
+ logger.debug("Buffer persisted to offline queue before unload");
930
1441
  }
931
- if (statusCode === 0) {
932
- return true;
1442
+ }
1443
+ // ── purchase backlog ────────────────────────────────────────────────────
1444
+ /** Move every purchase in `events` to the backlog; return the rest. */
1445
+ takePurchases(events) {
1446
+ const rest = [];
1447
+ for (const e of events) {
1448
+ if (isPurchaseEvent(e)) this.purchases.add(e);
1449
+ else rest.push(e);
933
1450
  }
934
- return statusCode >= 500 || statusCode === 429;
1451
+ return rest;
935
1452
  }
936
- async retryRequest(endpoint, payload, attempt) {
937
- const delay = Math.pow(this.config.retryBackoffMultiplier, attempt) * 1e3;
938
- logger.info(`Retrying request in ${delay}ms (attempt ${attempt + 1})`);
939
- await new Promise((resolve) => setTimeout(resolve, delay));
940
- return this.sendViaFetch(endpoint, payload, attempt + 1);
1453
+ setupPurchaseOnlineListener() {
1454
+ if (typeof window === "undefined") return;
1455
+ window.addEventListener("online", () => {
1456
+ this.isOnline = true;
1457
+ this.purchases.retryNow();
1458
+ });
941
1459
  }
942
- getActiveCell() {
943
- return this.activeCell;
1460
+ /** Send the backlog now (one request's worth; re-tries are scheduled). */
1461
+ flushPurchases() {
1462
+ return this.purchases.drain(false);
944
1463
  }
945
- getRegionLatencies() {
946
- return new Map(this.regionLatencyMap);
1464
+ /** Backoff before purchase try `attempt` (1-based), honouring Retry-After. */
1465
+ static purchaseRetryDelayMs(attempt, retryAfterMs, jitter = Math.random()) {
1466
+ return PurchaseBacklog.retryDelayMs(attempt, retryAfterMs, jitter);
1467
+ }
1468
+ getPurchaseBacklogSize() {
1469
+ return this.purchases.size();
1470
+ }
1471
+ /** Purchases evicted under a bound this page life (0 in normal use). */
1472
+ getDroppedPurchaseCount() {
1473
+ return this.purchases.totalDropped();
1474
+ }
1475
+ /** 401/403 refusals that paused purchase drains (nothing is evicted for them). */
1476
+ getAuthPausedCount() {
1477
+ return this.purchases.authPaused;
1478
+ }
1479
+ /** Purchases held under another write key's backlog on this origin. */
1480
+ getOrphanedPurchaseCount() {
1481
+ return this.purchases.orphaned;
1482
+ }
1483
+ getQueueSize() {
1484
+ return this.buffer.length;
1485
+ }
1486
+ getOfflineQueueSize() {
1487
+ return this.offlineQueue.length;
1488
+ }
1489
+ /**
1490
+ * Forget everything queued, purchases included. An explicit wipe by the
1491
+ * embedder (no SDK path calls it): the only way a held purchase is removed
1492
+ * without a 2xx, besides the MAX_PURCHASE_BACKLOG eviction.
1493
+ */
1494
+ clear() {
1495
+ this.buffer = [];
1496
+ this.offlineQueue = [];
1497
+ this.storage.remove("offline_queue");
1498
+ this.purchases.clear();
1499
+ logger.info("Queue cleared");
947
1500
  }
948
1501
  destroy() {
949
- if (this.healthCheckInterval) {
950
- clearInterval(this.healthCheckInterval);
951
- this.healthCheckInterval = null;
1502
+ if (this.flushInterval) {
1503
+ clearInterval(this.flushInterval);
1504
+ this.flushInterval = null;
952
1505
  }
1506
+ this.purchases.destroy();
1507
+ this.flush();
953
1508
  }
954
1509
  }
955
1510
  const STORAGE_PREFIX = "aegis_";
@@ -1711,6 +2266,27 @@ class ConsentManager {
1711
2266
  updateGoogleConsent();
1712
2267
  }
1713
2268
  }
2269
+ const MAX_TOKEN_LENGTH = 600;
2270
+ function previewAsOfToken() {
2271
+ if (typeof window === "undefined" || !window.location) return null;
2272
+ try {
2273
+ const v = new URLSearchParams(window.location.search || "").get("preview_as_of");
2274
+ return v && v.length <= MAX_TOKEN_LENGTH ? v : null;
2275
+ } catch {
2276
+ return null;
2277
+ }
2278
+ }
2279
+ function hasEditorPreviewMarker(search) {
2280
+ return search.has("preview_as_of") || search.get("section_names") === "1" || search.has("preview_store") || search.has("campaign_preview") || search.get("preview") === "admin";
2281
+ }
2282
+ function isPreviewPage() {
2283
+ if (typeof window === "undefined" || !window.location) return false;
2284
+ try {
2285
+ return hasEditorPreviewMarker(new URLSearchParams(window.location.search || ""));
2286
+ } catch {
2287
+ return false;
2288
+ }
2289
+ }
1714
2290
  const ITEM_TOUCH_KEY = "aegis_inapp_item_touch";
1715
2291
  const ITEM_TOUCH_TTL_MS = 30 * 60 * 1e3;
1716
2292
  function store() {
@@ -1751,6 +2327,15 @@ function readInAppItemTouch(sku, now = Date.now()) {
1751
2327
  function sumItems(products) {
1752
2328
  return products.reduce((sum, p) => sum + (p.quantity ?? 1), 0);
1753
2329
  }
2330
+ const ORDER_CHANNEL = "online_store";
2331
+ const FULFILLMENT_MODES = /* @__PURE__ */ new Set(["pickup", "delivery"]);
2332
+ function orderFulfillmentMode(order) {
2333
+ const raw = order.fulfillment_mode;
2334
+ const declared = typeof raw === "string" ? raw.trim().toLowerCase() : "";
2335
+ if (FULFILLMENT_MODES.has(declared)) return declared;
2336
+ if (typeof order.shipping === "number" && order.shipping > 0) return "delivery";
2337
+ return void 0;
2338
+ }
1754
2339
  function mapProducts(products) {
1755
2340
  return products.map((p) => ({
1756
2341
  product_id: p.product_id,
@@ -1957,6 +2542,12 @@ class EcommerceTracker {
1957
2542
  tax: order.tax,
1958
2543
  discount: order.discount,
1959
2544
  payment_method: order.payment_method,
2545
+ fulfillment_mode: orderFulfillmentMode(order),
2546
+ // Where the order was placed: the brand's own website. Said outright,
2547
+ // because a channel-less order with fulfillment_mode=delivery resolves to
2548
+ // the delivery-apps group server-side, and the order journey then sends
2549
+ // no confirmation. `online_store` is a value the resolver maps to online.
2550
+ channel: ORDER_CHANNEL,
1960
2551
  products: mapProducts(order.products)
1961
2552
  });
1962
2553
  }
@@ -2643,6 +3234,10 @@ class Aegis {
2643
3234
  logger.info("Do Not Track is enabled, SDK disabled");
2644
3235
  return;
2645
3236
  }
3237
+ if (isPreviewPage()) {
3238
+ logger.info("Editor preview, SDK records nothing");
3239
+ return;
3240
+ }
2646
3241
  if (isBot()) {
2647
3242
  logger.info("Bot detected, SDK disabled");
2648
3243
  return;
@@ -2696,7 +3291,8 @@ class Aegis {
2696
3291
  batchSize: this.config.batch_size,
2697
3292
  batchInterval: this.config.batch_interval,
2698
3293
  enableOfflineMode: this.config.enable_offline_mode,
2699
- maxOfflineEvents: this.config.max_offline_events
3294
+ maxOfflineEvents: this.config.max_offline_events,
3295
+ persistNamespace: this.config.write_key
2700
3296
  },
2701
3297
  this.transport,
2702
3298
  this.storage
@@ -3178,14 +3774,14 @@ class Aegis {
3178
3774
  if (event.type === "track") {
3179
3775
  const trackEvent = event;
3180
3776
  const isMetaEvent = typeof trackEvent.event === "string" && trackEvent.event.startsWith("aegis.client.");
3181
- if (!isMetaEvent && !this.nameGovernor.shouldSend(trackEvent.event)) {
3777
+ if (!isMetaEvent && !isPurchaseEvent(event) && !this.nameGovernor.shouldSend(trackEvent.event)) {
3182
3778
  return;
3183
3779
  }
3184
3780
  }
3185
3781
  if (this.rateLimiter) {
3186
3782
  const eventLabel = event.type === "track" && event.event ? event.event : event.type;
3187
3783
  const isMetaEvent = event.type === "track" && typeof event.event === "string" && event.event.startsWith("aegis.client.");
3188
- if (!isMetaEvent && !this.rateLimiter.tryConsume(eventLabel)) {
3784
+ if (!isMetaEvent && !isPurchaseEvent(event) && !this.rateLimiter.tryConsume(eventLabel)) {
3189
3785
  return;
3190
3786
  }
3191
3787
  }
@@ -3544,8 +4140,11 @@ export {
3544
4140
  UserNamespace as U,
3545
4141
  recordInAppItemTouch as a,
3546
4142
  ensureFbc as e,
4143
+ generateUUID as g,
4144
+ isPreviewPage as i,
3547
4145
  logger as l,
3548
4146
  murmurhash3_x86_32 as m,
4147
+ previewAsOfToken as p,
3549
4148
  redactUrl as r
3550
4149
  };
3551
- //# sourceMappingURL=analytics-zA6ckfKP.mjs.map
4150
+ //# sourceMappingURL=analytics-DMY0Q0rI.mjs.map