@vettvangur/ai-sdk 0.14.0 → 0.15.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.
package/README.md CHANGED
@@ -1,11 +1,16 @@
1
1
  # @vettvangur/ai-sdk
2
2
 
3
- Framework-agnostic AI chat primitives for server-rendered shells.
3
+ Framework-agnostic AI primitives for server-rendered pages, and an AI chat built on them.
4
4
 
5
- It exports protocol-v1 contracts, parsing and SSE stream-reading primitives, a headless chat session,
6
- a DOM binding for a server-rendered shell, and the few generic pieces a host draws tool results with. It
7
- ships no styles by default: every element it renders carries a BEM class. An opt-in stylesheet lays
8
- out and draws the chat, its window and launcher, themed by custom properties (see [Styles](#styles)).
5
+ The package root is the core: reading a streamed response, rendering model text as safe DOM, and the
6
+ link and image rules every renderer keeps (see [The core](#the-core)). It knows nothing of chat, so a
7
+ page that streams a generated product text or a classification uses it alone.
8
+
9
+ `@vettvangur/ai-sdk/chat` is the chat: protocol-v1 contracts, parsing and stream reading, a headless
10
+ chat session, a DOM binding for a server-rendered shell, and the few generic pieces a host draws tool
11
+ results with. It ships no styles by default: every element it renders carries a BEM class. An opt-in
12
+ stylesheet lays out and draws the chat, its window and launcher, themed by custom properties (see
13
+ [Styles](#styles)).
9
14
 
10
15
  ```html
11
16
  <section data-ai-chat data-ai-chat-endpoint="/webapi/aichat/stream"
@@ -24,7 +29,7 @@ out and draws the chat, its window and launcher, themed by custom properties (se
24
29
  ```
25
30
 
26
31
  ```ts
27
- import { bindChat, createAiChatRegistry } from '@vettvangur/ai-sdk'
32
+ import { bindChat, createAiChatRegistry } from '@vettvangur/ai-sdk/chat'
28
33
 
29
34
  const registry = createAiChatRegistry()
30
35
  registry.registerRenderer('weather', ({ document, data }) => {
@@ -37,6 +42,39 @@ const chat = bindChat(document.querySelector('[data-ai-chat]')!, { registry })
37
42
  // Call chat.destroy() when its server-rendered shell is removed.
38
43
  ```
39
44
 
45
+ ## The core
46
+
47
+ `readServerEvents(response, signal)` yields each record of a server-sent event stream as
48
+ `{ name, data }`, with `data` as the text of its `data:` lines. It knows no protocol: a record
49
+ without an `event:` name or `data:` line is skipped, the stream ends with the response, and breaking
50
+ out of the loop or aborting `signal` cancels the response body. A record that grows past 1 MiB
51
+ without closing throws.
52
+
53
+ ```ts
54
+ import { readServerEvents, renderMarkdown } from '@vettvangur/ai-sdk'
55
+
56
+ const controller = new AbortController()
57
+ const response = await fetch('/webapi/products/describe', { method: 'POST', body: form, signal: controller.signal })
58
+ let text = ''
59
+ for await (const { name, data } of readServerEvents(response, controller.signal)) {
60
+ if (name === 'delta') {
61
+ text += JSON.parse(data).text
62
+ output.replaceChildren(renderMarkdown(document, text))
63
+ }
64
+ }
65
+ ```
66
+
67
+ `renderMarkdown(document, source)` draws the Markdown subset a model writes as DOM nodes, never as
68
+ HTML, and keeps to `MAX_MARKDOWN_CHARACTERS`. `isSafeLinkUrl`, `createSafeLink`, `createSafeImage`
69
+ and `createPart` are described under [Cards](#cards).
70
+
71
+ ### Upgrading from 0.14
72
+
73
+ Everything the package root exported except `createPart`, `createSafeImage`, `createSafeLink` and
74
+ `isSafeLinkUrl` moved to `@vettvangur/ai-sdk/chat`: import `bindChat`, `createAiChatRegistry`,
75
+ `createChatSession`, `readEventStream`, `renderAnswerCard` and the `AiChat*` types from there. The
76
+ `live-chat`, `mount`, `binmx` and `styles.css` subpaths are unchanged.
77
+
40
78
  ## The shell
41
79
 
42
80
  `bindChat` needs the form, input and thread; the rest is optional.
@@ -200,7 +238,7 @@ hours from the widget's config and turns the Adaptive Card survey into text, cho
200
238
  fields, refusing a card with any other input rather than leaving a question out.
201
239
 
202
240
  ```ts
203
- import { bindChat } from '@vettvangur/ai-sdk'
241
+ import { bindChat } from '@vettvangur/ai-sdk/chat'
204
242
  import { createOmnichannelProvider } from '@vettvangur/ai-sdk/live-chat/omnichannel'
205
243
 
206
244
  const liveChat = createOmnichannelProvider({ orgId, orgUrl, widgetId })
@@ -275,7 +313,7 @@ answers through `liveChatFromAttributes` unless they name a `liveChat`:
275
313
  | `data-ai-chat-live-endpoint` | The AiChat Live desk, as `liveChatFromRoot` |
276
314
 
277
315
  ```ts
278
- import { createAiChatRegistry } from '@vettvangur/ai-sdk'
316
+ import { createAiChatRegistry } from '@vettvangur/ai-sdk/chat'
279
317
  import { mountAiChat } from '@vettvangur/ai-sdk/mount'
280
318
 
281
319
  const registry = createAiChatRegistry()
@@ -332,7 +370,7 @@ project; build them with the helpers below rather than adding them here.
332
370
 
333
371
  `createSafeImage` (web and site-relative URLs only, with srcset and size when given),
334
372
  `createSafeLink` (the `isSafeLinkUrl` rule, new tab for web URLs) and `createPart` (an element with
335
- a BEM class and text) are exported for a host's own renderers.
373
+ a BEM class and text) are exported from the package root for a host's own renderers.
336
374
 
337
375
  ## Answer cards
338
376
 
@@ -381,6 +419,11 @@ Every `vv-ai-chat__` class above is under the root. The page pins the root betwe
381
419
  corner from `36rem` up and fills the screen below it. The thread is the `vv-ai-chat-thread`
382
420
  container, so a host's cards can lay out by its width with `@container vv-ai-chat-thread`.
383
421
 
422
+ In the window, buttons and fields in the thread keep to the window's control size, whatever the host
423
+ draws them at elsewhere. That covers the package's own, `.button`, `.btn` and `.bttn` and any class
424
+ starting `button-`, `btn-` or `bttn-`, every `input` but checkboxes, radios, ranges, hidden and file
425
+ inputs, `select` and `textarea`. The composer is not in the thread and keeps its own.
426
+
384
427
  The theme's custom properties, set on the root or any ancestor of the chat and the launcher:
385
428
 
386
429
  | Property | Default |
@@ -399,6 +442,7 @@ The theme's custom properties, set on the root or any ancestor of the chat and t
399
442
  | `--vv-ai-chat-window-width`, `-height`, `-inset`, `-radius`, `-shadow` | `23.75rem`, `38.75rem`, `1.25rem`, `1rem`, a soft drop |
400
443
  | `--vv-ai-chat-window-header`, `-header-agent`, `-header-text`, `-header-muted`, `-header-hover` | the accent, its hover, on-accent, the header text at 85% and 15% |
401
444
  | `--vv-ai-chat-assistant-avatar` (an image in the window's assistant avatar) | `none` |
445
+ | `--vv-ai-chat-window-control-height`, `-control-font-size` (buttons and fields in the window's thread) | `2.25rem`, `0.875rem` |
402
446
  | `--vv-ai-launcher-shadow`, `--vv-ai-launcher-teaser-shadow`, `--vv-ai-menu-shadow` | soft drops |
403
447
  | `--vv-ai-chat-spring`, `--vv-ai-launcher-spring`, `--vv-ai-launcher-wind-up` | the window's and launcher's easings |
404
448
  | `--vv-ai-chat-window-delay` (the window opens once the launcher has mostly spun away) | `0.35s` |
package/dist/binmx.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { P as AiTemplateUrlSurfaceOptions, m as AiChatExtensionContext } from "./contracts.js";
1
+ import { N as AiTemplateUrlSurfaceOptions, p as AiChatExtensionContext } from "./contracts.js";
2
2
  //#region src/binmx.d.ts
3
3
  /**
4
4
  * Makes cloned markup live. binmx processes only the page it started on and what it swaps in
package/dist/chat.d.ts ADDED
@@ -0,0 +1,132 @@
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
+ import { t as AiCardImage } from "./dom.js";
3
+ import { A as AiLauncherTeaserOptions, C as AiChatSessionOptions, D as AiChatSurface, E as AiChatStreamEvent, M as AiTemplateItemSurfaceOptions, N as AiTemplateUrlSurfaceOptions, O as AiFormContextOptions, S as AiChatSession, T as AiChatSessionStatus, _ as AiChatMessage, a as AiAnswerCardSection, b as AiChatRenderer, c as AiChatActionItem, d as AiChatContext, f as AiChatEventMap, g as AiChatLabels, h as AiChatHandoverResult, i as AiAnswerCardLink, j as AiLiveChatFactoryContext, k as AiHandoverPayload, l as AiChatBinding, m as AiChatHandoverOptions, n as AiAnswerCardFact, o as AiAnswerCardTable, p as AiChatExtensionContext, r as AiAnswerCardLabels, s as AiChatAction, t as AiAnswerCard, u as AiChatBindings, v as AiChatMode, w as AiChatSessionResult, x as AiChatRequest, y as AiChatRegistry } from "./contracts.js";
4
+ //#region src/answer-card.d.ts
5
+ declare const MAX_ANSWER_CARD_SECTIONS = 12;
6
+ declare const MAX_ANSWER_CARD_FACTS = 24;
7
+ declare const MAX_ANSWER_CARD_LINKS = 24;
8
+ declare const MAX_ANSWER_CARD_TABLES = 8;
9
+ declare const MAX_ANSWER_CARD_TABLE_ROWS = 50;
10
+ declare const MAX_ANSWER_CARD_TABLE_CELLS = 12;
11
+ declare const MAX_ANSWER_CARD_TEXT_LENGTH = 8000;
12
+ declare const MAX_ANSWER_CARD_URL_LENGTH = 2048;
13
+ declare const MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS = 24000;
14
+ declare const MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS = 512;
15
+ declare const MAX_ANSWER_CARD_TOTAL_TABLE_CELLS = 512;
16
+ /**
17
+ * Every element an answer card renders carries a class under this block, so a host styles the card
18
+ * by class rather than by the order its elements happen to come in.
19
+ */
20
+ declare const ANSWER_CARD_CLASS = "vv-ai-answer-card";
21
+ /**
22
+ * Whether `renderAnswerCard` will draw `value` as a card. A host that builds cards elsewhere, a
23
+ * server or a test, can hold its output to the same limits the renderer applies.
24
+ */
25
+ declare function isAnswerCard(value: unknown): value is AiAnswerCard;
26
+ declare function renderAnswerCard(document: Document, data: unknown, labels: AiAnswerCardLabels): HTMLElement | null;
27
+ /**
28
+ * Throws when `card` is not an answer card `renderAnswerCard` will draw, or when a field it shows
29
+ * as plain text (titles, facts, table cells, notes) holds Markdown that would show literally. For
30
+ * a server's or a test's own cards; the message names what is wrong.
31
+ */
32
+ declare function assertAnswerCardContract(card: unknown): asserts card is AiAnswerCard;
33
+ //#endregion
34
+ //#region src/bind.d.ts
35
+ /**
36
+ * Every element the binding adds to the thread carries a class under this block, so a host styles
37
+ * the chat by class rather than by the order its elements happen to come in.
38
+ */
39
+ declare const CHAT_CLASS = "vv-ai-chat";
40
+ declare function bindChat(root: HTMLElement, options?: AiChatBindings): AiChatBinding;
41
+ //#endregion
42
+ //#region src/cards.d.ts
43
+ /** Block classes of the cards below. Every element a card renders carries a class under its block. */
44
+ declare const CARD_LIST_CLASS = "vv-ai-card-list";
45
+ declare const ACTIONS_CLASS = "vv-ai-actions";
46
+ /**
47
+ * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
48
+ * Items that render nothing are skipped, and a list with nothing in it is null.
49
+ */
50
+ declare function renderCardList<T>(document: Document, items: unknown, render: (item: T) => Node | null, modifier?: string): HTMLElement | null;
51
+ /**
52
+ * A row of things the visitor can do next. An item with `action` is a button that runs the action
53
+ * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
54
+ * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
55
+ */
56
+ declare function renderActions(document: Document, items: readonly AiChatActionItem[]): HTMLElement | null;
57
+ //#endregion
58
+ //#region src/chat.d.ts
59
+ declare function createChatSession(options: AiChatSessionOptions): AiChatSession;
60
+ //#endregion
61
+ //#region src/form-context.d.ts
62
+ /**
63
+ * Tells the AI what the visitor entered into a form embedded in the thread. Whenever `element`
64
+ * changes and holds `options.form`, its filled-in `fields` are summarised as `label: value` and
65
+ * sent with every later question through `binding.setFormContext`, framed as context rather than
66
+ * something the visitor said. Returns a function that stops watching.
67
+ */
68
+ declare function watchFormContext(binding: AiChatBinding, element: HTMLElement, options: AiFormContextOptions): () => void;
69
+ //#endregion
70
+ //#region src/handover.d.ts
71
+ /** The action the handover card's button runs; the binding hands over to a person with it. */
72
+ declare const LIVE_CHAT_ACTION = "livechat";
73
+ /** The tool the Vettvangur.AiChat engine hands over with, from before its payload named its kind. */
74
+ declare const HANDOVER_TOOL = "request_human_agent";
75
+ /** A payload of kind `handover`, or one from the handover tool that names no kind. */
76
+ declare function isHandoverPayload(tool: string, data: unknown): data is AiHandoverPayload;
77
+ /**
78
+ * The visitor's ways to a person: a primary `liveChat` button that runs the `livechat` action when
79
+ * a live chat is available, and a `contact` link to a safe contact URL. The payload's `prefill`
80
+ * goes on the button as its value. Null when neither applies.
81
+ */
82
+ declare function renderHandoverCard(document: Document, data: AiHandoverPayload, labels: Pick<AiChatLabels, 'liveChat' | 'contact'>): HTMLElement | null;
83
+ /**
84
+ * Puts `text` as `vv-ai-actions__note` in place of the live chat button under `parent`, for when
85
+ * no one can take the chat. The contact link stays.
86
+ */
87
+ declare function closeHandoverCard(parent: ParentNode, text: string): void;
88
+ //#endregion
89
+ //#region src/protocol.d.ts
90
+ declare const AI_CHAT_PROTOCOL_VERSION = 1;
91
+ declare function parseStreamEvent(name: string, data: unknown): AiChatStreamEvent | null;
92
+ //#endregion
93
+ //#region src/registry.d.ts
94
+ declare function createAiChatRegistry(): AiChatRegistry;
95
+ //#endregion
96
+ //#region src/stream.d.ts
97
+ declare function readEventStream(response: Response, signal: AbortSignal): AsyncGenerator<AiChatStreamEvent>;
98
+ //#endregion
99
+ //#region src/surfaces.d.ts
100
+ /**
101
+ * A surface that shows one item out of an authored list template. The template is cloned, every
102
+ * element carrying `attribute` whose value is not the payload's `key` field is removed, and the
103
+ * rest of the template stays as authored, so one item is the same markup the whole list shows.
104
+ * Null when the template is missing or no item matches.
105
+ */
106
+ declare function createTemplateItemSurface(options: AiTemplateItemSurfaceOptions): (context: Pick<AiChatExtensionContext, 'root' | 'data'>) => DocumentFragment | null;
107
+ /**
108
+ * A surface of which only the latest copy stays in the thread, for an embedded component whose
109
+ * script binds to the first match in the document or whose fields share ids. What it draws is
110
+ * marked with `data-ai-chat-single` under `key`, and drawing it again removes the earlier copies.
111
+ */
112
+ declare function createSingleSurface<C extends Pick<AiChatExtensionContext, 'root'>, N extends Node>(key: string, surface: (context: C) => N | null): (context: C) => N | null;
113
+ //#endregion
114
+ //#region src/window.d.ts
115
+ /**
116
+ * The binding as a window over the page. Anywhere in the document, a `data-ai-chat-window-open`
117
+ * element opens it, and one that is also `data-ai-chat-window-toggle` closes it again; toggles
118
+ * carry `aria-expanded` and get focus back when it closes. Escape closes the root's
119
+ * `details[data-ai-chat-menu]` first and then the window, a click anywhere but the menu's summary
120
+ * closes the menu, and a `data-ai-chat-expand` link closes the window before it navigates, so the
121
+ * next page does not open it again from the stored thread. Returns a function that undoes it all.
122
+ */
123
+ declare function bindChatWindow(binding: AiChatBinding): () => void;
124
+ /**
125
+ * The `data-ai-launcher-teaser` inside `container`, shown once a session to a visitor who has not
126
+ * started a chat: not while the window is open or its thread has messages. A
127
+ * `data-ai-launcher-dismiss` button in it hides it, as opening the window does. When storage
128
+ * cannot be read the teaser is not shown. Returns a function that undoes it.
129
+ */
130
+ declare function bindLauncherTeaser(binding: AiChatBinding, container: ParentNode, options?: AiLauncherTeaserOptions): () => void;
131
+ //#endregion
132
+ 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, closeHandoverCard, createAiChatRegistry, createChatSession, createSingleSurface, createTemplateItemSurface, isAnswerCard, isHandoverPayload, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderHandoverCard, watchFormContext };
package/dist/chat.js ADDED
@@ -0,0 +1,33 @@
1
+ import { A as MAX_ANSWER_CARD_URL_LENGTH, C as MAX_ANSWER_CARD_TABLES, D as MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, E as MAX_ANSWER_CARD_TEXT_LENGTH, M as isAnswerCard, N as renderAnswerCard, O as MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, S as MAX_ANSWER_CARD_SECTIONS, T as MAX_ANSWER_CARD_TABLE_ROWS, _ as renderActions, a as createAiChatRegistry, b as MAX_ANSWER_CARD_FACTS, c as closeHandoverCard, d as createChatSession, f as readEventStream, g as CARD_LIST_CLASS, h as ACTIONS_CLASS, i as bindChat, j as assertAnswerCardContract, k as MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, l as isHandoverPayload, m as parseStreamEvent, n as bindLauncherTeaser, o as HANDOVER_TOOL, p as AI_CHAT_PROTOCOL_VERSION, r as CHAT_CLASS, s as LIVE_CHAT_ACTION, t as bindChatWindow, u as renderHandoverCard, v as renderCardList, w as MAX_ANSWER_CARD_TABLE_CELLS, x as MAX_ANSWER_CARD_LINKS, y as ANSWER_CARD_CLASS } from "./window.js";
2
+ import { n as createTemplateItemSurface, t as createSingleSurface } from "./surfaces.js";
3
+ //#region src/form-context.ts
4
+ /**
5
+ * Tells the AI what the visitor entered into a form embedded in the thread. Whenever `element`
6
+ * changes and holds `options.form`, its filled-in `fields` are summarised as `label: value` and
7
+ * sent with every later question through `binding.setFormContext`, framed as context rather than
8
+ * something the visitor said. Returns a function that stops watching.
9
+ */
10
+ function watchFormContext(binding, element, options) {
11
+ const record = () => {
12
+ const form = element.querySelector(options.form);
13
+ if (!form) return;
14
+ const values = new FormData(form);
15
+ const parts = options.fields.map(([field, label]) => {
16
+ const raw = String(values.get(field) ?? "").trim();
17
+ const value = options.values?.[raw] ?? raw;
18
+ return value ? `${label}: ${value}` : "";
19
+ }).filter(Boolean);
20
+ if (!parts.length) return;
21
+ const note = options.note ? ` ${options.note}` : "";
22
+ binding.setFormContext(options.name, `Context, not a message from the visitor: they filled in ${options.title} with ${parts.join(", ")}.${note}`, options.followUp);
23
+ };
24
+ const observer = new MutationObserver(record);
25
+ observer.observe(element, {
26
+ childList: true,
27
+ subtree: true
28
+ });
29
+ record();
30
+ return () => observer.disconnect();
31
+ }
32
+ //#endregion
33
+ 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, closeHandoverCard, createAiChatRegistry, createChatSession, createSingleSurface, createTemplateItemSurface, isAnswerCard, isHandoverPayload, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderHandoverCard, watchFormContext };
@@ -280,13 +280,6 @@ type AiChatBinding = {
280
280
  on<K extends keyof AiChatEventMap>(name: K, listener: (detail: AiChatEventMap[K]) => void): () => void;
281
281
  destroy(): void;
282
282
  };
283
- type AiCardImage = {
284
- url: string;
285
- url2x?: string | null;
286
- alt?: string | null;
287
- width?: number | null;
288
- height?: number | null;
289
- };
290
283
  type AiChatActionItem = {
291
284
  label: string;
292
285
  action?: string | null;
@@ -342,4 +335,4 @@ type AiLauncherTeaserOptions = {
342
335
  storageKey?: string;
343
336
  };
344
337
  //#endregion
345
- export { AiHandoverPayload as A, AiChatSession as C, AiChatStreamEvent as D, AiChatSessionStatus as E, AiLiveChatFactoryContext as M, AiTemplateItemSurfaceOptions as N, AiChatSurface as O, AiTemplateUrlSurfaceOptions as P, AiChatRequest as S, AiChatSessionResult as T, AiChatLabels as _, AiAnswerCardSection as a, AiChatRegistry as b, AiChatAction as c, AiChatBindings as d, AiChatContext as f, AiChatHandoverResult as g, AiChatHandoverOptions as h, AiAnswerCardLink as i, AiLauncherTeaserOptions as j, AiFormContextOptions as k, AiChatActionItem as l, AiChatExtensionContext as m, AiAnswerCardFact as n, AiAnswerCardTable as o, AiChatEventMap as p, AiAnswerCardLabels as r, AiCardImage as s, AiAnswerCard as t, AiChatBinding as u, AiChatMessage as v, AiChatSessionOptions as w, AiChatRenderer as x, AiChatMode as y };
338
+ export { AiLauncherTeaserOptions as A, AiChatSessionOptions as C, AiChatSurface as D, AiChatStreamEvent as E, AiTemplateItemSurfaceOptions as M, AiTemplateUrlSurfaceOptions as N, AiFormContextOptions as O, AiChatSession as S, AiChatSessionStatus as T, AiChatMessage as _, AiAnswerCardSection as a, AiChatRenderer as b, AiChatActionItem as c, AiChatContext as d, AiChatEventMap as f, AiChatLabels as g, AiChatHandoverResult as h, AiAnswerCardLink as i, AiLiveChatFactoryContext as j, AiHandoverPayload as k, AiChatBinding as l, AiChatHandoverOptions as m, AiAnswerCardFact as n, AiAnswerCardTable as o, AiChatExtensionContext as p, AiAnswerCardLabels as r, AiChatAction as s, AiAnswerCard as t, AiChatBindings as u, AiChatMode as v, AiChatSessionResult as w, AiChatRequest as x, AiChatRegistry as y };
package/dist/dom.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ //#region src/dom.d.ts
2
+ /** An image a card or answer may show. */
3
+ type AiCardImage = {
4
+ url: string;
5
+ url2x?: string | null;
6
+ alt?: string | null;
7
+ width?: number | null;
8
+ height?: number | null;
9
+ };
10
+ declare function isSafeLinkUrl(url: string): boolean;
11
+ declare function createSafeLink(document: Document, label: string, url: string): HTMLAnchorElement | null;
12
+ /**
13
+ * An image only from a site-relative or web URL; anything else is left out rather than loaded. The
14
+ * width and height, when given, let the browser reserve the space before the image arrives.
15
+ */
16
+ declare function createSafeImage(document: Document, image: AiCardImage | null | undefined): HTMLImageElement | null;
17
+ /** An element carrying the BEM class for `part` of `block`, and `text` when there is any. */
18
+ declare function createPart<K extends keyof HTMLElementTagNameMap>(document: Document, tag: K, block: string, part?: string | null, text?: string | null): HTMLElementTagNameMap[K];
19
+ //#endregion
20
+ export { isSafeLinkUrl as a, createSafeLink as i, createPart as n, createSafeImage as r, AiCardImage as t };
package/dist/events.js ADDED
@@ -0,0 +1,76 @@
1
+ //#region src/events.ts
2
+ const MAX_RECORD_LENGTH = 1048576;
3
+ function findRecordBoundary(buffer) {
4
+ const lfIndex = buffer.indexOf("\n\n");
5
+ const crlfIndex = buffer.indexOf("\r\n\r\n");
6
+ if (lfIndex === -1 && crlfIndex === -1) return null;
7
+ if (lfIndex === -1 || crlfIndex !== -1 && crlfIndex < lfIndex) return {
8
+ index: crlfIndex,
9
+ length: 4
10
+ };
11
+ return {
12
+ index: lfIndex,
13
+ length: 2
14
+ };
15
+ }
16
+ function fieldValue(value) {
17
+ return value.startsWith(" ") ? value.slice(1) : value;
18
+ }
19
+ function parseRecord(record) {
20
+ let name;
21
+ const dataLines = [];
22
+ for (const line of record.split(/\r?\n/)) if (line.startsWith("event:")) name = fieldValue(line.slice(6));
23
+ else if (line.startsWith("data:")) dataLines.push(fieldValue(line.slice(5)));
24
+ if (!name || dataLines.length === 0) return null;
25
+ return {
26
+ name,
27
+ data: dataLines.join("\n")
28
+ };
29
+ }
30
+ function abortError() {
31
+ return /* @__PURE__ */ new Error("AI event stream was aborted");
32
+ }
33
+ /**
34
+ * The named records of a streamed response, as they arrive. A record without an `event:` name or
35
+ * `data:` line is skipped. The stream ends with the response; stopping early, by breaking out of
36
+ * the loop or aborting `signal`, cancels the response body.
37
+ */
38
+ async function* readServerEvents(response, signal) {
39
+ if (!response.body) throw new Error("AI response has no body");
40
+ if (signal.aborted) throw abortError();
41
+ const decoder = new TextDecoder();
42
+ const reader = response.body.getReader();
43
+ let buffer = "";
44
+ let readerDone = false;
45
+ const cancelReader = () => {
46
+ reader.cancel().catch(() => void 0);
47
+ };
48
+ signal.addEventListener("abort", cancelReader, { once: true });
49
+ try {
50
+ while (!readerDone) {
51
+ if (signal.aborted) throw abortError();
52
+ const { done, value } = await reader.read();
53
+ if (signal.aborted) throw abortError();
54
+ if (done) {
55
+ readerDone = true;
56
+ buffer += decoder.decode();
57
+ } else buffer += decoder.decode(value, { stream: true });
58
+ let boundary = findRecordBoundary(buffer);
59
+ while (boundary) {
60
+ const record = parseRecord(buffer.slice(0, boundary.index));
61
+ buffer = buffer.slice(boundary.index + boundary.length);
62
+ if (record) yield record;
63
+ boundary = findRecordBoundary(buffer);
64
+ }
65
+ if (buffer.length > MAX_RECORD_LENGTH) throw new Error("AI event stream sent an event that is too large");
66
+ }
67
+ } finally {
68
+ signal.removeEventListener("abort", cancelReader);
69
+ if (!readerDone) try {
70
+ await reader.cancel();
71
+ } catch {}
72
+ reader.releaseLock();
73
+ }
74
+ }
75
+ //#endregion
76
+ export { readServerEvents as t };
package/dist/index.d.ts CHANGED
@@ -1,142 +1,19 @@
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
- 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
- //#region src/answer-card.d.ts
4
- declare const MAX_ANSWER_CARD_SECTIONS = 12;
5
- declare const MAX_ANSWER_CARD_FACTS = 24;
6
- declare const MAX_ANSWER_CARD_LINKS = 24;
7
- declare const MAX_ANSWER_CARD_TABLES = 8;
8
- declare const MAX_ANSWER_CARD_TABLE_ROWS = 50;
9
- declare const MAX_ANSWER_CARD_TABLE_CELLS = 12;
10
- declare const MAX_ANSWER_CARD_TEXT_LENGTH = 8000;
11
- declare const MAX_ANSWER_CARD_URL_LENGTH = 2048;
12
- declare const MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS = 24000;
13
- declare const MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS = 512;
14
- declare const MAX_ANSWER_CARD_TOTAL_TABLE_CELLS = 512;
1
+ import { a as isSafeLinkUrl, i as createSafeLink, n as createPart, r as createSafeImage, t as AiCardImage } from "./dom.js";
2
+ //#region src/events.d.ts
3
+ /** One record of a server-sent event stream: its `event:` name and its `data:` lines joined. */
4
+ type AiServerEvent = {
5
+ name: string;
6
+ data: string;
7
+ };
15
8
  /**
16
- * Every element an answer card renders carries a class under this block, so a host styles the card
17
- * by class rather than by the order its elements happen to come in.
9
+ * The named records of a streamed response, as they arrive. A record without an `event:` name or
10
+ * `data:` line is skipped. The stream ends with the response; stopping early, by breaking out of
11
+ * the loop or aborting `signal`, cancels the response body.
18
12
  */
19
- declare const ANSWER_CARD_CLASS = "vv-ai-answer-card";
20
- /**
21
- * Whether `renderAnswerCard` will draw `value` as a card. A host that builds cards elsewhere, a
22
- * server or a test, can hold its output to the same limits the renderer applies.
23
- */
24
- declare function isAnswerCard(value: unknown): value is AiAnswerCard;
25
- declare function renderAnswerCard(document: Document, data: unknown, labels: AiAnswerCardLabels): HTMLElement | null;
26
- /**
27
- * Throws when `card` is not an answer card `renderAnswerCard` will draw, or when a field it shows
28
- * as plain text (titles, facts, table cells, notes) holds Markdown that would show literally. For
29
- * a server's or a test's own cards; the message names what is wrong.
30
- */
31
- declare function assertAnswerCardContract(card: unknown): asserts card is AiAnswerCard;
32
- //#endregion
33
- //#region src/bind.d.ts
34
- /**
35
- * Every element the binding adds to the thread carries a class under this block, so a host styles
36
- * the chat by class rather than by the order its elements happen to come in.
37
- */
38
- declare const CHAT_CLASS = "vv-ai-chat";
39
- declare function bindChat(root: HTMLElement, options?: AiChatBindings): AiChatBinding;
40
- //#endregion
41
- //#region src/cards.d.ts
42
- /** Block classes of the cards below. Every element a card renders carries a class under its block. */
43
- declare const CARD_LIST_CLASS = "vv-ai-card-list";
44
- declare const ACTIONS_CLASS = "vv-ai-actions";
45
- /**
46
- * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
47
- * Items that render nothing are skipped, and a list with nothing in it is null.
48
- */
49
- declare function renderCardList<T>(document: Document, items: unknown, render: (item: T) => Node | null, modifier?: string): HTMLElement | null;
50
- /**
51
- * A row of things the visitor can do next. An item with `action` is a button that runs the action
52
- * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
53
- * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
54
- */
55
- declare function renderActions(document: Document, items: readonly AiChatActionItem[]): HTMLElement | null;
56
- //#endregion
57
- //#region src/chat.d.ts
58
- declare function createChatSession(options: AiChatSessionOptions): AiChatSession;
59
- //#endregion
60
- //#region src/dom.d.ts
61
- declare function isSafeLinkUrl(url: string): boolean;
62
- declare function createSafeLink(document: Document, label: string, url: string): HTMLAnchorElement | null;
63
- /**
64
- * An image only from a site-relative or web URL; anything else is left out rather than loaded. The
65
- * width and height, when given, let the browser reserve the space before the image arrives.
66
- */
67
- declare function createSafeImage(document: Document, image: AiCardImage | null | undefined): HTMLImageElement | null;
68
- /** An element carrying the BEM class for `part` of `block`, and `text` when there is any. */
69
- declare function createPart<K extends keyof HTMLElementTagNameMap>(document: Document, tag: K, block: string, part?: string | null, text?: string | null): HTMLElementTagNameMap[K];
70
- //#endregion
71
- //#region src/form-context.d.ts
72
- /**
73
- * Tells the AI what the visitor entered into a form embedded in the thread. Whenever `element`
74
- * changes and holds `options.form`, its filled-in `fields` are summarised as `label: value` and
75
- * sent with every later question through `binding.setFormContext`, framed as context rather than
76
- * something the visitor said. Returns a function that stops watching.
77
- */
78
- declare function watchFormContext(binding: AiChatBinding, element: HTMLElement, options: AiFormContextOptions): () => void;
79
- //#endregion
80
- //#region src/handover.d.ts
81
- /** The action the handover card's button runs; the binding hands over to a person with it. */
82
- declare const LIVE_CHAT_ACTION = "livechat";
83
- /** The tool the Vettvangur.AiChat engine hands over with, from before its payload named its kind. */
84
- declare const HANDOVER_TOOL = "request_human_agent";
85
- /** A payload of kind `handover`, or one from the handover tool that names no kind. */
86
- declare function isHandoverPayload(tool: string, data: unknown): data is AiHandoverPayload;
87
- /**
88
- * The visitor's ways to a person: a primary `liveChat` button that runs the `livechat` action when
89
- * a live chat is available, and a `contact` link to a safe contact URL. The payload's `prefill`
90
- * goes on the button as its value. Null when neither applies.
91
- */
92
- declare function renderHandoverCard(document: Document, data: AiHandoverPayload, labels: Pick<AiChatLabels, 'liveChat' | 'contact'>): HTMLElement | null;
93
- /**
94
- * Puts `text` as `vv-ai-actions__note` in place of the live chat button under `parent`, for when
95
- * no one can take the chat. The contact link stays.
96
- */
97
- declare function closeHandoverCard(parent: ParentNode, text: string): void;
98
- //#endregion
99
- //#region src/protocol.d.ts
100
- declare const AI_CHAT_PROTOCOL_VERSION = 1;
101
- declare function parseStreamEvent(name: string, data: unknown): AiChatStreamEvent | null;
102
- //#endregion
103
- //#region src/registry.d.ts
104
- declare function createAiChatRegistry(): AiChatRegistry;
105
- //#endregion
106
- //#region src/stream.d.ts
107
- declare function readEventStream(response: Response, signal: AbortSignal): AsyncGenerator<AiChatStreamEvent>;
13
+ declare function readServerEvents(response: Response, signal: AbortSignal): AsyncGenerator<AiServerEvent>;
108
14
  //#endregion
109
- //#region src/surfaces.d.ts
110
- /**
111
- * A surface that shows one item out of an authored list template. The template is cloned, every
112
- * element carrying `attribute` whose value is not the payload's `key` field is removed, and the
113
- * rest of the template stays as authored, so one item is the same markup the whole list shows.
114
- * Null when the template is missing or no item matches.
115
- */
116
- declare function createTemplateItemSurface(options: AiTemplateItemSurfaceOptions): (context: Pick<AiChatExtensionContext, 'root' | 'data'>) => DocumentFragment | null;
117
- /**
118
- * A surface of which only the latest copy stays in the thread, for an embedded component whose
119
- * script binds to the first match in the document or whose fields share ids. What it draws is
120
- * marked with `data-ai-chat-single` under `key`, and drawing it again removes the earlier copies.
121
- */
122
- declare function createSingleSurface<C extends Pick<AiChatExtensionContext, 'root'>, N extends Node>(key: string, surface: (context: C) => N | null): (context: C) => N | null;
123
- //#endregion
124
- //#region src/window.d.ts
125
- /**
126
- * The binding as a window over the page. Anywhere in the document, a `data-ai-chat-window-open`
127
- * element opens it, and one that is also `data-ai-chat-window-toggle` closes it again; toggles
128
- * carry `aria-expanded` and get focus back when it closes. Escape closes the root's
129
- * `details[data-ai-chat-menu]` first and then the window, a click anywhere but the menu's summary
130
- * closes the menu, and a `data-ai-chat-expand` link closes the window before it navigates, so the
131
- * next page does not open it again from the stored thread. Returns a function that undoes it all.
132
- */
133
- declare function bindChatWindow(binding: AiChatBinding): () => void;
134
- /**
135
- * The `data-ai-launcher-teaser` inside `container`, shown once a session to a visitor who has not
136
- * started a chat: not while the window is open or its thread has messages. A
137
- * `data-ai-launcher-dismiss` button in it hides it, as opening the window does. When storage
138
- * cannot be read the teaser is not shown. Returns a function that undoes it.
139
- */
140
- declare function bindLauncherTeaser(binding: AiChatBinding, container: ParentNode, options?: AiLauncherTeaserOptions): () => void;
15
+ //#region src/markdown.d.ts
16
+ declare const MAX_MARKDOWN_CHARACTERS = 8000;
17
+ declare function renderMarkdown(document: Document, source: string): DocumentFragment;
141
18
  //#endregion
142
- 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, closeHandoverCard, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createSingleSurface, createTemplateItemSurface, isAnswerCard, isHandoverPayload, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderHandoverCard, watchFormContext };
19
+ export { type AiCardImage, type AiServerEvent, MAX_MARKDOWN_CHARACTERS, createPart, createSafeImage, createSafeLink, isSafeLinkUrl, readServerEvents, renderMarkdown };
package/dist/index.js CHANGED
@@ -1,34 +1,4 @@
1
1
  import { a as isSafeLinkUrl, n as createSafeImage, r as createSafeLink, t as createPart } from "./dom.js";
2
- import { A as MAX_ANSWER_CARD_URL_LENGTH, C as MAX_ANSWER_CARD_TABLES, D as MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, E as MAX_ANSWER_CARD_TEXT_LENGTH, M as isAnswerCard, N as renderAnswerCard, O as MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, S as MAX_ANSWER_CARD_SECTIONS, T as MAX_ANSWER_CARD_TABLE_ROWS, _ as renderActions, a as createAiChatRegistry, b as MAX_ANSWER_CARD_FACTS, c as closeHandoverCard, d as createChatSession, f as readEventStream, g as CARD_LIST_CLASS, h as ACTIONS_CLASS, i as bindChat, j as assertAnswerCardContract, k as MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, l as isHandoverPayload, m as parseStreamEvent, n as bindLauncherTeaser, o as HANDOVER_TOOL, p as AI_CHAT_PROTOCOL_VERSION, r as CHAT_CLASS, s as LIVE_CHAT_ACTION, t as bindChatWindow, u as renderHandoverCard, v as renderCardList, w as MAX_ANSWER_CARD_TABLE_CELLS, x as MAX_ANSWER_CARD_LINKS, y as ANSWER_CARD_CLASS } from "./window.js";
3
- import { n as createTemplateItemSurface, t as createSingleSurface } from "./surfaces.js";
4
- //#region src/form-context.ts
5
- /**
6
- * Tells the AI what the visitor entered into a form embedded in the thread. Whenever `element`
7
- * changes and holds `options.form`, its filled-in `fields` are summarised as `label: value` and
8
- * sent with every later question through `binding.setFormContext`, framed as context rather than
9
- * something the visitor said. Returns a function that stops watching.
10
- */
11
- function watchFormContext(binding, element, options) {
12
- const record = () => {
13
- const form = element.querySelector(options.form);
14
- if (!form) return;
15
- const values = new FormData(form);
16
- const parts = options.fields.map(([field, label]) => {
17
- const raw = String(values.get(field) ?? "").trim();
18
- const value = options.values?.[raw] ?? raw;
19
- return value ? `${label}: ${value}` : "";
20
- }).filter(Boolean);
21
- if (!parts.length) return;
22
- const note = options.note ? ` ${options.note}` : "";
23
- binding.setFormContext(options.name, `Context, not a message from the visitor: they filled in ${options.title} with ${parts.join(", ")}.${note}`, options.followUp);
24
- };
25
- const observer = new MutationObserver(record);
26
- observer.observe(element, {
27
- childList: true,
28
- subtree: true
29
- });
30
- record();
31
- return () => observer.disconnect();
32
- }
33
- //#endregion
34
- 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, closeHandoverCard, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createSingleSurface, createTemplateItemSurface, isAnswerCard, isHandoverPayload, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderHandoverCard, watchFormContext };
2
+ import { t as readServerEvents } from "./events.js";
3
+ import { r as renderMarkdown, t as MAX_MARKDOWN_CHARACTERS } from "./markdown.js";
4
+ export { MAX_MARKDOWN_CHARACTERS, createPart, createSafeImage, createSafeLink, isSafeLinkUrl, readServerEvents, renderMarkdown };
@@ -1,5 +1,5 @@
1
1
  import { l as AiLiveChatSurveyField, o as AiLiveChatProvider } from "../provider.js";
2
- import { M as AiLiveChatFactoryContext } from "../contracts.js";
2
+ import { j as AiLiveChatFactoryContext } from "../contracts.js";
3
3
  //#region src/live-chat/aichat.d.ts
4
4
  type AiChatLiveConfig = {
5
5
  /** The prefix the site maps the chat under with `MapAiChat`, such as `/webapi/aichat`. */
@@ -0,0 +1,230 @@
1
+ import { a as isSafeLinkUrl, r as createSafeLink } from "./dom.js";
2
+ //#region src/markdown.ts
3
+ const MAX_MARKDOWN_CHARACTERS = 8e3;
4
+ function isWordCharacter(character) {
5
+ return character !== void 0 && /[\p{L}\p{N}]/u.test(character);
6
+ }
7
+ function delimitedToken(source, start, marker, type) {
8
+ if (!source.startsWith(marker, start)) return null;
9
+ const contentStart = start + marker.length;
10
+ const closing = source.indexOf(marker, contentStart);
11
+ if (closing === -1 || closing === contentStart) return null;
12
+ return {
13
+ type,
14
+ content: source.slice(contentStart, closing),
15
+ end: closing + marker.length
16
+ };
17
+ }
18
+ function linkToken(source, start) {
19
+ if (source[start] !== "[") return null;
20
+ let labelEnd = start + 1;
21
+ while (labelEnd < source.length) {
22
+ if (source[labelEnd] === "[") return null;
23
+ if (source[labelEnd] === "]" && source[labelEnd + 1] === "(") break;
24
+ labelEnd += 1;
25
+ }
26
+ if (labelEnd === source.length) return {
27
+ type: "text",
28
+ content: source.slice(start),
29
+ end: source.length
30
+ };
31
+ if (labelEnd === start + 1) return null;
32
+ let depth = 1;
33
+ let end = labelEnd + 2;
34
+ while (end < source.length && depth > 0) {
35
+ if (source[end] === "(") depth += 1;
36
+ else if (source[end] === ")") depth -= 1;
37
+ end += 1;
38
+ }
39
+ if (depth !== 0) return {
40
+ type: "text",
41
+ content: source.slice(start),
42
+ end: source.length
43
+ };
44
+ const url = source.slice(labelEnd + 2, end - 1);
45
+ if (!isSafeLinkUrl(url)) return {
46
+ type: "text",
47
+ content: source.slice(start, end),
48
+ end
49
+ };
50
+ return {
51
+ type: "link",
52
+ label: source.slice(start + 1, labelEnd),
53
+ url,
54
+ end
55
+ };
56
+ }
57
+ function inlineToken(source, start) {
58
+ const link = linkToken(source, start);
59
+ if (link) return link;
60
+ const code = delimitedToken(source, start, "`", "code");
61
+ if (code) return code;
62
+ const bold = delimitedToken(source, start, "**", "bold") ?? delimitedToken(source, start, "__", "bold");
63
+ if (bold) return bold;
64
+ const marker = source[start];
65
+ if ((marker === "*" || marker === "_") && !isWordCharacter(source[start - 1])) return delimitedToken(source, start, marker, "italic");
66
+ return null;
67
+ }
68
+ function inlineStructuralItemCount(source) {
69
+ let count = 0;
70
+ let index = 0;
71
+ while (index < source.length) {
72
+ const token = inlineToken(source, index);
73
+ if (!token) {
74
+ index += 1;
75
+ continue;
76
+ }
77
+ switch (token.type) {
78
+ case "bold":
79
+ case "italic":
80
+ count += 1 + inlineStructuralItemCount(token.content);
81
+ break;
82
+ case "code":
83
+ case "link": count += 1;
84
+ }
85
+ index = token.end;
86
+ }
87
+ return count;
88
+ }
89
+ function appendInlineMarkdown(document, parent, source) {
90
+ let textStart = 0;
91
+ let index = 0;
92
+ while (index < source.length) {
93
+ const token = inlineToken(source, index);
94
+ if (!token) {
95
+ index += 1;
96
+ continue;
97
+ }
98
+ if (textStart < index) parent.append(document.createTextNode(source.slice(textStart, index)));
99
+ switch (token.type) {
100
+ case "code": {
101
+ const code = document.createElement("code");
102
+ code.append(document.createTextNode(token.content));
103
+ parent.append(code);
104
+ break;
105
+ }
106
+ case "bold": {
107
+ const strong = document.createElement("strong");
108
+ appendInlineMarkdown(document, strong, token.content);
109
+ parent.append(strong);
110
+ break;
111
+ }
112
+ case "italic": {
113
+ const emphasis = document.createElement("em");
114
+ appendInlineMarkdown(document, emphasis, token.content);
115
+ parent.append(emphasis);
116
+ break;
117
+ }
118
+ case "link": {
119
+ const link = createSafeLink(document, token.label, token.url);
120
+ if (link) parent.append(link);
121
+ else parent.append(document.createTextNode(source.slice(index, token.end)));
122
+ break;
123
+ }
124
+ case "text": parent.append(document.createTextNode(token.content));
125
+ }
126
+ index = token.end;
127
+ textStart = index;
128
+ }
129
+ if (textStart < source.length) parent.append(document.createTextNode(source.slice(textStart)));
130
+ }
131
+ function unorderedListItem(line) {
132
+ return /^\s*[-+*]\s+(.+)$/.exec(line)?.[1] ?? null;
133
+ }
134
+ function orderedListItem(line) {
135
+ return /^\s*\d+[.)]\s+(.+)$/.exec(line)?.[1] ?? null;
136
+ }
137
+ function heading(line) {
138
+ return /^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$/.exec(line)?.[1] ?? null;
139
+ }
140
+ function countMarkdownStructuralItems(source) {
141
+ const lines = source.slice(0, MAX_MARKDOWN_CHARACTERS).split(/\r\n?|\n/);
142
+ let count = 0;
143
+ let index = 0;
144
+ while (index < lines.length) {
145
+ const line = lines[index];
146
+ if (line.trim().length === 0) {
147
+ index += 1;
148
+ continue;
149
+ }
150
+ const headingText = heading(line);
151
+ if (headingText !== null) {
152
+ count += 2 + inlineStructuralItemCount(headingText);
153
+ index += 1;
154
+ continue;
155
+ }
156
+ const unorderedItem = unorderedListItem(line);
157
+ const orderedItem = orderedListItem(line);
158
+ if (unorderedItem !== null || orderedItem !== null) {
159
+ const itemForLine = unorderedItem === null ? orderedListItem : unorderedListItem;
160
+ count += 1;
161
+ while (index < lines.length) {
162
+ const item = itemForLine(lines[index]);
163
+ if (item === null) break;
164
+ count += 1 + inlineStructuralItemCount(item);
165
+ index += 1;
166
+ }
167
+ continue;
168
+ }
169
+ const paragraphLines = [];
170
+ while (index < lines.length) {
171
+ const paragraphLine = lines[index];
172
+ if (paragraphLine.trim().length === 0 || heading(paragraphLine) !== null || unorderedListItem(paragraphLine) !== null || orderedListItem(paragraphLine) !== null) break;
173
+ paragraphLines.push(paragraphLine);
174
+ index += 1;
175
+ }
176
+ count += 1 + inlineStructuralItemCount(paragraphLines.join(" "));
177
+ }
178
+ return count;
179
+ }
180
+ function renderMarkdown(document, source) {
181
+ const fragment = document.createDocumentFragment();
182
+ const lines = source.slice(0, MAX_MARKDOWN_CHARACTERS).split(/\r\n?|\n/);
183
+ let index = 0;
184
+ while (index < lines.length) {
185
+ const line = lines[index];
186
+ if (line.trim().length === 0) {
187
+ index += 1;
188
+ continue;
189
+ }
190
+ const headingText = heading(line);
191
+ if (headingText !== null) {
192
+ const paragraph = document.createElement("p");
193
+ const strong = document.createElement("strong");
194
+ appendInlineMarkdown(document, strong, headingText);
195
+ paragraph.append(strong);
196
+ fragment.append(paragraph);
197
+ index += 1;
198
+ continue;
199
+ }
200
+ const unorderedItem = unorderedListItem(line);
201
+ const orderedItem = orderedListItem(line);
202
+ if (unorderedItem !== null || orderedItem !== null) {
203
+ const list = document.createElement(unorderedItem === null ? "ol" : "ul");
204
+ const itemForLine = unorderedItem === null ? orderedListItem : unorderedListItem;
205
+ while (index < lines.length) {
206
+ const item = itemForLine(lines[index]);
207
+ if (item === null) break;
208
+ const listItem = document.createElement("li");
209
+ appendInlineMarkdown(document, listItem, item);
210
+ list.append(listItem);
211
+ index += 1;
212
+ }
213
+ fragment.append(list);
214
+ continue;
215
+ }
216
+ const paragraphLines = [];
217
+ while (index < lines.length) {
218
+ const paragraphLine = lines[index];
219
+ if (paragraphLine.trim().length === 0 || heading(paragraphLine) !== null || unorderedListItem(paragraphLine) !== null || orderedListItem(paragraphLine) !== null) break;
220
+ paragraphLines.push(paragraphLine);
221
+ index += 1;
222
+ }
223
+ const paragraph = document.createElement("p");
224
+ appendInlineMarkdown(document, paragraph, paragraphLines.join(" "));
225
+ fragment.append(paragraph);
226
+ }
227
+ return fragment;
228
+ }
229
+ //#endregion
230
+ export { countMarkdownStructuralItems as n, renderMarkdown as r, MAX_MARKDOWN_CHARACTERS as t };
package/dist/mount.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { o as AiLiveChatProvider } from "./provider.js";
2
- import { M as AiLiveChatFactoryContext, d as AiChatBindings, u as AiChatBinding } from "./contracts.js";
2
+ import { j as AiLiveChatFactoryContext, l as AiChatBinding, u as AiChatBindings } from "./contracts.js";
3
3
  //#region src/mount.d.ts
4
4
  /**
5
5
  * The provider a person answers through, chosen by the root's attributes: Omnichannel when
package/dist/styles.css CHANGED
@@ -58,6 +58,9 @@
58
58
  --vv-ai-chat-window-header-hover: color-mix(in srgb, var(--vv-ai-chat-window-header-text) 15%, transparent);
59
59
  /* An image in the circle beside each of the assistant's bubbles in the window. */
60
60
  --vv-ai-chat-assistant-avatar: none;
61
+ /* Buttons and fields in the window's thread, the host's own included. */
62
+ --vv-ai-chat-window-control-height: 2.25rem;
63
+ --vv-ai-chat-window-control-font-size: 0.875rem;
61
64
  --vv-ai-launcher-shadow: 0 0.375rem 1.25rem rgb(16 40 80 / 0.25);
62
65
  --vv-ai-launcher-teaser-shadow: 0 0.5rem 1.5rem rgb(16 40 80 / 0.15);
63
66
  --vv-ai-menu-shadow: 0 0.5rem 1.5rem rgb(16 40 80 / 0.18);
@@ -1385,6 +1388,42 @@ body:has(.vv-ai-chat:not(.vv-ai-chat--window)) {
1385
1388
  line-height: 1.4;
1386
1389
  }
1387
1390
 
1391
+ /*
1392
+ * Buttons and fields in the window's thread stay small. A component the host embeds there brings
1393
+ * the site's buttons and fields, sized for a page, so the common button classes are caught here as
1394
+ * well as the package's own. The composer below the thread keeps its own.
1395
+ */
1396
+ .vv-ai-chat--window .vv-ai-chat__thread-inner :is(
1397
+ .button, [class^="button-"], [class*=" button-"],
1398
+ .btn, [class^="btn-"], [class*=" btn-"],
1399
+ .bttn, [class^="bttn-"], [class*=" bttn-"],
1400
+ .vv-ai-actions__action,
1401
+ .vv-ai-survey__submit
1402
+ ) {
1403
+ min-height: var(--vv-ai-chat-window-control-height);
1404
+ padding-block: 0.375rem;
1405
+ padding-inline: 1rem;
1406
+ font-size: var(--vv-ai-chat-window-control-font-size);
1407
+ line-height: 1.5;
1408
+ }
1409
+
1410
+ .vv-ai-chat--window .vv-ai-chat__thread-inner :is(
1411
+ input:not([type="checkbox"], [type="radio"], [type="range"], [type="hidden"], [type="file"]),
1412
+ select
1413
+ ) {
1414
+ box-sizing: border-box;
1415
+ height: var(--vv-ai-chat-window-control-height);
1416
+ padding-block: 0.5rem;
1417
+ font-size: var(--vv-ai-chat-window-control-font-size);
1418
+ line-height: 1.2;
1419
+ }
1420
+
1421
+ .vv-ai-chat--window .vv-ai-chat__thread-inner textarea {
1422
+ padding-block: 0.5rem;
1423
+ font-size: var(--vv-ai-chat-window-control-font-size);
1424
+ line-height: 1.4;
1425
+ }
1426
+
1388
1427
  .vv-ai-chat--window .vv-ai-chat__composer-inner {
1389
1428
  max-width: none;
1390
1429
  padding: 0.75rem 0.75rem 0.5rem;
package/dist/survey.js CHANGED
@@ -1,232 +1,5 @@
1
- import { a as isSafeLinkUrl, r as createSafeLink, t as createPart } from "./dom.js";
2
- //#region src/markdown.ts
3
- const MAX_MARKDOWN_CHARACTERS = 8e3;
4
- function isWordCharacter(character) {
5
- return character !== void 0 && /[\p{L}\p{N}]/u.test(character);
6
- }
7
- function delimitedToken(source, start, marker, type) {
8
- if (!source.startsWith(marker, start)) return null;
9
- const contentStart = start + marker.length;
10
- const closing = source.indexOf(marker, contentStart);
11
- if (closing === -1 || closing === contentStart) return null;
12
- return {
13
- type,
14
- content: source.slice(contentStart, closing),
15
- end: closing + marker.length
16
- };
17
- }
18
- function linkToken(source, start) {
19
- if (source[start] !== "[") return null;
20
- let labelEnd = start + 1;
21
- while (labelEnd < source.length) {
22
- if (source[labelEnd] === "[") return null;
23
- if (source[labelEnd] === "]" && source[labelEnd + 1] === "(") break;
24
- labelEnd += 1;
25
- }
26
- if (labelEnd === source.length) return {
27
- type: "text",
28
- content: source.slice(start),
29
- end: source.length
30
- };
31
- if (labelEnd === start + 1) return null;
32
- let depth = 1;
33
- let end = labelEnd + 2;
34
- while (end < source.length && depth > 0) {
35
- if (source[end] === "(") depth += 1;
36
- else if (source[end] === ")") depth -= 1;
37
- end += 1;
38
- }
39
- if (depth !== 0) return {
40
- type: "text",
41
- content: source.slice(start),
42
- end: source.length
43
- };
44
- const url = source.slice(labelEnd + 2, end - 1);
45
- if (!isSafeLinkUrl(url)) return {
46
- type: "text",
47
- content: source.slice(start, end),
48
- end
49
- };
50
- return {
51
- type: "link",
52
- label: source.slice(start + 1, labelEnd),
53
- url,
54
- end
55
- };
56
- }
57
- function inlineToken(source, start) {
58
- const link = linkToken(source, start);
59
- if (link) return link;
60
- const code = delimitedToken(source, start, "`", "code");
61
- if (code) return code;
62
- const bold = delimitedToken(source, start, "**", "bold") ?? delimitedToken(source, start, "__", "bold");
63
- if (bold) return bold;
64
- const marker = source[start];
65
- if ((marker === "*" || marker === "_") && !isWordCharacter(source[start - 1])) return delimitedToken(source, start, marker, "italic");
66
- return null;
67
- }
68
- function inlineStructuralItemCount(source) {
69
- let count = 0;
70
- let index = 0;
71
- while (index < source.length) {
72
- const token = inlineToken(source, index);
73
- if (!token) {
74
- index += 1;
75
- continue;
76
- }
77
- switch (token.type) {
78
- case "bold":
79
- case "italic":
80
- count += 1 + inlineStructuralItemCount(token.content);
81
- break;
82
- case "code":
83
- case "link": count += 1;
84
- }
85
- index = token.end;
86
- }
87
- return count;
88
- }
89
- function appendInlineMarkdown(document, parent, source) {
90
- let textStart = 0;
91
- let index = 0;
92
- while (index < source.length) {
93
- const token = inlineToken(source, index);
94
- if (!token) {
95
- index += 1;
96
- continue;
97
- }
98
- if (textStart < index) parent.append(document.createTextNode(source.slice(textStart, index)));
99
- switch (token.type) {
100
- case "code": {
101
- const code = document.createElement("code");
102
- code.append(document.createTextNode(token.content));
103
- parent.append(code);
104
- break;
105
- }
106
- case "bold": {
107
- const strong = document.createElement("strong");
108
- appendInlineMarkdown(document, strong, token.content);
109
- parent.append(strong);
110
- break;
111
- }
112
- case "italic": {
113
- const emphasis = document.createElement("em");
114
- appendInlineMarkdown(document, emphasis, token.content);
115
- parent.append(emphasis);
116
- break;
117
- }
118
- case "link": {
119
- const link = createSafeLink(document, token.label, token.url);
120
- if (link) parent.append(link);
121
- else parent.append(document.createTextNode(source.slice(index, token.end)));
122
- break;
123
- }
124
- case "text": parent.append(document.createTextNode(token.content));
125
- }
126
- index = token.end;
127
- textStart = index;
128
- }
129
- if (textStart < source.length) parent.append(document.createTextNode(source.slice(textStart)));
130
- }
131
- function unorderedListItem(line) {
132
- return /^\s*[-+*]\s+(.+)$/.exec(line)?.[1] ?? null;
133
- }
134
- function orderedListItem(line) {
135
- return /^\s*\d+[.)]\s+(.+)$/.exec(line)?.[1] ?? null;
136
- }
137
- function heading(line) {
138
- return /^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$/.exec(line)?.[1] ?? null;
139
- }
140
- function countMarkdownStructuralItems(source) {
141
- const lines = source.slice(0, MAX_MARKDOWN_CHARACTERS).split(/\r\n?|\n/);
142
- let count = 0;
143
- let index = 0;
144
- while (index < lines.length) {
145
- const line = lines[index];
146
- if (line.trim().length === 0) {
147
- index += 1;
148
- continue;
149
- }
150
- const headingText = heading(line);
151
- if (headingText !== null) {
152
- count += 2 + inlineStructuralItemCount(headingText);
153
- index += 1;
154
- continue;
155
- }
156
- const unorderedItem = unorderedListItem(line);
157
- const orderedItem = orderedListItem(line);
158
- if (unorderedItem !== null || orderedItem !== null) {
159
- const itemForLine = unorderedItem === null ? orderedListItem : unorderedListItem;
160
- count += 1;
161
- while (index < lines.length) {
162
- const item = itemForLine(lines[index]);
163
- if (item === null) break;
164
- count += 1 + inlineStructuralItemCount(item);
165
- index += 1;
166
- }
167
- continue;
168
- }
169
- const paragraphLines = [];
170
- while (index < lines.length) {
171
- const paragraphLine = lines[index];
172
- if (paragraphLine.trim().length === 0 || heading(paragraphLine) !== null || unorderedListItem(paragraphLine) !== null || orderedListItem(paragraphLine) !== null) break;
173
- paragraphLines.push(paragraphLine);
174
- index += 1;
175
- }
176
- count += 1 + inlineStructuralItemCount(paragraphLines.join(" "));
177
- }
178
- return count;
179
- }
180
- function renderMarkdown(document, source) {
181
- const fragment = document.createDocumentFragment();
182
- const lines = source.slice(0, MAX_MARKDOWN_CHARACTERS).split(/\r\n?|\n/);
183
- let index = 0;
184
- while (index < lines.length) {
185
- const line = lines[index];
186
- if (line.trim().length === 0) {
187
- index += 1;
188
- continue;
189
- }
190
- const headingText = heading(line);
191
- if (headingText !== null) {
192
- const paragraph = document.createElement("p");
193
- const strong = document.createElement("strong");
194
- appendInlineMarkdown(document, strong, headingText);
195
- paragraph.append(strong);
196
- fragment.append(paragraph);
197
- index += 1;
198
- continue;
199
- }
200
- const unorderedItem = unorderedListItem(line);
201
- const orderedItem = orderedListItem(line);
202
- if (unorderedItem !== null || orderedItem !== null) {
203
- const list = document.createElement(unorderedItem === null ? "ol" : "ul");
204
- const itemForLine = unorderedItem === null ? orderedListItem : unorderedListItem;
205
- while (index < lines.length) {
206
- const item = itemForLine(lines[index]);
207
- if (item === null) break;
208
- const listItem = document.createElement("li");
209
- appendInlineMarkdown(document, listItem, item);
210
- list.append(listItem);
211
- index += 1;
212
- }
213
- fragment.append(list);
214
- continue;
215
- }
216
- const paragraphLines = [];
217
- while (index < lines.length) {
218
- const paragraphLine = lines[index];
219
- if (paragraphLine.trim().length === 0 || heading(paragraphLine) !== null || unorderedListItem(paragraphLine) !== null || orderedListItem(paragraphLine) !== null) break;
220
- paragraphLines.push(paragraphLine);
221
- index += 1;
222
- }
223
- const paragraph = document.createElement("p");
224
- appendInlineMarkdown(document, paragraph, paragraphLines.join(" "));
225
- fragment.append(paragraph);
226
- }
227
- return fragment;
228
- }
229
- //#endregion
1
+ import { t as createPart } from "./dom.js";
2
+ import { r as renderMarkdown } from "./markdown.js";
230
3
  //#region src/live-chat/survey.ts
231
4
  /** Every element of the survey form carries a class under this block. */
232
5
  const SURVEY_CLASS = "vv-ai-survey";
@@ -389,4 +162,4 @@ function renderSurveyForm(document, fields, options) {
389
162
  };
390
163
  }
391
164
  //#endregion
392
- export { renderMarkdown as i, renderSurveyForm as n, countMarkdownStructuralItems as r, SURVEY_CLASS as t };
165
+ export { renderSurveyForm as n, SURVEY_CLASS as t };
package/dist/window.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { a as isSafeLinkUrl, i as isPlainObject, o as readJsonAttribute, r as createSafeLink, t as createPart } from "./dom.js";
2
- import { i as renderMarkdown, n as renderSurveyForm, r as countMarkdownStructuralItems } from "./survey.js";
2
+ import { t as readServerEvents } from "./events.js";
3
+ import { n as countMarkdownStructuralItems, r as renderMarkdown } from "./markdown.js";
4
+ import { n as renderSurveyForm } from "./survey.js";
3
5
  //#region src/answer-card.ts
4
6
  const ANSWER_CARD_KEYS = /* @__PURE__ */ new Set([
5
7
  "kind",
@@ -517,81 +519,22 @@ function parseStreamEvent(name, data) {
517
519
  }
518
520
  //#endregion
519
521
  //#region src/stream.ts
520
- const MAX_RECORD_LENGTH = 1048576;
521
- function findRecordBoundary(buffer) {
522
- const lfIndex = buffer.indexOf("\n\n");
523
- const crlfIndex = buffer.indexOf("\r\n\r\n");
524
- if (lfIndex === -1 && crlfIndex === -1) return null;
525
- if (lfIndex === -1 || crlfIndex !== -1 && crlfIndex < lfIndex) return {
526
- index: crlfIndex,
527
- length: 4
528
- };
529
- return {
530
- index: lfIndex,
531
- length: 2
532
- };
533
- }
534
- function fieldValue(value) {
535
- return value.startsWith(" ") ? value.slice(1) : value;
536
- }
537
- function parseRecord(record) {
538
- let name;
539
- const dataLines = [];
540
- for (const line of record.split(/\r?\n/)) if (line.startsWith("event:")) name = fieldValue(line.slice(6));
541
- else if (line.startsWith("data:")) dataLines.push(fieldValue(line.slice(5)));
542
- if (!name || dataLines.length === 0) return null;
522
+ function parseEvent(name, data) {
543
523
  try {
544
- return parseStreamEvent(name, JSON.parse(dataLines.join("\n")));
524
+ return parseStreamEvent(name, JSON.parse(data));
545
525
  } catch {
546
526
  return null;
547
527
  }
548
528
  }
549
- function abortError$1() {
550
- return /* @__PURE__ */ new Error("AI chat event stream was aborted");
551
- }
552
529
  async function* readEventStream(response, signal) {
553
- if (!response.body) throw new Error("AI chat response has no body");
554
- if (signal.aborted) throw abortError$1();
555
- const decoder = new TextDecoder();
556
- const reader = response.body.getReader();
557
- let buffer = "";
558
- let readerDone = false;
559
- const cancelReader = () => {
560
- reader.cancel().catch(() => void 0);
561
- };
562
- signal.addEventListener("abort", cancelReader, { once: true });
563
- try {
564
- while (true) {
565
- if (signal.aborted) throw abortError$1();
566
- const { done, value } = await reader.read();
567
- if (signal.aborted) throw abortError$1();
568
- if (done) {
569
- readerDone = true;
570
- buffer += decoder.decode();
571
- } else buffer += decoder.decode(value, { stream: true });
572
- let boundary = findRecordBoundary(buffer);
573
- while (boundary) {
574
- const event = parseRecord(buffer.slice(0, boundary.index));
575
- buffer = buffer.slice(boundary.index + boundary.length);
576
- if (event) {
577
- if (event.name === "done" || event.name === "error") {
578
- yield event;
579
- return;
580
- }
581
- yield event;
582
- }
583
- boundary = findRecordBoundary(buffer);
584
- }
585
- if (buffer.length > MAX_RECORD_LENGTH) throw new Error("AI chat event stream sent an event that is too large");
586
- if (readerDone) throw new Error("AI chat event stream ended before a terminal event");
530
+ for await (const record of readServerEvents(response, signal)) {
531
+ const event = parseEvent(record.name, record.data);
532
+ if (event) {
533
+ yield event;
534
+ if (event.name === "done" || event.name === "error") return;
587
535
  }
588
- } finally {
589
- signal.removeEventListener("abort", cancelReader);
590
- if (!readerDone) try {
591
- await reader.cancel();
592
- } catch {}
593
- reader.releaseLock();
594
536
  }
537
+ throw new Error("AI chat event stream ended before a terminal event");
595
538
  }
596
539
  //#endregion
597
540
  //#region src/chat.ts
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vettvangur/ai-sdk",
3
- "version": "0.14.0",
4
- "description": "Framework-agnostic AI chat client for server-rendered shells",
3
+ "version": "0.15.0",
4
+ "description": "Framework-agnostic AI client primitives, and an AI chat for server-rendered shells",
5
5
  "type": "module",
6
6
  "access": "public",
7
7
  "author": "Vettvangur",
@@ -18,6 +18,10 @@
18
18
  "types": "./dist/index.d.ts",
19
19
  "import": "./dist/index.js"
20
20
  },
21
+ "./chat": {
22
+ "types": "./dist/chat.d.ts",
23
+ "import": "./dist/chat.js"
24
+ },
21
25
  "./live-chat": {
22
26
  "types": "./dist/live-chat.d.ts",
23
27
  "import": "./dist/live-chat.js"