@active-reach/web-sdk 1.46.1 → 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) {
@@ -1804,9 +1804,9 @@ function buildProgressElement(el2, ctx, accent, muted, compact) {
1804
1804
  }
1805
1805
  return wrap;
1806
1806
  }
1807
- function buildCtaAction(el2, card, meta, inline, sanitizeUrl) {
1807
+ function buildCtaAction(el2, card, meta, inline, sanitizeUrl2) {
1808
1808
  const kind = el2.cta_action ?? (inline ? "add_to_cart" : "navigate");
1809
- const safe = (u) => u ? sanitizeUrl(u) || void 0 : void 0;
1809
+ const safe = (u) => u ? sanitizeUrl2(u) || void 0 : void 0;
1810
1810
  const url = safe(el2.cta_url || card.cta_url);
1811
1811
  const productId = meta.product_id;
1812
1812
  const sku = meta.sku;
@@ -1860,7 +1860,7 @@ function findElement(els, type) {
1860
1860
  function renderCardFromTemplate(card, opts) {
1861
1861
  const { ctx, action, layout, layoutAccent } = opts;
1862
1862
  const inline = action === "cart";
1863
- const { campaign, trackEvent, sanitizeUrl, sanitizeColor } = ctx;
1863
+ const { campaign, trackEvent, sanitizeUrl: sanitizeUrl2, sanitizeColor } = ctx;
1864
1864
  const tpl = applyPerCardOverride(opts.template, asLook(card.style));
1865
1865
  const frame = tpl.frame || {};
1866
1866
  const meta = card.metadata || {};
@@ -1870,6 +1870,10 @@ function renderCardFromTemplate(card, opts) {
1870
1870
  const muted = fg === "#ffffff" ? "rgba(255,255,255,0.72)" : "#6b7280";
1871
1871
  const compact = slotVariant(ctx.slotEl) === "compact";
1872
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
+ };
1873
1877
  const tile = document.createElement("div");
1874
1878
  markEl(tile, "frame");
1875
1879
  if (compact) tile.setAttribute("data-aegis-variant", "compact");
@@ -1921,7 +1925,7 @@ function renderCardFromTemplate(card, opts) {
1921
1925
  case "image": {
1922
1926
  const wrap = document.createElement("div");
1923
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;`;
1924
- const safeVideo = card.video_url ? sanitizeUrl(card.video_url) : "";
1928
+ const safeVideo = card.video_url ? sanitizeUrl2(card.video_url) : "";
1925
1929
  if (safeVideo) {
1926
1930
  const v = document.createElement("video");
1927
1931
  v.src = safeVideo;
@@ -1933,7 +1937,7 @@ function renderCardFromTemplate(card, opts) {
1933
1937
  v.style.cssText = "width:100%;height:100%;object-fit:cover;display:block;";
1934
1938
  wrap.appendChild(v);
1935
1939
  } else if (card.image_url) {
1936
- const safe = sanitizeUrl(card.image_url);
1940
+ const safe = sanitizeUrl2(card.image_url);
1937
1941
  if (safe) {
1938
1942
  const img = document.createElement("img");
1939
1943
  const size = IMAGE_SIZE[el2.aspect || "1/1"] || IMAGE_SIZE["1/1"];
@@ -1982,7 +1986,7 @@ function renderCardFromTemplate(card, opts) {
1982
1986
  markEl(t, "title");
1983
1987
  t.textContent = card.title;
1984
1988
  const lines = el2.lines && el2.lines > 0 ? el2.lines : 2;
1985
- 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;`;
1986
1990
  container.appendChild(t);
1987
1991
  break;
1988
1992
  }
@@ -1992,7 +1996,7 @@ function renderCardFromTemplate(card, opts) {
1992
1996
  markEl(s, "subtitle");
1993
1997
  s.textContent = card.body;
1994
1998
  const lines = el2.lines && el2.lines > 0 ? el2.lines : 2;
1995
- 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;`;
1996
2000
  container.appendChild(s);
1997
2001
  break;
1998
2002
  }
@@ -2015,7 +2019,7 @@ function renderCardFromTemplate(card, opts) {
2015
2019
  const px = ICON_PX[el2.size || "md"] || 30;
2016
2020
  const node = document.createElement("div");
2017
2021
  markEl(node, "icon");
2018
- const iconColor = el2.color ? sanitizeColor(el2.color) : fg;
2022
+ const iconColor = compact ? "currentColor" : el2.color ? sanitizeColor(el2.color) : fg;
2019
2023
  if (el2.bubble) {
2020
2024
  const bubbleTint = el2.color ? sanitizeColor(el2.color) : brand;
2021
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);`;
@@ -2027,6 +2031,7 @@ function renderCardFromTemplate(card, opts) {
2027
2031
  color: iconColor,
2028
2032
  strokeWidth: 2
2029
2033
  });
2034
+ if (compact) node.style.cssText += `color:${ink("fg", el2.color)};`;
2030
2035
  if (svg) node.appendChild(svg);
2031
2036
  container.appendChild(node);
2032
2037
  break;
@@ -2035,7 +2040,7 @@ function renderCardFromTemplate(card, opts) {
2035
2040
  const t = document.createElement("div");
2036
2041
  markEl(t, "text");
2037
2042
  const fs = TEXT_PX[el2.size || "md"] || 13;
2038
- 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;`;
2039
2044
  t.textContent = interpolateTokens(el2.content ?? "", ctx);
2040
2045
  container.appendChild(t);
2041
2046
  break;
@@ -2099,7 +2104,7 @@ function renderCardFromTemplate(card, opts) {
2099
2104
  trackEvent(campaign.id, "clicked", { stepId: el2.id || "add" });
2100
2105
  (_a = ctx.dispatchAction) == null ? void 0 : _a.call(
2101
2106
  ctx,
2102
- buildCtaAction(el2, card, meta, inline, sanitizeUrl)
2107
+ buildCtaAction(el2, card, meta, inline, sanitizeUrl2)
2103
2108
  );
2104
2109
  });
2105
2110
  (overlayOnImage ? imageWrap : container).appendChild(cta);
@@ -2127,7 +2132,7 @@ function renderCardFromTemplate(card, opts) {
2127
2132
  e.stopPropagation();
2128
2133
  trackEvent(campaign.id, "clicked");
2129
2134
  const bm = meta;
2130
- const safe = (u) => u ? sanitizeUrl(u) || void 0 : void 0;
2135
+ const safe = (u) => u ? sanitizeUrl2(u) || void 0 : void 0;
2131
2136
  const act = inline ? {
2132
2137
  type: "open_product",
2133
2138
  productId: bm.product_id,
@@ -2340,7 +2345,7 @@ function renderCarouselCards(ctx) {
2340
2345
  }
2341
2346
  const DISMISS_STORAGE_PREFIX = "aegis_sticky_dismissed:";
2342
2347
  function renderStickyBar(ctx) {
2343
- const { campaign, trackEvent, sanitizeUrl, sanitizeColor, log, addAnimationStyles } = ctx;
2348
+ const { campaign, trackEvent, sanitizeUrl: sanitizeUrl2, sanitizeColor, log, addAnimationStyles } = ctx;
2344
2349
  const ic = campaign.interactive_config || {};
2345
2350
  const position = ic.sticky_position === "top" ? "top" : "bottom";
2346
2351
  const dismissible = ic.sticky_dismissible !== false;
@@ -2390,7 +2395,7 @@ function renderStickyBar(ctx) {
2390
2395
  cta.addEventListener("click", () => {
2391
2396
  trackEvent(campaign.id, "clicked");
2392
2397
  if (campaign.action_url) {
2393
- const safe = sanitizeUrl(campaign.action_url);
2398
+ const safe = sanitizeUrl2(campaign.action_url);
2394
2399
  if (safe) window.location.href = safe;
2395
2400
  }
2396
2401
  });
@@ -3231,7 +3236,7 @@ function buildGroupBubble(ctx, cfg, g, i, labelColor) {
3231
3236
  return wrap;
3232
3237
  }
3233
3238
  function openViewer(ctx, cfg, startGroupIndex, startFrameIndex = 0) {
3234
- const { campaign, trackEvent, sanitizeUrl, log } = ctx;
3239
+ const { campaign, trackEvent, sanitizeUrl: sanitizeUrl2, log } = ctx;
3235
3240
  const { loop, autoplay, showProgress, defaultDuration, reduceMotion } = cfg;
3236
3241
  const groups = cfg.groups;
3237
3242
  if (groups.length === 0) return;
@@ -3342,8 +3347,8 @@ function openViewer(ctx, cfg, startGroupIndex, startFrameIndex = 0) {
3342
3347
  const f = frames[i];
3343
3348
  frameLayer.replaceChildren();
3344
3349
  currentVideo = null;
3345
- const safeVideo = f.video_url ? sanitizeUrl(f.video_url) : null;
3346
- 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;
3347
3352
  if (safeVideo) {
3348
3353
  const vid = document.createElement("video");
3349
3354
  vid.src = safeVideo;
@@ -3385,7 +3390,7 @@ function openViewer(ctx, cfg, startGroupIndex, startFrameIndex = 0) {
3385
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);";
3386
3391
  copy.appendChild(b);
3387
3392
  }
3388
- const ctaUrl = f.cta_url ? sanitizeUrl(f.cta_url) : null;
3393
+ const ctaUrl = f.cta_url ? sanitizeUrl2(f.cta_url) : null;
3389
3394
  const ctaLabel = f.cta_text || (ctaUrl ? "Learn more" : "");
3390
3395
  if (ctaLabel) {
3391
3396
  const cta = document.createElement("button");
@@ -4239,10 +4244,10 @@ function renderGame(ctx, subType) {
4239
4244
  const ASPECT$1 = { "16:9": "16 / 9", "9:16": "9 / 16", "1:1": "1 / 1", "4:5": "4 / 5" };
4240
4245
  function buildVideo(ctx, aspect, autoplay, loop) {
4241
4246
  var _a;
4242
- const { campaign, sanitizeUrl } = ctx;
4247
+ const { campaign, sanitizeUrl: sanitizeUrl2 } = ctx;
4243
4248
  const ic = campaign.interactive_config || {};
4244
- const videoUrl = sanitizeUrl(ic.video_url || campaign.video_url || "");
4245
- 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;
4246
4251
  const wrap = document.createElement("div");
4247
4252
  wrap.style.cssText = `position:relative;width:100%;aspect-ratio:${ASPECT$1[aspect] || ASPECT$1["16:9"]};background:#0b1220;border-radius:14px;overflow:hidden;`;
4248
4253
  if (videoUrl) {
@@ -4466,7 +4471,7 @@ function cardUrl(c) {
4466
4471
  return "";
4467
4472
  }
4468
4473
  function renderHeroInline(ctx, target) {
4469
- const { campaign, sanitizeUrl, trackEvent } = ctx;
4474
+ const { campaign, sanitizeUrl: sanitizeUrl2, trackEvent } = ctx;
4470
4475
  const ic = campaign.interactive_config || {};
4471
4476
  const cards = Array.isArray(ic.cards) ? ic.cards : [];
4472
4477
  if (cards.length === 0) return false;
@@ -4481,7 +4486,7 @@ function renderHeroInline(ctx, target) {
4481
4486
  const bar = document.createElement("div");
4482
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;`;
4483
4488
  bar.textContent = [cardHeadline(c), cardSub(c)].filter(Boolean).join(" · ");
4484
- const url = sanitizeUrl(cardUrl(c));
4489
+ const url = sanitizeUrl2(cardUrl(c));
4485
4490
  if (url && cardCta(c)) {
4486
4491
  const a = document.createElement("span");
4487
4492
  a.style.cssText = "text-decoration:underline;cursor:pointer;white-space:nowrap;";
@@ -4500,7 +4505,7 @@ function renderHeroInline(ctx, target) {
4500
4505
  _injectHeroResponsiveCss();
4501
4506
  const explicitRatio = chrome.aspect_ratio ? ASPECT[chrome.aspect_ratio] : void 0;
4502
4507
  const hasPhoneImage = cards.some(
4503
- (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)
4504
4509
  );
4505
4510
  const root = document.createElement("div");
4506
4511
  root.className = explicitRatio ? "aegis-hero-root" : `aegis-hero-root aegis-hero-auto${hasPhoneImage ? " aegis-hero-phone-square" : ""}`;
@@ -4517,9 +4522,9 @@ function renderHeroInline(ctx, target) {
4517
4522
  cards.forEach((c, i) => {
4518
4523
  const slide = document.createElement("div");
4519
4524
  slide.style.cssText = "position:relative;flex:0 0 100%;width:100%;height:100%;min-height:inherit;background:#f1f5f9;";
4520
- const videoUrl = c.video_url ? sanitizeUrl(c.video_url) ?? "" : "";
4525
+ const videoUrl = c.video_url ? sanitizeUrl2(c.video_url) ?? "" : "";
4521
4526
  const isVideo = !!videoUrl || c.media_type === "video";
4522
- 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);
4523
4528
  if (mediaUrl) {
4524
4529
  if (isVideo) {
4525
4530
  const v = document.createElement("video");
@@ -4532,7 +4537,7 @@ function renderHeroInline(ctx, target) {
4532
4537
  slide.appendChild(v);
4533
4538
  } else {
4534
4539
  const picture = document.createElement("picture");
4535
- 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;
4536
4541
  const shell = i === 0 ? adoptableShell(ctx.shellImage, mediaUrl) : null;
4537
4542
  if (phoneUrl) {
4538
4543
  const source = document.createElement("source");
@@ -4593,7 +4598,7 @@ function renderHeroInline(ctx, target) {
4593
4598
  content.appendChild(sub);
4594
4599
  }
4595
4600
  const cta = cardCta(c);
4596
- const url = sanitizeUrl(cardUrl(c));
4601
+ const url = sanitizeUrl2(cardUrl(c));
4597
4602
  if (cta && chrome.cta_style !== "none") {
4598
4603
  const btn = document.createElement("button");
4599
4604
  btn.textContent = cta;
@@ -4645,8 +4650,124 @@ function renderHeroInline(ctx, target) {
4645
4650
  trackEvent(campaign.id, "impression");
4646
4651
  return true;
4647
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
+ }
4648
4744
  const STYLE_ID$1 = "aegis-chat-styles";
4649
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
+ }
4650
4771
  let currentLauncher = null;
4651
4772
  function getCurrentLauncher() {
4652
4773
  return currentLauncher;
@@ -4660,6 +4781,10 @@ function closeChat() {
4660
4781
  const ATTENTION_DELAY_MS = 4500;
4661
4782
  class AegisChat {
4662
4783
  constructor(config) {
4784
+ this.workspaceRejected = false;
4785
+ this.lastRemintAt = 0;
4786
+ this.authStopped = false;
4787
+ this.renderedRows = /* @__PURE__ */ new Map();
4663
4788
  this.sessionResumed = false;
4664
4789
  this.open = false;
4665
4790
  this.initialized = false;
@@ -4669,6 +4794,8 @@ class AegisChat {
4669
4794
  this.hasInteracted = false;
4670
4795
  this.writeKey = config.writeKey;
4671
4796
  this.organizationId = config.organizationId;
4797
+ const ws = typeof config.workspaceId === "string" ? config.workspaceId.trim() : "";
4798
+ this.workspaceId = ws || void 0;
4672
4799
  this.apiHost = (config.apiHost ?? "").replace(/\/$/, "");
4673
4800
  this.contactId = config.contactId;
4674
4801
  this.channel = config.channel ?? "web";
@@ -4717,6 +4844,8 @@ class AegisChat {
4717
4844
  this.dismissAttention();
4718
4845
  (_b = this.panel) == null ? void 0 : _b.classList.add("aegis-chat-panel--open");
4719
4846
  (_c = this.bubble) == null ? void 0 : _c.classList.add("aegis-chat-bubble--hidden");
4847
+ this.bindViewport();
4848
+ this.revealLatest();
4720
4849
  this.clearUnread();
4721
4850
  if (prefill && this.input) this.input.value = prefill;
4722
4851
  void this.resumeSession();
@@ -4729,6 +4858,7 @@ class AegisChat {
4729
4858
  this.open = false;
4730
4859
  (_a = this.panel) == null ? void 0 : _a.classList.remove("aegis-chat-panel--open");
4731
4860
  (_b = this.bubble) == null ? void 0 : _b.classList.remove("aegis-chat-bubble--hidden");
4861
+ this.unbindViewport();
4732
4862
  this.disconnectSSE();
4733
4863
  this.stopPolling();
4734
4864
  if (wasOpen) {
@@ -4740,6 +4870,7 @@ class AegisChat {
4740
4870
  }
4741
4871
  destroy() {
4742
4872
  var _a;
4873
+ this.unbindViewport();
4743
4874
  this.disconnectSSE();
4744
4875
  this.stopPolling();
4745
4876
  (_a = this.root) == null ? void 0 : _a.remove();
@@ -4767,10 +4898,11 @@ class AegisChat {
4767
4898
  }
4768
4899
  this.showTyping();
4769
4900
  try {
4770
- const res = await fetch(`${this.apiHost}/v1/chat/message`, {
4901
+ const post = () => fetch(`${this.apiHost}/v1/chat/message`, {
4771
4902
  method: "POST",
4772
4903
  headers: { "Content-Type": "application/json", "X-Aegis-Write-Key": this.writeKey },
4773
4904
  body: JSON.stringify({
4905
+ workspace_id: this.sentWorkspaceId(),
4774
4906
  message_text: message,
4775
4907
  channel: this.channel,
4776
4908
  anonymous_id: this.anonymousId,
@@ -4784,6 +4916,8 @@ class AegisChat {
4784
4916
  }),
4785
4917
  keepalive: true
4786
4918
  });
4919
+ let res = await post();
4920
+ if (await this.isWorkspaceMismatch(res)) res = await post();
4787
4921
  if (!res.ok) {
4788
4922
  this.log("send failed", res.status);
4789
4923
  this.appendSystem("Sorry — your message could not be delivered. Please try again.");
@@ -4797,6 +4931,7 @@ class AegisChat {
4797
4931
  this.contactId = data.contact_id;
4798
4932
  this.persistContactId(data.contact_id);
4799
4933
  this.sseTicket = data.sse_ticket;
4934
+ this.authStopped = false;
4800
4935
  this.connectSSE(data.sse_ticket);
4801
4936
  void this.refreshHistory();
4802
4937
  } catch (err) {
@@ -4859,6 +4994,8 @@ class AegisChat {
4859
4994
  url.searchParams.set("ticket", ticket);
4860
4995
  url.searchParams.set("mode", "ephemeral");
4861
4996
  if (this.organizationId) url.searchParams.set("org", this.organizationId);
4997
+ const ws = this.sentWorkspaceId();
4998
+ if (ws) url.searchParams.set("workspace_id", ws);
4862
4999
  try {
4863
5000
  this.eventSource = new EventSource(url.toString());
4864
5001
  this.eventSource.onopen = () => {
@@ -4869,6 +5006,11 @@ class AegisChat {
4869
5006
  void this.refreshHistory();
4870
5007
  });
4871
5008
  this.eventSource.onerror = () => {
5009
+ if (this.eventSource && this.eventSource.readyState === 2) {
5010
+ this.disconnectSSE();
5011
+ void this.recoverAuth();
5012
+ return;
5013
+ }
4872
5014
  this.startPolling();
4873
5015
  };
4874
5016
  } catch (err) {
@@ -4884,6 +5026,7 @@ class AegisChat {
4884
5026
  }
4885
5027
  startPolling() {
4886
5028
  if (!this.open) return;
5029
+ if (this.authStopped) return;
4887
5030
  if (this.pollTimer) return;
4888
5031
  this.pollTimer = setInterval(() => {
4889
5032
  void this.refreshHistory();
@@ -4895,7 +5038,7 @@ class AegisChat {
4895
5038
  this.pollTimer = void 0;
4896
5039
  }
4897
5040
  }
4898
- async refreshHistory() {
5041
+ async refreshHistory(retry = true) {
4899
5042
  if (!this.contactId) return;
4900
5043
  if (!this.sseTicket) return;
4901
5044
  try {
@@ -4904,15 +5047,31 @@ class AegisChat {
4904
5047
  url.searchParams.set("ticket", this.sseTicket);
4905
5048
  url.searchParams.set("channel", this.channel);
4906
5049
  url.searchParams.set("limit", "50");
5050
+ const ws = this.sentWorkspaceId();
5051
+ if (ws) url.searchParams.set("workspace_id", ws);
4907
5052
  const res = await fetch(url.toString(), {
4908
5053
  method: "GET",
4909
5054
  headers: { "X-Aegis-Write-Key": this.writeKey }
4910
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
+ }
4911
5068
  if (!res.ok) return;
4912
5069
  const data = await res.json();
4913
- let appended = false;
4914
5070
  for (const msg of data.messages || []) {
4915
- if (this.renderedIds.has(msg.id)) continue;
5071
+ if (this.renderedIds.has(msg.id)) {
5072
+ this.redrawIfInteractiveChanged(msg);
5073
+ continue;
5074
+ }
4916
5075
  if (msg.sender === "customer") {
4917
5076
  const idx = this.pendingEcho.indexOf(msg.content || "");
4918
5077
  if (idx !== -1) {
@@ -4923,10 +5082,8 @@ class AegisChat {
4923
5082
  }
4924
5083
  if (msg.sender === "assistant") this.hideTyping();
4925
5084
  this.appendBubble(msg);
4926
- appended = true;
4927
5085
  if (msg.sender === "assistant" && !this.open) this.bumpUnread();
4928
5086
  }
4929
- if (appended) this.scrollToBottom();
4930
5087
  } catch (err) {
4931
5088
  this.log("history fetch error", err);
4932
5089
  }
@@ -5077,6 +5234,37 @@ class AegisChat {
5077
5234
  appendBubble(msg) {
5078
5235
  if (!this.thread) return;
5079
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) {
5080
5268
  const row = document.createElement("div");
5081
5269
  row.className = `aegis-chat-msg aegis-chat-msg--${msg.sender}`;
5082
5270
  if (msg.media_url) {
@@ -5102,26 +5290,33 @@ class AegisChat {
5102
5290
  if (msg.content) {
5103
5291
  const bubble = document.createElement("div");
5104
5292
  bubble.className = "aegis-chat-bubbletext";
5105
- bubble.textContent = msg.content;
5293
+ if (msg.sender === "customer") bubble.textContent = msg.content;
5294
+ else appendWaMarkup(bubble, msg.content);
5106
5295
  row.appendChild(bubble);
5107
5296
  }
5108
5297
  if (msg.interactive && Array.isArray(msg.interactive)) {
5109
5298
  for (const inter of msg.interactive) {
5110
- const el2 = this.renderInteractive(inter);
5299
+ const el2 = this.renderInteractive(inter, msg.content || "");
5111
5300
  if (el2) row.appendChild(el2);
5112
5301
  }
5113
5302
  }
5114
- this.thread.appendChild(row);
5115
- this.scrollToBottom();
5303
+ return row;
5116
5304
  }
5117
5305
  /** Render one interactive message: the `web`-format product_carousel, or the
5118
- * WhatsApp-shape reply_button / list the store picker stores. */
5119
- 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 = "") {
5120
5309
  const type = inter == null ? void 0 : inter.type;
5121
5310
  const waShape = inter == null ? void 0 : inter.interactive_type;
5122
- if (type === "interactive" && waShape === "reply_button") return this.renderReplyButtons(inter);
5123
- if (type === "interactive" && waShape === "list") return this.renderListRows(inter);
5124
- 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);
5125
5320
  const products = inter.products || [];
5126
5321
  if (!products.length) return null;
5127
5322
  const carousel = document.createElement("div");
@@ -5164,6 +5359,99 @@ class AegisChat {
5164
5359
  }
5165
5360
  return carousel;
5166
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
+ }
5167
5455
  /** WhatsApp-shape `reply_button` (store picker: Nearest / Other stores / Change
5168
5456
  * store). The body is already the bubble text, so only the buttons render. A
5169
5457
  * tap sends the button title (the same text WhatsApp's inbound hands the bot)
@@ -5244,6 +5532,62 @@ class AegisChat {
5244
5532
  scrollToBottom() {
5245
5533
  if (this.thread) this.thread.scrollTop = this.thread.scrollHeight;
5246
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
+ }
5247
5591
  readAnonId() {
5248
5592
  if (typeof document === "undefined") return void 0;
5249
5593
  try {
@@ -5277,38 +5621,91 @@ class AegisChat {
5277
5621
  }
5278
5622
  if (this.sessionResumed) return;
5279
5623
  this.sessionResumed = true;
5280
- 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;
5281
5631
  try {
5282
- const res = await fetch(`${this.apiHost}/v1/chat/session`, {
5632
+ const post = () => fetch(`${this.apiHost}/v1/chat/session`, {
5283
5633
  method: "POST",
5284
5634
  headers: { "Content-Type": "application/json", "X-Aegis-Write-Key": this.writeKey },
5285
5635
  body: JSON.stringify({
5636
+ workspace_id: this.sentWorkspaceId(),
5286
5637
  anonymous_id: this.anonymousId,
5287
5638
  contact_id: this.contactId,
5288
5639
  channel: this.channel
5289
5640
  })
5290
5641
  });
5291
- if (!res.ok) return;
5642
+ let res = await post();
5643
+ if (await this.isWorkspaceMismatch(res)) res = await post();
5644
+ if (!res.ok) return false;
5292
5645
  const data = await res.json();
5293
- if (!data.contact_id || !data.sse_ticket) return;
5646
+ if (!data.contact_id || !data.sse_ticket) return false;
5294
5647
  this.contactId = data.contact_id;
5295
5648
  this.sseTicket = data.sse_ticket;
5296
5649
  this.persistContactId(data.contact_id);
5297
- await this.refreshHistory();
5650
+ if (refresh) await this.refreshHistory();
5298
5651
  if (this.open) this.connectSSE(data.sse_ticket);
5652
+ return true;
5299
5653
  } catch (err) {
5300
- this.log("resume session failed", err);
5654
+ this.log("session mint failed", err);
5655
+ return false;
5301
5656
  }
5302
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;
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);
5698
+ }
5303
5699
  // ── Typing indicator ───────────────────────────────────────────────────────
5304
5700
  showTyping() {
5305
5701
  if (!this.thread || this.typingEl) return;
5702
+ const follow = this.isNearBottom();
5306
5703
  const row = document.createElement("div");
5307
5704
  row.className = "aegis-chat-msg aegis-chat-msg--assistant aegis-chat-typing";
5308
5705
  row.innerHTML = '<div class="aegis-chat-bubbletext aegis-chat-typingdots"><span></span><span></span><span></span></div>';
5309
5706
  this.thread.appendChild(row);
5310
5707
  this.typingEl = row;
5311
- this.scrollToBottom();
5708
+ if (follow) this.scrollToBottom();
5312
5709
  }
5313
5710
  hideTyping() {
5314
5711
  if (this.typingEl) {
@@ -5371,11 +5768,11 @@ const CHAT_CSS = `
5371
5768
  .aegis-chat-panel--open{display:flex}
5372
5769
  /* Header + customer bubbles use the "fill" surface — accent solid by default, or
5373
5770
  a soft tint when surfaceStyle:'tinted' sets --aegis-chat-fill/-fg on the root. */
5374
- .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)}
5375
5772
  .aegis-chat-title{font-weight:600;font-size:15px}
5376
5773
  .aegis-chat-close{background:transparent;border:none;color:var(--aegis-chat-fill-fg,#fff);font-size:16px;cursor:pointer;opacity:.85}
5377
5774
  .aegis-chat-close:hover{opacity:1}
5378
- .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}
5379
5776
  .aegis-chat-msg{display:flex;flex-direction:column;max-width:85%}
5380
5777
  .aegis-chat-msg--customer{align-self:flex-end;align-items:flex-end}
5381
5778
  .aegis-chat-msg--assistant,.aegis-chat-msg--system{align-self:flex-start;align-items:flex-start}
@@ -5403,13 +5800,20 @@ const CHAT_CSS = `
5403
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}
5404
5801
  .aegis-chat-card-price{font-size:13px;font-weight:600;color:var(--aegis-chat-accent,#4169e1)}
5405
5802
  .aegis-chat-card--more{align-items:center;justify-content:center;font-weight:600;color:var(--aegis-chat-accent,#4169e1)}
5406
- .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}
5407
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}
5408
5805
  .aegis-chat-input:focus{border-color:var(--aegis-chat-accent,#4169e1)}
5409
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}
5410
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}
5411
5808
  .aegis-chat-attach:hover{background:#f1f5f9;color:var(--aegis-chat-accent,#4169e1)}
5412
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}
5413
5817
  .aegis-chat-media-img{max-width:200px;max-height:200px;border-radius:12px;object-fit:cover;cursor:pointer;display:block}
5414
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}
5415
5819
  .aegis-chat-msg--customer .aegis-chat-media-file{background:rgba(255,255,255,.18);border-color:transparent;color:#fff}
@@ -5420,6 +5824,9 @@ const CHAT_CSS = `
5420
5824
  /* Full-page chat on mobile — the open panel covers the whole viewport (incl.
5421
5825
  the bottom nav) like a native chat screen, instead of a floating card. */
5422
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)}
5423
5830
  .aegis-chat-tip{max-width:200px}
5424
5831
  }
5425
5832
  `;
@@ -6007,6 +6414,8 @@ function renderActiveWebChat(ctx, creds) {
6007
6414
  writeKey: creds.writeKey,
6008
6415
  apiHost: creds.apiHost,
6009
6416
  contactId: creds.contactId,
6417
+ // The brand this runtime is scoped to; chat history is per brand.
6418
+ workspaceId: ctx.workspaceId,
6010
6419
  channel: creds.channel ?? "web",
6011
6420
  title: str(ic.chat_title),
6012
6421
  greeting: str(ic.chat_greeting),
@@ -7318,6 +7727,14 @@ function productIdentitiesFor(campaign) {
7318
7727
  productIdentityCache.set(cards, encoded);
7319
7728
  return encoded || void 0;
7320
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
+ }
7321
7738
  const _AegisInAppManager = class _AegisInAppManager {
7322
7739
  constructor(config) {
7323
7740
  this.productUrl = productPath;
@@ -8198,7 +8615,7 @@ const _AegisInAppManager = class _AegisInAppManager {
8198
8615
  this.slotTimers.delete(slot);
8199
8616
  }
8200
8617
  slot.querySelectorAll(
8201
- ":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]"
8202
8619
  ).forEach((n) => n.remove());
8203
8620
  }
8204
8621
  // Re-fill slots that mount after a poll (SPA route changes). Observes the DOM
@@ -8362,14 +8779,26 @@ const _AegisInAppManager = class _AegisInAppManager {
8362
8779
  * while off-screen; only the visibility toggles every `rotateMs`. The impression
8363
8780
  * is deferred at render and fired per campaign on FIRST visibility, so hidden
8364
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"`.
8365
8791
  */
8366
8792
  renderRotatingSlot(slot, campaigns, rotateMs, flush = false) {
8367
8793
  const panes = [];
8368
8794
  for (const c of campaigns) {
8369
8795
  const pane = document.createElement("div");
8370
8796
  pane.setAttribute("data-aegis-rotate-pane", c.id);
8371
- pane.style.display = "none";
8797
+ pane.style.gridArea = "1 / 1";
8798
+ pane.style.minWidth = "0";
8799
+ pane.style.alignSelf = "center";
8372
8800
  slot.appendChild(pane);
8801
+ setPaneActive(pane, false);
8373
8802
  this.renderCampaignIntoSlot(c, pane, { deferImpression: true });
8374
8803
  if (pane.childElementCount > 0) {
8375
8804
  if (flush) this._flattenSlotCard(pane);
@@ -8377,6 +8806,17 @@ const _AegisInAppManager = class _AegisInAppManager {
8377
8806
  } else pane.remove();
8378
8807
  }
8379
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
+ }
8380
8820
  const impressed = /* @__PURE__ */ new Set();
8381
8821
  const markVisible = (c) => {
8382
8822
  if (impressed.has(c.id)) return;
@@ -8399,8 +8839,11 @@ const _AegisInAppManager = class _AegisInAppManager {
8399
8839
  return false;
8400
8840
  };
8401
8841
  const darkDots = panes.length > 0 && panes.every((p) => isDarkSurface(p.campaign));
8402
- const dotInactive = darkDots ? "rgba(255,255,255,0.4)" : "rgba(15,23,42,0.2)";
8403
- 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;
8404
8847
  const dots = [];
8405
8848
  if (panes.length > 1) {
8406
8849
  const bar = document.createElement("div");
@@ -8421,7 +8864,8 @@ const _AegisInAppManager = class _AegisInAppManager {
8421
8864
  dots.push(dot);
8422
8865
  bar.appendChild(dot);
8423
8866
  });
8424
- slot.appendChild(bar);
8867
+ bar.style.gridArea = "2 / 1";
8868
+ stack.appendChild(bar);
8425
8869
  }
8426
8870
  const paintDots = () => {
8427
8871
  dots.forEach((d, i) => {
@@ -8440,9 +8884,9 @@ const _AegisInAppManager = class _AegisInAppManager {
8440
8884
  return t;
8441
8885
  };
8442
8886
  function show(i, fromClick = false) {
8443
- panes[idx].el.style.display = "none";
8887
+ setPaneActive(panes[idx].el, false);
8444
8888
  idx = (i % panes.length + panes.length) % panes.length;
8445
- panes[idx].el.style.display = "";
8889
+ setPaneActive(panes[idx].el, true);
8446
8890
  markVisible(panes[idx].campaign);
8447
8891
  paintDots();
8448
8892
  if (fromClick && timer) {
@@ -8450,7 +8894,7 @@ const _AegisInAppManager = class _AegisInAppManager {
8450
8894
  timer = start();
8451
8895
  }
8452
8896
  }
8453
- panes[0].el.style.display = "";
8897
+ setPaneActive(panes[0].el, true);
8454
8898
  markVisible(panes[0].campaign);
8455
8899
  paintDots();
8456
8900
  if (panes.length === 1) return;
@@ -13154,18 +13598,11 @@ const _AegisInAppManager = class _AegisInAppManager {
13154
13598
  document.head.appendChild(style);
13155
13599
  }
13156
13600
  sanitizeUrl(url) {
13157
- if (typeof url !== "string" || url.trim() === "") return null;
13158
- try {
13159
- const parsedUrl = new URL(url, window.location.origin);
13160
- if (parsedUrl.protocol === "javascript:" || parsedUrl.protocol === "data:") {
13161
- this.log(`Blocked unsafe URL: ${url}`, "error");
13162
- return null;
13163
- }
13164
- return parsedUrl.href;
13165
- } catch (error) {
13166
- this.log(`Invalid URL: ${url}`, "error");
13167
- 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");
13168
13604
  }
13605
+ return safe;
13169
13606
  }
13170
13607
  sanitizeColor(color) {
13171
13608
  if (/^#[0-9A-Fa-f]{3,6}$/.test(color)) {
@@ -16033,11 +16470,11 @@ const _AegisMessageRuntime = class _AegisMessageRuntime {
16033
16470
  // updateContext). The renderer cart reader + the cart_value signal are DERIVED
16034
16471
  // from it; there is no parallel cart/context store on the runtime.
16035
16472
  constructor(config) {
16036
- var _a;
16473
+ var _a, _b, _c;
16037
16474
  this.initialized = false;
16038
16475
  this.armedInAppTriggers = /* @__PURE__ */ new Set();
16039
16476
  {
16040
- const v = "1.46.1";
16477
+ const v = "1.46.2";
16041
16478
  try {
16042
16479
  globalThis.__AEGIS_SDK_VERSION__ = v;
16043
16480
  } catch {
@@ -16135,9 +16572,12 @@ const _AegisMessageRuntime = class _AegisMessageRuntime {
16135
16572
  organizationId: config.organizationId,
16136
16573
  contactId: config.contactId,
16137
16574
  debugMode: config.debugMode,
16138
- ...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))
16139
16579
  });
16140
- 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);
16141
16581
  armBehaviouralTriggers(
16142
16582
  triggerEngine,
16143
16583
  proactive,