@vettvangur/ai-sdk 0.4.1 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/survey.js ADDED
@@ -0,0 +1,393 @@
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
230
+ //#region src/live-chat/survey.ts
231
+ /** Every element of the survey form carries a class under this block. */
232
+ const SURVEY_CLASS = "vv-ai-survey";
233
+ let forms = 0;
234
+ function prefillFor(field, prefill) {
235
+ return prefill?.[field.name] ?? prefill?.[field.id];
236
+ }
237
+ function textControl(document, field, value) {
238
+ const input = field.multiline ? createPart(document, "textarea", SURVEY_CLASS, "input") : createPart(document, "input", SURVEY_CLASS, "input");
239
+ if (input instanceof HTMLInputElement) input.type = field.inputType;
240
+ if (field.maxLength) input.maxLength = field.maxLength;
241
+ if (field.placeholder) input.placeholder = field.placeholder;
242
+ if (typeof value === "string") input.value = value;
243
+ return input;
244
+ }
245
+ function choiceControl(document, field, value) {
246
+ const select = createPart(document, "select", SURVEY_CLASS, "input");
247
+ select.multiple = field.multiple;
248
+ if (!field.multiple) select.append(document.createElement("option"));
249
+ const wanted = typeof value === "string" ? value.split(",").map((item) => item.trim()) : [];
250
+ for (const choice of field.choices) {
251
+ const option = document.createElement("option");
252
+ option.value = choice.value;
253
+ option.textContent = choice.label;
254
+ select.append(option);
255
+ option.selected = wanted.includes(choice.value) || wanted.includes(choice.label);
256
+ }
257
+ return select;
258
+ }
259
+ function answerOf(control) {
260
+ const { field, input } = control;
261
+ if (field.kind === "toggle") return input.checked;
262
+ if (input instanceof HTMLSelectElement && input.multiple) return Array.from(input.selectedOptions, (option) => option.value).join(",");
263
+ return input.value.trim();
264
+ }
265
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
266
+ function problemOf(control) {
267
+ const answer = answerOf(control);
268
+ if (control.field.required && (answer === "" || answer === false)) return "missing";
269
+ if (control.input instanceof HTMLInputElement && control.input.type === "email" && answer !== "" && !EMAIL.test(String(answer))) return "email";
270
+ return null;
271
+ }
272
+ /**
273
+ * The pre-chat survey as a form in the thread. Prefilled fields are still shown, so the visitor
274
+ * sees and can change everything that is sent. A required toggle must be on, as a consent is.
275
+ * Submit stays disabled until every answer is valid, and a field says what is wrong with it once
276
+ * the visitor leaves it.
277
+ */
278
+ function renderSurveyForm(document, fields, options) {
279
+ forms += 1;
280
+ const form = createPart(document, "form", SURVEY_CLASS);
281
+ form.noValidate = true;
282
+ const controls = [];
283
+ if (options.labels.title || options.labels.intro) {
284
+ const header = createPart(document, "div", SURVEY_CLASS, "header");
285
+ if (options.labels.title) header.append(createPart(document, "p", SURVEY_CLASS, "title", options.labels.title));
286
+ if (options.labels.intro) header.append(createPart(document, "p", SURVEY_CLASS, "intro", options.labels.intro));
287
+ form.append(header);
288
+ }
289
+ fields.forEach((field, index) => {
290
+ if (field.kind === "note") {
291
+ const note = createPart(document, "div", SURVEY_CLASS, "note");
292
+ note.append(renderMarkdown(document, field.text));
293
+ form.append(note);
294
+ return;
295
+ }
296
+ const id = `${SURVEY_CLASS}-${forms}-${index}`;
297
+ const wrapper = createPart(document, "div", SURVEY_CLASS, "field");
298
+ wrapper.classList.add(`${SURVEY_CLASS}__field--${field.kind}`);
299
+ const label = createPart(document, "label", SURVEY_CLASS, "label");
300
+ label.htmlFor = id;
301
+ label.append(renderMarkdown(document, field.label));
302
+ const value = prefillFor(field, options.prefill);
303
+ let input;
304
+ if (field.kind === "text") input = textControl(document, field, value);
305
+ else if (field.kind === "choice") input = choiceControl(document, field, value);
306
+ else {
307
+ input = createPart(document, "input", SURVEY_CLASS, "input");
308
+ input.type = "checkbox";
309
+ input.checked = value === true || value === "true";
310
+ }
311
+ input.id = id;
312
+ input.name = field.name;
313
+ input.required = field.required;
314
+ const error = createPart(document, "p", SURVEY_CLASS, "error", options.labels.required);
315
+ error.id = `${id}-error`;
316
+ error.hidden = true;
317
+ input.setAttribute("aria-describedby", error.id);
318
+ if (field.kind === "toggle") wrapper.append(input, label, error);
319
+ else {
320
+ wrapper.append(label, input);
321
+ if (options.labels.prefilled && input.value !== "") wrapper.append(createPart(document, "p", SURVEY_CLASS, "prefilled", options.labels.prefilled));
322
+ wrapper.append(error);
323
+ }
324
+ form.append(wrapper);
325
+ controls.push({
326
+ field,
327
+ wrapper,
328
+ input,
329
+ error
330
+ });
331
+ });
332
+ const actions = createPart(document, "div", SURVEY_CLASS, "actions");
333
+ const submit = createPart(document, "button", SURVEY_CLASS, "submit", options.labels.submit);
334
+ submit.type = "submit";
335
+ const cancelButton = createPart(document, "button", SURVEY_CLASS, "cancel", options.labels.cancel);
336
+ cancelButton.type = "button";
337
+ actions.append(submit, cancelButton);
338
+ form.append(actions);
339
+ let settle = () => void 0;
340
+ const answers = new Promise((resolve) => {
341
+ settle = resolve;
342
+ });
343
+ let settled = false;
344
+ function finish(result) {
345
+ if (settled) return;
346
+ settled = true;
347
+ form.classList.add(`${SURVEY_CLASS}--${result ? "submitted" : "canceled"}`);
348
+ for (const element of form.querySelectorAll("input, textarea, select, button")) element.disabled = true;
349
+ settle(result);
350
+ }
351
+ function check(control) {
352
+ const problem = problemOf(control);
353
+ control.error.textContent = problem === "email" ? options.labels.invalidEmail ?? options.labels.required : options.labels.required;
354
+ control.wrapper.classList.toggle(`${SURVEY_CLASS}__field--invalid`, problem !== null);
355
+ control.input.setAttribute("aria-invalid", String(problem !== null));
356
+ control.error.hidden = problem === null;
357
+ return problem === null;
358
+ }
359
+ function update() {
360
+ if (!settled) submit.disabled = controls.some((control) => problemOf(control) !== null);
361
+ }
362
+ for (const control of controls) {
363
+ control.input.addEventListener("input", () => {
364
+ if (control.wrapper.classList.contains(`vv-ai-survey__field--invalid`)) check(control);
365
+ update();
366
+ });
367
+ control.input.addEventListener("change", () => {
368
+ check(control);
369
+ update();
370
+ });
371
+ }
372
+ update();
373
+ form.addEventListener("submit", (event) => {
374
+ event.preventDefault();
375
+ const invalid = controls.filter((control) => !check(control));
376
+ if (invalid.length) {
377
+ invalid[0]?.input.focus();
378
+ update();
379
+ return;
380
+ }
381
+ const result = {};
382
+ for (const control of controls) result[control.field.id] = answerOf(control);
383
+ finish(result);
384
+ });
385
+ cancelButton.addEventListener("click", () => finish(null));
386
+ return {
387
+ form,
388
+ answers,
389
+ cancel: () => finish(null)
390
+ };
391
+ }
392
+ //#endregion
393
+ export { renderMarkdown as i, renderSurveyForm as n, countMarkdownStructuralItems as r, SURVEY_CLASS as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vettvangur/ai-sdk",
3
- "version": "0.4.1",
3
+ "version": "0.5.4",
4
4
  "description": "Framework-agnostic AI chat client for server-rendered shells",
5
5
  "type": "module",
6
6
  "access": "public",
@@ -15,10 +15,31 @@
15
15
  ".": {
16
16
  "types": "./dist/index.d.ts",
17
17
  "import": "./dist/index.js"
18
+ },
19
+ "./live-chat": {
20
+ "types": "./dist/live-chat.d.ts",
21
+ "import": "./dist/live-chat.js"
22
+ },
23
+ "./live-chat/omnichannel": {
24
+ "types": "./dist/live-chat/omnichannel.d.ts",
25
+ "import": "./dist/live-chat/omnichannel.js"
26
+ },
27
+ "./live-chat/aichat": {
28
+ "types": "./dist/live-chat/aichat.d.ts",
29
+ "import": "./dist/live-chat/aichat.js"
18
30
  }
19
31
  },
20
32
  "types": "./dist/index.d.ts",
33
+ "peerDependencies": {
34
+ "@microsoft/omnichannel-chat-sdk": "^2.0.2"
35
+ },
36
+ "peerDependenciesMeta": {
37
+ "@microsoft/omnichannel-chat-sdk": {
38
+ "optional": true
39
+ }
40
+ },
21
41
  "devDependencies": {
42
+ "@microsoft/omnichannel-chat-sdk": "2.0.2",
22
43
  "rimraf": "6.1.3",
23
44
  "tsdown": "0.22.14",
24
45
  "typescript": "7.0.2"