@vettvangur/ai-sdk 0.7.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -153,7 +153,14 @@ takes it, which the provider reports through its optional `onAgent`, or the firs
153
153
  does. Then an `__notice--joined` divider names them, the `agent` event fires, `data-ai-chat-live`
154
154
  on the root goes from `waiting` to `agent`, and elements marked `data-ai-chat-agent-name` and
155
155
  `data-ai-chat-agent-initials` are filled in. An agent's messages are `__message--person` with
156
- `__initials` and a `__sender` (their first name, then the `live-chat-team` label when set); the
156
+ `__initials` and a `__sender` (their first name, then the `live-chat-team` label when set), and
157
+ the buttons a message carries (`actions`) in its `__text` bubble (or in the message when it has
158
+ no text) in `renderActions` markup, the first primary. A
159
+ link button opens in a new tab. A `sheet` button opens its page in a `__sheet` dialog appended to
160
+ the root: a `__sheet-header` with a `__sheet-title` (the button's text) and a `__sheet-close`
161
+ button (the `sheet-close` label), and the page in a `__sheet-frame`. Escape closes it too, and
162
+ focus goes back to the button. A provider with `connectSheet(frame, { send, close })` connects the
163
+ page to its own app protocol, so the page can send the visitor's message and close the sheet. The
157
164
  provider's own messages are `__notice--system`. While live the input shows its
158
165
  `data-ai-chat-live-placeholder`, and while the survey is asked its
159
166
  `data-ai-chat-handover-placeholder`. When the agent ends the chat (an `__notice--agent-ended` divider),
@@ -167,7 +174,7 @@ binding read. `binding.liveChat` is the provider in use, for a host to offer its
167
174
  `live-chat-typing`, `live-chat-agent`, `live-chat-started`, `live-chat-joined` and
168
175
  `live-chat-agent-ended` (with `{name}`), `live-chat-waiting`, `live-chat-waiting-text`,
169
176
  `live-chat-team`, `survey-title`, `survey-intro`, `survey-prefilled`, `survey-submit`,
170
- `survey-cancel`, `survey-required`, `survey-invalid-email`.
177
+ `survey-cancel`, `survey-required`, `survey-invalid-email`, `sheet-close`.
171
178
 
172
179
  `@vettvangur/ai-sdk/live-chat` exports the provider contract (`AiLiveChatProvider`) and
173
180
  `renderSurveyForm`. `@vettvangur/ai-sdk/live-chat/omnichannel` exports
@@ -187,6 +194,28 @@ chat.on('end', ({ reason }) => track('chat_end', reason))
187
194
  await chat.handover({ context: { aiShipment: 'L26000008' }, prefill: { Email: email } })
188
195
  ```
189
196
 
197
+ `@vettvangur/ai-sdk/live-chat/livechat` exports `createLiveChatProvider({ organizationId, clientId,
198
+ groupId })` over LiveChat (livechat.com). `clientId` is a "Web app" client from the LiveChat
199
+ Developer Console with the `customers:own` scope, and chats go to `groupId`, or LiveChat's default
200
+ group without one. It needs the optional peer dependency `@livechat/customer-sdk` and connects only
201
+ when the provider is first used. It reports `no-agents` while LiveChat says the group is offline,
202
+ asks the group's pre-chat form (a header becomes a note, a group chooser routes the chat) and hands
203
+ the answers to the agent as a filled form, sets the visitor's name and email from the form's name
204
+ and email fields (prefill them as `name` and `email`), and gives the agent the handover context as
205
+ session fields. Agents see what the visitor types through `draft`. LiveChat allows a visitor one
206
+ chat, so a second handover starts a new thread in it; the resume token is the chat id. A form with
207
+ any field the window cannot ask, such as a rating, is refused rather than shortened. An agent's
208
+ card (a rich message) shows as its titles and subtitles with its `url` and `webview` buttons; a
209
+ webview button opens in the sheet, where the provider hosts LiveChat's Moments protocol, so an agent
210
+ app such as a sign-in works as it does in LiveChat's own widget: its `sendMessage` goes into the
211
+ chat as the visitor's message and its `close` closes the sheet.
212
+
213
+ ```ts
214
+ import { createLiveChatProvider } from '@vettvangur/ai-sdk/live-chat/livechat'
215
+
216
+ const liveChat = createLiveChatProvider({ organizationId, clientId })
217
+ ```
218
+
190
219
  `@vettvangur/ai-sdk/live-chat/aichat` exports `createAiChatLiveProvider({ endpoint, headers })` for
191
220
  sites without a contact centre: agents answer from the Live view of the Vettvangur.AiChat backoffice
192
221
  section. `endpoint` is the prefix the site maps with `MapAiChat`, and `headers` go with every
@@ -292,7 +321,9 @@ needs, not a look. It keeps `hidden` on `data-ai-chat-send`, `-stop`, `-end`,
292
321
  `data-ai-launcher-teaser` and survey errors whatever display a host gives them, pulses the tool and
293
322
  typing dots (and stops under reduced motion), hides the typing label for all but screen readers,
294
323
  draws the `started`, `joined`, `agent-ended`, `ended` and `system` notices as dividers, scrolls a
295
- wide answer-card table inside its region, and draws the survey's toggle as a switch. Load it before
324
+ wide answer-card table inside its region, draws the survey's toggle as a switch, and lays a sheet
325
+ over the root, its frame filling what the header leaves. The root needs a position for the sheet to
326
+ cover it. Load it before
296
327
  the host's own styles; its selectors are as plain as each rule allows, so a later host rule of the
297
328
  same weight wins. Colours and sizes come from custom properties, set on the root or any ancestor:
298
329
 
@@ -304,6 +335,7 @@ same weight wins. Colours and sizes come from custom properties, set on the root
304
335
  | `--vv-ai-chat-divider-gap` | `0.625rem` |
305
336
  | `--vv-ai-survey-toggle-width`, `-height`, `-inset` | `2.125rem`, `1.25rem`, `0.125rem` |
306
337
  | `--vv-ai-survey-toggle-off`, `-on`, `-knob` | `#9ca3af`, `currentColor`, `#fff` |
338
+ | `--vv-ai-chat-sheet-background` | `#fff` |
307
339
 
308
340
  The package accepts protocol-v1 events (`delta`, `tool`, `tool_result`, `tool_done`, `suggestions`,
309
341
  `done` with an optional `turn` token, and `error`) and ignores any other. Host-specific card
@@ -1,4 +1,4 @@
1
- import { a as AiLiveChatProvider, t as AiLiveChatAnswers } from "./provider.js";
1
+ import { n as AiLiveChatAnswers, o as AiLiveChatProvider } from "./provider.js";
2
2
  //#region src/contracts.d.ts
3
3
  type AiChatMessage = {
4
4
  role: 'user' | 'assistant';
@@ -152,6 +152,8 @@ type AiChatLabels = AiAnswerCardLabels & {
152
152
  surveyIntro: string;
153
153
  /** Under a field the host's prefill filled in, when not empty. */
154
154
  surveyPrefilled: string;
155
+ /** The button that closes a page an agent's message opened in a sheet over the thread. */
156
+ sheetClose: string;
155
157
  error: string;
156
158
  timeout: string;
157
159
  toolRunning: string;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as AiLiveChatProvider, i as AiLiveChatMessage, n as AiLiveChatAvailability, o as AiLiveChatStartOptions, s as AiLiveChatSurveyField, t as AiLiveChatAnswers } from "./provider.js";
1
+ import { a as AiLiveChatMessage, c as AiLiveChatStartOptions, l as AiLiveChatSurveyField, n as AiLiveChatAnswers, o as AiLiveChatProvider, r as AiLiveChatAvailability, s as AiLiveChatSheetHost, t as AiLiveChatAction } from "./provider.js";
2
2
  import { A as AiHandoverPayload, C as AiChatSession, D as AiChatStreamEvent, E as AiChatSessionStatus, M as AiLiveChatFactoryContext, N as AiTemplateItemSurfaceOptions, O as AiChatSurface, P as AiTemplateUrlSurfaceOptions, S as AiChatRequest, T as AiChatSessionResult, _ as AiChatLabels, a as AiAnswerCardSection, b as AiChatRegistry, c as AiChatAction, d as AiChatBindings, f as AiChatContext, g as AiChatHandoverResult, h as AiChatHandoverOptions, i as AiAnswerCardLink, j as AiLauncherTeaserOptions, k as AiFormContextOptions, l as AiChatActionItem, m as AiChatExtensionContext, n as AiAnswerCardFact, o as AiAnswerCardTable, p as AiChatEventMap, r as AiAnswerCardLabels, s as AiCardImage, t as AiAnswerCard, u as AiChatBinding, v as AiChatMessage, w as AiChatSessionOptions, x as AiChatRenderer, y as AiChatMode } from "./contracts.js";
3
3
  //#region src/answer-card.d.ts
4
4
  declare const MAX_ANSWER_CARD_SECTIONS = 12;
@@ -133,4 +133,4 @@ declare function bindChatWindow(binding: AiChatBinding): () => void;
133
133
  */
134
134
  declare function bindLauncherTeaser(binding: AiChatBinding, container: ParentNode, options?: AiLauncherTeaserOptions): () => void;
135
135
  //#endregion
136
- export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, type AiAnswerCard, type AiAnswerCardFact, type AiAnswerCardLabels, type AiAnswerCardLink, type AiAnswerCardSection, type AiAnswerCardTable, type AiCardImage, type AiChatAction, type AiChatActionItem, type AiChatBinding, type AiChatBindings, type AiChatContext, type AiChatEventMap, type AiChatExtensionContext, type AiChatHandoverOptions, type AiChatHandoverResult, type AiChatMessage, type AiChatMode, type AiChatRegistry, type AiChatRenderer, type AiChatRequest, type AiChatSession, type AiChatSessionOptions, type AiChatSessionResult, type AiChatSessionStatus, type AiChatStreamEvent, type AiChatSurface, type AiFormContextOptions, type AiHandoverPayload, type AiLauncherTeaserOptions, type AiLiveChatAnswers, type AiLiveChatAvailability, type AiLiveChatFactoryContext, type AiLiveChatMessage, type AiLiveChatProvider, type AiLiveChatStartOptions, type AiLiveChatSurveyField, type AiTemplateItemSurfaceOptions, type AiTemplateUrlSurfaceOptions, 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 };
136
+ export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, type AiAnswerCard, type AiAnswerCardFact, type AiAnswerCardLabels, type AiAnswerCardLink, type AiAnswerCardSection, type AiAnswerCardTable, type AiCardImage, type AiChatAction, type AiChatActionItem, type AiChatBinding, type AiChatBindings, type AiChatContext, type AiChatEventMap, type AiChatExtensionContext, type AiChatHandoverOptions, type AiChatHandoverResult, type AiChatMessage, type AiChatMode, type AiChatRegistry, type AiChatRenderer, type AiChatRequest, type AiChatSession, type AiChatSessionOptions, type AiChatSessionResult, type AiChatSessionStatus, type AiChatStreamEvent, type AiChatSurface, type AiFormContextOptions, type AiHandoverPayload, type AiLauncherTeaserOptions, type AiLiveChatAction, type AiLiveChatAnswers, type AiLiveChatAvailability, type AiLiveChatFactoryContext, type AiLiveChatMessage, type AiLiveChatProvider, type AiLiveChatSheetHost, type AiLiveChatStartOptions, type AiLiveChatSurveyField, type AiTemplateItemSurfaceOptions, type AiTemplateUrlSurfaceOptions, 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 };
package/dist/index.js CHANGED
@@ -364,6 +364,61 @@ function assertAnswerCardContract(card) {
364
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
365
  }
366
366
  //#endregion
367
+ //#region src/cards.ts
368
+ /** Block classes of the cards below. Every element a card renders carries a class under its block. */
369
+ const CARD_LIST_CLASS = "vv-ai-card-list";
370
+ const ACTIONS_CLASS = "vv-ai-actions";
371
+ function text(value) {
372
+ return typeof value === "string" && value.trim() ? value : null;
373
+ }
374
+ /**
375
+ * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
376
+ * Items that render nothing are skipped, and a list with nothing in it is null.
377
+ */
378
+ function renderCardList(document, items, render, modifier) {
379
+ if (!Array.isArray(items)) return null;
380
+ const cards = items.map(render).filter((card) => card !== null);
381
+ if (!cards.length) return null;
382
+ const list = createPart(document, "div", CARD_LIST_CLASS);
383
+ if (modifier) list.classList.add(`${CARD_LIST_CLASS}--${modifier}`);
384
+ list.append(...cards);
385
+ return list;
386
+ }
387
+ /**
388
+ * A row of things the visitor can do next. An item with `action` is a button that runs the action
389
+ * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
390
+ * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
391
+ */
392
+ function renderActions(document, items) {
393
+ const elements = [];
394
+ for (const item of items) {
395
+ const label = text(item?.label);
396
+ if (!label) continue;
397
+ let element = null;
398
+ const action = text(item.action);
399
+ const url = text(item.url);
400
+ if (action) {
401
+ const button = createPart(document, "button", ACTIONS_CLASS, "action", label);
402
+ button.type = "button";
403
+ button.dataset.aiAction = action;
404
+ const value = text(item.value);
405
+ if (value) button.dataset.aiActionValue = value;
406
+ element = button;
407
+ } else if (url) {
408
+ element = createSafeLink(document, label, url.trim());
409
+ if (element) element.className = `${ACTIONS_CLASS}__action`;
410
+ }
411
+ if (element) {
412
+ element.classList.add(`${ACTIONS_CLASS}__action--${item.primary ? "primary" : "secondary"}`);
413
+ elements.push(element);
414
+ }
415
+ }
416
+ if (!elements.length) return null;
417
+ const actions = createPart(document, "div", ACTIONS_CLASS);
418
+ actions.append(...elements);
419
+ return actions;
420
+ }
421
+ //#endregion
367
422
  //#region src/protocol.ts
368
423
  const AI_CHAT_PROTOCOL_VERSION = 1;
369
424
  const MAX_TURN_TOKEN_LENGTH = 1024;
@@ -678,61 +733,6 @@ function createChatSession(options) {
678
733
  return session;
679
734
  }
680
735
  //#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
736
  //#region src/handover.ts
737
737
  /** The action the handover card's button runs; the binding hands over to a person with it. */
738
738
  const LIVE_CHAT_ACTION = "livechat";
@@ -784,6 +784,60 @@ function registryEntries(registry) {
784
784
  return registry ? entries.get(registry) : void 0;
785
785
  }
786
786
  //#endregion
787
+ //#region src/sheet.ts
788
+ /** The `data-ai-action` of a button that opens its `data-ai-action-value` in a sheet. */
789
+ const SHEET_ACTION = "sheet";
790
+ const SHEET_CLASS = "vv-ai-chat";
791
+ /**
792
+ * A page in a sheet over the chat: a dialog with a title, a close button and the page in a frame,
793
+ * appended to `root`. Escape closes it too, and focus goes back to where it was. Null for a URL
794
+ * a link could not open either.
795
+ */
796
+ function openSheet(root, options) {
797
+ if (!isSafeLinkUrl(options.url)) return null;
798
+ const document = root.ownerDocument;
799
+ const returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
800
+ const titleId = `vv-ai-chat-sheet-${crypto.randomUUID()}`;
801
+ const sheet = createPart(document, "div", SHEET_CLASS, "sheet");
802
+ sheet.dataset.aiChatSheet = "";
803
+ sheet.setAttribute("role", "dialog");
804
+ sheet.setAttribute("aria-modal", "true");
805
+ sheet.setAttribute("aria-labelledby", titleId);
806
+ const header = createPart(document, "div", SHEET_CLASS, "sheet-header");
807
+ const title = createPart(document, "p", SHEET_CLASS, "sheet-title", options.title);
808
+ title.id = titleId;
809
+ const close = createPart(document, "button", SHEET_CLASS, "sheet-close", options.closeLabel);
810
+ close.type = "button";
811
+ header.append(title, close);
812
+ const frame = createPart(document, "iframe", SHEET_CLASS, "sheet-frame");
813
+ frame.title = options.title;
814
+ frame.src = options.url;
815
+ sheet.append(header, frame);
816
+ let open = true;
817
+ function dismiss() {
818
+ if (!open) return;
819
+ open = false;
820
+ sheet.removeEventListener("keydown", keydown);
821
+ sheet.remove();
822
+ returnFocus?.focus({ preventScroll: true });
823
+ options.onClose();
824
+ }
825
+ function keydown(event) {
826
+ if (event.key === "Escape") {
827
+ event.stopPropagation();
828
+ dismiss();
829
+ }
830
+ }
831
+ close.addEventListener("click", dismiss);
832
+ sheet.addEventListener("keydown", keydown);
833
+ root.append(sheet);
834
+ close.focus({ preventScroll: true });
835
+ return {
836
+ frame,
837
+ close: dismiss
838
+ };
839
+ }
840
+ //#endregion
787
841
  //#region src/thread-store.ts
788
842
  function storage() {
789
843
  try {
@@ -846,7 +900,8 @@ const defaultLabels = {
846
900
  surveyInvalidEmail: "Please enter an email address",
847
901
  surveyTitle: "",
848
902
  surveyIntro: "",
849
- surveyPrefilled: ""
903
+ surveyPrefilled: "",
904
+ sheetClose: "Close"
850
905
  };
851
906
  const NEAR_LIMIT = .9;
852
907
  const TYPING_SHOWN_MS = 5e3;
@@ -885,6 +940,10 @@ function stringRecord(value) {
885
940
  if (!isPlainObject(value)) return {};
886
941
  return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"));
887
942
  }
943
+ function storedActions(value) {
944
+ if (!Array.isArray(value)) return [];
945
+ return value.filter((item) => isPlainObject(item) && typeof item.label === "string" && typeof item.url === "string" && typeof item.sheet === "boolean");
946
+ }
888
947
  function dataString(data, name) {
889
948
  if (typeof data !== "object" || data === null || Array.isArray(data)) return null;
890
949
  const value = data[name];
@@ -937,6 +996,7 @@ function bindChat(root, options = {}) {
937
996
  let typingSentAt = 0;
938
997
  let draftTimer = null;
939
998
  let waitingCard = null;
999
+ let sheet = null;
940
1000
  const placeholder = input.placeholder;
941
1001
  const eventListeners = /* @__PURE__ */ new Map();
942
1002
  const session = createChatSession({
@@ -965,6 +1025,7 @@ function bindChat(root, options = {}) {
965
1025
  bubble.className = part("text");
966
1026
  bubble.append(renderMarkdown(root.ownerDocument, text));
967
1027
  parent.append(bubble);
1028
+ return bubble;
968
1029
  }
969
1030
  function appendStreamedMarkdown(text) {
970
1031
  if (!activeAssistant) return;
@@ -1227,7 +1288,7 @@ function bindChat(root, options = {}) {
1227
1288
  avatar.append(initials(name || labels.liveChatAgent));
1228
1289
  parent.append(avatar);
1229
1290
  }
1230
- function appendPerson(name, text) {
1291
+ function appendPerson(name, text, actions = []) {
1231
1292
  const message = appendMessage("person");
1232
1293
  appendInitials(message, name);
1233
1294
  const sender = root.ownerDocument.createElement("span");
@@ -1235,9 +1296,39 @@ function bindChat(root, options = {}) {
1235
1296
  const shown = name ? firstName(name) : labels.liveChatAgent;
1236
1297
  sender.append(labels.liveChatTeam ? `${shown} · ${labels.liveChatTeam}` : shown);
1237
1298
  message.append(sender);
1238
- appendMarkdown(message, text);
1299
+ const bubble = text ? appendMarkdown(message, text) : null;
1300
+ const buttons = renderActions(root.ownerDocument, actions.map((action, index) => action.sheet ? {
1301
+ label: action.label,
1302
+ action: SHEET_ACTION,
1303
+ value: action.url,
1304
+ primary: index === 0
1305
+ } : {
1306
+ label: action.label,
1307
+ url: action.url,
1308
+ primary: index === 0
1309
+ }));
1310
+ if (buttons) (bubble ?? message).append(buttons);
1239
1311
  scrollToEnd();
1240
1312
  }
1313
+ function showSheet(url, title) {
1314
+ sheet?.close();
1315
+ let disconnectSheet = () => {};
1316
+ const opened = openSheet(root, {
1317
+ url,
1318
+ title,
1319
+ closeLabel: labels.sheetClose,
1320
+ onClose: () => {
1321
+ disconnectSheet();
1322
+ if (sheet === opened) sheet = null;
1323
+ }
1324
+ });
1325
+ sheet = opened;
1326
+ const provider = live?.provider ?? liveChat;
1327
+ if (opened && provider?.connectSheet) disconnectSheet = provider.connectSheet(opened.frame, {
1328
+ send: sendLive,
1329
+ close: opened.close
1330
+ });
1331
+ }
1241
1332
  function notifyAgent(template, name, modifier) {
1242
1333
  const time = new Intl.DateTimeFormat(root.ownerDocument.documentElement.lang || void 0, {
1243
1334
  hour: "2-digit",
@@ -1311,7 +1402,7 @@ function bindChat(root, options = {}) {
1311
1402
  for (const item of entry.parts) if ("text" in item && typeof item.text === "string") appendMarkdown(message, item.text);
1312
1403
  else if ("result" in item && isPlainObject(item.result) && typeof item.result.name === "string") renderResult(message, item.result);
1313
1404
  appendReplyActions(message, typeof entry.turn === "string" ? entry.turn : null);
1314
- } else if (entry.kind === "person" && typeof entry.text === "string") appendPerson(typeof entry.name === "string" ? entry.name : null, entry.text);
1405
+ } else if (entry.kind === "person" && typeof entry.text === "string") appendPerson(typeof entry.name === "string" ? entry.name : null, entry.text, storedActions(entry.actions));
1315
1406
  else if (entry.kind === "notice" && typeof entry.text === "string" && typeof entry.modifier === "string") appendNotice(entry.text, entry.modifier);
1316
1407
  }
1317
1408
  const setMode = (next) => {
@@ -1339,12 +1430,13 @@ function bindChat(root, options = {}) {
1339
1430
  if (message.sender === "agent" && !live.agent) agentJoined({ name: message.name });
1340
1431
  if (message.sender === "system") notify(message.text, "system");
1341
1432
  else {
1342
- appendPerson(message.name, message.text);
1433
+ appendPerson(message.name, message.text, message.actions);
1343
1434
  record({
1344
1435
  kind: "person",
1345
1436
  id: message.id,
1346
1437
  text: message.text,
1347
- name: message.name
1438
+ name: message.name,
1439
+ ...message.actions?.length ? { actions: message.actions } : {}
1348
1440
  });
1349
1441
  }
1350
1442
  }
@@ -1497,7 +1589,10 @@ function bindChat(root, options = {}) {
1497
1589
  } catch (caught) {
1498
1590
  const error = caught instanceof Error ? caught : /* @__PURE__ */ new Error("AI chat handover failed");
1499
1591
  options.onError?.(error);
1500
- if (started) disconnect();
1592
+ if (started) {
1593
+ disconnect();
1594
+ provider.end().catch(() => void 0);
1595
+ }
1501
1596
  if (!stale()) {
1502
1597
  notify(labels.liveChatFailed, "failed");
1503
1598
  setMode("ai");
@@ -1524,11 +1619,6 @@ function bindChat(root, options = {}) {
1524
1619
  }
1525
1620
  async function sendLive(text) {
1526
1621
  if (!live) return;
1527
- if (draftTimer) {
1528
- clearTimeout(draftTimer);
1529
- draftTimer = null;
1530
- }
1531
- clearInput();
1532
1622
  clearStart();
1533
1623
  appendMarkdown(appendMessage("user"), text);
1534
1624
  record({
@@ -1543,6 +1633,11 @@ function bindChat(root, options = {}) {
1543
1633
  const question = input.value.trim();
1544
1634
  if (!question || mode === "handover") return;
1545
1635
  if (mode === "live") {
1636
+ if (draftTimer) {
1637
+ clearTimeout(draftTimer);
1638
+ draftTimer = null;
1639
+ }
1640
+ clearInput();
1546
1641
  sendLive(question).catch(report);
1547
1642
  return;
1548
1643
  }
@@ -1620,6 +1715,7 @@ function bindChat(root, options = {}) {
1620
1715
  }
1621
1716
  if (target?.closest("[data-ai-chat-reset]")) {
1622
1717
  const provider = live?.provider;
1718
+ sheet?.close();
1623
1719
  disconnect();
1624
1720
  handoverRuns += 1;
1625
1721
  pendingSurvey?.cancel();
@@ -1651,6 +1747,7 @@ function bindChat(root, options = {}) {
1651
1747
  const actionElement = target?.closest("[data-ai-action]");
1652
1748
  const action = actionElement ? registryEntries(options.registry)?.actions.get(actionElement.dataset.aiAction ?? "") : void 0;
1653
1749
  if (!action && actionElement?.dataset.aiAction === "livechat") binding.handover().catch(report);
1750
+ else if (!action && actionElement?.dataset.aiAction === "sheet") showSheet(actionElement.dataset.aiActionValue ?? "", actionElement.textContent?.trim() ?? "");
1654
1751
  else if (action && actionElement) Promise.resolve(action({
1655
1752
  root,
1656
1753
  element: actionElement,
@@ -1824,6 +1921,7 @@ function bindChat(root, options = {}) {
1824
1921
  destroy() {
1825
1922
  if (destroyed) return;
1826
1923
  destroyed = true;
1924
+ sheet?.close();
1827
1925
  pendingSurvey?.cancel();
1828
1926
  disconnect();
1829
1927
  eventListeners.clear();
@@ -1,4 +1,4 @@
1
- import { a as AiLiveChatProvider, s as AiLiveChatSurveyField } from "../provider.js";
1
+ import { l as AiLiveChatSurveyField, o as AiLiveChatProvider } from "../provider.js";
2
2
  import { M as AiLiveChatFactoryContext } from "../contracts.js";
3
3
  //#region src/live-chat/aichat.d.ts
4
4
  type AiChatLiveConfig = {
@@ -0,0 +1,18 @@
1
+ import { o as AiLiveChatProvider } from "../provider.js";
2
+ //#region src/live-chat/livechat.d.ts
3
+ type AiLiveChatConfig = {
4
+ organizationId: string;
5
+ /** A "Web app" client from the LiveChat Developer Console with the `customers:own` scope. */
6
+ clientId: string;
7
+ /** The group chats go to; LiveChat's default group when not given. */
8
+ groupId?: number;
9
+ };
10
+ /**
11
+ * A live chat provider over LiveChat (livechat.com), through `@livechat/customer-sdk`. The SDK is
12
+ * imported and connected the first time the provider is asked anything, so a page pays for it only
13
+ * when a visitor asks for a person. LiveChat keeps the visitor's identity in the browser and allows
14
+ * them one chat, which a later handover starts a new thread in.
15
+ */
16
+ declare function createLiveChatProvider(config: AiLiveChatConfig): AiLiveChatProvider;
17
+ //#endregion
18
+ export { AiLiveChatConfig, createLiveChatProvider };
@@ -0,0 +1,534 @@
1
+ //#region src/live-chat/moments.ts
2
+ const FINGERPRINT = "@@livechat/postmessenger";
3
+ const FOUR_WAY_HANDSHAKE = "@@livechat/4way";
4
+ const HANDSHAKE_INTERVAL_MS = 500;
5
+ const HANDSHAKE_TRIES = 10;
6
+ const ECHO_REQUEST = 0;
7
+ const SUPPORTED_METHODS = ["sendMessage", "close"];
8
+ function isEnvelope(value, owner) {
9
+ return typeof value === "object" && value !== null && value[FINGERPRINT] === true && value.owner === owner && value.instance === 0;
10
+ }
11
+ function call(data) {
12
+ if (typeof data !== "object" || data === null) return null;
13
+ const { method, args } = data;
14
+ return typeof method === "string" ? {
15
+ method,
16
+ args: Array.isArray(args) ? args : []
17
+ } : null;
18
+ }
19
+ function messageText(arg) {
20
+ const text = typeof arg === "object" && arg !== null ? arg.text : null;
21
+ return typeof text === "string" ? text.trim() : "";
22
+ }
23
+ /**
24
+ * Hosts a LiveChat Moments app in `frame`: its `sendMessage` goes into the chat as the visitor's
25
+ * message and its `close` closes the sheet. A page that is not a Moments app never answers the
26
+ * handshake and is left alone. Each load of the frame is a new handshake. Returns a disconnect.
27
+ */
28
+ function hostMoments(frame, host) {
29
+ const view = frame.ownerDocument.defaultView;
30
+ if (!view) return () => {};
31
+ const owner = crypto.randomUUID();
32
+ const origin = new URL(frame.src, frame.ownerDocument.baseURI).origin;
33
+ let state = "handshake";
34
+ let timer = null;
35
+ function post(message) {
36
+ frame.contentWindow?.postMessage(message, origin);
37
+ }
38
+ function envelope(type, data, request) {
39
+ return {
40
+ [FINGERPRINT]: true,
41
+ owner,
42
+ instance: 0,
43
+ type,
44
+ data,
45
+ request
46
+ };
47
+ }
48
+ function stopHandshake() {
49
+ if (timer) clearInterval(timer);
50
+ timer = null;
51
+ }
52
+ function handshake() {
53
+ stopHandshake();
54
+ state = "handshake";
55
+ let tries = 0;
56
+ const send = () => {
57
+ tries += 1;
58
+ if (state !== "handshake" || tries > HANDSHAKE_TRIES) {
59
+ stopHandshake();
60
+ return;
61
+ }
62
+ post(envelope("handshake", { supportedMethods: SUPPORTED_METHODS }, null));
63
+ };
64
+ send();
65
+ timer = setInterval(send, HANDSHAKE_INTERVAL_MS);
66
+ }
67
+ async function run(method, args) {
68
+ switch (method) {
69
+ case "sendMessage": {
70
+ const text = messageText(args[0]);
71
+ if (text) await host.send(text);
72
+ return null;
73
+ }
74
+ case "close":
75
+ host.close();
76
+ return null;
77
+ default: throw new Error(`The chat window does not support ${method}`);
78
+ }
79
+ }
80
+ function receive(event) {
81
+ if (event.source !== frame.contentWindow || event.origin !== origin || !isEnvelope(event.data, owner)) return;
82
+ const message = event.data;
83
+ if (message.type === "response" && state === "handshake" && message.request === null) {
84
+ stopHandshake();
85
+ const result = message.data?.result;
86
+ if (typeof result === "object" && result !== null && FOUR_WAY_HANDSHAKE in result) {
87
+ state = "echo";
88
+ post(envelope("handshake_echo", void 0, ECHO_REQUEST));
89
+ } else state = "connected";
90
+ return;
91
+ }
92
+ if (message.type === "response" && state === "echo" && message.request === ECHO_REQUEST) {
93
+ state = "connected";
94
+ return;
95
+ }
96
+ const request = message.type === "call" && state === "connected" ? call(message.data) : null;
97
+ if (!request) return;
98
+ run(request.method, request.args).then((result) => {
99
+ post(envelope("response", {
100
+ error: false,
101
+ result
102
+ }, message.request ?? null));
103
+ }, (caught) => {
104
+ post(envelope("response", {
105
+ error: true,
106
+ result: {
107
+ real: true,
108
+ error: { message: caught instanceof Error ? caught.message : String(caught) }
109
+ }
110
+ }, message.request ?? null));
111
+ });
112
+ }
113
+ view.addEventListener("message", receive);
114
+ frame.addEventListener("load", handshake);
115
+ return () => {
116
+ stopHandshake();
117
+ view.removeEventListener("message", receive);
118
+ frame.removeEventListener("load", handshake);
119
+ };
120
+ }
121
+ //#endregion
122
+ //#region src/live-chat/livechat.ts
123
+ function on(sdk, method, type, handler) {
124
+ sdk[method](type, handler);
125
+ }
126
+ function chosenOptions(options, answer) {
127
+ if (typeof answer !== "string" || !answer) return [];
128
+ const ids = answer.split(",");
129
+ return options.filter((option) => ids.includes(option.id));
130
+ }
131
+ function surveyField(field) {
132
+ switch (field.type) {
133
+ case "header": return field.label.trim() ? {
134
+ kind: "note",
135
+ text: field.label
136
+ } : null;
137
+ case "name":
138
+ case "email": return {
139
+ kind: "text",
140
+ id: field.id,
141
+ name: field.type,
142
+ label: field.label,
143
+ required: field.required,
144
+ inputType: field.type === "email" ? "email" : "text",
145
+ multiline: false,
146
+ maxLength: null,
147
+ placeholder: null
148
+ };
149
+ case "question":
150
+ case "subject":
151
+ case "textarea": return {
152
+ kind: "text",
153
+ id: field.id,
154
+ name: field.id,
155
+ label: field.label,
156
+ required: field.required,
157
+ inputType: "text",
158
+ multiline: field.type === "textarea",
159
+ maxLength: null,
160
+ placeholder: null
161
+ };
162
+ case "radio":
163
+ case "select":
164
+ case "checkbox":
165
+ case "group_chooser": return {
166
+ kind: "choice",
167
+ id: field.id,
168
+ name: field.id,
169
+ label: field.label,
170
+ required: field.required,
171
+ multiple: field.type === "checkbox",
172
+ choices: field.options.map((option) => ({
173
+ label: option.label,
174
+ value: option.id
175
+ }))
176
+ };
177
+ case "checkbox_for_email": return {
178
+ kind: "toggle",
179
+ id: field.id,
180
+ name: field.id,
181
+ label: field.label,
182
+ required: field.required
183
+ };
184
+ default: throw new Error(`LiveChat pre-chat form has a ${field.type} field the window cannot ask`);
185
+ }
186
+ }
187
+ /** The pre-chat form's fields as the window asks them; a header becomes a note. */
188
+ function surveyFieldsFromForm(form) {
189
+ return form.fields.map(surveyField).filter((field) => field !== null);
190
+ }
191
+ /** The answers as the `filled_form` event LiveChat shows the agent at the top of the chat. */
192
+ function filledFormFields(form, answers) {
193
+ const filled = [];
194
+ for (const field of form.fields) {
195
+ const answer = answers[field.id];
196
+ switch (field.type) {
197
+ case "name":
198
+ case "email":
199
+ case "question":
200
+ case "subject":
201
+ case "textarea":
202
+ if (typeof answer === "string" && answer.trim()) filled.push({
203
+ type: field.type,
204
+ id: field.id,
205
+ label: field.label,
206
+ answer: answer.trim()
207
+ });
208
+ break;
209
+ case "radio":
210
+ case "select": {
211
+ const [option] = chosenOptions(field.options, answer);
212
+ if (option) filled.push({
213
+ type: field.type,
214
+ id: field.id,
215
+ label: field.label,
216
+ answer: {
217
+ id: option.id,
218
+ label: option.label
219
+ }
220
+ });
221
+ break;
222
+ }
223
+ case "checkbox": {
224
+ const options = chosenOptions(field.options, answer);
225
+ if (options.length) filled.push({
226
+ type: "checkbox",
227
+ id: field.id,
228
+ label: field.label,
229
+ answers: options.map((option) => ({
230
+ id: option.id,
231
+ label: option.label
232
+ }))
233
+ });
234
+ break;
235
+ }
236
+ case "group_chooser": {
237
+ const [option] = chosenOptions(field.options, answer);
238
+ if (option) filled.push({
239
+ type: "group_chooser",
240
+ id: field.id,
241
+ label: field.label,
242
+ answer: {
243
+ id: option.id,
244
+ label: option.label,
245
+ groupId: option.groupId
246
+ }
247
+ });
248
+ break;
249
+ }
250
+ case "checkbox_for_email": filled.push({
251
+ type: "checkbox_for_email",
252
+ id: field.id,
253
+ label: field.label,
254
+ answer: answer === true
255
+ });
256
+ }
257
+ }
258
+ return filled;
259
+ }
260
+ /**
261
+ * A rich message as an agent message: each card's title and subtitle as its text, and its link
262
+ * buttons as its buttons. A webview button, such as an agent app's sign-in, opens in a sheet over
263
+ * the thread, as LiveChat's own widget does; buttons that post back to the agent are left out.
264
+ */
265
+ function richMessage(event) {
266
+ const parts = [];
267
+ const actions = [];
268
+ for (const element of event.elements) {
269
+ if (element.title?.trim()) parts.push(`**${element.title.trim()}**`);
270
+ if (element.subtitle?.trim()) parts.push(element.subtitle.trim());
271
+ for (const button of element.buttons ?? []) if ((button.type === "url" || button.type === "open_external" || button.type === "webview") && button.text.trim()) actions.push({
272
+ label: button.text.trim(),
273
+ url: button.value,
274
+ sheet: button.type === "webview"
275
+ });
276
+ }
277
+ return {
278
+ text: parts.join("\n\n"),
279
+ actions
280
+ };
281
+ }
282
+ function errorCode(caught) {
283
+ return caught && typeof caught === "object" && "code" in caught ? String(caught.code) : null;
284
+ }
285
+ /**
286
+ * A live chat provider over LiveChat (livechat.com), through `@livechat/customer-sdk`. The SDK is
287
+ * imported and connected the first time the provider is asked anything, so a page pays for it only
288
+ * when a visitor asks for a person. LiveChat keeps the visitor's identity in the browser and allows
289
+ * them one chat, which a later handover starts a new thread in.
290
+ */
291
+ function createLiveChatProvider(config) {
292
+ const messageListeners = /* @__PURE__ */ new Set();
293
+ const typingListeners = /* @__PURE__ */ new Set();
294
+ const endedListeners = /* @__PURE__ */ new Set();
295
+ const agentListeners = /* @__PURE__ */ new Set();
296
+ const agentNames = /* @__PURE__ */ new Map();
297
+ let connection = null;
298
+ let customerId = null;
299
+ let online = false;
300
+ let form = null;
301
+ let current = null;
302
+ function agentJoined(user) {
303
+ if (user.type !== "agent") return;
304
+ agentNames.set(user.id, user.name);
305
+ for (const listener of agentListeners) listener({ name: user.name.trim() || null });
306
+ }
307
+ function receive(event) {
308
+ if (!event || event.authorId === customerId) return;
309
+ if (event.type !== "message" && event.type !== "system_message" && event.type !== "rich_message") return;
310
+ const { text, actions } = event.type === "rich_message" ? richMessage(event) : {
311
+ text: event.text.trim(),
312
+ actions: []
313
+ };
314
+ if (!text && !actions.length) return;
315
+ const system = event.type === "system_message";
316
+ const item = {
317
+ id: event.id,
318
+ text,
319
+ sender: system ? "system" : "agent",
320
+ name: system ? null : agentNames.get(event.authorId)?.trim() || null,
321
+ ...actions.length ? { actions } : {}
322
+ };
323
+ for (const listener of messageListeners) listener(item);
324
+ }
325
+ function listen(sdk) {
326
+ on(sdk, "on", "availability_updated", ({ availability }) => {
327
+ online = availability === "online";
328
+ });
329
+ on(sdk, "on", "incoming_event", ({ chatId, event }) => {
330
+ if (chatId === current?.chatId) receive(event);
331
+ });
332
+ on(sdk, "on", "incoming_typing_indicator", ({ chatId, typingIndicator }) => {
333
+ if (chatId !== current?.chatId || !typingIndicator.isTyping || typingIndicator.authorId === customerId) return;
334
+ for (const listener of typingListeners) listener();
335
+ });
336
+ on(sdk, "on", "user_added_to_chat", ({ chatId, user }) => {
337
+ if (chatId === current?.chatId) agentJoined(user);
338
+ });
339
+ on(sdk, "on", "chat_deactivated", ({ chatId }) => {
340
+ if (chatId !== current?.chatId) return;
341
+ current = null;
342
+ for (const listener of endedListeners) listener();
343
+ });
344
+ }
345
+ function load() {
346
+ if (connection) return connection;
347
+ const pending = (async () => {
348
+ const sdk = (await import("@livechat/customer-sdk")).init({
349
+ organizationId: config.organizationId,
350
+ clientId: config.clientId,
351
+ ...config.groupId === void 0 ? {} : { groupId: config.groupId }
352
+ });
353
+ try {
354
+ await new Promise((resolve, reject) => {
355
+ on(sdk, "once", "connected", ({ customer, availability }) => {
356
+ customerId = customer.id;
357
+ online = availability === "online";
358
+ resolve();
359
+ });
360
+ on(sdk, "once", "disconnected", ({ reason }) => {
361
+ reject(/* @__PURE__ */ new Error(`LiveChat could not connect: ${reason}`));
362
+ });
363
+ });
364
+ } catch (caught) {
365
+ sdk.destroy();
366
+ throw caught;
367
+ }
368
+ listen(sdk);
369
+ return sdk;
370
+ })();
371
+ pending.catch(() => {
372
+ if (connection === pending) connection = null;
373
+ });
374
+ connection = pending;
375
+ return pending;
376
+ }
377
+ function adopt(chatId, thread, users, replay) {
378
+ current = {
379
+ chatId,
380
+ threadId: thread.id
381
+ };
382
+ for (const user of users) if (user.type === "agent" && user.present) agentJoined(user);
383
+ if (replay) for (const event of thread.events) receive(event);
384
+ }
385
+ return {
386
+ async availability() {
387
+ await load();
388
+ return online ? { status: "open" } : {
389
+ status: "closed",
390
+ reason: "no-agents"
391
+ };
392
+ },
393
+ async survey() {
394
+ const response = await (await load()).getForm({
395
+ groupId: config.groupId ?? 0,
396
+ type: "prechat"
397
+ });
398
+ form = response.enabled ? response.form : null;
399
+ return form ? surveyFieldsFromForm(form) : null;
400
+ },
401
+ async start(options) {
402
+ const sdk = await load();
403
+ if (options.resume) {
404
+ const chat = await sdk.getChat({ chatId: options.resume });
405
+ if (!chat.thread?.active) throw new Error("LiveChat chat has ended");
406
+ adopt(chat.id, chat.thread, chat.users, true);
407
+ return;
408
+ }
409
+ const answers = options.answers ?? {};
410
+ const filled = form ? filledFormFields(form, answers) : [];
411
+ const name = filled.find((field) => field.type === "name");
412
+ const email = filled.find((field) => field.type === "email");
413
+ const group = filled.find((field) => field.type === "group_chooser");
414
+ if (name?.answer || email?.answer) await sdk.updateCustomer({
415
+ ...name?.answer ? { name: name.answer } : {},
416
+ ...email?.answer ? { email: email.answer } : {}
417
+ });
418
+ if (options.context && Object.keys(options.context).length) await sdk.setCustomerSessionFields({ sessionFields: options.context });
419
+ const events = [];
420
+ if (form && filled.length) events.push({
421
+ type: "filled_form",
422
+ formId: form.id,
423
+ formType: "prechat",
424
+ properties: {},
425
+ fields: filled
426
+ });
427
+ if (options.openingMessage) events.push({
428
+ type: "message",
429
+ text: options.openingMessage,
430
+ properties: {}
431
+ });
432
+ const chat = {
433
+ ...group?.answer ? { access: { groupIds: [group.answer.groupId] } } : {},
434
+ thread: { events }
435
+ };
436
+ try {
437
+ const { chat: started } = await sdk.startChat({ chat });
438
+ adopt(started.id, started.thread, started.users, false);
439
+ } catch (caught) {
440
+ if (errorCode(caught) !== "CHAT_LIMIT_REACHED") throw caught;
441
+ const { chatsSummary } = await sdk.listChats({ limit: 1 });
442
+ const earlier = chatsSummary[0];
443
+ if (!earlier) throw caught;
444
+ if (earlier.active) {
445
+ const open = await sdk.getChat({ chatId: earlier.id });
446
+ if (open.thread?.active) {
447
+ adopt(open.id, open.thread, open.users, false);
448
+ return;
449
+ }
450
+ }
451
+ const { chat: resumed } = await sdk.resumeChat({ chat: {
452
+ id: earlier.id,
453
+ ...chat
454
+ } });
455
+ adopt(resumed.id, resumed.thread, resumed.users, false);
456
+ }
457
+ },
458
+ async send(text) {
459
+ const sdk = await load();
460
+ if (!current) throw new Error("LiveChat has no chat to send to");
461
+ await sdk.sendEvent({
462
+ chatId: current.chatId,
463
+ event: {
464
+ type: "message",
465
+ text,
466
+ properties: {}
467
+ }
468
+ });
469
+ },
470
+ async typing() {},
471
+ async draft(text) {
472
+ const sdk = await load();
473
+ if (current) sdk.setSneakPeek({
474
+ chatId: current.chatId,
475
+ sneakPeekText: text
476
+ });
477
+ },
478
+ async end() {
479
+ if (!connection || !current) return;
480
+ const sdk = await connection;
481
+ const { chatId } = current;
482
+ current = null;
483
+ await sdk.deactivateChat({ id: chatId });
484
+ },
485
+ onMessage(listener) {
486
+ messageListeners.add(listener);
487
+ return () => messageListeners.delete(listener);
488
+ },
489
+ onTyping(listener) {
490
+ typingListeners.add(listener);
491
+ return () => typingListeners.delete(listener);
492
+ },
493
+ onEnded(listener) {
494
+ endedListeners.add(listener);
495
+ return () => endedListeners.delete(listener);
496
+ },
497
+ onAgent(listener) {
498
+ agentListeners.add(listener);
499
+ return () => agentListeners.delete(listener);
500
+ },
501
+ async resumeToken() {
502
+ return current?.chatId ?? null;
503
+ },
504
+ async emailTranscript({ email }) {
505
+ const sdk = await load();
506
+ if (!current) throw new Error("LiveChat has no chat to send a transcript of");
507
+ await sdk.updateThreadProperties({
508
+ chatId: current.chatId,
509
+ threadId: current.threadId,
510
+ properties: { routing: { transcript_email: email } }
511
+ });
512
+ },
513
+ async upload(file) {
514
+ const sdk = await load();
515
+ if (!current) throw new Error("LiveChat has no chat to upload to");
516
+ const { chatId } = current;
517
+ const { url } = await sdk.uploadFile({ file }).promise;
518
+ await sdk.sendEvent({
519
+ chatId,
520
+ event: {
521
+ type: "file",
522
+ url,
523
+ alternativeText: file.name,
524
+ properties: {}
525
+ }
526
+ });
527
+ },
528
+ connectSheet(frame, host) {
529
+ return hostMoments(frame, host);
530
+ }
531
+ };
532
+ }
533
+ //#endregion
534
+ export { createLiveChatProvider };
@@ -1,4 +1,4 @@
1
- import { a as AiLiveChatProvider } from "../provider.js";
1
+ import { o as AiLiveChatProvider } from "../provider.js";
2
2
  //#region src/live-chat/omnichannel.d.ts
3
3
  type AiOmnichannelConfig = {
4
4
  orgId: string;
@@ -38,16 +38,30 @@ function question(id) {
38
38
  const parsed = JSON.parse(id);
39
39
  if (isPlainObject(parsed)) return {
40
40
  name: text(parsed.Name),
41
- text: text(parsed.QuestionText)
41
+ text: text(parsed.QuestionText),
42
+ required: parsed.IsRequired === true
42
43
  };
43
44
  } catch {}
44
45
  return {
45
46
  name: null,
46
- text: null
47
+ text: null,
48
+ required: false
47
49
  };
48
50
  }
51
+ function decode(value) {
52
+ return value.replace(/&#(x[0-9a-f]+|\d+);/gi, (entity, code) => {
53
+ const point = code[0] === "x" || code[0] === "X" ? Number.parseInt(code.slice(1), 16) : Number(code);
54
+ return point > 0 && point <= 1114111 ? String.fromCodePoint(point) : entity;
55
+ });
56
+ }
49
57
  function markdown(value) {
50
- return value.replace(/\]\(\s+/g, "](");
58
+ return decode(value).replace(/\]\(\s+/g, "](");
59
+ }
60
+ function label(value) {
61
+ return markdown(value).replace(/^\*\s+/, "");
62
+ }
63
+ function isPlaceholderChoice(title) {
64
+ return /^[-\u2013\u2014]+$/.test(title);
51
65
  }
52
66
  /**
53
67
  * The pre-chat survey Omnichannel keeps as an Adaptive Card, as the field list the chat window
@@ -77,14 +91,13 @@ function surveyFieldsFromAdaptiveCard(card) {
77
91
  const asked = question(id);
78
92
  const own = text(element.label) ?? (type === "Input.Toggle" ? text(element.title) : null);
79
93
  if (own) flush();
80
- const label = markdown(own ?? pending ?? asked.text ?? id);
81
- pending = null;
82
94
  const base = {
83
95
  id,
84
96
  name: asked.name ?? id,
85
- label,
86
- required: element.isRequired === true
97
+ label: label(own ?? pending ?? asked.text ?? id),
98
+ required: element.isRequired === true || asked.required
87
99
  };
100
+ pending = null;
88
101
  if (type === "Input.Text") {
89
102
  const style = String(element.style ?? "");
90
103
  fields.push({
@@ -101,8 +114,11 @@ function surveyFieldsFromAdaptiveCard(card) {
101
114
  ...base,
102
115
  kind: "choice",
103
116
  multiple: element.isMultiSelect === true,
104
- choices: choices.filter((choice) => text(choice.title) && typeof choice.value === "string").map((choice) => ({
105
- label: String(choice.title).trim(),
117
+ choices: choices.filter((choice) => {
118
+ const title = text(choice.title);
119
+ return title !== null && !isPlaceholderChoice(title) && typeof choice.value === "string";
120
+ }).map((choice) => ({
121
+ label: decode(String(choice.title).trim()),
106
122
  value: String(choice.value)
107
123
  }))
108
124
  });
@@ -1,4 +1,4 @@
1
- import { a as AiLiveChatProvider, c as AiLiveChatSurveyNote, i as AiLiveChatMessage, l as AiLiveChatTextField, n as AiLiveChatAvailability, o as AiLiveChatStartOptions, r as AiLiveChatChoiceField, s as AiLiveChatSurveyField, t as AiLiveChatAnswers, u as AiLiveChatToggleField } from "./provider.js";
1
+ import { a as AiLiveChatMessage, c as AiLiveChatStartOptions, d as AiLiveChatTextField, f as AiLiveChatToggleField, i as AiLiveChatChoiceField, l as AiLiveChatSurveyField, n as AiLiveChatAnswers, o as AiLiveChatProvider, r as AiLiveChatAvailability, s as AiLiveChatSheetHost, t as AiLiveChatAction, u as AiLiveChatSurveyNote } from "./provider.js";
2
2
  //#region src/live-chat/survey.d.ts
3
3
  /** Every element of the survey form carries a class under this block. */
4
4
  declare const SURVEY_CLASS = "vv-ai-survey";
@@ -33,4 +33,4 @@ type AiLiveChatSurveyForm = {
33
33
  */
34
34
  declare function renderSurveyForm(document: Document, fields: readonly AiLiveChatSurveyField[], options: AiLiveChatSurveyOptions): AiLiveChatSurveyForm;
35
35
  //#endregion
36
- export { type AiLiveChatAnswers, type AiLiveChatAvailability, type AiLiveChatChoiceField, type AiLiveChatMessage, type AiLiveChatProvider, type AiLiveChatStartOptions, type AiLiveChatSurveyField, type AiLiveChatSurveyForm, type AiLiveChatSurveyLabels, type AiLiveChatSurveyNote, type AiLiveChatSurveyOptions, type AiLiveChatTextField, type AiLiveChatToggleField, SURVEY_CLASS, renderSurveyForm };
36
+ export { type AiLiveChatAction, type AiLiveChatAnswers, type AiLiveChatAvailability, type AiLiveChatChoiceField, type AiLiveChatMessage, type AiLiveChatProvider, type AiLiveChatSheetHost, type AiLiveChatStartOptions, type AiLiveChatSurveyField, type AiLiveChatSurveyForm, type AiLiveChatSurveyLabels, type AiLiveChatSurveyNote, type AiLiveChatSurveyOptions, type AiLiveChatTextField, type AiLiveChatToggleField, SURVEY_CLASS, renderSurveyForm };
@@ -56,12 +56,28 @@ type AiLiveChatStartOptions = {
56
56
  /** A token from `resumeToken()`: reconnect to that chat instead of starting a new one. */
57
57
  resume?: string;
58
58
  };
59
+ /**
60
+ * A button under an agent's message: a link that opens in a new tab, or, with `sheet`, a page the
61
+ * window opens in a sheet over the thread, such as an agent app's sign-in.
62
+ */
63
+ type AiLiveChatAction = {
64
+ label: string;
65
+ url: string;
66
+ sheet: boolean;
67
+ };
59
68
  type AiLiveChatMessage = {
60
69
  id: string;
61
70
  text: string;
62
71
  sender: 'agent' | 'system';
63
72
  /** The agent's display name, when the provider has one. */
64
73
  name: string | null;
74
+ actions?: AiLiveChatAction[];
75
+ };
76
+ /** What a page in a sheet can ask of the window. */
77
+ type AiLiveChatSheetHost = {
78
+ /** Sends text into the live chat as the visitor's message. */
79
+ send(text: string): Promise<void>;
80
+ close(): void;
65
81
  };
66
82
  /**
67
83
  * What the chat window needs from a live chat service. `onMessage`, `onTyping` and `onEnded` may
@@ -97,6 +113,11 @@ type AiLiveChatProvider = {
97
113
  message?: string;
98
114
  }): Promise<void>;
99
115
  upload?(file: File): Promise<void>;
116
+ /**
117
+ * Connects a page the window opened in a sheet to the provider's own app protocol, so the page
118
+ * can send the visitor's message and close the sheet. Returns a disconnect.
119
+ */
120
+ connectSheet?(frame: HTMLIFrameElement, host: AiLiveChatSheetHost): () => void;
100
121
  };
101
122
  //#endregion
102
- export { AiLiveChatProvider as a, AiLiveChatSurveyNote as c, AiLiveChatMessage as i, AiLiveChatTextField as l, AiLiveChatAvailability as n, AiLiveChatStartOptions as o, AiLiveChatChoiceField as r, AiLiveChatSurveyField as s, AiLiveChatAnswers as t, AiLiveChatToggleField as u };
123
+ export { AiLiveChatMessage as a, AiLiveChatStartOptions as c, AiLiveChatTextField as d, AiLiveChatToggleField as f, AiLiveChatChoiceField as i, AiLiveChatSurveyField as l, AiLiveChatAnswers as n, AiLiveChatProvider as o, AiLiveChatAvailability as r, AiLiveChatSheetHost as s, AiLiveChatAction as t, AiLiveChatSurveyNote as u };
package/dist/styles.css CHANGED
@@ -15,6 +15,7 @@
15
15
  * --vv-ai-survey-toggle-off the switch's track when off (#9ca3af)
16
16
  * --vv-ai-survey-toggle-on the switch's track when on (currentColor)
17
17
  * --vv-ai-survey-toggle-knob the knob (#fff)
18
+ * --vv-ai-chat-sheet-background the sheet an agent's button opens (#fff)
18
19
  */
19
20
 
20
21
  /* What the binding shows and hides with `hidden` stays hidden whatever display a host gives it. */
@@ -111,6 +112,32 @@
111
112
  overscroll-behavior-x: contain;
112
113
  }
113
114
 
115
+ /*
116
+ * A page an agent's button opens, over the whole root, which needs a position for it to cover. The
117
+ * frame fills what the header leaves.
118
+ */
119
+ .vv-ai-chat__sheet {
120
+ position: absolute;
121
+ inset: 0;
122
+ z-index: 1;
123
+ display: flex;
124
+ flex-direction: column;
125
+ background: var(--vv-ai-chat-sheet-background, #fff);
126
+ }
127
+
128
+ .vv-ai-chat__sheet-header {
129
+ display: flex;
130
+ align-items: center;
131
+ justify-content: space-between;
132
+ }
133
+
134
+ .vv-ai-chat__sheet-frame {
135
+ flex: 1;
136
+ width: 100%;
137
+ min-height: 0;
138
+ border: 0;
139
+ }
140
+
114
141
  /*
115
142
  * The survey's yes-or-no question as a switch. The input selector outweighs a host's own rule for
116
143
  * every survey input, which would otherwise draw the switch as a text box.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vettvangur/ai-sdk",
3
- "version": "0.7.1",
3
+ "version": "0.7.2",
4
4
  "description": "Framework-agnostic AI chat client for server-rendered shells",
5
5
  "type": "module",
6
6
  "access": "public",
@@ -26,6 +26,10 @@
26
26
  "types": "./dist/live-chat/omnichannel.d.ts",
27
27
  "import": "./dist/live-chat/omnichannel.js"
28
28
  },
29
+ "./live-chat/livechat": {
30
+ "types": "./dist/live-chat/livechat.d.ts",
31
+ "import": "./dist/live-chat/livechat.js"
32
+ },
29
33
  "./live-chat/aichat": {
30
34
  "types": "./dist/live-chat/aichat.d.ts",
31
35
  "import": "./dist/live-chat/aichat.js"
@@ -39,18 +43,23 @@
39
43
  "types": "./dist/index.d.ts",
40
44
  "peerDependencies": {
41
45
  "@bgunnarsson/binmx": "^0.1.0",
46
+ "@livechat/customer-sdk": "^5.1.1",
42
47
  "@microsoft/omnichannel-chat-sdk": "^2.0.2"
43
48
  },
44
49
  "peerDependenciesMeta": {
45
50
  "@bgunnarsson/binmx": {
46
51
  "optional": true
47
52
  },
53
+ "@livechat/customer-sdk": {
54
+ "optional": true
55
+ },
48
56
  "@microsoft/omnichannel-chat-sdk": {
49
57
  "optional": true
50
58
  }
51
59
  },
52
60
  "devDependencies": {
53
61
  "@bgunnarsson/binmx": "0.1.0",
62
+ "@livechat/customer-sdk": "5.1.1",
54
63
  "@microsoft/omnichannel-chat-sdk": "2.0.2",
55
64
  "rimraf": "6.1.3",
56
65
  "tsdown": "0.22.14",