@vettvangur/ai-sdk 0.5.4 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
- import { a as isSafeLinkUrl, i as isPlainObject, n as createSafeImage, r as createSafeLink, t as createPart } from "./dom.js";
1
+ import { a as isSafeLinkUrl, i as isPlainObject, n as createSafeImage, o as readJsonAttribute, r as createSafeLink, t as createPart } from "./dom.js";
2
2
  import { i as renderMarkdown, n as renderSurveyForm, r as countMarkdownStructuralItems } from "./survey.js";
3
+ import { n as createTemplateItemSurface, t as createSingleSurface } from "./surfaces.js";
3
4
  //#region src/answer-card.ts
4
5
  const ANSWER_CARD_KEYS = /* @__PURE__ */ new Set([
5
6
  "kind",
@@ -333,6 +334,35 @@ function renderAnswerCard(document, data, labels) {
333
334
  if (isPlainObject(data) && data.kind === "answer") return isAnswerCard(data) ? renderKnownAnswerCard(document, data, labels) : null;
334
335
  return renderGenericAnswerCard(document, data);
335
336
  }
337
+ const MARKDOWN_IN_PLAIN_TEXT = /\]\(|\\[\\`*_{}[\]()#+.!|~-]/;
338
+ function plainTextFields(card) {
339
+ const facts = (items) => (items ?? []).flatMap((fact) => [fact.label, fact.value]);
340
+ return [
341
+ card.title,
342
+ card.note,
343
+ card.sourceNote,
344
+ ...facts(card.highlight ? [card.highlight] : null),
345
+ ...(card.sections ?? []).flatMap((section) => [
346
+ section.title,
347
+ section.note,
348
+ ...facts(section.facts),
349
+ ...(section.tables ?? []).flatMap((table) => [
350
+ table.label,
351
+ ...table.headers,
352
+ ...table.rows.flat()
353
+ ])
354
+ ])
355
+ ].filter((value) => typeof value === "string");
356
+ }
357
+ /**
358
+ * Throws when `card` is not an answer card `renderAnswerCard` will draw, or when a field it shows
359
+ * as plain text (titles, facts, table cells, notes) holds Markdown that would show literally. For
360
+ * a server's or a test's own cards; the message names what is wrong.
361
+ */
362
+ function assertAnswerCardContract(card) {
363
+ if (!isAnswerCard(card)) throw new Error("Not an answer card the renderer draws: check its kind, keys and limits");
364
+ for (const text of plainTextFields(card)) if (MARKDOWN_IN_PLAIN_TEXT.test(text)) throw new Error(`Markdown in a plain-text field of "${card.title}": ${text}`);
365
+ }
336
366
  //#endregion
337
367
  //#region src/protocol.ts
338
368
  const AI_CHAT_PROTOCOL_VERSION = 1;
@@ -648,6 +678,85 @@ function createChatSession(options) {
648
678
  return session;
649
679
  }
650
680
  //#endregion
681
+ //#region src/cards.ts
682
+ /** Block classes of the cards below. Every element a card renders carries a class under its block. */
683
+ const CARD_LIST_CLASS = "vv-ai-card-list";
684
+ const ACTIONS_CLASS = "vv-ai-actions";
685
+ function text(value) {
686
+ return typeof value === "string" && value.trim() ? value : null;
687
+ }
688
+ /**
689
+ * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
690
+ * Items that render nothing are skipped, and a list with nothing in it is null.
691
+ */
692
+ function renderCardList(document, items, render, modifier) {
693
+ if (!Array.isArray(items)) return null;
694
+ const cards = items.map(render).filter((card) => card !== null);
695
+ if (!cards.length) return null;
696
+ const list = createPart(document, "div", CARD_LIST_CLASS);
697
+ if (modifier) list.classList.add(`${CARD_LIST_CLASS}--${modifier}`);
698
+ list.append(...cards);
699
+ return list;
700
+ }
701
+ /**
702
+ * A row of things the visitor can do next. An item with `action` is a button that runs the action
703
+ * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
704
+ * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
705
+ */
706
+ function renderActions(document, items) {
707
+ const elements = [];
708
+ for (const item of items) {
709
+ const label = text(item?.label);
710
+ if (!label) continue;
711
+ let element = null;
712
+ const action = text(item.action);
713
+ const url = text(item.url);
714
+ if (action) {
715
+ const button = createPart(document, "button", ACTIONS_CLASS, "action", label);
716
+ button.type = "button";
717
+ button.dataset.aiAction = action;
718
+ const value = text(item.value);
719
+ if (value) button.dataset.aiActionValue = value;
720
+ element = button;
721
+ } else if (url) {
722
+ element = createSafeLink(document, label, url.trim());
723
+ if (element) element.className = `${ACTIONS_CLASS}__action`;
724
+ }
725
+ if (element) {
726
+ element.classList.add(`${ACTIONS_CLASS}__action--${item.primary ? "primary" : "secondary"}`);
727
+ elements.push(element);
728
+ }
729
+ }
730
+ if (!elements.length) return null;
731
+ const actions = createPart(document, "div", ACTIONS_CLASS);
732
+ actions.append(...elements);
733
+ return actions;
734
+ }
735
+ //#endregion
736
+ //#region src/handover.ts
737
+ /** The action the handover card's button runs; the binding hands over to a person with it. */
738
+ const LIVE_CHAT_ACTION = "livechat";
739
+ /** The tool the Vettvangur.AiChat engine hands over with, from before its payload named its kind. */
740
+ const HANDOVER_TOOL = "request_human_agent";
741
+ /** A payload of kind `handover`, or one from the handover tool that names no kind. */
742
+ function isHandoverPayload(tool, data) {
743
+ return isPlainObject(data) && (data.kind === "handover" || tool === "request_human_agent" && data.kind === void 0);
744
+ }
745
+ /**
746
+ * The visitor's ways to a person: a primary `liveChat` button that runs the `livechat` action when
747
+ * a live chat is available, and a `contact` link to a safe contact URL. Null when neither applies.
748
+ */
749
+ function renderHandoverCard(document, data, labels) {
750
+ return renderActions(document, [...data.liveChatAvailable === true ? [{
751
+ label: labels.liveChat,
752
+ action: LIVE_CHAT_ACTION,
753
+ primary: true
754
+ }] : [], ...typeof data.contactUrl === "string" ? [{
755
+ label: labels.contact,
756
+ url: data.contactUrl
757
+ }] : []]);
758
+ }
759
+ //#endregion
651
760
  //#region src/registry.ts
652
761
  const entries = /* @__PURE__ */ new WeakMap();
653
762
  function register(map, name, value) {
@@ -717,6 +826,8 @@ const defaultLabels = {
717
826
  table: "Published table",
718
827
  tableScroll: "Scroll sideways to see all columns",
719
828
  followUps: "Suggested questions",
829
+ liveChat: "Chat with a person",
830
+ contact: "Contact us",
720
831
  liveChatConnecting: "Connecting you to a person",
721
832
  liveChatClosed: "No one is available to chat right now.",
722
833
  liveChatEnded: "The chat has ended. You are talking to the AI again.",
@@ -766,6 +877,10 @@ function readLabels(root, labels) {
766
877
  for (const key of Object.keys(defaultLabels)) read[key] = labels?.[key] || root.getAttribute(`data-ai-chat-label-${kebab(key)}`) || defaultLabels[key];
767
878
  return read;
768
879
  }
880
+ function answers(value) {
881
+ if (!isPlainObject(value)) return;
882
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string" || typeof entry[1] === "boolean"));
883
+ }
769
884
  function stringRecord(value) {
770
885
  if (!isPlainObject(value)) return {};
771
886
  return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"));
@@ -790,10 +905,16 @@ function bindChat(root, options = {}) {
790
905
  const endpoint = options.endpoint ?? root.dataset.aiChatEndpoint ?? form.action;
791
906
  const header = options.antiforgeryHeader ?? root.dataset.aiChatAntiforgeryHeader;
792
907
  const token = options.antiforgeryToken ?? root.dataset.aiChatAntiforgeryToken;
793
- const headers = header && token ? { [header]: token } : void 0;
908
+ const headers = header && token ? { [header]: token } : {};
794
909
  const feedbackEndpoint = options.feedbackEndpoint ?? root.dataset.aiChatFeedbackEndpoint;
795
910
  const handoverEndpoint = options.handoverEndpoint ?? root.dataset.aiChatHandoverEndpoint;
796
911
  const storageKey = options.storageKey ?? root.dataset.aiChatStorageKey;
912
+ const handoverPrefill = options.handoverPrefill ?? answers(readJsonAttribute(root, "data-ai-chat-live-prefill", options.onError));
913
+ const liveChat = typeof options.liveChat === "function" ? options.liveChat({
914
+ root,
915
+ headers,
916
+ onError: (error) => options.onError?.(error)
917
+ }) : options.liveChat;
797
918
  let activeAssistant = null;
798
919
  let activeText = null;
799
920
  let activeTextContent = "";
@@ -864,6 +985,10 @@ function bindChat(root, options = {}) {
864
985
  message.append(error.name === "TimeoutError" ? labels.timeout : labels.error);
865
986
  chatThread.append(message);
866
987
  }
988
+ function label(name) {
989
+ if (name in labels) return labels[name];
990
+ return options.labels?.[name] || root.getAttribute(`data-ai-chat-label-${kebab(name)}`) || "";
991
+ }
867
992
  function toolLabel(name) {
868
993
  if (!/^[\w-]{1,64}$/.test(name)) return labels.toolRunning;
869
994
  return options.toolLabels?.[name] || root.getAttribute(`data-ai-chat-tool-${kebab(name)}`) || labels.toolRunning;
@@ -907,7 +1032,8 @@ function bindChat(root, options = {}) {
907
1032
  tool: result.name,
908
1033
  data: result.data,
909
1034
  reply: result.reply,
910
- labels
1035
+ labels,
1036
+ label
911
1037
  };
912
1038
  let content = null;
913
1039
  try {
@@ -916,7 +1042,8 @@ function bindChat(root, options = {}) {
916
1042
  if (templateName) content = root.querySelector(`template[data-template="${CSS.escape(templateName)}"]`)?.content.cloneNode(true) ?? null;
917
1043
  if (!content && surfaceName) content = registryEntries(options.registry)?.surfaces.get(surfaceName)?.(context) ?? root.querySelector(`template[data-ai-surface="${CSS.escape(surfaceName)}"]`)?.content.cloneNode(true) ?? null;
918
1044
  if (!content) content = registryEntries(options.registry)?.renderers.get(result.name)?.(context) ?? null;
919
- content ??= renderAnswerCard(root.ownerDocument, result.data, labels);
1045
+ if (!content && isHandoverPayload(result.name, result.data)) content = renderHandoverCard(root.ownerDocument, result.data, labels);
1046
+ else content ??= renderAnswerCard(root.ownerDocument, result.data, labels);
920
1047
  } catch (caught) {
921
1048
  options.onError?.(caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat extension failed"));
922
1049
  }
@@ -1295,7 +1422,7 @@ function bindChat(root, options = {}) {
1295
1422
  }
1296
1423
  }
1297
1424
  async function runHandover(handover) {
1298
- const provider = handover.provider ?? options.liveChat;
1425
+ const provider = handover.provider ?? liveChat;
1299
1426
  if (!provider) throw new Error("AI chat handover needs a live chat provider");
1300
1427
  const run = ++handoverRuns;
1301
1428
  const stale = () => destroyed || run !== handoverRuns;
@@ -1325,7 +1452,7 @@ function bindChat(root, options = {}) {
1325
1452
  intro: labels.surveyIntro,
1326
1453
  prefilled: labels.surveyPrefilled
1327
1454
  },
1328
- prefill: handover.prefill
1455
+ prefill: handover.prefill ?? handoverPrefill
1329
1456
  });
1330
1457
  pendingSurvey = survey;
1331
1458
  const wrapper = root.ownerDocument.createElement("div");
@@ -1382,7 +1509,7 @@ function bindChat(root, options = {}) {
1382
1509
  }
1383
1510
  }
1384
1511
  function resumeLive(stored) {
1385
- const provider = options.liveChat;
1512
+ const provider = liveChat;
1386
1513
  if (!provider) {
1387
1514
  notify(labels.liveChatEnded, "ended");
1388
1515
  return;
@@ -1523,7 +1650,8 @@ function bindChat(root, options = {}) {
1523
1650
  }
1524
1651
  const actionElement = target?.closest("[data-ai-action]");
1525
1652
  const action = actionElement ? registryEntries(options.registry)?.actions.get(actionElement.dataset.aiAction ?? "") : void 0;
1526
- if (action && actionElement) Promise.resolve(action({
1653
+ if (!action && actionElement?.dataset.aiAction === "livechat") binding.handover().catch(report);
1654
+ else if (action && actionElement) Promise.resolve(action({
1527
1655
  root,
1528
1656
  element: actionElement,
1529
1657
  value: actionElement.dataset.aiActionValue ?? null,
@@ -1628,8 +1756,10 @@ function bindChat(root, options = {}) {
1628
1756
  else startConversation();
1629
1757
  if (stored?.live) resumeLive(stored.live);
1630
1758
  const binding = {
1759
+ root,
1631
1760
  session,
1632
1761
  labels,
1762
+ headers,
1633
1763
  get mode() {
1634
1764
  return mode;
1635
1765
  },
@@ -1639,6 +1769,7 @@ function bindChat(root, options = {}) {
1639
1769
  get liveChat() {
1640
1770
  return live?.provider ?? null;
1641
1771
  },
1772
+ label,
1642
1773
  appendAssistantReply(text) {
1643
1774
  const content = text.trim();
1644
1775
  if (!content) return;
@@ -1704,79 +1835,121 @@ function bindChat(root, options = {}) {
1704
1835
  return binding;
1705
1836
  }
1706
1837
  //#endregion
1707
- //#region src/cards.ts
1708
- /** Block classes of the cards below. Every element a card renders carries a class under its block. */
1709
- const CARD_LIST_CLASS = "vv-ai-card-list";
1710
- const ACTIONS_CLASS = "vv-ai-actions";
1711
- function text(value) {
1712
- return typeof value === "string" && value.trim() ? value : null;
1713
- }
1838
+ //#region src/form-context.ts
1714
1839
  /**
1715
- * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
1716
- * Items that render nothing are skipped, and a list with nothing in it is null.
1840
+ * Tells the AI what the visitor entered into a form embedded in the thread. Whenever `element`
1841
+ * changes and holds `options.form`, its filled-in `fields` are summarised as `label: value` and
1842
+ * sent with every later question through `binding.setFormContext`, framed as context rather than
1843
+ * something the visitor said. Returns a function that stops watching.
1717
1844
  */
1718
- function renderCardList(document, items, render, modifier) {
1719
- if (!Array.isArray(items)) return null;
1720
- const cards = items.map(render).filter((card) => card !== null);
1721
- if (!cards.length) return null;
1722
- const list = createPart(document, "div", CARD_LIST_CLASS);
1723
- if (modifier) list.classList.add(`${CARD_LIST_CLASS}--${modifier}`);
1724
- list.append(...cards);
1725
- return list;
1845
+ function watchFormContext(binding, element, options) {
1846
+ const record = () => {
1847
+ const form = element.querySelector(options.form);
1848
+ if (!form) return;
1849
+ const values = new FormData(form);
1850
+ const parts = options.fields.map(([field, label]) => {
1851
+ const raw = String(values.get(field) ?? "").trim();
1852
+ const value = options.values?.[raw] ?? raw;
1853
+ return value ? `${label}: ${value}` : "";
1854
+ }).filter(Boolean);
1855
+ if (!parts.length) return;
1856
+ const note = options.note ? ` ${options.note}` : "";
1857
+ binding.setFormContext(options.name, `Context, not a message from the visitor: they filled in ${options.title} with ${parts.join(", ")}.${note}`, options.followUp);
1858
+ };
1859
+ const observer = new MutationObserver(record);
1860
+ observer.observe(element, {
1861
+ childList: true,
1862
+ subtree: true
1863
+ });
1864
+ record();
1865
+ return () => observer.disconnect();
1726
1866
  }
1867
+ //#endregion
1868
+ //#region src/window.ts
1727
1869
  /**
1728
- * A row of things the visitor can do next. An item with `action` is a button that runs the action
1729
- * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
1730
- * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
1870
+ * The binding as a window over the page. Anywhere in the document, a `data-ai-chat-window-open`
1871
+ * element opens it, and one that is also `data-ai-chat-window-toggle` closes it again; toggles
1872
+ * carry `aria-expanded` and get focus back when it closes. Escape closes the root's
1873
+ * `details[data-ai-chat-menu]` first and then the window, a click anywhere but the menu's summary
1874
+ * closes the menu, and a `data-ai-chat-expand` link closes the window before it navigates, so the
1875
+ * next page does not open it again from the stored thread. Returns a function that undoes it all.
1731
1876
  */
1732
- function renderActions(document, items) {
1733
- const elements = [];
1734
- for (const item of items) {
1735
- const label = text(item?.label);
1736
- if (!label) continue;
1737
- let element = null;
1738
- const action = text(item.action);
1739
- const url = text(item.url);
1740
- if (action) {
1741
- const button = createPart(document, "button", ACTIONS_CLASS, "action", label);
1742
- button.type = "button";
1743
- button.dataset.aiAction = action;
1744
- const value = text(item.value);
1745
- if (value) button.dataset.aiActionValue = value;
1746
- element = button;
1747
- } else if (url) {
1748
- element = createSafeLink(document, label, url.trim());
1749
- if (element) element.className = `${ACTIONS_CLASS}__action`;
1750
- }
1751
- if (element) {
1752
- element.classList.add(`${ACTIONS_CLASS}__action--${item.primary ? "primary" : "secondary"}`);
1753
- elements.push(element);
1877
+ function bindChatWindow(binding) {
1878
+ const document = binding.root.ownerDocument;
1879
+ const menu = binding.root.querySelector("details[data-ai-chat-menu]");
1880
+ const summary = menu?.querySelector("summary") ?? null;
1881
+ const toggles = () => document.querySelectorAll("[data-ai-chat-window-toggle]");
1882
+ const sync = () => {
1883
+ for (const toggle of toggles()) toggle.setAttribute("aria-expanded", String(binding.isOpen));
1884
+ };
1885
+ const click = (event) => {
1886
+ const target = event.target instanceof Element ? event.target : null;
1887
+ if (menu?.open && !(target && summary?.contains(target))) menu.open = false;
1888
+ const opener = target?.closest("[data-ai-chat-window-open]");
1889
+ if (opener) {
1890
+ if (opener.hasAttribute("data-ai-chat-window-toggle") && binding.isOpen) binding.close();
1891
+ else binding.open();
1892
+ return;
1754
1893
  }
1894
+ const expand = target?.closest("[data-ai-chat-expand]");
1895
+ if (expand && binding.root.contains(expand)) binding.close();
1896
+ };
1897
+ const keydown = (event) => {
1898
+ if (event.key !== "Escape") return;
1899
+ if (menu?.open) {
1900
+ menu.open = false;
1901
+ summary?.focus();
1902
+ } else if (binding.isOpen) binding.close();
1903
+ };
1904
+ document.addEventListener("click", click);
1905
+ document.addEventListener("keydown", keydown);
1906
+ const unsubscribes = [binding.on("open", sync), binding.on("close", () => {
1907
+ sync();
1908
+ toggles()[0]?.focus();
1909
+ })];
1910
+ sync();
1911
+ return () => {
1912
+ document.removeEventListener("click", click);
1913
+ document.removeEventListener("keydown", keydown);
1914
+ for (const unsubscribe of unsubscribes) unsubscribe();
1915
+ };
1916
+ }
1917
+ function teaserShown(key) {
1918
+ if (!key) return false;
1919
+ try {
1920
+ return window.sessionStorage.getItem(key) !== null;
1921
+ } catch {
1922
+ return true;
1755
1923
  }
1756
- if (!elements.length) return null;
1757
- const actions = createPart(document, "div", ACTIONS_CLASS);
1758
- actions.append(...elements);
1759
- return actions;
1760
1924
  }
1761
- //#endregion
1762
- //#region src/surfaces.ts
1925
+ function markTeaserShown(key) {
1926
+ if (!key) return;
1927
+ try {
1928
+ window.sessionStorage.setItem(key, "1");
1929
+ } catch {}
1930
+ }
1763
1931
  /**
1764
- * A surface that shows one item out of an authored list template. The template is cloned, every
1765
- * element carrying `attribute` whose value is not the payload's `key` field is removed, and the
1766
- * rest of the template stays as authored, so one item is the same markup the whole list shows.
1767
- * Null when the template is missing or no item matches.
1932
+ * The `data-ai-launcher-teaser` inside `container`, shown once a session to a visitor who has not
1933
+ * started a chat: not while the window is open or its thread has messages. A
1934
+ * `data-ai-launcher-dismiss` button in it hides it, as opening the window does. When storage
1935
+ * cannot be read the teaser is not shown. Returns a function that undoes it.
1768
1936
  */
1769
- function createTemplateItemSurface(options) {
1770
- return ({ root, data }) => {
1771
- const value = isPlainObject(data) ? data[options.key] : null;
1772
- const template = root.querySelector(`template[data-template="${CSS.escape(options.template)}"]`);
1773
- if (typeof value !== "string" || !template) return null;
1774
- const content = template.content.cloneNode(true);
1775
- let found = false;
1776
- for (const item of content.querySelectorAll(`[${CSS.escape(options.attribute)}]`)) if (item.getAttribute(options.attribute) === value) found = true;
1777
- else item.remove();
1778
- return found ? content : null;
1937
+ function bindLauncherTeaser(binding, container, options = {}) {
1938
+ const teaser = container.querySelector("[data-ai-launcher-teaser]");
1939
+ const key = options.storageKey || teaser?.dataset.aiLauncherTeaser || "";
1940
+ if (!teaser || binding.isOpen || teaserShown(key) || binding.root.querySelector("[data-ai-chat-message]")) return () => void 0;
1941
+ teaser.hidden = false;
1942
+ markTeaserShown(key);
1943
+ const hide = () => {
1944
+ teaser.hidden = true;
1945
+ };
1946
+ const dismiss = teaser.querySelector("[data-ai-launcher-dismiss]");
1947
+ dismiss?.addEventListener("click", hide);
1948
+ const unsubscribe = binding.on("open", hide);
1949
+ return () => {
1950
+ dismiss?.removeEventListener("click", hide);
1951
+ unsubscribe();
1779
1952
  };
1780
1953
  }
1781
1954
  //#endregion
1782
- export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, CARD_LIST_CLASS, CHAT_CLASS, MAX_ANSWER_CARD_FACTS, MAX_ANSWER_CARD_LINKS, MAX_ANSWER_CARD_SECTIONS, MAX_ANSWER_CARD_TABLES, MAX_ANSWER_CARD_TABLE_CELLS, MAX_ANSWER_CARD_TABLE_ROWS, MAX_ANSWER_CARD_TEXT_LENGTH, MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, MAX_ANSWER_CARD_URL_LENGTH, bindChat, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createTemplateItemSurface, isAnswerCard, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList };
1955
+ export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, CARD_LIST_CLASS, CHAT_CLASS, HANDOVER_TOOL, LIVE_CHAT_ACTION, MAX_ANSWER_CARD_FACTS, MAX_ANSWER_CARD_LINKS, MAX_ANSWER_CARD_SECTIONS, MAX_ANSWER_CARD_TABLES, MAX_ANSWER_CARD_TABLE_CELLS, MAX_ANSWER_CARD_TABLE_ROWS, MAX_ANSWER_CARD_TEXT_LENGTH, MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, MAX_ANSWER_CARD_URL_LENGTH, assertAnswerCardContract, bindChat, bindChatWindow, bindLauncherTeaser, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createSingleSurface, createTemplateItemSurface, isAnswerCard, isHandoverPayload, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderHandoverCard, watchFormContext };
@@ -1,4 +1,5 @@
1
1
  import { a as AiLiveChatProvider, s as AiLiveChatSurveyField } from "../provider.js";
2
+ import { M as AiLiveChatFactoryContext } from "../contracts.js";
2
3
  //#region src/live-chat/aichat.d.ts
3
4
  type AiChatLiveConfig = {
4
5
  /** The prefix the site maps the chat under with `MapAiChat`, such as `/webapi/aichat`. */
@@ -22,5 +23,13 @@ type AiChatLiveConfig = {
22
23
  * reconnect. `availability()` is `no-agents` while nobody has the Live view open.
23
24
  */
24
25
  declare function createAiChatLiveProvider(config: AiChatLiveConfig): AiLiveChatProvider;
26
+ /**
27
+ * The Live desk provider the shell's markup describes, for `bindChat`'s `liveChat` option, which
28
+ * calls it with the antiforgery headers it sends. `data-ai-chat-live-endpoint` on the root is the
29
+ * endpoint, and `data-ai-chat-live-survey` the survey as JSON, `{ fields, yes, no }`. Undefined
30
+ * without an endpoint. A survey that is not valid JSON or has no `fields` array is reported
31
+ * through `onError`, and the chat goes on without it.
32
+ */
33
+ declare function liveChatFromRoot({ root, headers, onError }: AiLiveChatFactoryContext): AiLiveChatProvider | undefined;
25
34
  //#endregion
26
- export { AiChatLiveConfig, createAiChatLiveProvider };
35
+ export { AiChatLiveConfig, createAiChatLiveProvider, liveChatFromRoot };
@@ -1,3 +1,4 @@
1
+ import { i as isPlainObject, o as readJsonAttribute } from "../dom.js";
1
2
  //#region src/live-chat/aichat.ts
2
3
  /** The header that carries the visitor's chat token after `start`. */
3
4
  const TOKEN_HEADER = "X-AiChat-Live";
@@ -227,5 +228,26 @@ function createAiChatLiveProvider(config) {
227
228
  }
228
229
  };
229
230
  }
231
+ /**
232
+ * The Live desk provider the shell's markup describes, for `bindChat`'s `liveChat` option, which
233
+ * calls it with the antiforgery headers it sends. `data-ai-chat-live-endpoint` on the root is the
234
+ * endpoint, and `data-ai-chat-live-survey` the survey as JSON, `{ fields, yes, no }`. Undefined
235
+ * without an endpoint. A survey that is not valid JSON or has no `fields` array is reported
236
+ * through `onError`, and the chat goes on without it.
237
+ */
238
+ function liveChatFromRoot({ root, headers, onError }) {
239
+ const endpoint = root.dataset.aiChatLiveEndpoint;
240
+ if (!endpoint) return;
241
+ const read = readJsonAttribute(root, "data-ai-chat-live-survey", onError);
242
+ const survey = isPlainObject(read) && Array.isArray(read.fields) ? read : null;
243
+ if (read !== void 0 && !survey) onError(/* @__PURE__ */ new Error("AI chat could not read data-ai-chat-live-survey: it needs a fields array"));
244
+ return createAiChatLiveProvider({
245
+ endpoint,
246
+ headers: { ...headers },
247
+ survey: survey?.fields,
248
+ yes: typeof survey?.yes === "string" ? survey.yes : void 0,
249
+ no: typeof survey?.no === "string" ? survey.no : void 0
250
+ });
251
+ }
230
252
  //#endregion
231
- export { createAiChatLiveProvider };
253
+ export { createAiChatLiveProvider, liveChatFromRoot };
@@ -0,0 +1,163 @@
1
+ /*
2
+ * @vettvangur/ai-sdk/styles.css: an opt-in base for the elements the SDK renders. It holds the
3
+ * mechanics a thread needs to behave, not a look: how things hide, pulse, divide, scroll and
4
+ * switch. Colours, type and spacing stay with the host. Load it before the host's own styles; its
5
+ * selectors are as plain as each rule allows, so a later host rule of the same weight wins.
6
+ *
7
+ * Custom properties, set on the root or any ancestor:
8
+ * --vv-ai-chat-dot-size the tool and typing dots (0.375rem)
9
+ * --vv-ai-chat-dot-color the typing dots (currentColor)
10
+ * --vv-ai-chat-divider-color the lines either side of a divider notice (currentColor)
11
+ * --vv-ai-chat-divider-gap between a divider's text and its lines (0.625rem)
12
+ * --vv-ai-survey-toggle-width the survey's switch (2.125rem)
13
+ * --vv-ai-survey-toggle-height (1.25rem)
14
+ * --vv-ai-survey-toggle-inset between the switch's edge and its knob (0.125rem)
15
+ * --vv-ai-survey-toggle-off the switch's track when off (#9ca3af)
16
+ * --vv-ai-survey-toggle-on the switch's track when on (currentColor)
17
+ * --vv-ai-survey-toggle-knob the knob (#fff)
18
+ */
19
+
20
+ /* What the binding shows and hides with `hidden` stays hidden whatever display a host gives it. */
21
+ [data-ai-chat-send][hidden],
22
+ [data-ai-chat-stop][hidden],
23
+ [data-ai-chat-end][hidden],
24
+ [data-ai-launcher-teaser][hidden],
25
+ .vv-ai-survey__error[hidden] {
26
+ display: none !important;
27
+ }
28
+
29
+ /* A tool's progress dot pulses until the tool is done; the agent's typing dots pulse in turn. */
30
+ .vv-ai-chat__tool-dot,
31
+ .vv-ai-chat__typing-dot {
32
+ flex-shrink: 0;
33
+ width: var(--vv-ai-chat-dot-size, 0.375rem);
34
+ height: var(--vv-ai-chat-dot-size, 0.375rem);
35
+ border-radius: 50%;
36
+ animation: vv-ai-chat-pulse 1.2s ease-in-out infinite;
37
+ }
38
+
39
+ .vv-ai-chat__typing-dot {
40
+ background: var(--vv-ai-chat-dot-color, currentColor);
41
+ }
42
+
43
+ .vv-ai-chat__typing-dot:nth-child(2) {
44
+ animation-delay: 0.15s;
45
+ }
46
+
47
+ .vv-ai-chat__typing-dot:nth-child(3) {
48
+ animation-delay: 0.3s;
49
+ }
50
+
51
+ .vv-ai-chat__tool--done .vv-ai-chat__tool-dot {
52
+ animation: none;
53
+ }
54
+
55
+ @keyframes vv-ai-chat-pulse {
56
+ 0%,
57
+ 100% {
58
+ opacity: 0.3;
59
+ }
60
+
61
+ 50% {
62
+ opacity: 1;
63
+ }
64
+ }
65
+
66
+ /* The typing indicator's text is for screen readers; the dots show it. */
67
+ .vv-ai-chat__typing-label {
68
+ position: absolute;
69
+ width: 1px;
70
+ height: 1px;
71
+ margin: -1px;
72
+ padding: 0;
73
+ overflow: hidden;
74
+ clip-path: inset(50%);
75
+ white-space: nowrap;
76
+ border: 0;
77
+ }
78
+
79
+ /* Who answers from here on: a divider, its text between two lines. */
80
+ .vv-ai-chat__notice--started,
81
+ .vv-ai-chat__notice--joined,
82
+ .vv-ai-chat__notice--agent-ended,
83
+ .vv-ai-chat__notice--ended,
84
+ .vv-ai-chat__notice--system {
85
+ display: flex;
86
+ align-items: center;
87
+ gap: var(--vv-ai-chat-divider-gap, 0.625rem);
88
+ text-align: center;
89
+ }
90
+
91
+ .vv-ai-chat__notice--started::before,
92
+ .vv-ai-chat__notice--started::after,
93
+ .vv-ai-chat__notice--joined::before,
94
+ .vv-ai-chat__notice--joined::after,
95
+ .vv-ai-chat__notice--agent-ended::before,
96
+ .vv-ai-chat__notice--agent-ended::after,
97
+ .vv-ai-chat__notice--ended::before,
98
+ .vv-ai-chat__notice--ended::after,
99
+ .vv-ai-chat__notice--system::before,
100
+ .vv-ai-chat__notice--system::after {
101
+ content: "";
102
+ flex: 1;
103
+ height: 1px;
104
+ background: var(--vv-ai-chat-divider-color, currentColor);
105
+ }
106
+
107
+ /* A wide table scrolls inside its own region, and the scroll does not carry on into the page. */
108
+ .vv-ai-answer-card__table-region {
109
+ max-width: 100%;
110
+ overflow-x: auto;
111
+ overscroll-behavior-x: contain;
112
+ }
113
+
114
+ /*
115
+ * The survey's yes-or-no question as a switch. The input selector outweighs a host's own rule for
116
+ * every survey input, which would otherwise draw the switch as a text box.
117
+ */
118
+ .vv-ai-survey__field--toggle .vv-ai-survey__input[type="checkbox"] {
119
+ position: relative;
120
+ flex-shrink: 0;
121
+ width: var(--vv-ai-survey-toggle-width, 2.125rem);
122
+ height: var(--vv-ai-survey-toggle-height, 1.25rem);
123
+ margin: 0;
124
+ padding: 0;
125
+ cursor: pointer;
126
+ appearance: none;
127
+ background: var(--vv-ai-survey-toggle-off, #9ca3af);
128
+ border: 0;
129
+ border-radius: calc(var(--vv-ai-survey-toggle-height, 1.25rem) / 2);
130
+ transition: background-color 0.2s ease;
131
+ }
132
+
133
+ .vv-ai-survey__field--toggle .vv-ai-survey__input[type="checkbox"]::after {
134
+ content: "";
135
+ position: absolute;
136
+ top: var(--vv-ai-survey-toggle-inset, 0.125rem);
137
+ left: var(--vv-ai-survey-toggle-inset, 0.125rem);
138
+ width: calc(var(--vv-ai-survey-toggle-height, 1.25rem) - 2 * var(--vv-ai-survey-toggle-inset, 0.125rem));
139
+ height: calc(var(--vv-ai-survey-toggle-height, 1.25rem) - 2 * var(--vv-ai-survey-toggle-inset, 0.125rem));
140
+ background: var(--vv-ai-survey-toggle-knob, #fff);
141
+ border-radius: 50%;
142
+ transition: transform 0.2s ease;
143
+ }
144
+
145
+ .vv-ai-survey__field--toggle .vv-ai-survey__input[type="checkbox"]:checked {
146
+ background: var(--vv-ai-survey-toggle-on, currentColor);
147
+ }
148
+
149
+ .vv-ai-survey__field--toggle .vv-ai-survey__input[type="checkbox"]:checked::after {
150
+ transform: translateX(calc(var(--vv-ai-survey-toggle-width, 2.125rem) - var(--vv-ai-survey-toggle-height, 1.25rem)));
151
+ }
152
+
153
+ @media (prefers-reduced-motion: reduce) {
154
+ .vv-ai-chat__tool-dot,
155
+ .vv-ai-chat__typing-dot {
156
+ animation: none;
157
+ }
158
+
159
+ .vv-ai-survey__field--toggle .vv-ai-survey__input[type="checkbox"],
160
+ .vv-ai-survey__field--toggle .vv-ai-survey__input[type="checkbox"]::after {
161
+ transition: none;
162
+ }
163
+ }