@active-reach/web-sdk 1.46.0 → 1.46.2

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,7 +1,7 @@
1
- import { S as Storage, r as redactUrl, l as logger, A as Aegis } from "./analytics-C-Go3Pm5.mjs";
2
- import { B, E, N, R, U, m } from "./analytics-C-Go3Pm5.mjs";
3
- import { a as assetIdOf } from "./AegisWebPush-BE9wJcx0.mjs";
4
- import { A } from "./AegisWebPush-BE9wJcx0.mjs";
1
+ import { S as Storage, r as redactUrl, l as logger, A as Aegis } from "./analytics-CfEHNTzy.mjs";
2
+ import { B, E, N, R, U, m } from "./analytics-CfEHNTzy.mjs";
3
+ import { a as assetIdOf } from "./AegisWebPush-B7eajKzP.mjs";
4
+ import { A } from "./AegisWebPush-B7eajKzP.mjs";
5
5
  function debounce(func, wait) {
6
6
  let timeoutId = null;
7
7
  return function debounced(...args) {
@@ -695,6 +695,23 @@ function isPhone() {
695
695
  function markEl(node, role) {
696
696
  node.setAttribute(DATA_EL_ATTR, role);
697
697
  }
698
+ const PROGRESS_VALUE_ATTR = "data-aegis-progress";
699
+ const PROGRESS_COMPLETE_ATTR = "data-aegis-complete";
700
+ function markProgress(track, pct, complete) {
701
+ track.setAttribute("role", "progressbar");
702
+ track.setAttribute("aria-valuemin", "0");
703
+ track.setAttribute("aria-valuemax", "100");
704
+ if (pct === null || !Number.isFinite(pct)) {
705
+ track.removeAttribute("aria-valuenow");
706
+ track.removeAttribute(PROGRESS_VALUE_ATTR);
707
+ track.removeAttribute(PROGRESS_COMPLETE_ATTR);
708
+ return;
709
+ }
710
+ const v = Math.min(100, Math.max(0, pct));
711
+ track.setAttribute("aria-valuenow", String(Math.round(v)));
712
+ track.setAttribute(PROGRESS_VALUE_ATTR, String(Math.round(v * 10) / 10));
713
+ track.setAttribute(PROGRESS_COMPLETE_ATTR, complete ? "true" : "false");
714
+ }
698
715
  const WEIGHT = {
699
716
  regular: "400",
700
717
  medium: "500",
@@ -1742,6 +1759,7 @@ function buildProgressElement(el2, ctx, accent, muted, compact) {
1742
1759
  const cur = readCur();
1743
1760
  if (th <= 0 && el2.threshold_source === "free_delivery_setting") {
1744
1761
  wrap.style.display = "none";
1762
+ markProgress(shell, null, false);
1745
1763
  (_a = compact == null ? void 0 : compact.onMeasured) == null ? void 0 : _a.call(compact, false);
1746
1764
  return;
1747
1765
  }
@@ -1749,6 +1767,7 @@ function buildProgressElement(el2, ctx, accent, muted, compact) {
1749
1767
  (_b = compact == null ? void 0 : compact.onMeasured) == null ? void 0 : _b.call(compact, true);
1750
1768
  const { pct, complete } = computeProgress({ threshold: th, current: cur });
1751
1769
  bar.style.width = `${pct}%`;
1770
+ markProgress(shell, pct, complete);
1752
1771
  const labeled = cardProgressSubLabel({
1753
1772
  goalType: goal,
1754
1773
  threshold: th,
@@ -1785,9 +1804,9 @@ function buildProgressElement(el2, ctx, accent, muted, compact) {
1785
1804
  }
1786
1805
  return wrap;
1787
1806
  }
1788
- function buildCtaAction(el2, card, meta, inline, sanitizeUrl) {
1807
+ function buildCtaAction(el2, card, meta, inline, sanitizeUrl2) {
1789
1808
  const kind = el2.cta_action ?? (inline ? "add_to_cart" : "navigate");
1790
- const safe = (u) => u ? sanitizeUrl(u) || void 0 : void 0;
1809
+ const safe = (u) => u ? sanitizeUrl2(u) || void 0 : void 0;
1791
1810
  const url = safe(el2.cta_url || card.cta_url);
1792
1811
  const productId = meta.product_id;
1793
1812
  const sku = meta.sku;
@@ -1841,7 +1860,7 @@ function findElement(els, type) {
1841
1860
  function renderCardFromTemplate(card, opts) {
1842
1861
  const { ctx, action, layout, layoutAccent } = opts;
1843
1862
  const inline = action === "cart";
1844
- const { campaign, trackEvent, sanitizeUrl, sanitizeColor } = ctx;
1863
+ const { campaign, trackEvent, sanitizeUrl: sanitizeUrl2, sanitizeColor } = ctx;
1845
1864
  const tpl = applyPerCardOverride(opts.template, asLook(card.style));
1846
1865
  const frame = tpl.frame || {};
1847
1866
  const meta = card.metadata || {};
@@ -1851,6 +1870,10 @@ function renderCardFromTemplate(card, opts) {
1851
1870
  const muted = fg === "#ffffff" ? "rgba(255,255,255,0.72)" : "#6b7280";
1852
1871
  const compact = slotVariant(ctx.slotEl) === "compact";
1853
1872
  const frameBg = frame.bg ? sanitizeColor(frame.bg) : "#ffffff";
1873
+ const ink = (role, own) => {
1874
+ const base = own ? sanitizeColor(own) : role === "fg" ? fg : muted;
1875
+ return compact ? `var(--aegis-card-${role}, ${base})` : base;
1876
+ };
1854
1877
  const tile = document.createElement("div");
1855
1878
  markEl(tile, "frame");
1856
1879
  if (compact) tile.setAttribute("data-aegis-variant", "compact");
@@ -1902,7 +1925,7 @@ function renderCardFromTemplate(card, opts) {
1902
1925
  case "image": {
1903
1926
  const wrap = document.createElement("div");
1904
1927
  wrap.style.cssText = `position:relative;width:100%;aspect-ratio:${ASPECT$2[el2.aspect || "1/1"] || "1 / 1"};border-radius:${el2.radius ?? 10}px;overflow:hidden;background:#f7f8fa;`;
1905
- const safeVideo = card.video_url ? sanitizeUrl(card.video_url) : "";
1928
+ const safeVideo = card.video_url ? sanitizeUrl2(card.video_url) : "";
1906
1929
  if (safeVideo) {
1907
1930
  const v = document.createElement("video");
1908
1931
  v.src = safeVideo;
@@ -1914,7 +1937,7 @@ function renderCardFromTemplate(card, opts) {
1914
1937
  v.style.cssText = "width:100%;height:100%;object-fit:cover;display:block;";
1915
1938
  wrap.appendChild(v);
1916
1939
  } else if (card.image_url) {
1917
- const safe = sanitizeUrl(card.image_url);
1940
+ const safe = sanitizeUrl2(card.image_url);
1918
1941
  if (safe) {
1919
1942
  const img = document.createElement("img");
1920
1943
  const size = IMAGE_SIZE[el2.aspect || "1/1"] || IMAGE_SIZE["1/1"];
@@ -1963,7 +1986,7 @@ function renderCardFromTemplate(card, opts) {
1963
1986
  markEl(t, "title");
1964
1987
  t.textContent = card.title;
1965
1988
  const lines = el2.lines && el2.lines > 0 ? el2.lines : 2;
1966
- t.style.cssText = `${displayFont}font-size:12.5px;font-weight:600;line-height:1.3;text-align:${el2.align ?? "left"};color:${el2.color ? sanitizeColor(el2.color) : fg};display:-webkit-box;-webkit-line-clamp:${lines};-webkit-box-orient:vertical;overflow:hidden;`;
1989
+ t.style.cssText = `${displayFont}font-size:12.5px;font-weight:600;line-height:1.3;text-align:${el2.align ?? "left"};color:${ink("fg", el2.color)};display:-webkit-box;-webkit-line-clamp:${lines};-webkit-box-orient:vertical;overflow:hidden;`;
1967
1990
  container.appendChild(t);
1968
1991
  break;
1969
1992
  }
@@ -1973,7 +1996,7 @@ function renderCardFromTemplate(card, opts) {
1973
1996
  markEl(s, "subtitle");
1974
1997
  s.textContent = card.body;
1975
1998
  const lines = el2.lines && el2.lines > 0 ? el2.lines : 2;
1976
- s.style.cssText = `font-size:11px;color:${el2.color ? sanitizeColor(el2.color) : muted};line-height:1.3;text-align:${el2.align ?? "left"};display:-webkit-box;-webkit-line-clamp:${lines};-webkit-box-orient:vertical;overflow:hidden;`;
1999
+ s.style.cssText = `font-size:11px;color:${ink("muted", el2.color)};line-height:1.3;text-align:${el2.align ?? "left"};display:-webkit-box;-webkit-line-clamp:${lines};-webkit-box-orient:vertical;overflow:hidden;`;
1977
2000
  container.appendChild(s);
1978
2001
  break;
1979
2002
  }
@@ -1996,7 +2019,7 @@ function renderCardFromTemplate(card, opts) {
1996
2019
  const px = ICON_PX[el2.size || "md"] || 30;
1997
2020
  const node = document.createElement("div");
1998
2021
  markEl(node, "icon");
1999
- const iconColor = el2.color ? sanitizeColor(el2.color) : fg;
2022
+ const iconColor = compact ? "currentColor" : el2.color ? sanitizeColor(el2.color) : fg;
2000
2023
  if (el2.bubble) {
2001
2024
  const bubbleTint = el2.color ? sanitizeColor(el2.color) : brand;
2002
2025
  node.style.cssText = `flex:0 0 auto;width:${px}px;height:${px}px;border-radius:999px;display:flex;align-items:center;justify-content:center;background:color-mix(in srgb, ${bubbleTint} 16%, transparent);`;
@@ -2008,6 +2031,7 @@ function renderCardFromTemplate(card, opts) {
2008
2031
  color: iconColor,
2009
2032
  strokeWidth: 2
2010
2033
  });
2034
+ if (compact) node.style.cssText += `color:${ink("fg", el2.color)};`;
2011
2035
  if (svg) node.appendChild(svg);
2012
2036
  container.appendChild(node);
2013
2037
  break;
@@ -2016,7 +2040,7 @@ function renderCardFromTemplate(card, opts) {
2016
2040
  const t = document.createElement("div");
2017
2041
  markEl(t, "text");
2018
2042
  const fs = TEXT_PX[el2.size || "md"] || 13;
2019
- t.style.cssText = `font-size:${fs}px;font-weight:${WEIGHT[el2.weight ?? "medium"]};text-align:${el2.align ?? "left"};color:${el2.color ? sanitizeColor(el2.color) : fg};line-height:1.25;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;`;
2043
+ t.style.cssText = `font-size:${fs}px;font-weight:${WEIGHT[el2.weight ?? "medium"]};text-align:${el2.align ?? "left"};color:${ink("fg", el2.color)};line-height:1.25;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;`;
2020
2044
  t.textContent = interpolateTokens(el2.content ?? "", ctx);
2021
2045
  container.appendChild(t);
2022
2046
  break;
@@ -2080,7 +2104,7 @@ function renderCardFromTemplate(card, opts) {
2080
2104
  trackEvent(campaign.id, "clicked", { stepId: el2.id || "add" });
2081
2105
  (_a = ctx.dispatchAction) == null ? void 0 : _a.call(
2082
2106
  ctx,
2083
- buildCtaAction(el2, card, meta, inline, sanitizeUrl)
2107
+ buildCtaAction(el2, card, meta, inline, sanitizeUrl2)
2084
2108
  );
2085
2109
  });
2086
2110
  (overlayOnImage ? imageWrap : container).appendChild(cta);
@@ -2108,7 +2132,7 @@ function renderCardFromTemplate(card, opts) {
2108
2132
  e.stopPropagation();
2109
2133
  trackEvent(campaign.id, "clicked");
2110
2134
  const bm = meta;
2111
- const safe = (u) => u ? sanitizeUrl(u) || void 0 : void 0;
2135
+ const safe = (u) => u ? sanitizeUrl2(u) || void 0 : void 0;
2112
2136
  const act = inline ? {
2113
2137
  type: "open_product",
2114
2138
  productId: bm.product_id,
@@ -2321,7 +2345,7 @@ function renderCarouselCards(ctx) {
2321
2345
  }
2322
2346
  const DISMISS_STORAGE_PREFIX = "aegis_sticky_dismissed:";
2323
2347
  function renderStickyBar(ctx) {
2324
- const { campaign, trackEvent, sanitizeUrl, sanitizeColor, log, addAnimationStyles } = ctx;
2348
+ const { campaign, trackEvent, sanitizeUrl: sanitizeUrl2, sanitizeColor, log, addAnimationStyles } = ctx;
2325
2349
  const ic = campaign.interactive_config || {};
2326
2350
  const position = ic.sticky_position === "top" ? "top" : "bottom";
2327
2351
  const dismissible = ic.sticky_dismissible !== false;
@@ -2371,7 +2395,7 @@ function renderStickyBar(ctx) {
2371
2395
  cta.addEventListener("click", () => {
2372
2396
  trackEvent(campaign.id, "clicked");
2373
2397
  if (campaign.action_url) {
2374
- const safe = sanitizeUrl(campaign.action_url);
2398
+ const safe = sanitizeUrl2(campaign.action_url);
2375
2399
  if (safe) window.location.href = safe;
2376
2400
  }
2377
2401
  });
@@ -2549,6 +2573,7 @@ function buildProgressBar(ctx, inline, compact = false) {
2549
2573
  current: cur
2550
2574
  });
2551
2575
  fillEl.style.width = `${pct}%`;
2576
+ markProgress(shell, pct, complete);
2552
2577
  numeric.textContent = `${cur.toFixed(0)} / ${threshold.toFixed(0)} · ${Math.round(pct)}%`;
2553
2578
  shimmer.style.display = complete ? "none" : "";
2554
2579
  for (const m2 of milestonesReached) {
@@ -3211,7 +3236,7 @@ function buildGroupBubble(ctx, cfg, g, i, labelColor) {
3211
3236
  return wrap;
3212
3237
  }
3213
3238
  function openViewer(ctx, cfg, startGroupIndex, startFrameIndex = 0) {
3214
- const { campaign, trackEvent, sanitizeUrl, log } = ctx;
3239
+ const { campaign, trackEvent, sanitizeUrl: sanitizeUrl2, log } = ctx;
3215
3240
  const { loop, autoplay, showProgress, defaultDuration, reduceMotion } = cfg;
3216
3241
  const groups = cfg.groups;
3217
3242
  if (groups.length === 0) return;
@@ -3322,8 +3347,8 @@ function openViewer(ctx, cfg, startGroupIndex, startFrameIndex = 0) {
3322
3347
  const f = frames[i];
3323
3348
  frameLayer.replaceChildren();
3324
3349
  currentVideo = null;
3325
- const safeVideo = f.video_url ? sanitizeUrl(f.video_url) : null;
3326
- const safeImage = f.image_url ? sanitizeUrl(f.image_url) : null;
3350
+ const safeVideo = f.video_url ? sanitizeUrl2(f.video_url) : null;
3351
+ const safeImage = f.image_url ? sanitizeUrl2(f.image_url) : null;
3327
3352
  if (safeVideo) {
3328
3353
  const vid = document.createElement("video");
3329
3354
  vid.src = safeVideo;
@@ -3365,7 +3390,7 @@ function openViewer(ctx, cfg, startGroupIndex, startFrameIndex = 0) {
3365
3390
  b.style.cssText = "font-size: 14px; line-height: 1.45; opacity: 0.92; text-shadow: 0 1px 6px rgba(0,0,0,0.4);";
3366
3391
  copy.appendChild(b);
3367
3392
  }
3368
- const ctaUrl = f.cta_url ? sanitizeUrl(f.cta_url) : null;
3393
+ const ctaUrl = f.cta_url ? sanitizeUrl2(f.cta_url) : null;
3369
3394
  const ctaLabel = f.cta_text || (ctaUrl ? "Learn more" : "");
3370
3395
  if (ctaLabel) {
3371
3396
  const cta = document.createElement("button");
@@ -4219,10 +4244,10 @@ function renderGame(ctx, subType) {
4219
4244
  const ASPECT$1 = { "16:9": "16 / 9", "9:16": "9 / 16", "1:1": "1 / 1", "4:5": "4 / 5" };
4220
4245
  function buildVideo(ctx, aspect, autoplay, loop) {
4221
4246
  var _a;
4222
- const { campaign, sanitizeUrl } = ctx;
4247
+ const { campaign, sanitizeUrl: sanitizeUrl2 } = ctx;
4223
4248
  const ic = campaign.interactive_config || {};
4224
- const videoUrl = sanitizeUrl(ic.video_url || campaign.video_url || "");
4225
- const poster = campaign.image_url ? sanitizeUrl(campaign.image_url) : null;
4249
+ const videoUrl = sanitizeUrl2(ic.video_url || campaign.video_url || "");
4250
+ const poster = campaign.image_url ? sanitizeUrl2(campaign.image_url) : null;
4226
4251
  const wrap = document.createElement("div");
4227
4252
  wrap.style.cssText = `position:relative;width:100%;aspect-ratio:${ASPECT$1[aspect] || ASPECT$1["16:9"]};background:#0b1220;border-radius:14px;overflow:hidden;`;
4228
4253
  if (videoUrl) {
@@ -4446,7 +4471,7 @@ function cardUrl(c) {
4446
4471
  return "";
4447
4472
  }
4448
4473
  function renderHeroInline(ctx, target) {
4449
- const { campaign, sanitizeUrl, trackEvent } = ctx;
4474
+ const { campaign, sanitizeUrl: sanitizeUrl2, trackEvent } = ctx;
4450
4475
  const ic = campaign.interactive_config || {};
4451
4476
  const cards = Array.isArray(ic.cards) ? ic.cards : [];
4452
4477
  if (cards.length === 0) return false;
@@ -4461,7 +4486,7 @@ function renderHeroInline(ctx, target) {
4461
4486
  const bar = document.createElement("div");
4462
4487
  bar.style.cssText = `display:flex;align-items:center;justify-content:center;gap:10px;background:${accent};color:#fff;padding:8px 14px;font-weight:600;font-size:13px;line-height:1.3;${fontFamilyCss("body")}text-align:center;`;
4463
4488
  bar.textContent = [cardHeadline(c), cardSub(c)].filter(Boolean).join(" · ");
4464
- const url = sanitizeUrl(cardUrl(c));
4489
+ const url = sanitizeUrl2(cardUrl(c));
4465
4490
  if (url && cardCta(c)) {
4466
4491
  const a = document.createElement("span");
4467
4492
  a.style.cssText = "text-decoration:underline;cursor:pointer;white-space:nowrap;";
@@ -4480,7 +4505,7 @@ function renderHeroInline(ctx, target) {
4480
4505
  _injectHeroResponsiveCss();
4481
4506
  const explicitRatio = chrome.aspect_ratio ? ASPECT[chrome.aspect_ratio] : void 0;
4482
4507
  const hasPhoneImage = cards.some(
4483
- (c) => !c.video_url && c.media_type !== "video" && !!c.image_url_mobile && !!sanitizeUrl(c.image_url_mobile)
4508
+ (c) => !c.video_url && c.media_type !== "video" && !!c.image_url_mobile && !!sanitizeUrl2(c.image_url_mobile)
4484
4509
  );
4485
4510
  const root = document.createElement("div");
4486
4511
  root.className = explicitRatio ? "aegis-hero-root" : `aegis-hero-root aegis-hero-auto${hasPhoneImage ? " aegis-hero-phone-square" : ""}`;
@@ -4497,9 +4522,9 @@ function renderHeroInline(ctx, target) {
4497
4522
  cards.forEach((c, i) => {
4498
4523
  const slide = document.createElement("div");
4499
4524
  slide.style.cssText = "position:relative;flex:0 0 100%;width:100%;height:100%;min-height:inherit;background:#f1f5f9;";
4500
- const videoUrl = c.video_url ? sanitizeUrl(c.video_url) ?? "" : "";
4525
+ const videoUrl = c.video_url ? sanitizeUrl2(c.video_url) ?? "" : "";
4501
4526
  const isVideo = !!videoUrl || c.media_type === "video";
4502
- const mediaUrl = isVideo ? videoUrl || sanitizeUrl(c.media_url ?? "") : sanitizeUrl(c.image_url || c.media_url || "") ?? (c.image_url_mobile ? sanitizeUrl(c.image_url_mobile) : null);
4527
+ const mediaUrl = isVideo ? videoUrl || sanitizeUrl2(c.media_url ?? "") : sanitizeUrl2(c.image_url || c.media_url || "") ?? (c.image_url_mobile ? sanitizeUrl2(c.image_url_mobile) : null);
4503
4528
  if (mediaUrl) {
4504
4529
  if (isVideo) {
4505
4530
  const v = document.createElement("video");
@@ -4512,7 +4537,7 @@ function renderHeroInline(ctx, target) {
4512
4537
  slide.appendChild(v);
4513
4538
  } else {
4514
4539
  const picture = document.createElement("picture");
4515
- const phoneUrl = c.image_url_mobile ? sanitizeUrl(c.image_url_mobile) : null;
4540
+ const phoneUrl = c.image_url_mobile ? sanitizeUrl2(c.image_url_mobile) : null;
4516
4541
  const shell = i === 0 ? adoptableShell(ctx.shellImage, mediaUrl) : null;
4517
4542
  if (phoneUrl) {
4518
4543
  const source = document.createElement("source");
@@ -4573,7 +4598,7 @@ function renderHeroInline(ctx, target) {
4573
4598
  content.appendChild(sub);
4574
4599
  }
4575
4600
  const cta = cardCta(c);
4576
- const url = sanitizeUrl(cardUrl(c));
4601
+ const url = sanitizeUrl2(cardUrl(c));
4577
4602
  if (cta && chrome.cta_style !== "none") {
4578
4603
  const btn = document.createElement("button");
4579
4604
  btn.textContent = cta;
@@ -4625,8 +4650,124 @@ function renderHeroInline(ctx, target) {
4625
4650
  trackEvent(campaign.id, "impression");
4626
4651
  return true;
4627
4652
  }
4653
+ function sanitizeUrl(url) {
4654
+ if (typeof url !== "string" || url.trim() === "") return null;
4655
+ try {
4656
+ const base = typeof window !== "undefined" ? window.location.origin : void 0;
4657
+ const parsed = base ? new URL(url, base) : new URL(url);
4658
+ const protocol = parsed.protocol.toLowerCase();
4659
+ if (protocol === "javascript:" || protocol === "data:" || protocol === "vbscript:") return null;
4660
+ return parsed.href;
4661
+ } catch {
4662
+ return null;
4663
+ }
4664
+ }
4665
+ const TAG = { "*": "strong", _: "em", "~": "s" };
4666
+ const WORD_CHAR = /[\p{L}\p{N}]/u;
4667
+ const SPACE = /\s/u;
4668
+ function isMarker(c) {
4669
+ return c === "*" || c === "_" || c === "~";
4670
+ }
4671
+ function canOpen(text, i) {
4672
+ const next = text[i + 1];
4673
+ if (next === void 0 || SPACE.test(next) || next === text[i]) return false;
4674
+ const prev = text[i - 1];
4675
+ return prev === void 0 || !WORD_CHAR.test(prev);
4676
+ }
4677
+ function canClose(text, j) {
4678
+ const prev = text[j - 1];
4679
+ if (prev === void 0 || SPACE.test(prev)) return false;
4680
+ const next = text[j + 1];
4681
+ return next === void 0 || !WORD_CHAR.test(next);
4682
+ }
4683
+ function findClose(text, i) {
4684
+ const marker = text[i];
4685
+ for (let j = i + 2; j < text.length; j += 1) {
4686
+ const c = text[j];
4687
+ if (c === "\n") return -1;
4688
+ if (c === marker && canClose(text, j)) return j;
4689
+ }
4690
+ return -1;
4691
+ }
4692
+ function parseWaMarkup(text) {
4693
+ const out = [];
4694
+ let buf = "";
4695
+ let i = 0;
4696
+ while (i < text.length) {
4697
+ const c = text[i];
4698
+ if (isMarker(c) && canOpen(text, i)) {
4699
+ const j = findClose(text, i);
4700
+ if (j !== -1) {
4701
+ if (buf) out.push(buf);
4702
+ buf = "";
4703
+ out.push({ marker: c, children: parseWaMarkup(text.slice(i + 1, j)) });
4704
+ i = j + 1;
4705
+ continue;
4706
+ }
4707
+ }
4708
+ buf += c;
4709
+ i += 1;
4710
+ }
4711
+ if (buf) out.push(buf);
4712
+ return out;
4713
+ }
4714
+ function appendNodes(parent, nodes) {
4715
+ const doc = parent.ownerDocument ?? document;
4716
+ for (const n of nodes) {
4717
+ if (typeof n === "string") {
4718
+ parent.appendChild(doc.createTextNode(n));
4719
+ } else {
4720
+ const el2 = doc.createElement(TAG[n.marker]);
4721
+ appendNodes(el2, n.children);
4722
+ parent.appendChild(el2);
4723
+ }
4724
+ }
4725
+ }
4726
+ function appendWaMarkup(parent, text) {
4727
+ appendNodes(parent, parseWaMarkup(text));
4728
+ }
4729
+ const WORKSPACE_MISMATCH_CODE = "chat_workspace_mismatch";
4730
+ const REMINT_WINDOW_MS = 3e4;
4731
+ const AUTH_STOPPED_TEXT = "Sorry, chat is unavailable right now. Please try again in a moment.";
4732
+ async function errorCode(res) {
4733
+ try {
4734
+ const body = await res.clone().json();
4735
+ for (const v of [body, body == null ? void 0 : body.detail, body == null ? void 0 : body.error]) {
4736
+ if (v && typeof v === "object" && typeof v.code === "string") {
4737
+ return v.code;
4738
+ }
4739
+ }
4740
+ } catch {
4741
+ }
4742
+ return void 0;
4743
+ }
4628
4744
  const STYLE_ID$1 = "aegis-chat-styles";
4629
4745
  const POLL_INTERVAL_MS = 5e3;
4746
+ const NEAR_BOTTOM_PX = 48;
4747
+ const MESSAGE_TOP_GAP_PX = 8;
4748
+ function chatScrollTarget(m2) {
4749
+ const bottom = Math.max(0, m2.scrollHeight - m2.viewportHeight);
4750
+ if (m2.sender === "customer") return bottom;
4751
+ if (m2.rowHeight <= m2.viewportHeight - MESSAGE_TOP_GAP_PX) return bottom;
4752
+ return Math.min(bottom, Math.max(0, m2.rowTop - MESSAGE_TOP_GAP_PX));
4753
+ }
4754
+ function ctaTarget(inter) {
4755
+ const buttons = Array.isArray(inter.buttons) ? inter.buttons : [];
4756
+ const first = buttons.find((b) => b && typeof b.url === "string" && b.url) || {};
4757
+ const action = inter.action && typeof inter.action === "object" ? inter.action : {};
4758
+ const params = action.parameters && typeof action.parameters === "object" ? action.parameters : {};
4759
+ const url = first.url ?? params.url ?? inter.url;
4760
+ const label = first.title ?? params.display_text ?? inter.display_text;
4761
+ return { url, title: typeof label === "string" ? label : "" };
4762
+ }
4763
+ function interactiveSig(msg) {
4764
+ if (!msg.interactive || !msg.interactive.length) return "";
4765
+ try {
4766
+ return JSON.stringify(msg.interactive);
4767
+ } catch {
4768
+ return String(msg.interactive.length);
4769
+ }
4770
+ }
4630
4771
  let currentLauncher = null;
4631
4772
  function getCurrentLauncher() {
4632
4773
  return currentLauncher;
@@ -4640,6 +4781,10 @@ function closeChat() {
4640
4781
  const ATTENTION_DELAY_MS = 4500;
4641
4782
  class AegisChat {
4642
4783
  constructor(config) {
4784
+ this.workspaceRejected = false;
4785
+ this.lastRemintAt = 0;
4786
+ this.authStopped = false;
4787
+ this.renderedRows = /* @__PURE__ */ new Map();
4643
4788
  this.sessionResumed = false;
4644
4789
  this.open = false;
4645
4790
  this.initialized = false;
@@ -4649,6 +4794,8 @@ class AegisChat {
4649
4794
  this.hasInteracted = false;
4650
4795
  this.writeKey = config.writeKey;
4651
4796
  this.organizationId = config.organizationId;
4797
+ const ws = typeof config.workspaceId === "string" ? config.workspaceId.trim() : "";
4798
+ this.workspaceId = ws || void 0;
4652
4799
  this.apiHost = (config.apiHost ?? "").replace(/\/$/, "");
4653
4800
  this.contactId = config.contactId;
4654
4801
  this.channel = config.channel ?? "web";
@@ -4697,6 +4844,8 @@ class AegisChat {
4697
4844
  this.dismissAttention();
4698
4845
  (_b = this.panel) == null ? void 0 : _b.classList.add("aegis-chat-panel--open");
4699
4846
  (_c = this.bubble) == null ? void 0 : _c.classList.add("aegis-chat-bubble--hidden");
4847
+ this.bindViewport();
4848
+ this.revealLatest();
4700
4849
  this.clearUnread();
4701
4850
  if (prefill && this.input) this.input.value = prefill;
4702
4851
  void this.resumeSession();
@@ -4709,6 +4858,7 @@ class AegisChat {
4709
4858
  this.open = false;
4710
4859
  (_a = this.panel) == null ? void 0 : _a.classList.remove("aegis-chat-panel--open");
4711
4860
  (_b = this.bubble) == null ? void 0 : _b.classList.remove("aegis-chat-bubble--hidden");
4861
+ this.unbindViewport();
4712
4862
  this.disconnectSSE();
4713
4863
  this.stopPolling();
4714
4864
  if (wasOpen) {
@@ -4720,6 +4870,7 @@ class AegisChat {
4720
4870
  }
4721
4871
  destroy() {
4722
4872
  var _a;
4873
+ this.unbindViewport();
4723
4874
  this.disconnectSSE();
4724
4875
  this.stopPolling();
4725
4876
  (_a = this.root) == null ? void 0 : _a.remove();
@@ -4747,10 +4898,11 @@ class AegisChat {
4747
4898
  }
4748
4899
  this.showTyping();
4749
4900
  try {
4750
- const res = await fetch(`${this.apiHost}/v1/chat/message`, {
4901
+ const post = () => fetch(`${this.apiHost}/v1/chat/message`, {
4751
4902
  method: "POST",
4752
4903
  headers: { "Content-Type": "application/json", "X-Aegis-Write-Key": this.writeKey },
4753
4904
  body: JSON.stringify({
4905
+ workspace_id: this.sentWorkspaceId(),
4754
4906
  message_text: message,
4755
4907
  channel: this.channel,
4756
4908
  anonymous_id: this.anonymousId,
@@ -4764,6 +4916,8 @@ class AegisChat {
4764
4916
  }),
4765
4917
  keepalive: true
4766
4918
  });
4919
+ let res = await post();
4920
+ if (await this.isWorkspaceMismatch(res)) res = await post();
4767
4921
  if (!res.ok) {
4768
4922
  this.log("send failed", res.status);
4769
4923
  this.appendSystem("Sorry — your message could not be delivered. Please try again.");
@@ -4777,6 +4931,7 @@ class AegisChat {
4777
4931
  this.contactId = data.contact_id;
4778
4932
  this.persistContactId(data.contact_id);
4779
4933
  this.sseTicket = data.sse_ticket;
4934
+ this.authStopped = false;
4780
4935
  this.connectSSE(data.sse_ticket);
4781
4936
  void this.refreshHistory();
4782
4937
  } catch (err) {
@@ -4839,6 +4994,8 @@ class AegisChat {
4839
4994
  url.searchParams.set("ticket", ticket);
4840
4995
  url.searchParams.set("mode", "ephemeral");
4841
4996
  if (this.organizationId) url.searchParams.set("org", this.organizationId);
4997
+ const ws = this.sentWorkspaceId();
4998
+ if (ws) url.searchParams.set("workspace_id", ws);
4842
4999
  try {
4843
5000
  this.eventSource = new EventSource(url.toString());
4844
5001
  this.eventSource.onopen = () => {
@@ -4849,6 +5006,11 @@ class AegisChat {
4849
5006
  void this.refreshHistory();
4850
5007
  });
4851
5008
  this.eventSource.onerror = () => {
5009
+ if (this.eventSource && this.eventSource.readyState === 2) {
5010
+ this.disconnectSSE();
5011
+ void this.recoverAuth();
5012
+ return;
5013
+ }
4852
5014
  this.startPolling();
4853
5015
  };
4854
5016
  } catch (err) {
@@ -4864,6 +5026,7 @@ class AegisChat {
4864
5026
  }
4865
5027
  startPolling() {
4866
5028
  if (!this.open) return;
5029
+ if (this.authStopped) return;
4867
5030
  if (this.pollTimer) return;
4868
5031
  this.pollTimer = setInterval(() => {
4869
5032
  void this.refreshHistory();
@@ -4875,7 +5038,7 @@ class AegisChat {
4875
5038
  this.pollTimer = void 0;
4876
5039
  }
4877
5040
  }
4878
- async refreshHistory() {
5041
+ async refreshHistory(retry = true) {
4879
5042
  if (!this.contactId) return;
4880
5043
  if (!this.sseTicket) return;
4881
5044
  try {
@@ -4884,15 +5047,31 @@ class AegisChat {
4884
5047
  url.searchParams.set("ticket", this.sseTicket);
4885
5048
  url.searchParams.set("channel", this.channel);
4886
5049
  url.searchParams.set("limit", "50");
5050
+ const ws = this.sentWorkspaceId();
5051
+ if (ws) url.searchParams.set("workspace_id", ws);
4887
5052
  const res = await fetch(url.toString(), {
4888
5053
  method: "GET",
4889
5054
  headers: { "X-Aegis-Write-Key": this.writeKey }
4890
5055
  });
5056
+ if (res.status === 401 || res.status === 403) {
5057
+ if (!retry) {
5058
+ this.stopAuth();
5059
+ return;
5060
+ }
5061
+ if (await this.isWorkspaceMismatch(res)) {
5062
+ await this.refreshHistory(false);
5063
+ return;
5064
+ }
5065
+ if (await this.recoverAuth({ refresh: false })) await this.refreshHistory(false);
5066
+ return;
5067
+ }
4891
5068
  if (!res.ok) return;
4892
5069
  const data = await res.json();
4893
- let appended = false;
4894
5070
  for (const msg of data.messages || []) {
4895
- if (this.renderedIds.has(msg.id)) continue;
5071
+ if (this.renderedIds.has(msg.id)) {
5072
+ this.redrawIfInteractiveChanged(msg);
5073
+ continue;
5074
+ }
4896
5075
  if (msg.sender === "customer") {
4897
5076
  const idx = this.pendingEcho.indexOf(msg.content || "");
4898
5077
  if (idx !== -1) {
@@ -4903,10 +5082,8 @@ class AegisChat {
4903
5082
  }
4904
5083
  if (msg.sender === "assistant") this.hideTyping();
4905
5084
  this.appendBubble(msg);
4906
- appended = true;
4907
5085
  if (msg.sender === "assistant" && !this.open) this.bumpUnread();
4908
5086
  }
4909
- if (appended) this.scrollToBottom();
4910
5087
  } catch (err) {
4911
5088
  this.log("history fetch error", err);
4912
5089
  }
@@ -5057,6 +5234,37 @@ class AegisChat {
5057
5234
  appendBubble(msg) {
5058
5235
  if (!this.thread) return;
5059
5236
  if (msg.id) this.renderedIds.add(msg.id);
5237
+ const row = this.buildRow(msg);
5238
+ this.thread.appendChild(row);
5239
+ if (msg.id) this.renderedRows.set(msg.id, { row, sig: interactiveSig(msg) });
5240
+ this.reveal(row, msg.sender);
5241
+ }
5242
+ /** The server attaches `interactive` to a bot row a few ms AFTER the insert
5243
+ * that nudged SSE, so the first fetch can draw the text alone. When a later
5244
+ * fetch carries a different interactive, re-draw that row IN PLACE: no
5245
+ * duplicate, scroll position kept, an answered (disabled) group stays so. */
5246
+ redrawIfInteractiveChanged(msg) {
5247
+ var _a;
5248
+ if (!msg.id || !this.thread) return;
5249
+ const drawn = this.renderedRows.get(msg.id);
5250
+ if (!drawn || !drawn.row.isConnected) return;
5251
+ const sig = interactiveSig(msg);
5252
+ if (sig === drawn.sig || !((_a = msg.interactive) == null ? void 0 : _a.length)) return;
5253
+ const answered = !!drawn.row.querySelector(
5254
+ ".aegis-chat-chip:disabled, .aegis-chat-listrow:disabled"
5255
+ );
5256
+ const top = this.thread.scrollTop;
5257
+ const row = this.buildRow(msg);
5258
+ if (answered) {
5259
+ row.querySelectorAll(".aegis-chat-chip, .aegis-chat-listrow").forEach((b) => {
5260
+ b.disabled = true;
5261
+ });
5262
+ }
5263
+ drawn.row.replaceWith(row);
5264
+ this.renderedRows.set(msg.id, { row, sig });
5265
+ this.thread.scrollTop = top;
5266
+ }
5267
+ buildRow(msg) {
5060
5268
  const row = document.createElement("div");
5061
5269
  row.className = `aegis-chat-msg aegis-chat-msg--${msg.sender}`;
5062
5270
  if (msg.media_url) {
@@ -5082,26 +5290,33 @@ class AegisChat {
5082
5290
  if (msg.content) {
5083
5291
  const bubble = document.createElement("div");
5084
5292
  bubble.className = "aegis-chat-bubbletext";
5085
- bubble.textContent = msg.content;
5293
+ if (msg.sender === "customer") bubble.textContent = msg.content;
5294
+ else appendWaMarkup(bubble, msg.content);
5086
5295
  row.appendChild(bubble);
5087
5296
  }
5088
5297
  if (msg.interactive && Array.isArray(msg.interactive)) {
5089
5298
  for (const inter of msg.interactive) {
5090
- const el2 = this.renderInteractive(inter);
5299
+ const el2 = this.renderInteractive(inter, msg.content || "");
5091
5300
  if (el2) row.appendChild(el2);
5092
5301
  }
5093
5302
  }
5094
- this.thread.appendChild(row);
5095
- this.scrollToBottom();
5303
+ return row;
5096
5304
  }
5097
5305
  /** Render one interactive message: the `web`-format product_carousel, or the
5098
- * WhatsApp-shape reply_button / list the store picker stores. */
5099
- renderInteractive(inter) {
5306
+ * WhatsApp-shape reply_button / list / cta_url the agent stores. Any other
5307
+ * shape falls back to its body text, so a message is never silently lost. */
5308
+ renderInteractive(inter, bubbleText = "") {
5100
5309
  const type = inter == null ? void 0 : inter.type;
5101
5310
  const waShape = inter == null ? void 0 : inter.interactive_type;
5102
- if (type === "interactive" && waShape === "reply_button") return this.renderReplyButtons(inter);
5103
- if (type === "interactive" && waShape === "list") return this.renderListRows(inter);
5104
- if (type !== "product_carousel") return null;
5311
+ if (type === "interactive" && waShape === "reply_button") {
5312
+ return this.withBody(inter, bubbleText, this.renderReplyButtons(inter));
5313
+ }
5314
+ if (type === "interactive" && waShape === "list") {
5315
+ return this.withBody(inter, bubbleText, this.renderListRows(inter));
5316
+ }
5317
+ if (waShape === "cta_url" || type === "cta_url") return this.renderCtaUrl(inter, bubbleText);
5318
+ if (waShape === "flow" || type === "flow") return this.renderFlowFallback(inter, bubbleText);
5319
+ if (type !== "product_carousel") return this.renderBodyFallback(inter, bubbleText);
5105
5320
  const products = inter.products || [];
5106
5321
  if (!products.length) return null;
5107
5322
  const carousel = document.createElement("div");
@@ -5144,6 +5359,99 @@ class AegisChat {
5144
5359
  }
5145
5360
  return carousel;
5146
5361
  }
5362
+ /** WhatsApp-shape `cta_url` (link_buttons.link_message / pay offers): the body
5363
+ * (when the bubble does not already say it), an optional header image (the
5364
+ * UPI QR) and ONE link button. The URL goes through sanitizeUrl and opens in
5365
+ * a new tab with rel=noopener; an unsafe or missing URL leaves the body only. */
5366
+ renderCtaUrl(inter, bubbleText) {
5367
+ const { url, title: rawTitle } = ctaTarget(inter);
5368
+ const href = sanitizeUrl(url);
5369
+ const title = rawTitle.trim();
5370
+ if (!href || !title) return this.renderBodyFallback(inter, bubbleText);
5371
+ const group = document.createElement("div");
5372
+ group.className = "aegis-chat-cta";
5373
+ const image = sanitizeUrl(inter.header_image);
5374
+ if (image && /^https?:/i.test(image)) {
5375
+ const img = document.createElement("img");
5376
+ img.className = "aegis-chat-cta-img";
5377
+ img.src = image;
5378
+ img.alt = "";
5379
+ img.loading = "lazy";
5380
+ group.appendChild(img);
5381
+ }
5382
+ const body = this.distinctBody(inter, bubbleText);
5383
+ if (body) {
5384
+ const text = document.createElement("div");
5385
+ text.className = "aegis-chat-bubbletext";
5386
+ appendWaMarkup(text, body);
5387
+ group.appendChild(text);
5388
+ }
5389
+ const link = document.createElement("a");
5390
+ link.className = "aegis-chat-ctabtn";
5391
+ link.href = href;
5392
+ link.target = "_blank";
5393
+ link.rel = "noopener noreferrer";
5394
+ link.textContent = title;
5395
+ group.appendChild(link);
5396
+ return group;
5397
+ }
5398
+ /** A Flow's `native_fallback` is one ordinary message (reply_button / list /
5399
+ * text) or `{text, messages[]}`; it is drawn by the same renderer, never as
5400
+ * another Flow (one level only). */
5401
+ renderFlowFallback(inter, bubbleText) {
5402
+ const fb = inter.native_fallback;
5403
+ if (!fb || typeof fb !== "object") return this.renderBodyFallback(inter, bubbleText);
5404
+ const f = fb;
5405
+ const parts = [];
5406
+ const isFlow = (m2) => m2.interactive_type === "flow" || m2.type === "flow";
5407
+ if (typeof f.type === "string" || typeof f.interactive_type === "string") {
5408
+ const el2 = isFlow(f) ? this.renderBodyFallback(f, bubbleText) : this.renderInteractive(f, bubbleText);
5409
+ if (el2) parts.push(el2);
5410
+ } else {
5411
+ const text = this.renderBodyFallback({ body: f.text }, bubbleText);
5412
+ if (text) parts.push(text);
5413
+ const messages = Array.isArray(f.messages) ? f.messages : [];
5414
+ for (const m2 of messages) {
5415
+ if (!m2 || typeof m2 !== "object") continue;
5416
+ const el2 = isFlow(m2) ? this.renderBodyFallback(m2, bubbleText) : this.renderInteractive(m2, bubbleText);
5417
+ if (el2) parts.push(el2);
5418
+ }
5419
+ }
5420
+ if (!parts.length) return this.renderBodyFallback(inter, bubbleText);
5421
+ if (parts.length === 1) return parts[0];
5422
+ const wrap = document.createElement("div");
5423
+ wrap.className = "aegis-chat-interactive";
5424
+ for (const el2 of parts) wrap.appendChild(el2);
5425
+ return wrap;
5426
+ }
5427
+ /** reply_button / list: the choices, preceded by the message body when the
5428
+ * bubble text does not already carry it (WA markup rendered). */
5429
+ withBody(inter, bubbleText, choices) {
5430
+ const body = this.renderBodyFallback(inter, bubbleText);
5431
+ if (!body) return choices ?? null;
5432
+ if (!choices) return body;
5433
+ const wrap = document.createElement("div");
5434
+ wrap.className = "aegis-chat-interactive";
5435
+ wrap.appendChild(body);
5436
+ wrap.appendChild(choices);
5437
+ return wrap;
5438
+ }
5439
+ /** An interactive shape this launcher does not draw: show its body text (if
5440
+ * the bubble does not already carry it) instead of dropping it silently. */
5441
+ renderBodyFallback(inter, bubbleText) {
5442
+ const body = this.distinctBody(inter, bubbleText);
5443
+ if (!body) return null;
5444
+ const text = document.createElement("div");
5445
+ text.className = "aegis-chat-bubbletext aegis-chat-fallback";
5446
+ appendWaMarkup(text, body);
5447
+ return text;
5448
+ }
5449
+ distinctBody(inter, bubbleText) {
5450
+ const raw = typeof inter.body === "string" ? inter.body : typeof inter.text === "string" ? inter.text : "";
5451
+ const body = raw.trim();
5452
+ if (!body || body === bubbleText.trim() || bubbleText.includes(body)) return "";
5453
+ return body;
5454
+ }
5147
5455
  /** WhatsApp-shape `reply_button` (store picker: Nearest / Other stores / Change
5148
5456
  * store). The body is already the bubble text, so only the buttons render. A
5149
5457
  * tap sends the button title (the same text WhatsApp's inbound hands the bot)
@@ -5224,6 +5532,62 @@ class AegisChat {
5224
5532
  scrollToBottom() {
5225
5533
  if (this.thread) this.thread.scrollTop = this.thread.scrollHeight;
5226
5534
  }
5535
+ isNearBottom() {
5536
+ const t = this.thread;
5537
+ if (!t) return true;
5538
+ return t.scrollHeight - t.scrollTop - t.clientHeight <= NEAR_BOTTOM_PX;
5539
+ }
5540
+ /** Place the view for a just-appended message (rule: chatScrollTarget). */
5541
+ reveal(row, sender) {
5542
+ const t = this.thread;
5543
+ if (!t) return;
5544
+ t.scrollTop = chatScrollTarget({
5545
+ sender,
5546
+ rowTop: row.offsetTop,
5547
+ rowHeight: row.offsetHeight,
5548
+ viewportHeight: t.clientHeight,
5549
+ scrollHeight: t.scrollHeight
5550
+ });
5551
+ }
5552
+ revealLatest() {
5553
+ var _a;
5554
+ const rows = (_a = this.thread) == null ? void 0 : _a.querySelectorAll(".aegis-chat-msg:not(.aegis-chat-typing)");
5555
+ const last = rows && rows.length ? rows[rows.length - 1] : void 0;
5556
+ if (!last) return;
5557
+ const sender = last.classList.contains("aegis-chat-msg--customer") ? "customer" : last.classList.contains("aegis-chat-msg--system") ? "system" : "assistant";
5558
+ this.reveal(last, sender);
5559
+ }
5560
+ /** Phones: size the open panel to the VISUAL viewport. `100dvh` does not
5561
+ * shrink for the soft keyboard, so the browser scrolled the full-height panel
5562
+ * and pushed the header (title + close) off the top. The panel's height and
5563
+ * top follow visualViewport while open; without it the CSS keeps 100dvh. */
5564
+ bindViewport() {
5565
+ const vv = typeof window !== "undefined" ? window.visualViewport : null;
5566
+ const panel = this.panel;
5567
+ if (!vv || !panel || this.viewportCleanup) return;
5568
+ const apply = () => {
5569
+ const stick = this.isNearBottom();
5570
+ panel.style.setProperty("--aegis-chat-vh", `${Math.round(vv.height)}px`);
5571
+ panel.style.setProperty("--aegis-chat-top", `${Math.round(vv.offsetTop)}px`);
5572
+ if (stick) this.scrollToBottom();
5573
+ };
5574
+ panel.classList.add("aegis-chat-panel--vv");
5575
+ apply();
5576
+ vv.addEventListener("resize", apply);
5577
+ vv.addEventListener("scroll", apply);
5578
+ this.viewportCleanup = () => {
5579
+ vv.removeEventListener("resize", apply);
5580
+ vv.removeEventListener("scroll", apply);
5581
+ panel.classList.remove("aegis-chat-panel--vv");
5582
+ panel.style.removeProperty("--aegis-chat-vh");
5583
+ panel.style.removeProperty("--aegis-chat-top");
5584
+ };
5585
+ }
5586
+ unbindViewport() {
5587
+ var _a;
5588
+ (_a = this.viewportCleanup) == null ? void 0 : _a.call(this);
5589
+ this.viewportCleanup = void 0;
5590
+ }
5227
5591
  readAnonId() {
5228
5592
  if (typeof document === "undefined") return void 0;
5229
5593
  try {
@@ -5257,38 +5621,91 @@ class AegisChat {
5257
5621
  }
5258
5622
  if (this.sessionResumed) return;
5259
5623
  this.sessionResumed = true;
5260
- if (!this.contactId && !this.anonymousId) return;
5624
+ await this.mintSession();
5625
+ }
5626
+ /** POST /v1/chat/session: resolve the contact and mint a ticket (no message
5627
+ * sent). Loads history and connects SSE when `refresh`. True when a ticket
5628
+ * was minted. A workspace mismatch retries once without the workspace. */
5629
+ async mintSession({ refresh = true } = {}) {
5630
+ if (!this.contactId && !this.anonymousId) return false;
5261
5631
  try {
5262
- const res = await fetch(`${this.apiHost}/v1/chat/session`, {
5632
+ const post = () => fetch(`${this.apiHost}/v1/chat/session`, {
5263
5633
  method: "POST",
5264
5634
  headers: { "Content-Type": "application/json", "X-Aegis-Write-Key": this.writeKey },
5265
5635
  body: JSON.stringify({
5636
+ workspace_id: this.sentWorkspaceId(),
5266
5637
  anonymous_id: this.anonymousId,
5267
5638
  contact_id: this.contactId,
5268
5639
  channel: this.channel
5269
5640
  })
5270
5641
  });
5271
- if (!res.ok) return;
5642
+ let res = await post();
5643
+ if (await this.isWorkspaceMismatch(res)) res = await post();
5644
+ if (!res.ok) return false;
5272
5645
  const data = await res.json();
5273
- if (!data.contact_id || !data.sse_ticket) return;
5646
+ if (!data.contact_id || !data.sse_ticket) return false;
5274
5647
  this.contactId = data.contact_id;
5275
5648
  this.sseTicket = data.sse_ticket;
5276
5649
  this.persistContactId(data.contact_id);
5277
- await this.refreshHistory();
5650
+ if (refresh) await this.refreshHistory();
5278
5651
  if (this.open) this.connectSSE(data.sse_ticket);
5652
+ return true;
5279
5653
  } catch (err) {
5280
- this.log("resume session failed", err);
5654
+ this.log("session mint failed", err);
5655
+ return false;
5656
+ }
5657
+ }
5658
+ // ── Workspace + auth recovery ─────────────────────────────────────────────
5659
+ /** The workspace_id to send: the configured one until the server refused it. */
5660
+ sentWorkspaceId() {
5661
+ return this.workspaceRejected ? void 0 : this.workspaceId;
5662
+ }
5663
+ /** True (once) when `res` is the server refusing our workspace_id: the
5664
+ * launcher drops it for the rest of the page-load and warns once. */
5665
+ async isWorkspaceMismatch(res) {
5666
+ if (res.status !== 403 || !this.sentWorkspaceId()) return false;
5667
+ if (await errorCode(res) !== WORKSPACE_MISMATCH_CODE) return false;
5668
+ this.workspaceRejected = true;
5669
+ console.warn(
5670
+ `[AegisChat] workspace_id "${this.workspaceId}" does not belong to this write key's property; continuing without it (the server uses the key's property).`
5671
+ );
5672
+ return true;
5673
+ }
5674
+ /** An old/expired ticket (401/403 other than a workspace mismatch): drop it
5675
+ * and mint a new one, at most once per REMINT_WINDOW_MS. A failure inside the
5676
+ * window (or a failed mint) stops the transport and shows the error line. */
5677
+ async recoverAuth({ refresh = true } = {}) {
5678
+ if (this.authStopped) return false;
5679
+ const now = Date.now();
5680
+ if (this.lastRemintAt && now - this.lastRemintAt < REMINT_WINDOW_MS) {
5681
+ this.stopAuth();
5682
+ return false;
5281
5683
  }
5684
+ this.lastRemintAt = now;
5685
+ this.sseTicket = void 0;
5686
+ this.disconnectSSE();
5687
+ const ok = await this.mintSession({ refresh });
5688
+ if (!ok) this.stopAuth();
5689
+ return ok;
5690
+ }
5691
+ stopAuth() {
5692
+ if (this.authStopped) return;
5693
+ this.authStopped = true;
5694
+ this.stopPolling();
5695
+ this.disconnectSSE();
5696
+ this.hideTyping();
5697
+ this.appendSystem(AUTH_STOPPED_TEXT);
5282
5698
  }
5283
5699
  // ── Typing indicator ───────────────────────────────────────────────────────
5284
5700
  showTyping() {
5285
5701
  if (!this.thread || this.typingEl) return;
5702
+ const follow = this.isNearBottom();
5286
5703
  const row = document.createElement("div");
5287
5704
  row.className = "aegis-chat-msg aegis-chat-msg--assistant aegis-chat-typing";
5288
5705
  row.innerHTML = '<div class="aegis-chat-bubbletext aegis-chat-typingdots"><span></span><span></span><span></span></div>';
5289
5706
  this.thread.appendChild(row);
5290
5707
  this.typingEl = row;
5291
- this.scrollToBottom();
5708
+ if (follow) this.scrollToBottom();
5292
5709
  }
5293
5710
  hideTyping() {
5294
5711
  if (this.typingEl) {
@@ -5351,11 +5768,11 @@ const CHAT_CSS = `
5351
5768
  .aegis-chat-panel--open{display:flex}
5352
5769
  /* Header + customer bubbles use the "fill" surface — accent solid by default, or
5353
5770
  a soft tint when surfaceStyle:'tinted' sets --aegis-chat-fill/-fg on the root. */
5354
- .aegis-chat-header{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;background:var(--aegis-chat-fill,var(--aegis-chat-accent,#4169e1));color:var(--aegis-chat-fill-fg,#fff)}
5771
+ .aegis-chat-header{flex:0 0 auto;display:flex;align-items:center;justify-content:space-between;padding:14px 16px;background:var(--aegis-chat-fill,var(--aegis-chat-accent,#4169e1));color:var(--aegis-chat-fill-fg,#fff)}
5355
5772
  .aegis-chat-title{font-weight:600;font-size:15px}
5356
5773
  .aegis-chat-close{background:transparent;border:none;color:var(--aegis-chat-fill-fg,#fff);font-size:16px;cursor:pointer;opacity:.85}
5357
5774
  .aegis-chat-close:hover{opacity:1}
5358
- .aegis-chat-thread{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:10px;background:#f8fafc}
5775
+ .aegis-chat-thread{position:relative;flex:1 1 auto;min-height:0;overflow-y:auto;overscroll-behavior:contain;padding:16px;display:flex;flex-direction:column;gap:10px;background:#f8fafc}
5359
5776
  .aegis-chat-msg{display:flex;flex-direction:column;max-width:85%}
5360
5777
  .aegis-chat-msg--customer{align-self:flex-end;align-items:flex-end}
5361
5778
  .aegis-chat-msg--assistant,.aegis-chat-msg--system{align-self:flex-start;align-items:flex-start}
@@ -5383,13 +5800,20 @@ const CHAT_CSS = `
5383
5800
  .aegis-chat-card-name{font-size:13px;font-weight:500;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
5384
5801
  .aegis-chat-card-price{font-size:13px;font-weight:600;color:var(--aegis-chat-accent,#4169e1)}
5385
5802
  .aegis-chat-card--more{align-items:center;justify-content:center;font-weight:600;color:var(--aegis-chat-accent,#4169e1)}
5386
- .aegis-chat-composer{display:flex;align-items:flex-end;gap:8px;padding:12px;border-top:1px solid #e2e8f0;background:#fff}
5803
+ .aegis-chat-composer{flex:0 0 auto;display:flex;align-items:flex-end;gap:8px;padding:12px;border-top:1px solid #e2e8f0;background:#fff}
5387
5804
  .aegis-chat-input{flex:1;resize:none;border:1px solid #e2e8f0;border-radius:12px;padding:9px 12px;font-size:14px;font-family:inherit;max-height:96px;outline:none}
5388
5805
  .aegis-chat-input:focus{border-color:var(--aegis-chat-accent,#4169e1)}
5389
5806
  .aegis-chat-send{width:40px;height:40px;border-radius:9999px;border:none;background:var(--aegis-chat-accent,#4169e1);color:#fff;display:flex;align-items:center;justify-content:center;cursor:pointer;flex:0 0 auto}
5390
5807
  .aegis-chat-attach{width:38px;height:38px;border-radius:9999px;border:none;background:transparent;color:#64748b;display:flex;align-items:center;justify-content:center;cursor:pointer;flex:0 0 auto;transition:background .15s ease,color .15s ease}
5391
5808
  .aegis-chat-attach:hover{background:#f1f5f9;color:var(--aegis-chat-accent,#4169e1)}
5392
5809
  .aegis-chat-fileinput{display:none}
5810
+ .aegis-chat-interactive{display:flex;flex-direction:column;align-items:flex-start;gap:6px}
5811
+ .aegis-chat-cta{display:flex;flex-direction:column;align-items:flex-start;gap:6px;padding:4px 0;max-width:320px}
5812
+ .aegis-chat-cta-img{max-width:200px;border-radius:12px;display:block}
5813
+ .aegis-chat-ctabtn{display:inline-flex;align-items:center;justify-content:center;min-height:40px;padding:8px 16px;border-radius:9999px;background:var(--aegis-chat-accent,#4169e1);color:#fff;font-size:14px;font-weight:600;text-decoration:none}
5814
+ .aegis-chat-ctabtn:hover{filter:brightness(1.05)}
5815
+ .aegis-chat-ctabtn:focus-visible{outline:2px solid var(--aegis-chat-accent,#4169e1);outline-offset:2px}
5816
+ .aegis-chat-msg--assistant .aegis-chat-fallback,.aegis-chat-cta .aegis-chat-bubbletext{background:#fff;color:#0f172a;border:1px solid #e2e8f0}
5393
5817
  .aegis-chat-media-img{max-width:200px;max-height:200px;border-radius:12px;object-fit:cover;cursor:pointer;display:block}
5394
5818
  .aegis-chat-media-file{display:inline-flex;align-items:center;gap:6px;padding:8px 12px;border-radius:12px;background:#fff;border:1px solid #e2e8f0;font-size:13px;color:#0f172a;text-decoration:none;max-width:220px}
5395
5819
  .aegis-chat-msg--customer .aegis-chat-media-file{background:rgba(255,255,255,.18);border-color:transparent;color:#fff}
@@ -5400,6 +5824,9 @@ const CHAT_CSS = `
5400
5824
  /* Full-page chat on mobile — the open panel covers the whole viewport (incl.
5401
5825
  the bottom nav) like a native chat screen, instead of a floating card. */
5402
5826
  .aegis-chat-panel{position:fixed;inset:0;left:0;right:0;width:100vw;height:100vh;height:100dvh;max-width:none;max-height:none;border-radius:0}
5827
+ /* Keyboard open: follow the visual viewport (bindViewport) so the header and
5828
+ composer stay on screen. Without visualViewport the 100dvh rule stands. */
5829
+ .aegis-chat-panel.aegis-chat-panel--vv{top:var(--aegis-chat-top,0px);bottom:auto;height:var(--aegis-chat-vh,100dvh)}
5403
5830
  .aegis-chat-tip{max-width:200px}
5404
5831
  }
5405
5832
  `;
@@ -5987,6 +6414,8 @@ function renderActiveWebChat(ctx, creds) {
5987
6414
  writeKey: creds.writeKey,
5988
6415
  apiHost: creds.apiHost,
5989
6416
  contactId: creds.contactId,
6417
+ // The brand this runtime is scoped to; chat history is per brand.
6418
+ workspaceId: ctx.workspaceId,
5990
6419
  channel: creds.channel ?? "web",
5991
6420
  title: str(ic.chat_title),
5992
6421
  greeting: str(ic.chat_greeting),
@@ -7298,6 +7727,14 @@ function productIdentitiesFor(campaign) {
7298
7727
  productIdentityCache.set(cards, encoded);
7299
7728
  return encoded || void 0;
7300
7729
  }
7730
+ function setPaneActive(pane, active) {
7731
+ var _a;
7732
+ pane.style.visibility = active ? "visible" : "hidden";
7733
+ pane.setAttribute("data-aegis-rotate-active", active ? "true" : "false");
7734
+ pane.setAttribute("aria-hidden", active ? "false" : "true");
7735
+ if (active) (_a = pane.removeAttribute) == null ? void 0 : _a.call(pane, "inert");
7736
+ else pane.setAttribute("inert", "");
7737
+ }
7301
7738
  const _AegisInAppManager = class _AegisInAppManager {
7302
7739
  constructor(config) {
7303
7740
  this.productUrl = productPath;
@@ -8178,7 +8615,7 @@ const _AegisInAppManager = class _AegisInAppManager {
8178
8615
  this.slotTimers.delete(slot);
8179
8616
  }
8180
8617
  slot.querySelectorAll(
8181
- ":scope > [data-aegis-rotate-pane], :scope > [data-aegis-slot-rendered], :scope > [data-aegis-rotate-dots]"
8618
+ ":scope > [data-aegis-rotate-stack], :scope > [data-aegis-rotate-pane], :scope > [data-aegis-slot-rendered], :scope > [data-aegis-rotate-dots]"
8182
8619
  ).forEach((n) => n.remove());
8183
8620
  }
8184
8621
  // Re-fill slots that mount after a poll (SPA route changes). Observes the DOM
@@ -8342,14 +8779,26 @@ const _AegisInAppManager = class _AegisInAppManager {
8342
8779
  * while off-screen; only the visibility toggles every `rotateMs`. The impression
8343
8780
  * is deferred at render and fired per campaign on FIRST visibility, so hidden
8344
8781
  * panes never over-count. One rendered pane → no rotation (just shows it).
8782
+ *
8783
+ * Stable height (1.46.2): with >1 pane every pane sits in the SAME grid cell
8784
+ * of an SDK-owned wrapper (`data-aegis-rotate-stack`, panes + dots row), so
8785
+ * the HOST element's own display (`hidden md:block`, flex, …) is never
8786
+ * touched. The inactive ones are `visibility:hidden` + `aria-hidden` + `inert`
8787
+ * (not `display:none`), so the slot is always as tall as its tallest pane. A
8788
+ * one-line value bar rotating with a two-line card no longer grows and shrinks
8789
+ * the slot (and the page around it) on every turn. The visible pane carries
8790
+ * `data-aegis-rotate-active="true"`, the others `"false"`.
8345
8791
  */
8346
8792
  renderRotatingSlot(slot, campaigns, rotateMs, flush = false) {
8347
8793
  const panes = [];
8348
8794
  for (const c of campaigns) {
8349
8795
  const pane = document.createElement("div");
8350
8796
  pane.setAttribute("data-aegis-rotate-pane", c.id);
8351
- pane.style.display = "none";
8797
+ pane.style.gridArea = "1 / 1";
8798
+ pane.style.minWidth = "0";
8799
+ pane.style.alignSelf = "center";
8352
8800
  slot.appendChild(pane);
8801
+ setPaneActive(pane, false);
8353
8802
  this.renderCampaignIntoSlot(c, pane, { deferImpression: true });
8354
8803
  if (pane.childElementCount > 0) {
8355
8804
  if (flush) this._flattenSlotCard(pane);
@@ -8357,6 +8806,17 @@ const _AegisInAppManager = class _AegisInAppManager {
8357
8806
  } else pane.remove();
8358
8807
  }
8359
8808
  if (panes.length === 0) return;
8809
+ let stack = slot;
8810
+ if (panes.length > 1) {
8811
+ stack = document.createElement("div");
8812
+ stack.setAttribute("data-aegis-rotate-stack", "");
8813
+ stack.style.display = "grid";
8814
+ stack.style.gridTemplateColumns = "minmax(0, 1fr)";
8815
+ stack.style.width = "100%";
8816
+ stack.style.minWidth = "0";
8817
+ for (const p of panes) stack.appendChild(p.el);
8818
+ slot.appendChild(stack);
8819
+ }
8360
8820
  const impressed = /* @__PURE__ */ new Set();
8361
8821
  const markVisible = (c) => {
8362
8822
  if (impressed.has(c.id)) return;
@@ -8379,8 +8839,11 @@ const _AegisInAppManager = class _AegisInAppManager {
8379
8839
  return false;
8380
8840
  };
8381
8841
  const darkDots = panes.length > 0 && panes.every((p) => isDarkSurface(p.campaign));
8382
- const dotInactive = darkDots ? "rgba(255,255,255,0.4)" : "rgba(15,23,42,0.2)";
8383
- const dotActive = darkDots ? "#ffffff" : "var(--aegis-brand-accent, #4169e1)";
8842
+ const compactSlot = slotVariant(slot) === "compact";
8843
+ const dotInactiveBase = darkDots ? "rgba(255,255,255,0.4)" : "rgba(15,23,42,0.2)";
8844
+ const dotActiveBase = darkDots ? "#ffffff" : "var(--aegis-brand-accent, #4169e1)";
8845
+ const dotInactive = compactSlot ? `var(--aegis-card-muted, ${dotInactiveBase})` : dotInactiveBase;
8846
+ const dotActive = compactSlot ? `var(--aegis-card-fg, ${dotActiveBase})` : dotActiveBase;
8384
8847
  const dots = [];
8385
8848
  if (panes.length > 1) {
8386
8849
  const bar = document.createElement("div");
@@ -8401,7 +8864,8 @@ const _AegisInAppManager = class _AegisInAppManager {
8401
8864
  dots.push(dot);
8402
8865
  bar.appendChild(dot);
8403
8866
  });
8404
- slot.appendChild(bar);
8867
+ bar.style.gridArea = "2 / 1";
8868
+ stack.appendChild(bar);
8405
8869
  }
8406
8870
  const paintDots = () => {
8407
8871
  dots.forEach((d, i) => {
@@ -8420,9 +8884,9 @@ const _AegisInAppManager = class _AegisInAppManager {
8420
8884
  return t;
8421
8885
  };
8422
8886
  function show(i, fromClick = false) {
8423
- panes[idx].el.style.display = "none";
8887
+ setPaneActive(panes[idx].el, false);
8424
8888
  idx = (i % panes.length + panes.length) % panes.length;
8425
- panes[idx].el.style.display = "";
8889
+ setPaneActive(panes[idx].el, true);
8426
8890
  markVisible(panes[idx].campaign);
8427
8891
  paintDots();
8428
8892
  if (fromClick && timer) {
@@ -8430,7 +8894,7 @@ const _AegisInAppManager = class _AegisInAppManager {
8430
8894
  timer = start();
8431
8895
  }
8432
8896
  }
8433
- panes[0].el.style.display = "";
8897
+ setPaneActive(panes[0].el, true);
8434
8898
  markVisible(panes[0].campaign);
8435
8899
  paintDots();
8436
8900
  if (panes.length === 1) return;
@@ -13134,18 +13598,11 @@ const _AegisInAppManager = class _AegisInAppManager {
13134
13598
  document.head.appendChild(style);
13135
13599
  }
13136
13600
  sanitizeUrl(url) {
13137
- if (typeof url !== "string" || url.trim() === "") return null;
13138
- try {
13139
- const parsedUrl = new URL(url, window.location.origin);
13140
- if (parsedUrl.protocol === "javascript:" || parsedUrl.protocol === "data:") {
13141
- this.log(`Blocked unsafe URL: ${url}`, "error");
13142
- return null;
13143
- }
13144
- return parsedUrl.href;
13145
- } catch (error) {
13146
- this.log(`Invalid URL: ${url}`, "error");
13147
- return null;
13601
+ const safe = sanitizeUrl(url);
13602
+ if (safe === null && typeof url === "string" && url.trim() !== "") {
13603
+ this.log(`Blocked unsafe or invalid URL: ${url}`, "error");
13148
13604
  }
13605
+ return safe;
13149
13606
  }
13150
13607
  sanitizeColor(color) {
13151
13608
  if (/^#[0-9A-Fa-f]{3,6}$/.test(color)) {
@@ -16013,11 +16470,11 @@ const _AegisMessageRuntime = class _AegisMessageRuntime {
16013
16470
  // updateContext). The renderer cart reader + the cart_value signal are DERIVED
16014
16471
  // from it; there is no parallel cart/context store on the runtime.
16015
16472
  constructor(config) {
16016
- var _a;
16473
+ var _a, _b, _c;
16017
16474
  this.initialized = false;
16018
16475
  this.armedInAppTriggers = /* @__PURE__ */ new Set();
16019
16476
  {
16020
- const v = "1.46.0";
16477
+ const v = "1.46.2";
16021
16478
  try {
16022
16479
  globalThis.__AEGIS_SDK_VERSION__ = v;
16023
16480
  } catch {
@@ -16115,9 +16572,12 @@ const _AegisMessageRuntime = class _AegisMessageRuntime {
16115
16572
  organizationId: config.organizationId,
16116
16573
  contactId: config.contactId,
16117
16574
  debugMode: config.debugMode,
16118
- ...config.chat
16575
+ ...config.chat,
16576
+ // The brand the chat talks for: the host's explicit value, else the
16577
+ // runtime's effective workspace (the same one in-app reads send).
16578
+ workspaceId: ((_a = config.chat) == null ? void 0 : _a.workspaceId) ?? ((_b = config.getWorkspaceId) == null ? void 0 : _b.call(config))
16119
16579
  });
16120
- const proactive = (((_a = config.chat) == null ? void 0 : _a.proactiveTriggers) ?? []).map(triggerFromEngineEvent);
16580
+ const proactive = (((_c = config.chat) == null ? void 0 : _c.proactiveTriggers) ?? []).map(triggerFromEngineEvent);
16121
16581
  armBehaviouralTriggers(
16122
16582
  triggerEngine,
16123
16583
  proactive,