@saar-ai/web-widget 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -462,8 +462,8 @@ function createScrollRecede(options) {
462
462
  enabled = next;
463
463
  if (next) anchor = last;
464
464
  },
465
- markProgrammatic() {
466
- programmaticUntil = Date.now() + PROGRAMMATIC_WINDOW_MS;
465
+ markProgrammatic(ms) {
466
+ programmaticUntil = Date.now() + (ms ?? PROGRAMMATIC_WINDOW_MS);
467
467
  if (timer !== void 0) {
468
468
  clearTimeout(timer);
469
469
  timer = void 0;
@@ -1620,6 +1620,20 @@ var SWAP_EASING = "cubic-bezier(0.2, 0, 0, 1)";
1620
1620
  /** §7.2 — the waveform's per-frame smoothing. */
1621
1621
  var LEVEL_LERP = .25;
1622
1622
  /**
1623
+ * §5.3/§5.5's concierge-scroll exception — how long a flagged scroll stays
1624
+ * ours.
1625
+ *
1626
+ * Longer than `recede.ts`'s own default window, deliberately: that one is
1627
+ * sized for the few frames a bridge `navigate` emits before the document goes
1628
+ * away, and a `spotlight` is a SMOOTH scroll across an arbitrary distance —
1629
+ * the length of a collection page, on a slow phone. The cost of being generous
1630
+ * is asymmetric and that is why it is generous: too long and the dock ignores
1631
+ * one deliberate shopper scroll a second after the concierge acted; too short
1632
+ * and it recedes and ducks in the middle of its own gesture, which is the
1633
+ * failure the exception exists for.
1634
+ */
1635
+ var CONCIERGE_SCROLL_WINDOW_MS = 1200;
1636
+ /**
1623
1637
  * `prefers-reduced-motion`, as a subscription rather than a one-shot read.
1624
1638
  *
1625
1639
  * A shopper can turn it on mid-session (iOS has it in Control Center), and a
@@ -3542,7 +3556,7 @@ var DEFAULT_LAYOUT = {
3542
3556
  };
3543
3557
  var INTERRUPT_SEEN_STORAGE_KEY = "wgt_dock_interrupt_seen";
3544
3558
  function Dock(props) {
3545
- const { identity, color = DEFAULT_COLOR, type = DEFAULT_TYPE, layout = DEFAULT_LAYOUT, copy = {}, direction = "ltr", locale = "en", messages = defaultWidgetMessages, voice, escalated = false, offline = false, status, notice, statusKind, operatorLine, reconnecting = false, roomDropped = false, partialTranscript, preamble, clause, channel = "text", shelf, transcript, latestExchange, exchangeCount, sheetExtra, followKey, revealSheet = false, showPrice = true, cardImageAspect = DEFAULT_CARD_ASPECT, bottomOffset = "auto", curationHref, productHref, navigate, draft, onDraftChange, onSubmit, composerDisabled = false, onAttach, attachSlot, attachBusy, proactive, pageKey, onEndCall, skinStyle, skin, preview = false, announcement, attribution, initialDraft, initialSelection, initialFocus, initialMinimised, insets, hold, audio, onReady } = props;
3559
+ const { identity, color = DEFAULT_COLOR, type = DEFAULT_TYPE, layout = DEFAULT_LAYOUT, copy = {}, direction = "ltr", locale = "en", messages = defaultWidgetMessages, voice, escalated = false, offline = false, status, notice, statusKind, operatorLine, reconnecting = false, roomDropped = false, partialTranscript, preamble, clause, channel = "text", shelf, transcript, latestExchange, exchangeCount, sheetExtra, followKey, revealSheet = false, showPrice = true, cardImageAspect = DEFAULT_CARD_ASPECT, bottomOffset = "auto", curationHref, productHref, navigate, draft, onDraftChange, onSubmit, composerDisabled = false, onAttach, attachSlot, attachBusy, proactive, pageKey, conciergeScrollRef, onEndCall, skinStyle, skin, preview = false, announcement, attribution, initialDraft, initialSelection, initialFocus, initialMinimised, insets, hold, audio, onReady } = props;
3546
3560
  const scopeId = useId().replace(/[^a-zA-Z0-9_-]/g, "");
3547
3561
  const rootRef = useRef(null);
3548
3562
  const rowRef = useRef(null);
@@ -4068,6 +4082,10 @@ function Dock(props) {
4068
4082
  anchor = offset;
4069
4083
  return;
4070
4084
  }
4085
+ if (Date.now() < conciergeScrollUntilRef.current) {
4086
+ anchor = offset;
4087
+ return;
4088
+ }
4071
4089
  if (Math.abs(offset - anchor) <= 24) return;
4072
4090
  anchor = offset;
4073
4091
  duckRef.current();
@@ -4104,6 +4122,32 @@ function Dock(props) {
4104
4122
  speaking,
4105
4123
  ownScroller
4106
4124
  ]);
4125
+ /**
4126
+ * Until when the page's own scroll is the CONCIERGE's, not the shopper's —
4127
+ * see {@link DockProps.conciergeScrollRef}. A timestamp rather than a
4128
+ * boolean so it lapses on its own: a `spotlight` whose smooth scroll never
4129
+ * arrives (the card was removed, the host cancelled it) must not deafen the
4130
+ * dock to the shopper for the rest of the session.
4131
+ */
4132
+ const conciergeScrollUntilRef = useRef(0);
4133
+ /**
4134
+ * Publish the flag-raiser. Both halves of the exception are raised together
4135
+ * and by the SAME call — §5.5's duck guard (this component's own scroll
4136
+ * listener) and §5.3's recede (`cdn/recede.ts`, which keeps its own window)
4137
+ * — because a spotlight that ducked the sheet but not the row, or the other
4138
+ * way round, is half a bug rather than none.
4139
+ */
4140
+ useEffect(() => {
4141
+ const ref = conciergeScrollRef;
4142
+ if (!ref) return;
4143
+ ref.current = (ms = CONCIERGE_SCROLL_WINDOW_MS) => {
4144
+ conciergeScrollUntilRef.current = ms > 0 ? Date.now() + ms : 0;
4145
+ recedeRef.current?.markProgrammatic(ms);
4146
+ };
4147
+ return () => {
4148
+ ref.current = null;
4149
+ };
4150
+ }, [conciergeScrollRef]);
4107
4151
  const firstPage = useRef(true);
4108
4152
  useEffect(() => {
4109
4153
  if (firstPage.current) {
@@ -6096,14 +6140,319 @@ function VoiceWidget({ state, turns, onToggleMic, onEndCall, callPhase = "idle",
6096
6140
  exchangeCount: exchangeCount(speakers)
6097
6141
  });
6098
6142
  }
6099
- new Set([
6143
+ //#endregion
6144
+ //#region ../widget-bridge/dist/index.js
6145
+ /**
6146
+ * The subset of {@link VISITOR_EVENT_KIND_NAMES} that is BEHAVIOURAL tracking
6147
+ * — a record of what a shopper looked at or did while merely browsing — and
6148
+ * therefore requires consent before it ships. Single source of truth for
6149
+ * BOTH sides of the wire: `apps/api/src/widget/widget-chat.service.ts`'s
6150
+ * `CONSENT_REQUIRED_WIDGET_EVENT_KINDS` imports this directly (replacing a
6151
+ * hand-duplicated literal that had drifted from `packages/widget-bridge`'s
6152
+ * own client-side gate — the client was gating everything except
6153
+ * `checkout.handoff`, which silently dropped `session.started`/
6154
+ * `session.ended` forever since they were never queued in the first place),
6155
+ * and `packages/widget-bridge`'s `VisitorEventCollector` imports it too (via
6156
+ * the zod-free `/constants` subpath, same as every other constant here).
6157
+ *
6158
+ * `checkout.handoff` is deliberately EXCLUDED — it records a transaction the
6159
+ * shopper themselves just initiated, not a browsing observation (GDPR Art.
6160
+ * 6(1)(b) contract necessity), so it ships regardless of consent on both
6161
+ * sides. `session.started`/`session.ended`, `scroll.depth`, `exit.intent`
6162
+ * and `search.performed` are also excluded: a session's start/end and a
6163
+ * scroll/exit-intent signal carry no identifying browsing content on their
6164
+ * own, and a shopper's own search text is the one allowlisted content field
6165
+ * in the registry (`payloads.ts`) — none of the five is the kind of
6166
+ * behavioural profiling a consent banner is asking permission for. See
6167
+ * `widget-chat.service.ts`'s doc comment on `recordEvents` for the full
6168
+ * reasoning on the server side.
6169
+ */
6170
+ var CONSENT_REQUIRED_VISITOR_EVENT_KINDS$1 = [
6100
6171
  "page.viewed",
6101
6172
  "product.viewed",
6102
6173
  "collection.viewed",
6103
6174
  "cart.viewed",
6104
6175
  "cart.changed",
6105
6176
  "product.hovered"
6106
- ]);
6177
+ ];
6178
+ /** How long the ring stays on screen. Long enough to be seen, short enough not to become furniture. */
6179
+ var SPOTLIGHT_RING_MS = 2e3;
6180
+ /**
6181
+ * Above every storefront's own stacking context, below the widget's dock.
6182
+ * `2147483647` is the maximum, and taking it outright would put a decorative
6183
+ * ring above a merchant's cookie banner and their own modals.
6184
+ */
6185
+ var RING_Z_INDEX = 2147483e3;
6186
+ /** How far outside the card's own box the ring is drawn, so it reads as around the card rather than as a border on it. */
6187
+ var RING_INSET_PX = 4;
6188
+ /** The same defaults `page-tracker.ts` uses — one answer to "which element is a product card". */
6189
+ var DEFAULT_PRODUCT_CARD$1 = {
6190
+ selector: ".product-card, [data-product-id]",
6191
+ idFrom: "data-attr",
6192
+ idAttr: "data-product-id"
6193
+ };
6194
+ /**
6195
+ * CSS-escape a value that is about to be spliced into an attribute selector.
6196
+ *
6197
+ * These ids come from OUR server (a catalogue uuid, a parsed Shopify GID), not
6198
+ * from the page — but a selector built by concatenation is a selector
6199
+ * injection waiting for the day one of them contains a quote, and
6200
+ * `querySelector` throws on a malformed selector rather than returning null,
6201
+ * which would take a live call down over a highlight. `CSS.escape` where the
6202
+ * browser has it (every browser above this package's floor), a conservative
6203
+ * manual escape where it does not.
6204
+ */
6205
+ function escapeAttrValue(win, value) {
6206
+ const css = win.CSS;
6207
+ if (typeof css?.escape === "function") return css.escape(value);
6208
+ return value.replace(/["\\]/g, "\\$&");
6209
+ }
6210
+ /**
6211
+ * Does `href` contain `needle` (`/products/<handle>`) as a whole path SEGMENT
6212
+ * — followed by the end of the string, a `/` (a collection-scoped url
6213
+ * continues past it), a `?` or a `#`?
6214
+ *
6215
+ * Plain string scanning rather than a constructed `RegExp`, and that is not a
6216
+ * style choice: a regex built by concatenation from a catalogue field is a
6217
+ * ReDoS surface a security scanner is right to refuse, and this needs no
6218
+ * backtracking at all. Every occurrence is checked, because a url may name the
6219
+ * handle twice (`/collections/rug/products/rug`).
6220
+ */
6221
+ function endsHandleSegment(href, needle) {
6222
+ for (let at = href.indexOf(needle); at !== -1; at = href.indexOf(needle, at + 1)) {
6223
+ const after = href.charAt(at + needle.length);
6224
+ if (after === "" || after === "/" || after === "?" || after === "#") return true;
6225
+ }
6226
+ return false;
6227
+ }
6228
+ /**
6229
+ * Find the element for `target`, or `null`.
6230
+ *
6231
+ * The ladder, in order of how reliably a storefront actually carries each:
6232
+ *
6233
+ * 1. **The id attribute** the site profile names (`data-product-id` by
6234
+ * default) — tried with the PLATFORM id first, because that is what a
6235
+ * theme emits, then with our internal uuid, because a host that built its
6236
+ * grid from our catalogue would emit that one instead.
6237
+ * 2. **A PDP link** — `a[href*="/products/<handle>"]`, then the nearest
6238
+ * enclosing card. A link is what exists on a theme that carries no id
6239
+ * attribute at all, and the enclosing card is what the shopper sees as
6240
+ * "the product", so the ring goes round the card and not round the anchor.
6241
+ *
6242
+ * Never throws: a malformed profile selector, a document mid-teardown, an
6243
+ * element without `closest` — all answer `null`, and a highlight that did not
6244
+ * happen is reported honestly rather than crashing a merchant's page.
6245
+ */
6246
+ function findProductCard(win, doc, target, profile) {
6247
+ const config = profile?.productCard ?? DEFAULT_PRODUCT_CARD$1;
6248
+ const idAttr = config.idAttr ?? DEFAULT_PRODUCT_CARD$1.idAttr ?? "data-product-id";
6249
+ try {
6250
+ for (const id of [target.platformProductId, target.productId]) {
6251
+ if (!id) continue;
6252
+ const byAttr = doc.querySelector(`[${idAttr}="${escapeAttrValue(win, id)}"]`);
6253
+ if (byAttr) return byAttr.closest(config.selector) ?? byAttr;
6254
+ }
6255
+ if (target.handle) {
6256
+ const escaped = escapeAttrValue(win, target.handle);
6257
+ const needle = `/products/${target.handle}`;
6258
+ for (const link of Array.from(doc.querySelectorAll(`a[href*="/products/${escaped}"]`))) {
6259
+ if (!endsHandleSegment(link.getAttribute("href") ?? "", needle)) continue;
6260
+ return link.closest(config.selector) ?? link;
6261
+ }
6262
+ }
6263
+ } catch {}
6264
+ return null;
6265
+ }
6266
+ /**
6267
+ * Scroll `target`'s card into view and ring it. `false` when the card is not
6268
+ * on this page — see the module doc comment on why that is ordinary.
6269
+ *
6270
+ * The scroll is `block: 'center'` so the card lands where a shopper looks, and
6271
+ * it is `behavior: 'smooth'` ONLY when the shopper has not asked for less
6272
+ * motion. `prefers-reduced-motion: reduce` gets an instant jump: the point of
6273
+ * the setting is that nothing slides, and this is the one scroll on the page
6274
+ * the shopper did not start themselves.
6275
+ *
6276
+ * The CALLER is responsible for telling the dock that this scroll was ours
6277
+ * (§5.3/§5.5 — otherwise the row recedes and the sheet ducks at the exact
6278
+ * moment the concierge acted). That flag lives in `@saar-ai/web-widget`'s
6279
+ * dock, which this package deliberately knows nothing about.
6280
+ */
6281
+ function spotlightProductCard(win, doc, target, options = {}) {
6282
+ const card = findProductCard(win, doc, target, options.siteProfile);
6283
+ if (!card) return false;
6284
+ try {
6285
+ let smooth = true;
6286
+ try {
6287
+ smooth = win.matchMedia?.("(prefers-reduced-motion: reduce)").matches !== true;
6288
+ } catch {}
6289
+ card.scrollIntoView({
6290
+ block: "center",
6291
+ behavior: smooth ? "smooth" : "auto"
6292
+ });
6293
+ drawRing(win, doc, card, options.setTimeoutImpl ?? win.setTimeout.bind(win));
6294
+ } catch {}
6295
+ return true;
6296
+ }
6297
+ /**
6298
+ * One FIXED element over the card's box, re-placed on scroll, removed on a
6299
+ * timer.
6300
+ *
6301
+ * The double `box-shadow` is what makes this legible on a storefront whose
6302
+ * colours we do not know: a dark inner ring reads on a light theme, the light
6303
+ * outer one reads on a dark theme, and together they read on a photograph.
6304
+ * Static — no transition, no keyframes, nothing for §7.1 rule 1 to object to.
6305
+ *
6306
+ * The element sits at the viewport origin and is moved by `transform` alone,
6307
+ * so tracking the card through the smooth scroll costs a compositor property
6308
+ * per event and never a `top`/`left` write. The listener is PASSIVE and
6309
+ * capturing (a card inside the merchant's own scroll container emits its
6310
+ * scroll there, not on `window`), and it is removed with the ring — a stray
6311
+ * listener outliving a two-second decoration would be our bytes running on a
6312
+ * merchant's page for the rest of the session.
6313
+ */
6314
+ function drawRing(win, doc, card, schedule) {
6315
+ const body = doc.body;
6316
+ if (!body) return;
6317
+ const ring = doc.createElement("div");
6318
+ ring.setAttribute("aria-hidden", "true");
6319
+ ring.setAttribute("data-concierge-spotlight", "");
6320
+ const px = (value) => `${Math.round(value)}px`;
6321
+ const place = () => {
6322
+ const rect = card.getBoundingClientRect();
6323
+ ring.style.width = px(rect.width + RING_INSET_PX * 2);
6324
+ ring.style.height = px(rect.height + RING_INSET_PX * 2);
6325
+ ring.style.transform = `translate(${px(rect.left - RING_INSET_PX)},${px(rect.top - RING_INSET_PX)})`;
6326
+ };
6327
+ ring.style.cssText = `position:fixed;top:0;left:0;border-radius:10px;pointer-events:none;z-index:${RING_Z_INDEX};box-shadow:0 0 0 2px rgba(17,17,17,.85),0 0 0 5px rgba(255,255,255,.9)`;
6328
+ place();
6329
+ body.appendChild(ring);
6330
+ const onMove = () => {
6331
+ try {
6332
+ place();
6333
+ } catch {}
6334
+ };
6335
+ const listen = (add) => {
6336
+ try {
6337
+ if (add) {
6338
+ win.addEventListener("scroll", onMove, {
6339
+ passive: true,
6340
+ capture: true
6341
+ });
6342
+ win.addEventListener("resize", onMove, { passive: true });
6343
+ } else {
6344
+ win.removeEventListener("scroll", onMove, { capture: true });
6345
+ win.removeEventListener("resize", onMove);
6346
+ }
6347
+ } catch {}
6348
+ };
6349
+ listen(true);
6350
+ schedule(() => {
6351
+ listen(false);
6352
+ try {
6353
+ ring.remove();
6354
+ } catch {}
6355
+ }, SPOTLIGHT_RING_MS);
6356
+ }
6357
+ /**
6358
+ * STOREFRONT PATHS — the two things every act event's destination has to be
6359
+ * rewritten for before a browser is sent to it.
6360
+ *
6361
+ * Both are facts about the SHOPPER'S storefront that the server cannot know,
6362
+ * which is why neither belongs in `apps/api`'s `act-destinations.ts`:
6363
+ *
6364
+ * 1. **The locale prefix.** Shopify Markets puts a locale/market code on the
6365
+ * front of every path — `/en-gb/collections/rugs`, `/fr-ca/cart`. The
6366
+ * catalogue holds handles, not markets, so a resolved path is always
6367
+ * spelt without one. Sending a shopper who is browsing `/en-gb/...` to a
6368
+ * bare `/collections/rugs` drops them out of their own market: a different
6369
+ * currency, a different language, and on some storefronts a redirect that
6370
+ * loses the path entirely. {@link storefrontLocalePrefix} reads the prefix
6371
+ * off the page they are actually on and {@link withStorefrontLocale} puts
6372
+ * it back.
6373
+ * 2. **The facet query.** A filter for a collection the shopper is NOT on
6374
+ * cannot go through `applyFilter` — that method narrows the CURRENT page
6375
+ * by construction — so the facets have to travel in the destination's own
6376
+ * query string instead. {@link withStorefrontFacets} builds it, and
6377
+ * `ShopifyBridge.applyFilter` uses the same function so the scheme exists
6378
+ * in one place.
6379
+ *
6380
+ * Pure string functions, no `window`, no DOM: everything here is testable
6381
+ * against a literal and is shared by the bridge and by `@saar-ai/web-widget`.
6382
+ */
6383
+ /**
6384
+ * Shopify's own facet query-param scheme — `filter.<key>=<value>`, one param
6385
+ * per value (repeated for a multi-select facet).
6386
+ *
6387
+ * The KEY is the exact suffix after `filter.` in Shopify's URL scheme
6388
+ * (`v.option.color`, `p.vendor`, `p.product_type`), which is what the
6389
+ * `apply_filter` tool emits and what `ShopifyBridge.applyFilter` documents
6390
+ * itself as taking. Neither this module nor that method invents a mapping.
6391
+ *
6392
+ * Exported because `ShopifyBridge` READS the same params back for the page
6393
+ * context it hands the model (`pageContextExtras`) — one reader, one writer,
6394
+ * one spelling of the convention.
6395
+ */
6396
+ var FILTER_PARAM_PREFIX = "filter.";
6397
+ /**
6398
+ * The leading locale/market segment of a storefront path, WITH its slash
6399
+ * (`/en-gb`), or `''` when there is none.
6400
+ *
6401
+ * `[a-z]{2}` language, optional `-[a-z]{2}` region — the same shape
6402
+ * `shopify-bridge.ts`'s own `LOCALE_PREFIX` matches, and deliberately no
6403
+ * wider: every storefront route this concierge can name (`/products`,
6404
+ * `/collections`, `/search`, `/cart`, `/pages`, `/policies`) is longer than
6405
+ * two characters, so a two-letter first segment on a storefront is a market
6406
+ * code and not a page.
6407
+ */
6408
+ function storefrontLocalePrefix(path) {
6409
+ const match = /^\/([a-z]{2}(?:-[a-z]{2})?)(?=\/|$)/i.exec(path);
6410
+ return match ? `/${match[1]}` : "";
6411
+ }
6412
+ /**
6413
+ * Put `prefix` (from {@link storefrontLocalePrefix}) on the front of a
6414
+ * resolved path — unless that path already carries one of its own.
6415
+ *
6416
+ * The "already carries one" case is real rather than defensive: `navigate`'s
6417
+ * `target: 'url'` accepts a locale-prefixed storefront path, so a model
6418
+ * echoing the URL it was shown produces `/en-gb/collections/rugs` and
6419
+ * prefixing it again would produce `/en-gb/en-gb/...`.
6420
+ */
6421
+ function withStorefrontLocale(prefix, path) {
6422
+ if (prefix === "" || storefrontLocalePrefix(path) !== "") return path;
6423
+ return `${prefix}${path}`;
6424
+ }
6425
+ /**
6426
+ * `path` with `filters` applied as Shopify's own facet query params, REPLACING
6427
+ * any `filter.*` params it already carried.
6428
+ *
6429
+ * Replacing rather than accumulating is the documented contract of
6430
+ * `apply_filter` ("applying a filter replaces the previous one rather than
6431
+ * adding to it") and of `ShopifyBridge.applyFilter`; anything else turns a
6432
+ * shopper's second thought into an intersection that matches nothing. Every
6433
+ * other query param on the path is kept: a collection url may legitimately
6434
+ * carry `?sort_by=`, and dropping it would undo a choice the shopper made.
6435
+ *
6436
+ * Never throws — a path this cannot parse comes back unchanged, which is a
6437
+ * destination without a filter rather than a navigation that did not happen.
6438
+ */
6439
+ function withStorefrontFacets(path, filters) {
6440
+ try {
6441
+ const hash = path.indexOf("#");
6442
+ const withoutHash = hash === -1 ? path : path.slice(0, hash);
6443
+ const fragment = hash === -1 ? "" : path.slice(hash);
6444
+ const split = withoutHash.indexOf("?");
6445
+ const base = split === -1 ? withoutHash : withoutHash.slice(0, split);
6446
+ const params = new URLSearchParams(split === -1 ? "" : withoutHash.slice(split + 1));
6447
+ for (const key of Array.from(params.keys())) if (key.startsWith("filter.")) params.delete(key);
6448
+ for (const [key, values] of Object.entries(filters)) for (const value of values) params.append(`${FILTER_PARAM_PREFIX}${key}`, value);
6449
+ const query = params.toString();
6450
+ return `${base}${query ? `?${query}` : ""}${fragment}`;
6451
+ } catch {
6452
+ return path;
6453
+ }
6454
+ }
6455
+ new Set(CONSENT_REQUIRED_VISITOR_EVENT_KINDS$1);
6107
6456
  /**
6108
6457
  * Append `embedKey` as a query param, preserving whatever query string `url`
6109
6458
  * already carries — a CORS preflight for `/widget/*` has neither the
@@ -6354,7 +6703,7 @@ var DEFAULT_PATTERNS = {
6354
6703
  search: ["/search"],
6355
6704
  cart: ["/cart"]
6356
6705
  };
6357
- var DEFAULT_SEARCH_QUERY_PARAMS$1 = [
6706
+ var DEFAULT_SEARCH_QUERY_PARAMS = [
6358
6707
  "q",
6359
6708
  "s",
6360
6709
  "search"
@@ -6382,7 +6731,7 @@ function detectFromUrlAndDom(doc, location, profile) {
6382
6731
  cart: profile?.cart ?? DEFAULT_PATTERNS.cart
6383
6732
  };
6384
6733
  const path = location.pathname;
6385
- const hasSearchQueryParam = DEFAULT_SEARCH_QUERY_PARAMS$1.some((p) => new URLSearchParams(location.search).has(p));
6734
+ const hasSearchQueryParam = DEFAULT_SEARCH_QUERY_PARAMS.some((p) => new URLSearchParams(location.search).has(p));
6386
6735
  if (matchesAny(path, patterns.cart)) return {
6387
6736
  pageKind: "cart",
6388
6737
  source: "heuristic"
@@ -6452,6 +6801,30 @@ var DESK_TYPING_INDICATOR_TTL_MS = 6e3;
6452
6801
  //#endregion
6453
6802
  //#region src/use-chat-session.ts
6454
6803
  /**
6804
+ * The RUNTIME twin of `@saar-ai/widget-protocol`'s `SameOriginPathSchema`,
6805
+ * kept as a bare regex because that module is zod-backed and `ui` is a
6806
+ * `forbidZod` CDN artefact (`tools/check-config.json`).
6807
+ *
6808
+ * Two copies of one predicate is a drift risk and is worth naming: the SERVER
6809
+ * is the boundary, this is defence in depth, and `act.ts`'s own doc comment
6810
+ * carries the reasoning for every character of it. Kept byte-identical
6811
+ * deliberately — a looser copy would be worse than no copy, because it would
6812
+ * read as a check.
6813
+ */
6814
+ var SAME_ORIGIN_PATH_RE = /^\/(?![/\\])[^\s\\]*$/;
6815
+ /**
6816
+ * Is `value` a root-relative, same-origin storefront path?
6817
+ *
6818
+ * Exported so `host-widget.tsx` re-checks at the POINT OF USE as well — the
6819
+ * two act events that carry a navigable field arrive on two different
6820
+ * transports (this hook's SSE stream, and `use-voice-session.ts`'s data
6821
+ * channel), and a check that lived only here would cover one of them. The
6822
+ * bytes are one regex either way.
6823
+ */
6824
+ function isSameOriginPath(value) {
6825
+ return typeof value === "string" && SAME_ORIGIN_PATH_RE.test(value);
6826
+ }
6827
+ /**
6455
6828
  * `''` = same-origin — every fetch/socket URL this hook builds is relative to
6456
6829
  * whatever origin the browser loaded the widget from (docs/WIDGET_EMBED_PLAN.md
6457
6830
  * §4 Phase 3, coupling (4)). `apps/web` overrides this to its own same-origin
@@ -6640,7 +7013,7 @@ function speakerFor(role) {
6640
7013
  return role === "user" ? "caller" : "agent";
6641
7014
  }
6642
7015
  function useChatSession(options) {
6643
- const { embedKey, attribution, apiBase = DEFAULT_API_BASE, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, idlePollIntervalMs = DEFAULT_IDLE_POLL_INTERVAL_MS, socketUrl, socketPath = DEFAULT_SOCKET_PATH, collector } = options;
7016
+ const { embedKey, attribution, apiBase = DEFAULT_API_BASE, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, idlePollIntervalMs = DEFAULT_IDLE_POLL_INTERVAL_MS, socketUrl, socketPath = DEFAULT_SOCKET_PATH, collector, hostRoutes } = options;
6644
7017
  const fetchImpl = options.fetchImpl ?? fetch;
6645
7018
  const socketFactory = options.socketImpl;
6646
7019
  const now = useMemo(() => options.now ?? (() => Date.now()), []);
@@ -6674,6 +7047,7 @@ function useChatSession(options) {
6674
7047
  * field's doc comment on `UseChatSessionResult`.
6675
7048
  */
6676
7049
  const [cartAdds, setCartAdds] = useState([]);
7050
+ const [actEvents, setActEvents] = useState([]);
6677
7051
  /**
6678
7052
  * The basket the caller last told us about — see
6679
7053
  * {@link UseChatSessionResult.setCart}. A ref because nothing renders from
@@ -7071,7 +7445,8 @@ function useChatSession(options) {
7071
7445
  embedKey,
7072
7446
  attribution,
7073
7447
  ...stored.visitorId ? { visitorId: stored.visitorId } : {},
7074
- ...stored.visitorProof ? { visitorProof: stored.visitorProof } : {}
7448
+ ...stored.visitorProof ? { visitorProof: stored.visitorProof } : {},
7449
+ ...hostRoutes !== void 0 ? { hostRoutes } : {}
7075
7450
  })
7076
7451
  });
7077
7452
  if (!res.ok) throw new Error(`Session boot failed (${res.status}).`);
@@ -7163,6 +7538,7 @@ function useChatSession(options) {
7163
7538
  collector,
7164
7539
  embedKey,
7165
7540
  fetchImpl,
7541
+ hostRoutes,
7166
7542
  now,
7167
7543
  poll,
7168
7544
  scheduleRefresh
@@ -7509,6 +7885,9 @@ function useChatSession(options) {
7509
7885
  onCartAddEvent: (evt) => {
7510
7886
  if (mountedRef.current) setCartAdds((prev) => [...prev, evt]);
7511
7887
  },
7888
+ onActEvent: (evt) => {
7889
+ if (mountedRef.current) setActEvents((prev) => [...prev, evt]);
7890
+ },
7512
7891
  onEscalated: () => {
7513
7892
  markHandoffToHuman();
7514
7893
  },
@@ -7551,19 +7930,30 @@ function useChatSession(options) {
7551
7930
  const setCart = useCallback((cart) => {
7552
7931
  cartRef.current = cart;
7553
7932
  }, []);
7554
- /** See {@link UseChatSessionResult.pushCart}. */
7555
- const pushCart = useCallback(async (cart) => {
7933
+ /**
7934
+ * The shape `pushCart` and `pushPageContext` share: a tokened POST of one
7935
+ * JSON body, with every failure reported as `false` and none of them ever
7936
+ * thrown at the shopper.
7937
+ *
7938
+ * Both are STATEMENTS INSIDE a conversation and never the thing that starts
7939
+ * one, so both refuse before there is a token — the same gate the
7940
+ * add-to-cart nudge applies. And both treat a 204 as a refusal rather than a
7941
+ * success: `POST /widget/context` answers one when the server's own consent
7942
+ * and tracking gates decline the push, and `Response.ok` is `true` for it.
7943
+ */
7944
+ const postSessionState = useCallback(async (path, body) => {
7556
7945
  const chatToken = chatTokenRef.current;
7557
7946
  if (chatToken === void 0) return false;
7558
7947
  try {
7559
- return (await fetchImpl(withEmbedKeyParam(`${apiBase}/cart`, embedKey), {
7948
+ const res = await fetchImpl(withEmbedKeyParam(`${apiBase}${path}`, embedKey), {
7560
7949
  method: "POST",
7561
7950
  headers: {
7562
7951
  "content-type": "application/json",
7563
7952
  authorization: `Bearer ${chatToken}`
7564
7953
  },
7565
- body: JSON.stringify({ cart })
7566
- })).ok;
7954
+ body: JSON.stringify(body)
7955
+ });
7956
+ return res.ok && res.status !== 204;
7567
7957
  } catch {
7568
7958
  return false;
7569
7959
  }
@@ -7572,6 +7962,10 @@ function useChatSession(options) {
7572
7962
  embedKey,
7573
7963
  fetchImpl
7574
7964
  ]);
7965
+ /** See {@link UseChatSessionResult.pushCart}. */
7966
+ const pushCart = useCallback(async (cart) => postSessionState("/cart", { cart }), [postSessionState]);
7967
+ /** See {@link UseChatSessionResult.pushPageContext}. */
7968
+ const pushPageContext = useCallback(async (context) => postSessionState("/context", { context }), [postSessionState]);
7575
7969
  const sendEvent = useCallback(async (events) => {
7576
7970
  const chatToken = chatTokenRef.current;
7577
7971
  if (chatToken === void 0 || events.length === 0) return false;
@@ -7901,8 +8295,10 @@ function useChatSession(options) {
7901
8295
  cartAdds,
7902
8296
  send,
7903
8297
  sendReport,
8298
+ actEvents,
7904
8299
  setCart,
7905
8300
  pushCart,
8301
+ pushPageContext,
7906
8302
  sendEvent,
7907
8303
  notifyTyping,
7908
8304
  checkout,
@@ -7916,7 +8312,7 @@ function useChatSession(options) {
7916
8312
  * promise and is trivially unit-testable with a synthetic `ReadableStream`.
7917
8313
  */
7918
8314
  async function streamReply(args) {
7919
- const { body, agentTurnId, setTurns, onCardsEvent, onCheckoutEvent, onCartAddEvent, onEscalated, onDone, onError, isMounted } = args;
8315
+ const { body, agentTurnId, setTurns, onCardsEvent, onCheckoutEvent, onCartAddEvent, onActEvent, onEscalated, onDone, onError, isMounted } = args;
7920
8316
  const reader = body.getReader();
7921
8317
  const decoder = new TextDecoder();
7922
8318
  const parser = new SseFrameParser();
@@ -8034,6 +8430,21 @@ async function streamReply(args) {
8034
8430
  onCartAddEvent({ item });
8035
8431
  break;
8036
8432
  }
8433
+ case "navigate": {
8434
+ const data = evt.data;
8435
+ if (!isSameOriginPath(data?.url)) break;
8436
+ onActEvent(evt.data);
8437
+ break;
8438
+ }
8439
+ case "filter": {
8440
+ const data = evt.data;
8441
+ if (data?.collectionUrl !== void 0 && !isSameOriginPath(data.collectionUrl)) break;
8442
+ onActEvent(evt.data);
8443
+ break;
8444
+ }
8445
+ case "spotlight":
8446
+ onActEvent(evt.data);
8447
+ break;
8037
8448
  case "escalated":
8038
8449
  onEscalated();
8039
8450
  break;
@@ -8059,7 +8470,7 @@ async function streamReply(args) {
8059
8470
  * cache makes a second `start()` after `stop()` free).
8060
8471
  */
8061
8472
  async function loadVoiceProtocol() {
8062
- const [telemetry, chat] = await Promise.all([import("./telemetry-BI_SEWTb.js"), import("./chat-tMKkYmTC.js")]);
8473
+ const [telemetry, chat] = await Promise.all([import("./telemetry-DQUulENJ.js"), import("./chat-DAgqVvIS.js")]);
8063
8474
  return {
8064
8475
  decodeTelemetry: telemetry.decodeTelemetry,
8065
8476
  encodeCallerText: telemetry.encodeCallerText,
@@ -8570,7 +8981,7 @@ function useVoiceSession(options = {}) {
8570
8981
  if (!message) return;
8571
8982
  if (message.type === "turn.latency") {
8572
8983
  setTurns((t) => [...t.filter((x) => x.turnId !== message.turnId), message].slice(-20));
8573
- record("turn_latency", `${message.overallMs ?? "—"}ms overall`);
8984
+ record("turn_latency", `${message.overallMs ?? "—"}ms overall` + (typeof message.firstActMs === "number" ? `, act ${message.firstActMs}ms` : ""));
8574
8985
  return;
8575
8986
  }
8576
8987
  if (message.type === "turn.cost") {
@@ -8723,6 +9134,23 @@ function useVoiceSession(options = {}) {
8723
9134
  reason
8724
9135
  }), [publishControl]);
8725
9136
  /**
9137
+ * §8.6's hint, sent DELIBERATELY rather than from `pagehide` — the
9138
+ * concierge's own `navigate` is about to move the page.
9139
+ *
9140
+ * `pagehide` already covers a shopper's click and a full-document
9141
+ * `location.assign`, and it still does. It does not cover the case this
9142
+ * exists for: a SOFT navigation (a `NextBridge` host, any bridge with a
9143
+ * router) fires no `pagehide` at all, so a concierge-driven move on a
9144
+ * headless storefront would look, at the transport layer, exactly like a
9145
+ * caller who said nothing for a while. Sending it explicitly means the
9146
+ * session gets its bounded hold either way — and on a hard navigation the
9147
+ * duplicate is free: the worker reads the hint as a flag, not a counter.
9148
+ *
9149
+ * Resolves `false` and sends nothing when there is no room, so a typed-only
9150
+ * panel calling this pays one function call.
9151
+ */
9152
+ const notifyNavigating = useCallback(async () => publishControl({ type: "navigating" }), [publishControl]);
9153
+ /**
8726
9154
  * §8.6 — `navigating`, sent from `pagehide` while a call is live.
8727
9155
  *
8728
9156
  * The caller's participant disconnects on EVERY click of a conventionally
@@ -8818,10 +9246,461 @@ function useVoiceSession(options = {}) {
8818
9246
  sendText,
8819
9247
  sendEouHint,
8820
9248
  sendResume,
8821
- interrupt
9249
+ interrupt,
9250
+ notifyNavigating
8822
9251
  };
8823
9252
  }
8824
9253
  //#endregion
9254
+ //#region ../widget-bridge/dist/page-context.js
9255
+ function clampId(value, max) {
9256
+ if (typeof value !== "string") return void 0;
9257
+ const trimmed = value.replace(/\s+/gu, " ").trim();
9258
+ if (trimmed === "") return void 0;
9259
+ return trimmed.slice(0, max);
9260
+ }
9261
+ /**
9262
+ * A pathname, or `undefined`.
9263
+ *
9264
+ * Deliberately NOT a URL parser. Every caller hands this `location.pathname`
9265
+ * (or an adapter's own classification of it), so the `new URL()` branch this
9266
+ * used to carry was defensive code for a caller that does not exist — and
9267
+ * this module is bundled into `ui.mjs`, which has a few hundred bytes of
9268
+ * headroom. What survives is the rule that actually matters: anything
9269
+ * carrying a `?`, a `#`, whitespace, or no leading `/` is REFUSED rather than
9270
+ * repaired, because a query string is where storefronts put session ids and
9271
+ * email addresses and this field must never carry one.
9272
+ */
9273
+ function clampPath(value) {
9274
+ if (typeof value !== "string") return void 0;
9275
+ const path = value.trim();
9276
+ if (!path.startsWith("/") || /[?#\s]/u.test(path)) return void 0;
9277
+ return path.slice(0, 512);
9278
+ }
9279
+ function clampFilters(filters) {
9280
+ if (!filters) return void 0;
9281
+ const out = {};
9282
+ for (const [rawKey, rawValue] of Object.entries(filters)) {
9283
+ if (Object.keys(out).length >= 8) break;
9284
+ const key = clampId(rawKey, 64);
9285
+ const value = clampId(rawValue, 64);
9286
+ if (key === void 0 || value === void 0) continue;
9287
+ out[key] = value;
9288
+ }
9289
+ return Object.keys(out).length > 0 ? out : void 0;
9290
+ }
9291
+ function byteLength(context) {
9292
+ return new TextEncoder().encode(JSON.stringify(context)).byteLength;
9293
+ }
9294
+ /**
9295
+ * Build a bounded, wire-legal `PageContext`, or `undefined` when there is not
9296
+ * even a path to report.
9297
+ *
9298
+ * ## Degrade, never fabricate — and never drop the whole thing
9299
+ *
9300
+ * Every optional field is omitted rather than defaulted: no `cartCount: 0` for
9301
+ * a host that does not report one (zero is a real answer, "the cart is
9302
+ * empty"), no handle substituted for a missing id. `pageType` and `path` are
9303
+ * the only things this needs, and a page that cannot supply a path supplies no
9304
+ * context at all.
9305
+ *
9306
+ * ## Trimming to the byte ceiling
9307
+ *
9308
+ * `PAGE_CONTEXT_MAX_BYTES` is a hard ceiling on both wires, and a payload over
9309
+ * it is dropped WHOLE by the decoder on the other side. Rather than let a
9310
+ * merchant with very long handles lose their context entirely, this trims in
9311
+ * increasing order of usefulness to the model: the facets go first, then the
9312
+ * search text and the ids together. The page type and the path always
9313
+ * survive, and they are together far below the ceiling by construction.
9314
+ *
9315
+ * @param draft the raw values, from whichever `HostBridge` resolved them
9316
+ */
9317
+ /**
9318
+ * The locale shape `PageContextSchema` accepts, mirrored here rather than
9319
+ * imported.
9320
+ *
9321
+ * This package deliberately does not depend on `@saar-ai/widget-protocol` —
9322
+ * zod would land in `core.mjs` — so the contract is written down on both
9323
+ * sides with a pointer between them, the same way the bridge's other
9324
+ * cross-package literals are. `page-context-contract.test.ts` in
9325
+ * `@saar-ai/web-widget` pins the two together.
9326
+ *
9327
+ * It is applied as a DROP rather than a repair, and that is the whole point.
9328
+ * `<html lang>` is whatever the merchant's theme wrote, and themes write
9329
+ * `EN`, `en_US` and `en-us` as readily as `en-US`. Passing one of those
9330
+ * through is not a cosmetic problem: the wire schema is strict, so the server
9331
+ * refuses the entire body with a 400 and the shopper loses their page context
9332
+ * because of one optional field. Dropping it costs a locale the model barely
9333
+ * uses and keeps the page. A platform adapter that knows the real locale
9334
+ * supplies it through `pageContextExtras()` and is unaffected — Shopify's
9335
+ * does, from `Shopify.locale`.
9336
+ *
9337
+ * Normalising the case instead was measured at ~115 bytes of `ui.mjs` against
9338
+ * 77 bytes of headroom, and buys only the generic fallback path on badly
9339
+ * written themes. Not worth the budget; revisit if `ui` ever has room.
9340
+ */
9341
+ var WIRE_LOCALE_PATTERN = /^[a-z]{2,3}(-[A-Za-z]{2,4})?(-[A-Z]{2}|-\d{3})?$/u;
9342
+ function buildPageContext(draft) {
9343
+ const path = clampPath(draft.path);
9344
+ if (path === void 0) return void 0;
9345
+ const capturedAt = new Date(draft.capturedAt ?? Date.now()).toISOString();
9346
+ const cartCount = typeof draft.cartCount === "number" && Number.isFinite(draft.cartCount) && draft.cartCount >= 0 ? Math.min(9999, Math.floor(draft.cartCount)) : void 0;
9347
+ let filters = clampFilters(draft.filters);
9348
+ let searchQuery = clampId(draft.searchQuery, 128);
9349
+ let productId = clampId(draft.productId, 128);
9350
+ let variantId = clampId(draft.variantId, 128);
9351
+ let collectionHandle = clampId(draft.collectionHandle, 128);
9352
+ const clampedLocale = clampId(draft.locale, 35);
9353
+ const locale = clampedLocale !== void 0 && WIRE_LOCALE_PATTERN.test(clampedLocale) ? clampedLocale : void 0;
9354
+ const assemble = () => ({
9355
+ pageType: draft.pageType,
9356
+ path,
9357
+ ...productId !== void 0 ? { productId } : {},
9358
+ ...variantId !== void 0 ? { variantId } : {},
9359
+ ...collectionHandle !== void 0 ? { collectionHandle } : {},
9360
+ ...filters !== void 0 ? { filters } : {},
9361
+ ...searchQuery !== void 0 ? { searchQuery } : {},
9362
+ ...cartCount !== void 0 ? { cartCount } : {},
9363
+ ...locale !== void 0 ? { locale } : {},
9364
+ capturedAt
9365
+ });
9366
+ let context = assemble();
9367
+ if (byteLength(context) > 2048) {
9368
+ filters = void 0;
9369
+ context = assemble();
9370
+ }
9371
+ if (byteLength(context) > 2048) {
9372
+ searchQuery = void 0;
9373
+ productId = void 0;
9374
+ variantId = void 0;
9375
+ collectionHandle = void 0;
9376
+ context = assemble();
9377
+ }
9378
+ return context;
9379
+ }
9380
+ /**
9381
+ * Are these two contexts the same PLACE?
9382
+ *
9383
+ * `capturedAt` is excluded deliberately — it moves on every capture and is
9384
+ * descriptive, never the thing that makes a context new. Used by
9385
+ * `PageContextTracker` to avoid re-pushing an identical context when a host's
9386
+ * router fires `onPageChange` twice for one navigation, which several
9387
+ * storefront themes do.
9388
+ *
9389
+ * Compares the JSON up to `capturedAt`, which {@link buildPageContext} always
9390
+ * emits LAST — cheaper than rebuilding both objects without it, on a module
9391
+ * that ships inside a budgeted bundle. A hand-written field-by-field compare
9392
+ * would be cheaper still and is exactly the thing that silently stops
9393
+ * comparing a field somebody adds later.
9394
+ *
9395
+ * @param a one context, or nothing
9396
+ * @param b the other, or nothing
9397
+ */
9398
+ function samePageContext(a, b) {
9399
+ if (a === void 0 || b === void 0) return a === b;
9400
+ return place(a) === place(b);
9401
+ }
9402
+ function place(context) {
9403
+ const json = JSON.stringify(context);
9404
+ return json.slice(0, json.lastIndexOf("\"capturedAt\""));
9405
+ }
9406
+ /**
9407
+ * The query-string parameter names a storefront's search box puts its text
9408
+ * in, in the order they are tried.
9409
+ *
9410
+ * ONE list, read by both callers: `PageTracker` builds `search.performed`
9411
+ * from it and `GenericBridge.pageContextExtras` builds the page context's
9412
+ * `searchQuery` from it. A second spelling would let the visitor timeline and
9413
+ * the model's prompt disagree about what the shopper searched for — and, on a
9414
+ * bundle with a few hundred bytes of headroom, a second copy of the loop is
9415
+ * not free either.
9416
+ */
9417
+ var SEARCH_QUERY_PARAMS = [
9418
+ "q",
9419
+ "s",
9420
+ "search"
9421
+ ];
9422
+ /**
9423
+ * The shopper's own search text out of a query string, or `undefined`.
9424
+ *
9425
+ * @param search `location.search`, with or without its leading `?`
9426
+ */
9427
+ function readSearchQueryParam(search) {
9428
+ try {
9429
+ const params = new URLSearchParams(search);
9430
+ for (const name of SEARCH_QUERY_PARAMS) {
9431
+ const value = params.get(name);
9432
+ if (value && value.trim()) return value.trim();
9433
+ }
9434
+ return;
9435
+ } catch {
9436
+ return;
9437
+ }
9438
+ }
9439
+ /** The real `location.search` and `<html lang>`, or nothing outside a browser. */
9440
+ function browserPageContextGlobals() {
9441
+ if (typeof window === "undefined") return {};
9442
+ return {
9443
+ search: window.location?.search ?? "",
9444
+ ...typeof document !== "undefined" && typeof document.documentElement?.lang === "string" ? { documentLang: document.documentElement.lang } : {}
9445
+ };
9446
+ }
9447
+ /**
9448
+ * `HostPageKind` → `PageContextType`.
9449
+ *
9450
+ * The one mapping that is not the identity is `'other'` at the site root,
9451
+ * which becomes `'home'`. The bridge's kind list never needed a name for the
9452
+ * front page because a home page is a `page.viewed` like any other; the model
9453
+ * does need one, because "they are on the front page" and "they are on some
9454
+ * page we could not classify" call for different opening sentences.
9455
+ *
9456
+ * @param kind the classified page kind
9457
+ * @param path the page's pathname
9458
+ */
9459
+ function pageContextTypeFor(kind, path) {
9460
+ if (kind === "other") return /^\/(?:[a-z]{2}(?:-[a-z]{2})?\/?)?$/iu.test(path) ? "home" : "other";
9461
+ return kind;
9462
+ }
9463
+ /**
9464
+ * Where the shopper is standing, as `PageContextSchema` wants it — or `null`
9465
+ * when there is no usable page to describe.
9466
+ *
9467
+ * Never throws: an adapter that explodes costs the concierge a grounded
9468
+ * phrase, never the merchant's page. Everything is CLAMPED rather than
9469
+ * rejected (`buildPageContext`), so a storefront with unusually long handles
9470
+ * loses a facet rather than its whole context.
9471
+ *
9472
+ * @param bridge the host adapter to ask
9473
+ */
9474
+ function currentPageContext(bridge, globals) {
9475
+ try {
9476
+ const page = bridge.currentPage();
9477
+ const { search, documentLang } = globals ?? browserPageContextGlobals();
9478
+ const extras = bridge.pageContextExtras?.() ?? {};
9479
+ return buildPageContext({
9480
+ pageType: pageContextTypeFor(page.kind, page.path),
9481
+ path: page.path,
9482
+ searchQuery: readSearchQueryParam(search ?? ""),
9483
+ locale: documentLang,
9484
+ ...page.kind === "product" ? { productId: page.entityId } : {},
9485
+ ...page.kind === "collection" ? { collectionHandle: page.handle ?? page.entityId } : {},
9486
+ ...extras
9487
+ }) ?? null;
9488
+ } catch {
9489
+ return null;
9490
+ }
9491
+ }
9492
+ /**
9493
+ * The default timer, declared here rather than imported from `coalescer.ts`.
9494
+ *
9495
+ * `realTimer` there is identical, and importing it would be the obvious
9496
+ * thing — but `coalescer.ts` also holds `ScrollDepthCoalescer`,
9497
+ * `ProductHoverTracker` and `PageViewDeduper`, none of which this module
9498
+ * uses, and this module is bundled into `ui.mjs` (which carries none of them
9499
+ * either) through the `@saar-ai/widget-bridge/page-context` entry. Two lines
9500
+ * of duplication against several hundred bytes on an artefact with under a
9501
+ * kilobyte of headroom. The TYPE is still imported, so the two cannot drift.
9502
+ */
9503
+ var defaultTimer = {
9504
+ setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
9505
+ clearTimeout: (handle) => globalThis.clearTimeout(handle)
9506
+ };
9507
+ /** The visitor-event kind whose gates this tracker borrows. See the class doc comment. */
9508
+ var GATED_AS = "page.viewed";
9509
+ var PageContextTracker = class {
9510
+ bridge;
9511
+ consent;
9512
+ trackingEnabled;
9513
+ send;
9514
+ timer;
9515
+ debounceMs;
9516
+ started = false;
9517
+ destroyed = false;
9518
+ unsubscribePageChange;
9519
+ pending;
9520
+ /** The last context that actually went out — see {@link samePageContext}. */
9521
+ lastSent;
9522
+ pageChangeListener = () => {
9523
+ try {
9524
+ this.schedule();
9525
+ } catch {}
9526
+ };
9527
+ constructor(options) {
9528
+ this.bridge = options.bridge;
9529
+ this.consent = options.consent;
9530
+ this.trackingEnabled = options.trackingEnabled ?? (() => true);
9531
+ this.send = options.send;
9532
+ this.timer = options.timer ?? defaultTimer;
9533
+ this.debounceMs = options.debounceMs ?? 250;
9534
+ }
9535
+ /**
9536
+ * Boot the tracker: capture the page the shopper opened on, then follow
9537
+ * every navigation.
9538
+ *
9539
+ * The FIRST capture is not debounced — it is the context the model needs
9540
+ * before the first turn, and a quarter-second of deliberate lateness on a
9541
+ * page that has only just loaded buys nothing. Every later capture is.
9542
+ *
9543
+ * Calling twice is a no-op. Never throws.
9544
+ */
9545
+ start() {
9546
+ try {
9547
+ if (this.started || this.destroyed) return;
9548
+ this.started = true;
9549
+ this.capture();
9550
+ this.unsubscribePageChange = this.bridge.onPageChange(this.pageChangeListener);
9551
+ } catch {}
9552
+ }
9553
+ destroy() {
9554
+ try {
9555
+ this.destroyed = true;
9556
+ this.unsubscribePageChange?.();
9557
+ if (this.pending !== void 0) this.timer.clearTimeout(this.pending);
9558
+ this.pending = void 0;
9559
+ } catch {}
9560
+ }
9561
+ /** `true` when both gates allow a push right now. Exposed for the caller's own diagnostics. */
9562
+ mayPush() {
9563
+ return this.consent.mayTrack(GATED_AS) && this.trackingEnabled();
9564
+ }
9565
+ schedule() {
9566
+ if (this.destroyed) return;
9567
+ if (this.pending !== void 0) this.timer.clearTimeout(this.pending);
9568
+ this.pending = this.timer.setTimeout(() => {
9569
+ this.pending = void 0;
9570
+ this.capture();
9571
+ }, this.debounceMs);
9572
+ }
9573
+ /**
9574
+ * The whole decision, in order: gates first, then the bridge.
9575
+ *
9576
+ * Gates BEFORE `currentPageContext()` is deliberate. Reading the page is
9577
+ * cheap but not free (a `querySelectorAll` on some adapters), and more to
9578
+ * the point a visitor who denied consent should have nothing about their
9579
+ * page read at all — not read, then discarded.
9580
+ */
9581
+ capture() {
9582
+ try {
9583
+ if (this.destroyed || !this.mayPush()) return;
9584
+ const context = currentPageContext(this.bridge) ?? void 0;
9585
+ if (context === void 0 || samePageContext(context, this.lastSent)) return;
9586
+ this.lastSent = context;
9587
+ const result = this.send(context);
9588
+ if (typeof result?.catch === "function") result.catch(() => {});
9589
+ } catch {}
9590
+ }
9591
+ };
9592
+ //#endregion
9593
+ //#region src/host-routes.ts
9594
+ /**
9595
+ * What to declare to the server on session boot, or `undefined` when this host
9596
+ * declares nothing (⇒ the field is omitted, and the server keeps its Shopify
9597
+ * assumption).
9598
+ *
9599
+ * `'url'` is never declared. That target exists so a model can name a
9600
+ * storefront path directly, and a host with a scheme of its own has no closed
9601
+ * route list the server could check such a path against — so on a declaring
9602
+ * host it is refused outright rather than allowed to become the one hole every
9603
+ * other narrowing here would leave.
9604
+ *
9605
+ * @param routes the resolvers, from {@link hostRouteResolvers}
9606
+ */
9607
+ function hostRouteTargets(routes) {
9608
+ if (!routes) return void 0;
9609
+ return [
9610
+ ...routes.product ? ["product"] : [],
9611
+ ...routes.collection ? ["collection"] : [],
9612
+ ...routes.search ? ["search"] : [],
9613
+ ...routes.cart ? ["cart"] : []
9614
+ ];
9615
+ }
9616
+ /** `/collections/rugs?filter.p.vendor=X#top` split into the three parts a rewrite needs. */
9617
+ function splitPath(path) {
9618
+ const withoutFragment = path.split("#")[0] ?? path;
9619
+ const split = withoutFragment.indexOf("?");
9620
+ return split === -1 ? {
9621
+ route: withoutFragment,
9622
+ query: ""
9623
+ } : {
9624
+ route: withoutFragment.slice(0, split),
9625
+ query: withoutFragment.slice(split + 1)
9626
+ };
9627
+ }
9628
+ /**
9629
+ * The handle in `/products/<handle>` or `/collections/<handle>`, or
9630
+ * `undefined`. Tolerates a trailing slash; rejects a deeper path, which is not
9631
+ * a route the server emits.
9632
+ *
9633
+ * The decode is GUARDED because it can genuinely throw and this module must
9634
+ * not: the server builds `/products/<handle>` from the merchant's own
9635
+ * catalogue handle without encoding it, and `SameOriginPathSchema` permits a
9636
+ * bare `%`, so a product handled `50%-off-rug` reaches here and
9637
+ * `decodeURIComponent` raises `URIError: URI malformed`. Nothing between this
9638
+ * and the act queue catches — the drain is `try`/`finally` with no `catch` —
9639
+ * so an unguarded throw would abandon every act still queued in that batch AND
9640
+ * skip the `navigate_failed` report, which is the one failure with no
9641
+ * correction path. `undefined` instead means "this is not a shape I can
9642
+ * rewrite", which the caller turns into a refusal the model can read.
9643
+ */
9644
+ function handleAfter(route, prefix) {
9645
+ if (!route.startsWith(prefix)) return void 0;
9646
+ const rest = route.slice(prefix.length).replace(/\/$/, "");
9647
+ if (rest === "" || rest.includes("/")) return void 0;
9648
+ try {
9649
+ return decodeURIComponent(rest);
9650
+ } catch {
9651
+ return;
9652
+ }
9653
+ }
9654
+ /**
9655
+ * Rewrite a server-resolved destination into the path THIS host serves.
9656
+ *
9657
+ * Three answers, and the difference between the last two is the whole point:
9658
+ *
9659
+ * - the path itself — this host declared nothing, so the server's Shopify
9660
+ * spelling is the right one and nothing is rewritten;
9661
+ * - a rewritten path — the host declared this target and the destination
9662
+ * matched its shape;
9663
+ * - `null` — this host cannot serve the destination, so NOTHING should
9664
+ * happen. The caller reports a failed navigate rather than assigning a URL
9665
+ * the host will 404 (or, on the console, bounce to a login page).
9666
+ *
9667
+ * `null` for a declared target whose path does not match the expected shape is
9668
+ * deliberate rather than a fallthrough to the raw path: a `product` target
9669
+ * carrying something that is not `/products/<handle>` is a destination this
9670
+ * function does not understand, and passing an un-rewritten Shopify path to a
9671
+ * host that just told us it has no Shopify routes is precisely the defect.
9672
+ *
9673
+ * @param url the server-resolved, root-relative destination
9674
+ * @param target which kind of destination the server said it was
9675
+ * @param routes this host's declared scheme, or `undefined`
9676
+ */
9677
+ function resolveHostRoutePath(url, target, routes) {
9678
+ if (!routes) return url;
9679
+ if (target === void 0 || target === "url") return null;
9680
+ if (target === "cart") return routes.cart ?? null;
9681
+ const { route, query } = splitPath(url);
9682
+ if (target === "search") {
9683
+ if (!routes.search) return null;
9684
+ let q;
9685
+ try {
9686
+ q = new URLSearchParams(query).get("q");
9687
+ } catch {
9688
+ q = null;
9689
+ }
9690
+ return q ? routes.search(q) : null;
9691
+ }
9692
+ const build = target === "product" ? routes.product : routes.collection;
9693
+ if (!build) return null;
9694
+ const handle = handleAfter(route, target === "product" ? "/products/" : "/collections/");
9695
+ if (handle === void 0) return null;
9696
+ const built = build(handle);
9697
+ if (query === "") return built;
9698
+ const hash = built.indexOf("#");
9699
+ const base = hash === -1 ? built : built.slice(0, hash);
9700
+ const fragment = hash === -1 ? "" : built.slice(hash);
9701
+ return `${base}${base.includes("?") ? "&" : "?"}${query}${fragment}`;
9702
+ }
9703
+ //#endregion
8825
9704
  //#region src/turn-order.ts
8826
9705
  /**
8827
9706
  * The widget's arrival clock. One instance per mounted widget (`useRef`), fed
@@ -8935,6 +9814,66 @@ var TurnOrderClock = class {
8935
9814
  //#endregion
8936
9815
  //#region src/host-widget.tsx
8937
9816
  /**
9817
+ * DOCK_SPEC §6 — how long the TYPED leg waits before performing a
9818
+ * concierge-driven `navigate` or `filter`.
9819
+ *
9820
+ * "Agent-initiated navigation is scheduled, not immediate. Finish the clause,
9821
+ * then navigate." On a call the realtime tier does the scheduling
9822
+ * (`apps/voice/src/session/scheduled-widget-events.ts` holds the event until
9823
+ * the utterance ends), so by the time the event reaches this widget the
9824
+ * concierge has stopped speaking. A typed reply has no utterance to finish and
9825
+ * the event arrives mid-stream — the shopper would read half a sentence and
9826
+ * watch the page take the rest of it away. One beat is what lets the sentence
9827
+ * land, and it is short on purpose: a navigation the shopper asked for should
9828
+ * feel like a click, not like a wait.
9829
+ */
9830
+ var NAVIGATE_BEAT_MS = 300;
9831
+ /**
9832
+ * How often `performAct` re-checks whether the typed turn has landed.
9833
+ *
9834
+ * Short enough that it disappears inside the 300 ms beat that follows it.
9835
+ */
9836
+ var ACT_HOLD_POLL_MS = 50;
9837
+ /**
9838
+ * The longest a page-moving act waits for a typed turn to finish streaming.
9839
+ *
9840
+ * A bound rather than a hope, for the same reason `ScheduledWidgetEventQueue`
9841
+ * caps what it holds: a stream that never settles — a dropped socket with no
9842
+ * error, a tab backgrounded mid-turn — must not strand a navigation the shopper
9843
+ * asked for. A late page change is recoverable; one that never comes is not.
9844
+ */
9845
+ var ACT_HOLD_MAX_MS = 15e3;
9846
+ /**
9847
+ * Is this widget event one the concierge wants PERFORMED on the host page?
9848
+ *
9849
+ * Hand-written rather than imported from `@saar-ai/widget-protocol`'s
9850
+ * `ACT_EVENT_TYPES`, and that is a build constraint rather than a preference:
9851
+ * that module is zod-backed, and `ui` is a `forbidZod` CDN artefact
9852
+ * (`tools/check-config.json`) — a VALUE import from it would pull zod into an
9853
+ * artefact a shopper downloads the moment they open the concierge. The type
9854
+ * still comes from there, so a fourth act event is a compile error here rather
9855
+ * than a silent no-op.
9856
+ */
9857
+ function isActEvent(event) {
9858
+ return event.type === "navigate" || event.type === "filter" || event.type === "spotlight";
9859
+ }
9860
+ /**
9861
+ * Do two storefront paths name the same PAGE — ignoring the query, the
9862
+ * fragment and a trailing slash?
9863
+ *
9864
+ * It decides one thing: whether a `filter`'s `collectionUrl` is the page the
9865
+ * shopper is already on (narrow it in place) or a different one (walk them
9866
+ * there with the facets in the url). Deliberately a string comparison rather
9867
+ * than a `URL` parse: both sides are root-relative by construction — the
9868
+ * server's schema and `isSameOriginPath` have both refused anything else — so
9869
+ * there is no origin to resolve against and nothing a parser would add except
9870
+ * a second place for the two to disagree.
9871
+ */
9872
+ function isSamePagePath(a, b) {
9873
+ const bare = (value) => (value.split("#")[0] ?? "").split("?")[0]?.replace(/\/+$/, "") ?? "";
9874
+ return bare(a) === bare(b);
9875
+ }
9876
+ /**
8938
9877
  * Resolves the widget's "add to cart" handler from the bridge's OWN degraded
8939
9878
  * path — docs/WIDGET_EMBED_PLAN.md §3, rule 1 ("every optional method is
8940
9879
  * genuinely optional... the widget has a working degraded path for each —
@@ -9240,7 +10179,7 @@ function deriveCallPhase(voice) {
9240
10179
  * about offering voice here costs a byte until a caller actually presses
9241
10180
  * the microphone.
9242
10181
  */
9243
- function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, collector, messages = defaultWidgetMessages, locale = "en", productHref, curationHref, brandPrimary, brandSecondary, brandAccent, avatar, attribution, color, type, identity, layout, copy, bottomOffset, showPrice, cardImageAspect, voiceAvailable, direction, proactive, initialDraft, initialSelection, initialFocus, initialMinimised, insets, hold, audio, onReady }) {
10182
+ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, siteProfile, collector, messages = defaultWidgetMessages, locale = "en", productHref, hostRoutes, curationHref, brandPrimary, brandSecondary, brandAccent, avatar, attribution, color, type, identity, layout, copy, bottomOffset, showPrice, cardImageAspect, voiceAvailable, direction, proactive, initialDraft, initialSelection, initialFocus, initialMinimised, insets, hold, audio, onReady }) {
9244
10183
  /**
9245
10184
  * Maps the tenant's semantic config fields onto the widget's historical
9246
10185
  * CSS custom properties — this is the "one becomes the other" site
@@ -9269,12 +10208,14 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
9269
10208
  brandSecondary,
9270
10209
  brandAccent
9271
10210
  ]);
10211
+ const hostRouteDeclaration = useMemo(() => hostRouteTargets(hostRoutes), [hostRoutes]);
9272
10212
  const session = useChatSession({
9273
10213
  embedKey,
9274
10214
  ...apiBase !== void 0 ? { apiBase } : {},
9275
10215
  ...socketUrl !== void 0 ? { socketUrl } : {},
9276
10216
  ...socketPath !== void 0 ? { socketPath } : {},
9277
- ...collector ? { collector } : {}
10217
+ ...collector ? { collector } : {},
10218
+ ...hostRouteDeclaration ? { hostRoutes: hostRouteDeclaration } : {}
9278
10219
  });
9279
10220
  const chatToken = session.chatToken;
9280
10221
  const canReachVoiceToken = apiBase !== void 0 && chatToken !== void 0;
@@ -9299,6 +10240,66 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
9299
10240
  */
9300
10241
  const escalated = session.status === "escalated";
9301
10242
  /**
10243
+ * Page context — where the shopper is standing, pushed to both legs
10244
+ * (ADR 0014).
10245
+ *
10246
+ * ## Why it is wired HERE and not in `core.ts`
10247
+ *
10248
+ * `core.ts` is where `PageTracker` starts, and this tracker's sibling
10249
+ * naturally belongs beside it — the ENTRY page is the one that says which
10250
+ * campaign or product brought the shopper, and by the time this component
10251
+ * mounts they may have navigated twice. It is here anyway, for one reason
10252
+ * that is not a preference: `core.mjs` has a hard min+gz budget
10253
+ * (`tools/check-config.json`, `bundle-budget.artefacts.core`) with under
10254
+ * 250 bytes of headroom at the time of writing, and a tracker plus a POST
10255
+ * does not fit in it. `ui.mjs` has room and is where the chat token already
10256
+ * lives.
10257
+ *
10258
+ * What that costs, stated plainly rather than hidden: no page context
10259
+ * exists until the shopper OPENS the concierge, because `ui.mjs` is not
10260
+ * requested until intent (§4.1). A context still arrives before the first
10261
+ * TURN, which is what the feature needs — the concierge grounds its first
10262
+ * reply — but a proactive opener cannot be grounded on the page, and a
10263
+ * visitor who never opens the widget pushes nothing at all. Moving this to
10264
+ * `core` is the follow-up, and it is gated on the theme derivation coming
10265
+ * out of `core` (option 2 of `packages/web-widget/AGENTS.md`'s "Measured
10266
+ * sizes" table), which returns eight times what this would spend.
10267
+ *
10268
+ * ## ONE push, and both legs read what it stored
10269
+ *
10270
+ * The tracker decides WHETHER; this decides WHERE, and the answer is the
10271
+ * one gated endpoint. `POST /widget/context` re-checks the visitor's
10272
+ * consent and the tenant's tracking toggle server-side and stores the
10273
+ * context against the session; the typed leg renders it from there, and the
10274
+ * turn tier reads the SAME key per turn (`PageContextStore`, `apps/agent`).
10275
+ *
10276
+ * There is deliberately no second push down the call's data channel. A
10277
+ * frame like that reaches a model without passing any server gate, so a
10278
+ * merchant who switched behavioural tracking off would still have their
10279
+ * shoppers' browsing narrated into a prompt on every call — and no check
10280
+ * running in the merchant's own page could prevent it. One gated write, two
10281
+ * readers. See ADR 0014.
10282
+ */
10283
+ const pushPageContext = session.pushPageContext;
10284
+ const sendPageContextRef = useRef(() => {});
10285
+ sendPageContextRef.current = (context) => {
10286
+ pushPageContext(context);
10287
+ };
10288
+ useEffect(() => {
10289
+ if (!bridge || !collector || chatToken === void 0) return;
10290
+ const tracker = new PageContextTracker({
10291
+ bridge,
10292
+ consent: collector,
10293
+ send: (context) => sendPageContextRef.current(context)
10294
+ });
10295
+ tracker.start();
10296
+ return () => tracker.destroy();
10297
+ }, [
10298
+ bridge,
10299
+ collector,
10300
+ chatToken
10301
+ ]);
10302
+ /**
9302
10303
  * The basket this widget built from its OWN adds — see `AddedCartLine`.
9303
10304
  * Always accumulated, even when the host has a `readCart` that reports
9304
10305
  * lines: the host read is asynchronous and can fail, and this is what the
@@ -9635,6 +10636,309 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
9635
10636
  * `/cart/add.js`, and a storefront cart is one resource — two concurrent
9636
10637
  * posts against it is exactly the shape that loses one of them.
9637
10638
  */
10639
+ /**
10640
+ * §5.3/§5.5's concierge-scroll flag, as a function the DOCK publishes.
10641
+ *
10642
+ * Called immediately BEFORE a spotlight scroll and synchronously, which is
10643
+ * the whole point of it being a callback rather than the state nonce it
10644
+ * started as: the dock's scroll listener is a capture listener on
10645
+ * `document`, so the first `scroll` event of a smooth scroll can arrive in
10646
+ * the same task — before React has re-rendered — and a flag raised by a
10647
+ * `setState` would be raised one event too late. The row receding and the
10648
+ * sheet ducking at the exact moment the concierge pointed at something is
10649
+ * precisely the failure §5.3's exception exists to prevent.
10650
+ *
10651
+ * `null` until the dock mounts (a harness with no dock at all), and calling
10652
+ * it with `0` DISARMS — see `performAct`'s spotlight branch.
10653
+ */
10654
+ const conciergeScrollRef = useRef(null);
10655
+ /**
10656
+ * The facts an act reads at the moment it RUNS, rather than at the moment
10657
+ * its callback was built.
10658
+ *
10659
+ * An act is asynchronous by construction — `navigate` waits a beat, a bridge
10660
+ * returns a promise — so a call that starts during that window changes the
10661
+ * right answer after the closure was made. `inCall` decides whether a
10662
+ * failure report is sent now or held (`heldFailureReportsRef`), and a stale
10663
+ * `false` there is a chat request answered out loud over whatever the caller
10664
+ * is saying. `actLive` is the unmount latch: nothing may assign
10665
+ * `location`, and nothing may send a report, after this widget is gone.
10666
+ */
10667
+ const inCallRef = useRef(inCall);
10668
+ const actLiveRef = useRef(true);
10669
+ /**
10670
+ * Is a typed turn still streaming in?
10671
+ *
10672
+ * The typed leg's answer to the realtime tier's "is the agent still
10673
+ * speaking" — see `performAct`. A ref rather than a dependency because
10674
+ * `performAct` is read out of a ref by the drain loop and must see the
10675
+ * CURRENT value at the moment it runs, not the one captured when the act
10676
+ * was queued.
10677
+ */
10678
+ const streamingRef = useRef(false);
10679
+ useEffect(() => {
10680
+ inCallRef.current = inCall;
10681
+ }, [inCall]);
10682
+ useEffect(() => {
10683
+ streamingRef.current = session.status === "streaming";
10684
+ }, [session.status]);
10685
+ useEffect(() => () => {
10686
+ actLiveRef.current = false;
10687
+ actQueueRef.current = [];
10688
+ }, []);
10689
+ /**
10690
+ * Send a storefront report about an act that did not happen, or hold it
10691
+ * until the call ends.
10692
+ *
10693
+ * The exact gates `reportFailedAgentCartAdd` keeps, and for the identical
10694
+ * reasons: no conversation ⇒ nothing to correct; mid-call ⇒ a chat request
10695
+ * is answered OUT LOUD over whatever the caller is saying, so it is held and
10696
+ * flushed when the call ends, never dropped. `inCall` is read from the ref
10697
+ * because this is called at the END of an asynchronous act.
10698
+ */
10699
+ const sendActReport = useCallback((report) => {
10700
+ if (chatToken === void 0 || !actLiveRef.current) return;
10701
+ if (inCallRef.current) {
10702
+ heldFailureReportsRef.current = [...heldFailureReportsRef.current, report];
10703
+ return;
10704
+ }
10705
+ session.sendReport(report).catch(() => void 0);
10706
+ }, [chatToken, session]);
10707
+ /**
10708
+ * Tell the concierge that a `spotlight` it asked for found NOTHING.
10709
+ *
10710
+ * The exact mirror of `reportFailedAgentCartAdd`: the server said
10711
+ * `status: 'requested'` because the card lives in a DOM it cannot see, so
10712
+ * this widget is the only party that learns the answer. A caller is not
10713
+ * looking at the panel at all, and by then the concierge has said "that's
10714
+ * the one, highlighted on your screen" out loud.
10715
+ */
10716
+ const reportFailedSpotlight = useCallback((event) => {
10717
+ sendActReport({
10718
+ kind: "spotlight_failed",
10719
+ title: event.title ?? event.productId,
10720
+ productId: event.productId
10721
+ });
10722
+ }, [sendActReport]);
10723
+ /**
10724
+ * Tell the concierge the page did NOT move.
10725
+ *
10726
+ * This used to be a comment explaining that there was no correction channel
10727
+ * for a navigation the way there is for a cart add. There is now
10728
+ * (`navigate_failed`), and it is needed more than the cart one: a bridge
10729
+ * with no `navigate` is §3's ordinary case rather than an exotic one, and
10730
+ * "taking you to the cushions" is the most concrete claim the concierge
10731
+ * makes. A caller cannot see that the page stayed put.
10732
+ *
10733
+ * It deliberately carries no path — the guardrails forbid the concierge to
10734
+ * say one out loud, and a report holding a url puts it in the model's
10735
+ * context with nothing but an instruction in the way.
10736
+ */
10737
+ const reportFailedNavigate = useCallback((target) => {
10738
+ sendActReport({
10739
+ kind: "navigate_failed",
10740
+ ...target !== void 0 ? { target } : {}
10741
+ });
10742
+ }, [sendActReport]);
10743
+ /**
10744
+ * The path prefix of the storefront the shopper is ACTUALLY on.
10745
+ *
10746
+ * Shopify Markets puts a locale/market code on the front of every path
10747
+ * (`/en-gb/collections/rugs`). The catalogue holds handles, not markets, so
10748
+ * every path the server resolves is spelt without one — and sending a
10749
+ * shopper browsing `/en-gb/...` to a bare `/collections/rugs` drops them out
10750
+ * of their own market: another currency, another language, and on some
10751
+ * storefronts a redirect that loses the path entirely. The bridge already
10752
+ * classifies these prefixes; this reads the one it is looking at.
10753
+ */
10754
+ const bridgePath = useCallback(() => {
10755
+ try {
10756
+ return bridge?.currentPage?.().path ?? "";
10757
+ } catch {
10758
+ return "";
10759
+ }
10760
+ }, [bridge]);
10761
+ /**
10762
+ * Walk the shopper to another page — `navigate` (§6).
10763
+ *
10764
+ * The §6 beat is NOT here — `performAct` waits it once per page-moving
10765
+ * event, so the `filter` fallback below does not wait it twice.
10766
+ *
10767
+ * ## Same-origin, re-checked HERE
10768
+ *
10769
+ * The server's schema is the boundary and `useChatSession` re-checks the
10770
+ * SSE frame, but the spoken leg does not come through that hook at all, and
10771
+ * a `filter`'s `collectionUrl` reaches this function by the same route a
10772
+ * `navigate`'s url does. This is the one place both legs and both fields
10773
+ * meet, so the predicate lives here too. A path that fails it is not
10774
+ * repaired: it is a page nobody meant to open.
10775
+ *
10776
+ * ## The `navigating` hint goes FIRST
10777
+ *
10778
+ * §8.6 — a caller's participant disconnects on every navigation, and at the
10779
+ * transport layer that is indistinguishable from a hangup. The hint is what
10780
+ * buys the session its bounded hold so the next page REJOINS the same
10781
+ * conversation. Awaited, not fired and forgotten: `location.assign` can tear
10782
+ * the page down before an unawaited publish reaches the wire.
10783
+ */
10784
+ const notifyNavigating = voice.notifyNavigating;
10785
+ const performNavigate = useCallback(async (url, target) => {
10786
+ if (!isSameOriginPath(url) || !bridge?.navigate) {
10787
+ reportFailedNavigate(target);
10788
+ return;
10789
+ }
10790
+ const routed = resolveHostRoutePath(url, target, hostRoutes);
10791
+ if (routed === null) {
10792
+ reportFailedNavigate(target);
10793
+ return;
10794
+ }
10795
+ const path = hostRoutes ? routed : withStorefrontLocale(storefrontLocalePrefix(bridgePath()), routed);
10796
+ if (!isSameOriginPath(path)) {
10797
+ reportFailedNavigate(target);
10798
+ return;
10799
+ }
10800
+ if (!actLiveRef.current) return;
10801
+ if (voiceEnabled) await notifyNavigating().catch(() => false);
10802
+ if (!actLiveRef.current) return;
10803
+ try {
10804
+ await bridge.navigate(path);
10805
+ } catch {
10806
+ reportFailedNavigate(target);
10807
+ }
10808
+ }, [
10809
+ bridge,
10810
+ bridgePath,
10811
+ hostRoutes,
10812
+ voiceEnabled,
10813
+ notifyNavigating,
10814
+ reportFailedNavigate
10815
+ ]);
10816
+ /**
10817
+ * Perform ONE act event. Never throws — every branch is a host-facing call.
10818
+ */
10819
+ /**
10820
+ * Block until the typed turn carrying this act has finished streaming.
10821
+ *
10822
+ * Polled rather than promised: the only signal is `session.status`, which is
10823
+ * React state, and a resolver registry keyed off it would be more machinery
10824
+ * than a 50 ms tick in a path that already waits 300 ms afterwards.
10825
+ *
10826
+ * BOUNDED, and the bound is the point. A stream that never settles — a socket
10827
+ * the network dropped without an error, a tab backgrounded mid-turn — must
10828
+ * not strand a navigation the shopper asked for forever; after
10829
+ * {@link ACT_HOLD_MAX_MS} the act goes anyway, because a late page change is
10830
+ * recoverable and a page change that never happens is not. It also stops at
10831
+ * unmount, so nothing assigns `location` after the widget is gone.
10832
+ */
10833
+ const waitForTypedTurnToLand = useCallback(async () => {
10834
+ const deadline = Date.now() + ACT_HOLD_MAX_MS;
10835
+ while (streamingRef.current && actLiveRef.current && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, ACT_HOLD_POLL_MS));
10836
+ }, []);
10837
+ const performAct = useCallback(async (event) => {
10838
+ if (event.type !== "spotlight") {
10839
+ if (!inCallRef.current) {
10840
+ await waitForTypedTurnToLand();
10841
+ await new Promise((resolve) => setTimeout(resolve, NAVIGATE_BEAT_MS));
10842
+ }
10843
+ if (!actLiveRef.current) return;
10844
+ }
10845
+ if (event.type === "navigate") {
10846
+ await performNavigate(event.url, event.target);
10847
+ return;
10848
+ }
10849
+ if (event.type === "filter") {
10850
+ if (event.collectionUrl !== void 0 && !isSameOriginPath(event.collectionUrl)) return;
10851
+ const prefix = storefrontLocalePrefix(bridgePath());
10852
+ const collectionUrl = event.collectionUrl;
10853
+ if (!(collectionUrl !== void 0 && !isSamePagePath(withStorefrontLocale(prefix, collectionUrl), bridgePath())) && bridge?.applyFilter) try {
10854
+ if (await bridge.applyFilter(event.filters) !== false) return;
10855
+ } catch {}
10856
+ if (collectionUrl !== void 0) await performNavigate(withStorefrontFacets(collectionUrl, event.filters), "collection");
10857
+ return;
10858
+ }
10859
+ conciergeScrollRef.current?.();
10860
+ const target = event;
10861
+ let found = false;
10862
+ try {
10863
+ found = bridge?.spotlight?.(target) ?? (typeof window === "undefined" ? false : spotlightProductCard(window, window.document, target, { ...siteProfile ? { siteProfile } : {} }));
10864
+ } catch {}
10865
+ if (!found) {
10866
+ conciergeScrollRef.current?.(0);
10867
+ reportFailedSpotlight(event);
10868
+ }
10869
+ }, [
10870
+ bridge,
10871
+ bridgePath,
10872
+ siteProfile,
10873
+ performNavigate,
10874
+ reportFailedSpotlight,
10875
+ waitForTypedTurnToLand
10876
+ ]);
10877
+ /**
10878
+ * The acts the concierge asked for, from both legs, performed exactly once
10879
+ * each and one at a time.
10880
+ *
10881
+ * Two sources (`session.actEvents` for the typed leg, `voice.widgetEvents`
10882
+ * for the spoken one), one consumption record, **consumed by object
10883
+ * IDENTITY**, marked consumed BEFORE they are performed — all of that is the
10884
+ * agent-cart-add effect's discipline and the reasons are the same there.
10885
+ * Identity matters MORE here: a shopper who says "that one again" produces a
10886
+ * second `spotlight` for the SAME product, and a consumer keyed on the
10887
+ * payload would silently swallow the repeat.
10888
+ *
10889
+ * ## Why a queue and a ref, rather than an async loop per run
10890
+ *
10891
+ * The effect used to depend on `performAct`, whose identity churns on every
10892
+ * render (`useChatSession` returns a fresh object, so every callback built
10893
+ * from `session` is new every frame). So the effect re-ran constantly, and
10894
+ * an event arriving while a previous act was still in flight started a
10895
+ * SECOND async loop beside the first: a `filter` and a `navigate` racing to
10896
+ * assign `location`, or two beats elapsing concurrently. The events were
10897
+ * still performed once each — identity saw to that — but "sequential" was
10898
+ * never true.
10899
+ *
10900
+ * Now the effect only ENQUEUES, and depends on nothing but the two lists. A
10901
+ * single drain runs at a time (`actDrainingRef`), reads the latest
10902
+ * `performAct` out of a ref at the moment it runs each event (so nothing is
10903
+ * performed with a stale `bridge` or a stale call state), and stops on
10904
+ * unmount — no `location.assign` and no `sendReport` after teardown.
10905
+ */
10906
+ const consumedActsRef = useRef(/* @__PURE__ */ new WeakSet());
10907
+ const actQueueRef = useRef([]);
10908
+ const actDrainingRef = useRef(false);
10909
+ const performActRef = useRef(performAct);
10910
+ useEffect(() => {
10911
+ performActRef.current = performAct;
10912
+ }, [performAct]);
10913
+ const voiceWidgetEventsForActs = voice.widgetEvents;
10914
+ const sessionActEvents = session.actEvents;
10915
+ useEffect(() => {
10916
+ for (const event of voiceWidgetEventsForActs) {
10917
+ if (!isActEvent(event)) continue;
10918
+ if (consumedActsRef.current.has(event)) continue;
10919
+ consumedActsRef.current.add(event);
10920
+ actQueueRef.current.push(event);
10921
+ }
10922
+ for (const event of sessionActEvents) {
10923
+ if (consumedActsRef.current.has(event)) continue;
10924
+ consumedActsRef.current.add(event);
10925
+ actQueueRef.current.push(event);
10926
+ }
10927
+ if (actDrainingRef.current || actQueueRef.current.length === 0) return;
10928
+ actDrainingRef.current = true;
10929
+ (async () => {
10930
+ try {
10931
+ for (;;) {
10932
+ if (!actLiveRef.current) break;
10933
+ const next = actQueueRef.current.shift();
10934
+ if (next === void 0) break;
10935
+ await performActRef.current(next);
10936
+ }
10937
+ } finally {
10938
+ actDrainingRef.current = false;
10939
+ }
10940
+ })();
10941
+ }, [voiceWidgetEventsForActs, sessionActEvents]);
9638
10942
  const consumedCartAddsRef = useRef(/* @__PURE__ */ new WeakSet());
9639
10943
  const voiceWidgetEvents = voice.widgetEvents;
9640
10944
  const sessionCartAdds = session.cartAdds;
@@ -10396,6 +11700,7 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
10396
11700
  roomDropped: voiceEnabled && voice.phase === "disconnected",
10397
11701
  ...latestCuration ? { shelf: latestCuration } : {},
10398
11702
  pageKey,
11703
+ conciergeScrollRef,
10399
11704
  ...initialDraft !== void 0 ? { initialDraft } : {},
10400
11705
  ...initialSelection !== void 0 ? { initialSelection } : {},
10401
11706
  ...initialFocus !== void 0 ? { initialFocus } : {},
@@ -10436,4 +11741,4 @@ function ConciergeWidget({ embedKey, apiBase, socketUrl, socketPath, bridge, col
10436
11741
  });
10437
11742
  }
10438
11743
  //#endregion
10439
- export { ROW_H as $, Dock as A, mixToward as At, DESKTOP_BOTTOM as B, withAlpha as Bt, IDLE_SNAPSHOT as C, themeToInlineStyle as Ct, SessionLog as D, hexToOklch as Dt, SESSION_EVENTS as E, hexToOklab as Et, latestExchangeStart as F, oklchToOklab as Ft, DOCK_MINIMISED_STORAGE_KEY as G, DESKTOP_GUTTER as H, formatMessage as Ht, formatMoney as I, parseHex as It, MOBILE_MARGIN as J, DRAG_TAP_SLOP_PX as K, ACTIVITY_W as L, relativeLuminance as Lt, deriveDockState as M, oklabToLinearRgb as Mt, exchangeCount as N, oklabToOklch as Nt, formatMs as O, linearRgbToOklab as Ot, idleDockInput as P, oklchToHex as Pt, RADII as Q, BOTTOM_FLOOR as R, rotateHue as Rt, parseBlocks as S, themeToCss as St, SseFrameParser as T, formatHex as Tt, DESKTOP_WIDTHS as U, resolveWidgetMessages as Ut, DESKTOP_BREAKPOINT as V, defaultWidgetMessages as Vt, DOCK_ALIGN_STORAGE_KEY as W, widgetMessagesFromCopy as Wt, PILL_MARK as X, PILL_H as Y, PROACTIVE_NUDGE_MS as Z, readsAsCheckoutIntent as _, CARD_RADIUS_MAX_PX as _t, mergeAddedCartLine as a, SHORT_VIEWPORT as at, WidgetCardList as b, WIDGET_THEME_TOKENS as bt, toChatCart as c, geometryVars as ct, useVoiceSession as d, readStored as dt, SHEET_EXPANDED_DESKTOP_MAX as et, useChatSession as f, readStoredAlign as ft, readsAsCartViewIntent as g, writeStored as gt, basketIntentFromTurns as h, snapAlign as ht, deriveCallPhase as i, SHEET_TOP_CLEARANCE as it, DOCK_STATES as j, oklabToHex as jt, latencyBetween as k, linearToSrgb as kt, ROOM_EVENTS as l, persistAlign as lt, VoiceWidget as m, sheetMaxHeightLen as mt, MAX_REPORTED_CART_LINES as n, SHEET_GAP as nt, resolveAddToCartHandler as o, Z_INDEX as ot, detectPage as p, rowWidthLen as pt, MARK as q, cartLinesFromSnapshot as r, SHEET_PEEK_MAX as rt, resolveCheckoutUrl as s, bottomLen as st, ConciergeWidget as t, SHEET_EXPANDED_VH as tt, createWidgetVoiceTokenFetcher as u, pillAnchor as ut, textDirectionFor as v, SHEET_RADIUS_MAX_PX as vt, botStateFor as w, contrastRatio as wt, WidgetMarkdown as x, deriveTheme as xt, WidgetCartSummary as y, SYSTEM_FONT_STACK as yt, CONTROL as z, srgbToLinear as zt };
11744
+ export { RADII as $, latencyBetween as A, linearToSrgb as At, CONTROL as B, srgbToLinear as Bt, parseBlocks as C, themeToCss as Ct, SESSION_EVENTS as D, hexToOklab as Dt, SseFrameParser as E, formatHex as Et, idleDockInput as F, oklchToHex as Ft, DOCK_ALIGN_STORAGE_KEY as G, widgetMessagesFromCopy as Gt, DESKTOP_BREAKPOINT as H, defaultWidgetMessages as Ht, latestExchangeStart as I, oklchToOklab as It, MARK as J, DOCK_MINIMISED_STORAGE_KEY as K, formatMoney as L, parseHex as Lt, DOCK_STATES as M, oklabToHex as Mt, deriveDockState as N, oklabToLinearRgb as Nt, SessionLog as O, hexToOklch as Ot, exchangeCount as P, oklabToOklch as Pt, PROACTIVE_NUDGE_MS as Q, ACTIVITY_W as R, relativeLuminance as Rt, WidgetMarkdown as S, deriveTheme as St, botStateFor as T, contrastRatio as Tt, DESKTOP_GUTTER as U, formatMessage as Ut, DESKTOP_BOTTOM as V, withAlpha as Vt, DESKTOP_WIDTHS as W, resolveWidgetMessages as Wt, PILL_H as X, MOBILE_MARGIN as Y, PILL_MARK as Z, readsAsCartViewIntent as _, writeStored as _t, mergeAddedCartLine as a, SHEET_TOP_CLEARANCE as at, WidgetCartSummary as b, SYSTEM_FONT_STACK as bt, toChatCart as c, bottomLen as ct, useVoiceSession as d, pillAnchor as dt, ROW_H as et, isSameOriginPath as f, readStored as ft, basketIntentFromTurns as g, snapAlign as gt, VoiceWidget as h, sheetMaxHeightLen as ht, deriveCallPhase as i, SHEET_PEEK_MAX as it, Dock as j, mixToward as jt, formatMs as k, linearRgbToOklab as kt, ROOM_EVENTS as l, geometryVars as lt, detectPage as m, rowWidthLen as mt, MAX_REPORTED_CART_LINES as n, SHEET_EXPANDED_VH as nt, resolveAddToCartHandler as o, SHORT_VIEWPORT as ot, useChatSession as p, readStoredAlign as pt, DRAG_TAP_SLOP_PX as q, cartLinesFromSnapshot as r, SHEET_GAP as rt, resolveCheckoutUrl as s, Z_INDEX as st, ConciergeWidget as t, SHEET_EXPANDED_DESKTOP_MAX as tt, createWidgetVoiceTokenFetcher as u, persistAlign as ut, readsAsCheckoutIntent as v, CARD_RADIUS_MAX_PX as vt, IDLE_SNAPSHOT as w, themeToInlineStyle as wt, WidgetCardList as x, WIDGET_THEME_TOKENS as xt, textDirectionFor as y, SHEET_RADIUS_MAX_PX as yt, BOTTOM_FLOOR as z, rotateHue as zt };