@active-reach/web-sdk 1.52.0 → 1.53.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.
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
- import { g as generateUUID, S as Storage, r as redactUrl, i as isPreviewPage, p as previewAsOfToken, a as recordInAppItemTouch, e as ensureFbc, l as logger, A as Aegis } from "./analytics-DMY0Q0rI.mjs";
2
- import { B, E, N, R, U, m } from "./analytics-DMY0Q0rI.mjs";
1
+ import { g as generateUUID, r as recordInAppItemTouch, e as ensureFbc, l as logger, A as Aegis } from "./analytics-CM31xECy.mjs";
2
+ import { B, E, N, R, U, m } from "./analytics-CM31xECy.mjs";
3
+ import { S as Storage, r as redactUrl, i as isPreviewPage } from "./storage-D5jp9bO-.mjs";
4
+ import { r as readAnonIdFromStorage$1, m as markReturningVisitor, a as activeRequestKey, c as cartKeyPartOf, K as KNOWN_SURFACES, b as buildActiveRequest, t as takeActiveBoot, d as fetchWithAbort, f as fetchWithAbortRetry, e as detectDeviceType, g as readABAssignments, h as currentPageUrl, i as isNewVisitor, j as isAbortError, S as SDK_FETCH_ABORT_MS } from "./fetch-abort-Bs-Stg-I.mjs";
3
5
  import { a as assetIdOf } from "./AegisWebPush-BE9wJcx0.mjs";
4
6
  import { A } from "./AegisWebPush-BE9wJcx0.mjs";
5
7
  function debounce(func, wait) {
@@ -8667,54 +8669,6 @@ function drawSlotShells(ctx, doc = document) {
8667
8669
  });
8668
8670
  return drawn;
8669
8671
  }
8670
- const RETURNING_MARKER_KEY = "aegis_returning_user";
8671
- const SESSION_VERDICT_KEY = "aegis_new_visitor_session";
8672
- let cachedVerdict = null;
8673
- function readSessionVerdict() {
8674
- try {
8675
- if (typeof sessionStorage === "undefined") return null;
8676
- const stored = sessionStorage.getItem(SESSION_VERDICT_KEY);
8677
- if (stored === "1") return true;
8678
- if (stored === "0") return false;
8679
- return null;
8680
- } catch {
8681
- return null;
8682
- }
8683
- }
8684
- function writeSessionVerdict(verdict) {
8685
- try {
8686
- if (typeof sessionStorage === "undefined") return;
8687
- sessionStorage.setItem(SESSION_VERDICT_KEY, verdict ? "1" : "0");
8688
- } catch {
8689
- }
8690
- }
8691
- function readMarkerVerdict() {
8692
- try {
8693
- if (typeof localStorage === "undefined") return false;
8694
- return localStorage.getItem(RETURNING_MARKER_KEY) === null;
8695
- } catch {
8696
- return false;
8697
- }
8698
- }
8699
- function isNewVisitor() {
8700
- if (cachedVerdict !== null) return cachedVerdict;
8701
- const sessionVerdict = readSessionVerdict();
8702
- if (sessionVerdict !== null) {
8703
- cachedVerdict = sessionVerdict;
8704
- return cachedVerdict;
8705
- }
8706
- cachedVerdict = readMarkerVerdict();
8707
- writeSessionVerdict(cachedVerdict);
8708
- return cachedVerdict;
8709
- }
8710
- function markReturningVisitor() {
8711
- isNewVisitor();
8712
- try {
8713
- if (typeof localStorage === "undefined") return;
8714
- localStorage.setItem(RETURNING_MARKER_KEY, "1");
8715
- } catch {
8716
- }
8717
- }
8718
8672
  const DEFAULT_SCROLL_DEPTH_PERCENT = 50;
8719
8673
  const DEFAULT_TIME_ON_PAGE_SECONDS = 30;
8720
8674
  const DEFAULT_IDLE_SECONDS = 30;
@@ -8779,27 +8733,6 @@ function armBehaviouralTriggers(engine, triggers, armed, fire, isMobile) {
8779
8733
  }
8780
8734
  return newlyArmed;
8781
8735
  }
8782
- const SDK_FETCH_ABORT_MS = 800;
8783
- function fetchWithAbort(input, init = {}, timeoutMs = SDK_FETCH_ABORT_MS) {
8784
- const budget = Math.min(timeoutMs, SDK_FETCH_ABORT_MS);
8785
- if (typeof AbortController === "undefined") {
8786
- return fetch(input, init);
8787
- }
8788
- const controller = new AbortController();
8789
- const outer = init.signal;
8790
- if (outer) {
8791
- if (outer.aborted) controller.abort();
8792
- else outer.addEventListener("abort", () => controller.abort(), { once: true });
8793
- }
8794
- const timer = setTimeout(() => controller.abort(), budget);
8795
- return fetch(input, { ...init, signal: controller.signal }).catch((err) => {
8796
- clearTimeout(timer);
8797
- throw err;
8798
- });
8799
- }
8800
- function isAbortError(err) {
8801
- return !!err && typeof err === "object" && (err.name === "AbortError" || err.name === "TimeoutError");
8802
- }
8803
8736
  const LAST_GOOD_PREFIX = "aegis_rail_lastgood:v1:";
8804
8737
  const LAST_GOOD_SPECIFIC_PREFIX = "aegis_rail_lastgood_specific:v1:";
8805
8738
  const POPULAR_PREFIX = "aegis_rail_popular:v1:";
@@ -8938,15 +8871,6 @@ function readRailFallback(ctx, now = Date.now(), audience = {}) {
8938
8871
  if (popular.length > 0) return { tier: "popular", campaigns: popular };
8939
8872
  return { tier: "hidden", campaigns: [] };
8940
8873
  }
8941
- function readAnonIdFromStorage$1() {
8942
- if (typeof document === "undefined") return void 0;
8943
- try {
8944
- const storage = new Storage();
8945
- return storage.get("anon_id") ?? void 0;
8946
- } catch {
8947
- return void 0;
8948
- }
8949
- }
8950
8874
  function readAdClickIdsFromStorage() {
8951
8875
  const out = {};
8952
8876
  if (typeof document === "undefined") return out;
@@ -9061,6 +8985,8 @@ const _AegisInAppManager = class _AegisInAppManager {
9061
8985
  this.pendingAnchorRender = false;
9062
8986
  this.slotsTornDown = false;
9063
8987
  this.campaignsLoaded = false;
8988
+ this.activeETag = null;
8989
+ this.activeETagKey = void 0;
9064
8990
  this.shellTimeout = null;
9065
8991
  this.lifecycleGen = 0;
9066
8992
  this.slotUnfilledBeaconed = /* @__PURE__ */ new Set();
@@ -9321,8 +9247,25 @@ const _AegisInAppManager = class _AegisInAppManager {
9321
9247
  }
9322
9248
  /** The page context a `/v1/in-app/active` request is built from now. */
9323
9249
  activeRequestKey() {
9324
- const url = this.currentPageUrl() ?? "/";
9325
- return [url, this.currentSurface ?? "", this.currentScreen ?? "", this.currentLocationId ?? "", this.cartKeyPart()].join("|");
9250
+ return activeRequestKey(this.requestContext());
9251
+ }
9252
+ /** Everything the shared /active builder needs (inapp/active-request.ts):
9253
+ * the ONE place this manager's request is described. */
9254
+ requestContext() {
9255
+ return {
9256
+ apiHost: this.apiHost,
9257
+ writeKey: this.writeKey,
9258
+ userId: this.userId,
9259
+ contactId: this.contactId,
9260
+ contactToken: this.contactToken,
9261
+ organizationId: this.organizationId,
9262
+ propertyId: this.propertyId,
9263
+ surface: this.currentSurface,
9264
+ screen: this.currentScreen,
9265
+ locationId: this.currentLocationId,
9266
+ cartProductIds: this.currentCartProductIds,
9267
+ previewOnly: this.previewOnly
9268
+ };
9326
9269
  }
9327
9270
  /** The cart ids as a request-key part: sorted + deduped so a reorder is not a
9328
9271
  * change; `-` = no cart known, distinct from `` = an empty cart. */
@@ -9345,7 +9288,7 @@ const _AegisInAppManager = class _AegisInAppManager {
9345
9288
  return out;
9346
9289
  }
9347
9290
  cartKeyPartOf(ids) {
9348
- return ids === null ? "-" : [...ids].sort().join(",");
9291
+ return cartKeyPartOf(ids);
9349
9292
  }
9350
9293
  /**
9351
9294
  * Qualifying-event refresh — schedule a debounced `refreshCampaigns()`
@@ -9668,75 +9611,57 @@ const _AegisInAppManager = class _AegisInAppManager {
9668
9611
  }
9669
9612
  }, delay);
9670
9613
  }
9671
- async refreshCampaigns() {
9614
+ refreshCampaigns() {
9615
+ const key = this.activeRequestKey();
9616
+ if (this.inflightActive && this.inflightActive.key === key) {
9617
+ this.log("refreshCampaigns() — joining the in-flight /active for this page context");
9618
+ return this.inflightActive.promise;
9619
+ }
9620
+ const entry = { key, promise: Promise.resolve() };
9621
+ entry.promise = this.refreshCampaignsNow().finally(() => {
9622
+ if (this.inflightActive === entry) this.inflightActive = void 0;
9623
+ });
9624
+ this.inflightActive = entry;
9625
+ return entry.promise;
9626
+ }
9627
+ async refreshCampaignsNow() {
9672
9628
  const gen = this.lifecycleGen;
9673
9629
  let requestKey;
9674
9630
  try {
9675
- const context = new URLSearchParams({
9676
- device_type: this.detectDeviceType(),
9677
- // Credential params keep their key and lose their value, so a
9678
- // `*placed=1*` / `*?step=cart*` rule still matches.
9679
- page_url: typeof window !== "undefined" ? redactUrl(window.location.pathname + window.location.search) : "/"
9680
- });
9681
- context.set("is_new_user", isNewVisitor() ? "true" : "false");
9682
- if (this.currentSurface) {
9683
- context.set("current_surface", this.currentSurface);
9684
- }
9685
- if (this.currentScreen) {
9686
- context.set("current_screen", this.currentScreen);
9687
- }
9688
- if (this.currentLocationId) {
9689
- context.set("location_id", this.currentLocationId);
9690
- }
9691
- if (this.currentCartProductIds !== null) {
9692
- context.set("cart_product_ids", this.currentCartProductIds.join(","));
9693
- }
9694
- const previewAsOf = previewAsOfToken();
9695
- if (previewAsOf) {
9696
- context.set("preview_as_of", previewAsOf);
9697
- }
9698
- if (this.previewOnly) {
9699
- context.set("preview", "1");
9700
- }
9701
- const url = `${this.apiHost}/v1/in-app/active?${context.toString()}`;
9702
- requestKey = this.activeRequestKey();
9631
+ const req = buildActiveRequest(this.requestContext());
9632
+ const url = req.url;
9633
+ requestKey = req.key;
9703
9634
  this.lastActiveRequestKey = requestKey;
9704
9635
  const shellCtx = this.shellContext();
9705
9636
  const railAudience = this.railAudience();
9706
- const headers = {
9707
- "X-Aegis-Write-Key": this.writeKey,
9708
- "Content-Type": "application/json"
9709
- };
9710
- if (this.userId) {
9711
- headers["X-User-ID"] = this.userId;
9712
- }
9713
- if (this.contactId) {
9714
- headers["X-Contact-ID"] = this.contactId;
9715
- }
9716
- if (this.contactId && this.contactToken) {
9717
- headers["X-Contact-Token"] = this.contactToken;
9718
- }
9719
- if (this.organizationId) {
9720
- headers["X-Organization-ID"] = this.organizationId;
9721
- }
9722
- if (this.propertyId) {
9723
- headers["X-Property-Id"] = this.propertyId;
9724
- }
9725
- const abAssignments = this.getABAssignments();
9726
- if (Object.keys(abAssignments).length > 0) {
9727
- headers["X-AB-Assignments"] = btoa(JSON.stringify(abAssignments));
9728
- }
9729
- const response = await fetchWithAbort(url, {
9637
+ const conditional = this.campaignsLoaded && this.activeETag !== null && this.activeETagKey === requestKey;
9638
+ if (conditional && this.activeETag) {
9639
+ req.headers["If-None-Match"] = this.activeETag;
9640
+ }
9641
+ const boot = takeActiveBoot(req);
9642
+ const adopted = this.campaignsLoaded ? null : boot;
9643
+ if (adopted) this.log("Adopting the early-boot /active read for this page");
9644
+ const fetchActive = this.campaignsLoaded ? fetchWithAbort : fetchWithAbortRetry;
9645
+ const response = adopted ? await adopted : await fetchActive(url, {
9730
9646
  method: "GET",
9731
- headers,
9647
+ headers: req.headers,
9732
9648
  credentials: "include"
9733
9649
  });
9734
9650
  if (gen !== this.lifecycleGen) return;
9735
- if (!response.ok) {
9736
- throw new Error(`Failed to fetch campaigns: ${response.status}`);
9651
+ let payload;
9652
+ if (response.status === 304 && conditional) {
9653
+ this.log("Active campaigns unchanged (304)");
9654
+ payload = this.campaigns;
9655
+ } else {
9656
+ if (!response.ok) {
9657
+ throw new Error(`Failed to fetch campaigns: ${response.status}`);
9658
+ }
9659
+ payload = await response.json();
9660
+ if (gen !== this.lifecycleGen) return;
9661
+ const tag = response.headers && typeof response.headers.get === "function" ? response.headers.get("ETag") : null;
9662
+ this.activeETag = tag;
9663
+ this.activeETagKey = tag ? requestKey : void 0;
9737
9664
  }
9738
- const payload = await response.json();
9739
- if (gen !== this.lifecycleGen) return;
9740
9665
  this.campaigns = Array.isArray(payload) ? payload : [];
9741
9666
  this.campaignsLoaded = true;
9742
9667
  this.railFallbackTier = null;
@@ -9789,22 +9714,13 @@ const _AegisInAppManager = class _AegisInAppManager {
9789
9714
  }
9790
9715
  // --- Client Context Helpers (Critical Fix B) ---
9791
9716
  detectDeviceType() {
9792
- if (typeof navigator === "undefined") return "desktop";
9793
- const ua = navigator.userAgent;
9794
- if (/Mobi|Android/i.test(ua)) return "mobile";
9795
- if (/iPad|Tablet/i.test(ua)) return "tablet";
9796
- return "desktop";
9717
+ return detectDeviceType();
9797
9718
  }
9798
9719
  // --- A/B Assignment Persistence (Critical Fix C) ---
9799
9720
  // Both A/B helpers sit on the campaign-fetch path, so blocked storage
9800
9721
  // (where even `typeof localStorage` throws) must not abort the fetch.
9801
9722
  getABAssignments() {
9802
- try {
9803
- if (typeof localStorage === "undefined") return {};
9804
- return JSON.parse(localStorage.getItem("aegis_ab_assignments") || "{}");
9805
- } catch {
9806
- return {};
9807
- }
9723
+ return readABAssignments();
9808
9724
  }
9809
9725
  processABAssignments(campaigns) {
9810
9726
  const stored = this.getABAssignments();
@@ -9934,8 +9850,7 @@ const _AegisInAppManager = class _AegisInAppManager {
9934
9850
  * as `page_url` (pathname + search, credential values redacted). Null off
9935
9851
  * the browser — no page, no filter (the server's rule too). */
9936
9852
  currentPageUrl() {
9937
- if (typeof window === "undefined" || !window.location) return null;
9938
- return redactUrl((window.location.pathname || "") + (window.location.search || ""));
9853
+ return currentPageUrl();
9939
9854
  }
9940
9855
  /** The full client placement gate: screen/surface tier AND page rules, both
9941
9856
  * mirroring `/v1/in-app/active`, applied to CACHED campaigns (the page may
@@ -15584,6 +15499,9 @@ const _AegisInAppManager = class _AegisInAppManager {
15584
15499
  this.removeShells({ sdkOnly: true });
15585
15500
  this.campaignsLoaded = false;
15586
15501
  this.campaignsRequestKey = void 0;
15502
+ this.inflightActive = void 0;
15503
+ this.activeETag = null;
15504
+ this.activeETagKey = void 0;
15587
15505
  if (typeof document !== "undefined") {
15588
15506
  document.querySelectorAll(
15589
15507
  ".aegis-in-app-banner, .aegis-in-app-modal-overlay, .aegis-in-app-fullscreen-overlay, .aegis-in-app-half-interstitial-overlay, .aegis-in-app-alert-overlay, .aegis-in-app-pip, .aegis-in-app-nps-overlay, .aegis-in-app-countdown-overlay, .aegis-in-app-rating-overlay, .aegis-in-app-poll-overlay, .aegis-in-app-quiz-overlay, .aegis-in-app-rating-card, .aegis-in-app-nps-card"
@@ -15606,19 +15524,7 @@ const _AegisInAppManager = class _AegisInAppManager {
15606
15524
  };
15607
15525
  _AegisInAppManager.CONVERSION_STORAGE_PREFIX = "aegis_conv_";
15608
15526
  _AegisInAppManager.REFRESH_DEBOUNCE_MS = 300;
15609
- _AegisInAppManager.KNOWN_SURFACES = /* @__PURE__ */ new Set([
15610
- "bill",
15611
- "storefront_catalog",
15612
- "storefront_rewards",
15613
- "storefront_feedback",
15614
- "storefront_reviews",
15615
- "storefront_members",
15616
- "storefront_orders",
15617
- "storefront_account",
15618
- "storefront_referrals",
15619
- "external_website",
15620
- "external_mobile_screen"
15621
- ]);
15527
+ _AegisInAppManager.KNOWN_SURFACES = KNOWN_SURFACES;
15622
15528
  _AegisInAppManager.SERVED_DEDUP_PREFIX = "aegis_served_fired:";
15623
15529
  _AegisInAppManager.SHELL_TIMEOUT_MS = 1e4;
15624
15530
  _AegisInAppManager.JOURNEY_ACK_RETRY_MS = 2e3;
@@ -16384,7 +16290,8 @@ class PrefetchBundleClient {
16384
16290
  }
16385
16291
  let response;
16386
16292
  try {
16387
- response = await fetchWithAbort(url, { method: "GET", headers, cache: "no-cache" });
16293
+ const fetchBundle = this.currentBundle ? fetchWithAbort : fetchWithAbortRetry;
16294
+ response = await fetchBundle(url, { method: "GET", headers, cache: "no-cache" });
16388
16295
  } catch (err) {
16389
16296
  logger.warn("prefetch-bundle fetch network error:", err);
16390
16297
  return this.currentBundle;
@@ -16766,6 +16673,8 @@ class AegisWidgetManager {
16766
16673
  this.isInitialized = false;
16767
16674
  this.isDestroyed = false;
16768
16675
  this.prefetchWidgetConfigs = {};
16676
+ this.widgetsLoaded = false;
16677
+ this.prefetchConfigsLoaded = false;
16769
16678
  this.writeKey = config.writeKey;
16770
16679
  this.apiHost = config.apiHost || "https://api.aegis.ai";
16771
16680
  this.userId = config.userId ?? readAnonIdFromStorage();
@@ -16992,11 +16901,13 @@ class AegisWidgetManager {
16992
16901
  if (this.contactId) headers["X-Contact-ID"] = this.contactId;
16993
16902
  if (this.contactId && this.contactToken) headers["X-Contact-Token"] = this.contactToken;
16994
16903
  if (this.organizationId) headers["X-Organization-ID"] = this.organizationId;
16995
- const response = await fetch(url, { headers, credentials: "include" });
16904
+ const fetchConfigs = this.prefetchConfigsLoaded ? fetchWithAbort : fetchWithAbortRetry;
16905
+ const response = await fetchConfigs(url, { headers, credentials: "include" });
16996
16906
  if (!response.ok) {
16997
16907
  throw new Error(`Failed to fetch prefetch configs: ${response.status}`);
16998
16908
  }
16999
16909
  this.prefetchWidgetConfigs = await response.json();
16910
+ this.prefetchConfigsLoaded = true;
17000
16911
  const elapsed = performance.now() - startTime;
17001
16912
  this.log(`Fetched prefetch widget configs in ${elapsed.toFixed(2)}ms`);
17002
16913
  } catch (error) {
@@ -17016,11 +16927,13 @@ class AegisWidgetManager {
17016
16927
  if (this.contactId && this.contactToken) headers["X-Contact-Token"] = this.contactToken;
17017
16928
  if (this.organizationId) headers["X-Organization-ID"] = this.organizationId;
17018
16929
  if (this.sourcePlatform) headers["X-Source-Platform"] = this.sourcePlatform;
17019
- const response = await fetch(url, { headers, credentials: "include" });
16930
+ const fetchConfig = this.widgetsLoaded ? fetchWithAbort : fetchWithAbortRetry;
16931
+ const response = await fetchConfig(url, { headers, credentials: "include" });
17020
16932
  if (!response.ok) {
17021
16933
  throw new Error(`Failed to fetch widgets: ${response.status}`);
17022
16934
  }
17023
16935
  this.widgets = await response.json();
16936
+ this.widgetsLoaded = true;
17024
16937
  this.log(`Fetched ${this.widgets.length} widgets`);
17025
16938
  } catch (error) {
17026
16939
  this.log(`Error fetching widgets: ${error}`, true);
@@ -17146,7 +17059,10 @@ class AegisWidgetManager {
17146
17059
  return;
17147
17060
  }
17148
17061
  const beaconData = {
17149
- organization_id: this.organizationId || "default",
17062
+ // PL-9 (2026-11-20): never a 'default' tenant. The cell takes the WRITE
17063
+ // KEY's org and refuses (403) a body org that differs, so the field is
17064
+ // sent only when the SDK was configured with its org.
17065
+ ...this.organizationId ? { organization_id: this.organizationId } : {},
17150
17066
  contact_id: this.contactId,
17151
17067
  cart_id: this.cartData.cart_id,
17152
17068
  cart_total: this.cartData.cart_total,
@@ -18242,7 +18158,7 @@ const _AegisMessageRuntime = class _AegisMessageRuntime {
18242
18158
  this.initialized = false;
18243
18159
  this.armedInAppTriggers = /* @__PURE__ */ new Set();
18244
18160
  {
18245
- const v = "1.52.0";
18161
+ const v = "1.53.0";
18246
18162
  try {
18247
18163
  globalThis.__AEGIS_SDK_VERSION__ = v;
18248
18164
  } catch {
@@ -18674,7 +18590,7 @@ async function bootstrap(apiHost, req) {
18674
18590
  const url = `${apiHost.replace(/\/$/, "")}/v1/sdk/bootstrap`;
18675
18591
  const doFetch = async () => {
18676
18592
  try {
18677
- return await fetchWithAbort(url, {
18593
+ return await fetchWithAbortRetry(url, {
18678
18594
  method: "POST",
18679
18595
  headers: { "Content-Type": "application/json" },
18680
18596
  body: JSON.stringify(body),
@@ -18687,13 +18603,7 @@ async function bootstrap(apiHost, req) {
18687
18603
  throw err;
18688
18604
  }
18689
18605
  };
18690
- let resp;
18691
- try {
18692
- resp = await doFetch();
18693
- } catch (err) {
18694
- if (!(err instanceof BootstrapError) || err.status !== 0) throw err;
18695
- resp = await doFetch();
18696
- }
18606
+ let resp = await doFetch();
18697
18607
  if (resp.status >= 500) {
18698
18608
  await new Promise((r) => setTimeout(r, 750));
18699
18609
  resp = await doFetch();