@wakflo/react 0.0.0-stage → 0.1.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/dist/index.cjs ADDED
@@ -0,0 +1,900 @@
1
+ "use client";
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ PublicError: () => import_client3.PublicError,
25
+ WakfloChat: () => WakfloChat,
26
+ contactFields: () => contactFields,
27
+ useWakfloChat: () => useWakfloChat
28
+ });
29
+ module.exports = __toCommonJS(index_exports);
30
+ var import_client3 = require("@wakflo/client");
31
+
32
+ // src/contact-form.tsx
33
+ var import_react = require("react");
34
+ var import_jsx_runtime = require("react/jsx-runtime");
35
+ var TYPES = ["text", "email", "number", "textarea"];
36
+ var DEFAULT_CONTACT_FIELDS = [
37
+ { key: "name", label: "Name", required: true, type: "text" },
38
+ { key: "email", label: "Work email", required: true, type: "email" },
39
+ { key: "company", label: "Company", required: false, type: "text" },
40
+ { key: "team_size", label: "Team size", required: false, type: "text" },
41
+ {
42
+ key: "question",
43
+ label: "What would you like to talk about?",
44
+ required: false,
45
+ type: "textarea"
46
+ }
47
+ ];
48
+ function contactPrefill(args) {
49
+ const out = {};
50
+ for (const [k, v] of Object.entries(args)) {
51
+ if (k === "fields" || k === "title") {
52
+ continue;
53
+ }
54
+ if (typeof v === "string" || typeof v === "number") {
55
+ out[k] = String(v);
56
+ }
57
+ }
58
+ return out;
59
+ }
60
+ function contactFields(args) {
61
+ const raw = Array.isArray(args.fields) ? args.fields : [];
62
+ const fields = [];
63
+ for (const f of raw) {
64
+ if (!(f && typeof f === "object")) {
65
+ continue;
66
+ }
67
+ const r = f;
68
+ if (typeof r.key !== "string" || r.key === "") {
69
+ continue;
70
+ }
71
+ fields.push({
72
+ key: r.key,
73
+ label: typeof r.label === "string" && r.label ? r.label : r.key,
74
+ type: TYPES.includes(r.type) ? r.type : "text",
75
+ required: r.required === true
76
+ });
77
+ }
78
+ return fields.length > 0 ? fields : [...DEFAULT_CONTACT_FIELDS];
79
+ }
80
+ function ContactForm({ call, onSubmit }) {
81
+ const id = (0, import_react.useId)();
82
+ const fields = contactFields(call.args);
83
+ const title = typeof call.args.title === "string" && call.args.title ? call.args.title : "Your details";
84
+ const [values, setValues] = (0, import_react.useState)(
85
+ () => contactPrefill(call.args)
86
+ );
87
+ const [sent, setSent] = (0, import_react.useState)(false);
88
+ const submit = (e) => {
89
+ e.preventDefault();
90
+ const out = {};
91
+ for (const f of fields) {
92
+ const v = (values[f.key] ?? "").trim();
93
+ if (v === "") {
94
+ continue;
95
+ }
96
+ const n = Number(v);
97
+ out[f.key] = f.type === "number" && !Number.isNaN(n) ? n : v;
98
+ }
99
+ setSent(true);
100
+ onSubmit(out);
101
+ };
102
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("form", { "aria-label": title, className: "wakflo-chat__card", onSubmit: submit, children: [
103
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "wakflo-chat__card-title", children: title }),
104
+ fields.map((f) => {
105
+ const fieldId = `${id}-${f.key}`;
106
+ const common = {
107
+ className: "wakflo-chat__input",
108
+ disabled: sent,
109
+ id: fieldId,
110
+ name: f.key,
111
+ required: f.required,
112
+ value: values[f.key] ?? "",
113
+ onChange: (e) => setValues((v) => ({ ...v, [f.key]: e.target.value }))
114
+ };
115
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { className: "wakflo-chat__field", htmlFor: fieldId, children: [
116
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
117
+ f.label,
118
+ f.required ? null : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "wakflo-chat__optional", children: " (optional)" })
119
+ ] }),
120
+ f.type === "textarea" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("textarea", { ...common, rows: 3 }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { ...common, type: f.type })
121
+ ] }, f.key);
122
+ }),
123
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { className: "wakflo-chat__button", disabled: sent, type: "submit", children: sent ? "Sent" : "Send" })
124
+ ] });
125
+ }
126
+
127
+ // src/use-wakflo-chat.ts
128
+ var import_client = require("@wakflo/client");
129
+ var import_react2 = require("react");
130
+ var ok = (p) => p.then(
131
+ () => true,
132
+ () => false
133
+ );
134
+ function useWakfloChat(options) {
135
+ const latest = (0, import_react2.useRef)(options);
136
+ latest.current = options;
137
+ const { apiUrl, baseUrl, publishableKey } = options;
138
+ const client = (0, import_react2.useMemo)(() => {
139
+ const o = latest.current;
140
+ return (0, import_client.createClient)({
141
+ apiUrl,
142
+ baseUrl,
143
+ publishableKey,
144
+ fetch: o.fetch,
145
+ storage: o.storage,
146
+ reconnectDelay: o.reconnectDelay,
147
+ // Asked each time, so a changed prop is used without a new client.
148
+ botToken: () => latest.current.botToken?.() ?? null,
149
+ portalToken: () => latest.current.portalToken?.() ?? null
150
+ });
151
+ }, [apiUrl, baseUrl, publishableKey]);
152
+ const chat = (0, import_react2.useMemo)(() => client.conversation(), [client]);
153
+ const subscribe = (0, import_react2.useCallback)(
154
+ (listener) => chat.subscribe(listener),
155
+ [chat]
156
+ );
157
+ const read = (0, import_react2.useCallback)(() => chat.state, [chat]);
158
+ const state = (0, import_react2.useSyncExternalStore)(subscribe, read, read);
159
+ const [config, setConfig] = (0, import_react2.useState)(null);
160
+ (0, import_react2.useEffect)(() => {
161
+ let live = true;
162
+ client.config().then(
163
+ (c) => {
164
+ if (live) {
165
+ setConfig(c);
166
+ }
167
+ },
168
+ () => {
169
+ }
170
+ );
171
+ return () => {
172
+ live = false;
173
+ };
174
+ }, [client]);
175
+ const connect = options.connect !== false;
176
+ (0, import_react2.useEffect)(() => {
177
+ if (!connect) {
178
+ return;
179
+ }
180
+ chat.connect();
181
+ return () => chat.disconnect();
182
+ }, [chat, connect]);
183
+ const [open, setOpen] = (0, import_react2.useState)(options.defaultOpen ?? false);
184
+ const answers = (0, import_react2.useRef)({
185
+ runId: "",
186
+ results: /* @__PURE__ */ new Map()
187
+ });
188
+ const respond = (0, import_react2.useCallback)(
189
+ (callId, result, error) => {
190
+ const pending = chat.pendingTool;
191
+ if (!pending?.calls.some((c) => c.id === callId)) {
192
+ return;
193
+ }
194
+ if (answers.current.runId !== pending.runId) {
195
+ answers.current = { runId: pending.runId, results: /* @__PURE__ */ new Map() };
196
+ }
197
+ const { results } = answers.current;
198
+ results.set(callId, {
199
+ toolCallId: callId,
200
+ result,
201
+ ...error ? { error } : {}
202
+ });
203
+ if (pending.calls.every((c) => results.has(c.id))) {
204
+ const all = pending.calls.map((c) => results.get(c.id)).filter((r) => r !== void 0);
205
+ chat.answerTool(pending.runId, all).catch(() => {
206
+ results.clear();
207
+ });
208
+ }
209
+ },
210
+ [chat]
211
+ );
212
+ const send = (0, import_react2.useCallback)((content) => ok(chat.send(content)), [chat]);
213
+ const handover = (0, import_react2.useCallback)(() => ok(chat.handover()), [chat]);
214
+ const setEmail = (0, import_react2.useCallback)(
215
+ (email, name) => ok(chat.setEmail(email, name)),
216
+ [chat]
217
+ );
218
+ const reset = (0, import_react2.useCallback)(() => chat.reset(), [chat]);
219
+ return {
220
+ client,
221
+ chat,
222
+ config,
223
+ conversation: state.conversation,
224
+ status: state.conversation?.status ?? null,
225
+ messages: state.messages,
226
+ typing: state.typing,
227
+ pendingTool: state.pendingTool,
228
+ toolCall: state.pendingTool,
229
+ notices: state.notices,
230
+ connection: state.connection,
231
+ error: state.error,
232
+ send,
233
+ handover,
234
+ setEmail,
235
+ respond,
236
+ reset,
237
+ open,
238
+ setOpen
239
+ };
240
+ }
241
+
242
+ // src/wakflo-chat.tsx
243
+ var import_client2 = require("@wakflo/client");
244
+ var import_react3 = require("react");
245
+
246
+ // src/icons.tsx
247
+ var import_jsx_runtime2 = require("react/jsx-runtime");
248
+ function Spark() {
249
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
250
+ "svg",
251
+ {
252
+ "aria-hidden": "true",
253
+ fill: "currentColor",
254
+ focusable: "false",
255
+ height: "13",
256
+ viewBox: "0 0 24 24",
257
+ width: "13",
258
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M12 2.5c.4 4.6 2.9 7.1 7.5 7.5v.1c-4.6.4-7.1 2.9-7.5 7.5h-.1c-.4-4.6-2.9-7.1-7.4-7.5V10c4.5-.4 7-2.9 7.4-7.5z" })
259
+ }
260
+ );
261
+ }
262
+ var stroke = {
263
+ fill: "none",
264
+ height: 16,
265
+ stroke: "currentColor",
266
+ strokeLinecap: "round",
267
+ strokeLinejoin: "round",
268
+ strokeWidth: 2,
269
+ viewBox: "0 0 24 24",
270
+ width: 16
271
+ };
272
+ function Pencil() {
273
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("svg", { "aria-hidden": "true", focusable: "false", ...stroke, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z" }) });
274
+ }
275
+ function Close() {
276
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("svg", { "aria-hidden": "true", focusable: "false", ...stroke, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M18 6 6 18M6 6l12 12" }) });
277
+ }
278
+ function Arrow() {
279
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("svg", { "aria-hidden": "true", focusable: "false", ...stroke, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M5 12h14M13 6l6 6-6 6" }) });
280
+ }
281
+
282
+ // src/markdown.tsx
283
+ var import_jsx_runtime3 = require("react/jsx-runtime");
284
+ var BULLET = /^\s*[-*+]\s+(.*)$/;
285
+ var NUMBERED = /^\s*\d+[.)]\s+(.*)$/;
286
+ var HEADING = /^\s*#{1,6}\s+(.*)$/;
287
+ var INLINE = /\*\*([^*]+)\*\*|\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|(https?:\/\/[^\s<]+)/g;
288
+ var TRAILING_PUNCTUATION = /[.,;:!?)]+$/;
289
+ var SAFE_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:", "mailto:"]);
290
+ function parseBlocks(text) {
291
+ const blocks = [];
292
+ let para = [];
293
+ let list2 = null;
294
+ const flush = () => {
295
+ if (para.length > 0) {
296
+ blocks.push({ kind: "p", lines: para });
297
+ para = [];
298
+ }
299
+ if (list2) {
300
+ blocks.push(list2);
301
+ list2 = null;
302
+ }
303
+ };
304
+ for (const line of text.replace(/\r\n?/g, "\n").split("\n")) {
305
+ const bullet = BULLET.exec(line);
306
+ const numbered = bullet ? null : NUMBERED.exec(line);
307
+ const item = bullet ?? numbered;
308
+ if (item) {
309
+ const kind = bullet ? "ul" : "ol";
310
+ if (para.length > 0 || list2?.kind !== kind) {
311
+ flush();
312
+ list2 = { kind, items: [] };
313
+ }
314
+ list2?.items.push(item[1] ?? "");
315
+ continue;
316
+ }
317
+ if (line.trim() === "") {
318
+ flush();
319
+ continue;
320
+ }
321
+ if (list2) {
322
+ flush();
323
+ }
324
+ para.push(HEADING.exec(line)?.[1] ?? line);
325
+ }
326
+ flush();
327
+ return blocks;
328
+ }
329
+ function safeHref(url) {
330
+ try {
331
+ const parsed = new URL(url);
332
+ return SAFE_PROTOCOLS.has(parsed.protocol) ? parsed.href : null;
333
+ } catch {
334
+ return null;
335
+ }
336
+ }
337
+ function link(href, label, key) {
338
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("a", { href, rel: "noopener noreferrer", target: "_blank", children: label }, key);
339
+ }
340
+ function inline(text, prefix = "i") {
341
+ const out = [];
342
+ let last = 0;
343
+ let n = 0;
344
+ for (const m of text.matchAll(INLINE)) {
345
+ const at = m.index ?? 0;
346
+ if (at > last) {
347
+ out.push(text.slice(last, at));
348
+ }
349
+ n += 1;
350
+ const key = `${prefix}.${n}`;
351
+ const [whole, bold, label, url, code, bare] = m;
352
+ let end = at + whole.length;
353
+ if (bold !== void 0) {
354
+ out.push(/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("strong", { children: inline(bold, key) }, key));
355
+ } else if (label !== void 0 && url !== void 0) {
356
+ const href = safeHref(url);
357
+ out.push(href ? link(href, label, key) : label);
358
+ } else if (code !== void 0) {
359
+ out.push(/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("code", { children: code }, key));
360
+ } else if (bare !== void 0) {
361
+ const trimmed = bare.replace(TRAILING_PUNCTUATION, "");
362
+ end = at + trimmed.length;
363
+ const href = safeHref(trimmed);
364
+ out.push(href ? link(href, trimmed, key) : trimmed);
365
+ }
366
+ last = end;
367
+ }
368
+ if (last < text.length) {
369
+ out.push(text.slice(last));
370
+ }
371
+ return out;
372
+ }
373
+ function paragraph(lines, key) {
374
+ const out = [];
375
+ let l = 0;
376
+ for (const line of lines) {
377
+ if (l > 0) {
378
+ out.push(/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("br", {}, `${key}.br${l}`));
379
+ }
380
+ out.push(...inline(line, `${key}.${l}`));
381
+ l += 1;
382
+ }
383
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { children: out }, key);
384
+ }
385
+ function list(block, key) {
386
+ const items = [];
387
+ let i = 0;
388
+ for (const item of block.items) {
389
+ const itemKey = `${key}.${i}`;
390
+ items.push(/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("li", { children: inline(item, itemKey) }, itemKey));
391
+ i += 1;
392
+ }
393
+ return block.kind === "ul" ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("ul", { children: items }, key) : /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("ol", { children: items }, key);
394
+ }
395
+ function Markdown({ text }) {
396
+ const out = [];
397
+ let b = 0;
398
+ for (const block of parseBlocks(text)) {
399
+ const key = `b${b}`;
400
+ out.push(
401
+ block.kind === "p" ? paragraph(block.lines, key) : list(block, key)
402
+ );
403
+ b += 1;
404
+ }
405
+ return out;
406
+ }
407
+
408
+ // src/wakflo-chat.tsx
409
+ var import_jsx_runtime4 = require("react/jsx-runtime");
410
+ var WAITING_LINE = "I've asked the team. Someone usually answers within a few minutes.";
411
+ var EMAIL_ASK = "Nobody from the team is free right now. Leave your email and we'll answer there.";
412
+ var UNSUPPORTED = "unsupported_tool";
413
+ var ASK_PREFIX = /^ask\s+/i;
414
+ var SPACE = /\s+/;
415
+ var APPLE = /mac|iphone|ipad/i;
416
+ function initials(name) {
417
+ const parts = name.trim().split(SPACE).filter(Boolean);
418
+ const first = parts[0]?.[0] ?? "";
419
+ const last = parts.length > 1 ? parts.at(-1)?.[0] ?? "" : "";
420
+ return (first + last).toUpperCase() || "?";
421
+ }
422
+ function placeholderFor(title) {
423
+ return ASK_PREFIX.test(title) ? `Ask about ${title.replace(ASK_PREFIX, "")}` : "Ask a question";
424
+ }
425
+ function useIsMac() {
426
+ const [mac, setMac] = (0, import_react3.useState)(true);
427
+ (0, import_react3.useEffect)(() => {
428
+ const nav = globalThis.navigator;
429
+ const platform = nav?.userAgentData?.platform ?? nav?.platform ?? "";
430
+ setMac(APPLE.test(platform));
431
+ }, []);
432
+ return mac;
433
+ }
434
+ function MessageView({
435
+ message,
436
+ onRetry
437
+ }) {
438
+ const { author } = message;
439
+ if (author.kind === "system") {
440
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { className: "wakflo-chat__system", children: message.content });
441
+ }
442
+ if (author.kind === "visitor") {
443
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "wakflo-chat__mine", children: [
444
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "wakflo-chat__bubble wakflo-chat__bubble--me", children: message.content }),
445
+ message.failed ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
446
+ "button",
447
+ {
448
+ className: "wakflo-chat__retry",
449
+ onClick: () => onRetry(message.id),
450
+ type: "button",
451
+ children: "Not sent. Try again"
452
+ }
453
+ ) : null
454
+ ] });
455
+ }
456
+ const body = message.streaming && message.content === "" ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Dots, {}) : /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Markdown, { text: message.content });
457
+ if (author.kind === "member") {
458
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "wakflo-chat__member", children: [
459
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { "aria-hidden": "true", className: "wakflo-chat__avatar", children: initials(author.name) }),
460
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "wakflo-chat__member-body", children: [
461
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { className: "wakflo-chat__name", children: author.name }),
462
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "wakflo-chat__bubble", children: body })
463
+ ] })
464
+ ] });
465
+ }
466
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
467
+ "div",
468
+ {
469
+ "aria-busy": message.streaming ? true : void 0,
470
+ className: "wakflo-chat__bubble",
471
+ "data-streaming": message.streaming ? "true" : void 0,
472
+ children: body
473
+ }
474
+ );
475
+ }
476
+ function Dots() {
477
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("span", { className: "wakflo-chat__dots", children: [
478
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", {}),
479
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", {}),
480
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", {})
481
+ ] });
482
+ }
483
+ function EmailAsk({
484
+ notice,
485
+ onSubmit
486
+ }) {
487
+ const id = (0, import_react3.useId)();
488
+ const [email, setEmail] = (0, import_react3.useState)("");
489
+ const [name, setName] = (0, import_react3.useState)("");
490
+ const [busy, setBusy] = (0, import_react3.useState)(false);
491
+ const submit = async (e) => {
492
+ e.preventDefault();
493
+ if (!email.trim()) {
494
+ return;
495
+ }
496
+ setBusy(true);
497
+ await onSubmit(email.trim(), name.trim() || void 0);
498
+ setBusy(false);
499
+ };
500
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
501
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "wakflo-chat__bubble", children: notice.message || EMAIL_ASK }),
502
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
503
+ "form",
504
+ {
505
+ "aria-label": "Leave your email",
506
+ className: "wakflo-chat__card",
507
+ onSubmit: submit,
508
+ children: [
509
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { className: "wakflo-chat__field", htmlFor: `${id}-email`, children: [
510
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { children: "Email" }),
511
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
512
+ "input",
513
+ {
514
+ autoComplete: "email",
515
+ className: "wakflo-chat__input",
516
+ disabled: busy,
517
+ id: `${id}-email`,
518
+ onChange: (e) => setEmail(e.target.value),
519
+ required: true,
520
+ type: "email",
521
+ value: email
522
+ }
523
+ )
524
+ ] }),
525
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { className: "wakflo-chat__field", htmlFor: `${id}-name`, children: [
526
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("span", { children: [
527
+ "Name",
528
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { className: "wakflo-chat__optional", children: " (optional)" })
529
+ ] }),
530
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
531
+ "input",
532
+ {
533
+ autoComplete: "name",
534
+ className: "wakflo-chat__input",
535
+ disabled: busy,
536
+ id: `${id}-name`,
537
+ onChange: (e) => setName(e.target.value),
538
+ type: "text",
539
+ value: name
540
+ }
541
+ )
542
+ ] }),
543
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("button", { className: "wakflo-chat__button", disabled: busy, type: "submit", children: "Send" })
544
+ ]
545
+ }
546
+ )
547
+ ] });
548
+ }
549
+ function StatusLines({
550
+ available,
551
+ conversation,
552
+ notices,
553
+ setEmail
554
+ }) {
555
+ const askEmail = [...notices].reverse().find((n) => n.code === "ask_email");
556
+ const others = notices.filter((n) => n.code !== "ask_email");
557
+ const status = conversation?.status;
558
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
559
+ status === "waiting" && available && !askEmail ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "wakflo-chat__bubble", children: WAITING_LINE }) : null,
560
+ askEmail && !conversation?.email ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(EmailAsk, { notice: askEmail, onSubmit: setEmail }) : null,
561
+ conversation?.email && status === "waiting" ? /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("p", { className: "wakflo-chat__system", children: [
562
+ "We'll answer at ",
563
+ conversation.email,
564
+ "."
565
+ ] }) : null,
566
+ others.map((n) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { className: "wakflo-chat__system", children: n.message || n.code }, `${n.code}:${n.message}`))
567
+ ] });
568
+ }
569
+ function themeOf(prop, config) {
570
+ return prop ?? config?.theme ?? "system";
571
+ }
572
+ function useTools(state, renderTool) {
573
+ const drawn = [];
574
+ const declined = [];
575
+ for (const call of state.pendingTool?.calls ?? []) {
576
+ const respond2 = (result, error) => state.respond(call.id, result, error);
577
+ const custom = renderTool?.(call, respond2);
578
+ if (custom !== void 0 && custom !== null) {
579
+ drawn.push({ call, node: custom });
580
+ } else if (call.name === "contact_form") {
581
+ drawn.push({
582
+ call,
583
+ node: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ContactForm, { call, onSubmit: (values) => respond2(values) })
584
+ });
585
+ } else {
586
+ declined.push(call.id);
587
+ }
588
+ }
589
+ const declinedKey = declined.join(",");
590
+ const { respond } = state;
591
+ (0, import_react3.useEffect)(() => {
592
+ if (!declinedKey) {
593
+ return;
594
+ }
595
+ for (const id of declinedKey.split(",")) {
596
+ respond(id, null, UNSUPPORTED);
597
+ }
598
+ }, [declinedKey, respond]);
599
+ return drawn;
600
+ }
601
+ function Header({
602
+ onClose,
603
+ onReset,
604
+ title,
605
+ titleId
606
+ }) {
607
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "wakflo-chat__header", children: [
608
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { "aria-hidden": "true", className: "wakflo-chat__tile", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Spark, {}) }),
609
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("h2", { className: "wakflo-chat__title", id: titleId, children: title }),
610
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
611
+ "button",
612
+ {
613
+ "aria-label": "New chat",
614
+ className: "wakflo-chat__icon-btn",
615
+ onClick: onReset,
616
+ title: "New chat",
617
+ type: "button",
618
+ children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Pencil, {})
619
+ }
620
+ ),
621
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
622
+ "button",
623
+ {
624
+ "aria-label": "Close chat",
625
+ className: "wakflo-chat__icon-btn",
626
+ onClick: onClose,
627
+ title: "Close",
628
+ type: "button",
629
+ children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Close, {})
630
+ }
631
+ )
632
+ ] });
633
+ }
634
+ function Typing({ state }) {
635
+ const streaming = state.messages.some((m) => m.streaming);
636
+ if (state.typing.length === 0 || streaming) {
637
+ return null;
638
+ }
639
+ const names = state.typing.map((a) => a.name).filter(Boolean);
640
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("output", { className: "wakflo-chat__bubble wakflo-chat__typing", children: [
641
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { className: "wakflo-chat__sr", children: names.length > 0 ? `${names.join(", ")} is typing` : "Typing" }),
642
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Dots, {})
643
+ ] });
644
+ }
645
+ function ErrorLine({ state }) {
646
+ if (!state.error || state.messages.some((m) => m.failed)) {
647
+ return null;
648
+ }
649
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { className: "wakflo-chat__system wakflo-chat__system--error", children: state.connection === "closed" ? "The chat can't connect right now." : state.error.message || "Something went wrong." });
650
+ }
651
+ function Log({
652
+ available,
653
+ greeting,
654
+ state,
655
+ tools
656
+ }) {
657
+ const ref = (0, import_react3.useRef)(null);
658
+ const { messages } = state;
659
+ const lastKey = [
660
+ messages.length,
661
+ messages.at(-1)?.content.length ?? 0,
662
+ state.typing.length,
663
+ state.notices.length,
664
+ state.pendingTool?.runId ?? "",
665
+ state.status ?? ""
666
+ ].join(":");
667
+ (0, import_react3.useEffect)(() => {
668
+ const log = ref.current;
669
+ if (log && lastKey) {
670
+ log.scrollTop = log.scrollHeight;
671
+ }
672
+ }, [lastKey]);
673
+ const retry = (id) => {
674
+ state.chat.retry(id).catch(() => void 0);
675
+ };
676
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { "aria-live": "polite", className: "wakflo-chat__log", ref, role: "log", children: [
677
+ greeting ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "wakflo-chat__bubble", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Markdown, { text: greeting }) }) : null,
678
+ messages.map((m) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(MessageView, { message: m, onRetry: retry }, m.id)),
679
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
680
+ StatusLines,
681
+ {
682
+ available,
683
+ conversation: state.conversation,
684
+ notices: state.notices,
685
+ setEmail: state.setEmail
686
+ }
687
+ ),
688
+ tools.map((d) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "wakflo-chat__tool", children: d.node }, d.call.id)),
689
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Typing, { state }),
690
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ErrorLine, { state })
691
+ ] });
692
+ }
693
+ function Composer({
694
+ inputRef,
695
+ onSend,
696
+ placeholder
697
+ }) {
698
+ const inputId = (0, import_react3.useId)();
699
+ const [draft, setDraft] = (0, import_react3.useState)("");
700
+ const submit = (e) => {
701
+ e.preventDefault();
702
+ const text = draft.trim();
703
+ if (!text) {
704
+ return;
705
+ }
706
+ setDraft("");
707
+ onSend(text);
708
+ };
709
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("form", { className: "wakflo-chat__composer", onSubmit: submit, children: [
710
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("label", { className: "wakflo-chat__sr", htmlFor: inputId, children: "Message" }),
711
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
712
+ "input",
713
+ {
714
+ autoComplete: "off",
715
+ className: "wakflo-chat__input wakflo-chat__input--composer",
716
+ id: inputId,
717
+ maxLength: import_client2.MAX_MESSAGE_LENGTH,
718
+ onChange: (e) => setDraft(e.target.value),
719
+ placeholder,
720
+ ref: inputRef,
721
+ value: draft
722
+ }
723
+ ),
724
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
725
+ "button",
726
+ {
727
+ "aria-label": "Send",
728
+ className: "wakflo-chat__send",
729
+ disabled: !draft.trim(),
730
+ type: "submit",
731
+ children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Arrow, {})
732
+ }
733
+ )
734
+ ] });
735
+ }
736
+ function Suggestions({
737
+ onAsk,
738
+ suggestions
739
+ }) {
740
+ if (suggestions.length === 0) {
741
+ return null;
742
+ }
743
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "wakflo-chat__chips", children: suggestions.map((q) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
744
+ "button",
745
+ {
746
+ className: "wakflo-chat__chip",
747
+ onClick: () => onAsk(q),
748
+ type: "button",
749
+ children: q
750
+ },
751
+ q
752
+ )) });
753
+ }
754
+ function useKeyboard(open, setOpen, refs) {
755
+ (0, import_react3.useEffect)(() => {
756
+ const onKey = (e) => {
757
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "j") {
758
+ e.preventDefault();
759
+ setOpen((o) => !o);
760
+ return;
761
+ }
762
+ const panel = refs.panel.current;
763
+ if (e.key === "Escape" && panel && panel.contains(document.activeElement)) {
764
+ setOpen(false);
765
+ }
766
+ };
767
+ document.addEventListener("keydown", onKey);
768
+ return () => document.removeEventListener("keydown", onKey);
769
+ }, [setOpen, refs]);
770
+ const wasOpen = (0, import_react3.useRef)(open);
771
+ (0, import_react3.useEffect)(() => {
772
+ if (open && !wasOpen.current) {
773
+ refs.input.current?.focus();
774
+ } else if (!open && wasOpen.current) {
775
+ refs.launcher.current?.focus();
776
+ }
777
+ wasOpen.current = open;
778
+ }, [open, refs]);
779
+ }
780
+ function WakfloChat(props) {
781
+ const { position = "bottom-right" } = props;
782
+ const state = useWakfloChat({
783
+ apiUrl: props.apiUrl,
784
+ baseUrl: props.baseUrl,
785
+ publishableKey: props.publishableKey,
786
+ defaultOpen: props.defaultOpen,
787
+ botToken: props.botToken,
788
+ fetch: props.fetch,
789
+ portalToken: props.portalToken,
790
+ storage: props.storage
791
+ });
792
+ const { config, conversation, messages, open, setOpen } = state;
793
+ const title = props.title ?? (config?.title || "Chat");
794
+ const accent = props.accent ?? config?.accent ?? void 0;
795
+ const mac = useIsMac();
796
+ const tools = useTools(state, props.renderTool);
797
+ const panelId = (0, import_react3.useId)();
798
+ const titleId = (0, import_react3.useId)();
799
+ const input = (0, import_react3.useRef)(null);
800
+ const launcher = (0, import_react3.useRef)(null);
801
+ const panel = (0, import_react3.useRef)(null);
802
+ const refs = (0, import_react3.useMemo)(() => ({ input, launcher, panel }), []);
803
+ useKeyboard(open, setOpen, refs);
804
+ const send = (text) => {
805
+ state.send(text);
806
+ };
807
+ const className = props.className ? `wakflo-chat ${props.className}` : "wakflo-chat";
808
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
809
+ "div",
810
+ {
811
+ className,
812
+ "data-open": open ? "true" : "false",
813
+ "data-position": position,
814
+ "data-theme": themeOf(props.theme, config),
815
+ style: accent ? { "--wakflo-accent": accent } : void 0,
816
+ children: [
817
+ open ? /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
818
+ "section",
819
+ {
820
+ "aria-labelledby": titleId,
821
+ className: "wakflo-chat__panel",
822
+ id: panelId,
823
+ ref: panel,
824
+ children: [
825
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
826
+ Header,
827
+ {
828
+ onClose: () => setOpen(false),
829
+ onReset: () => {
830
+ state.reset();
831
+ },
832
+ title,
833
+ titleId
834
+ }
835
+ ),
836
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
837
+ Log,
838
+ {
839
+ available: config?.available !== false,
840
+ greeting: props.greeting ?? config?.greeting ?? "",
841
+ state,
842
+ tools
843
+ }
844
+ ),
845
+ messages.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
846
+ Suggestions,
847
+ {
848
+ onAsk: send,
849
+ suggestions: props.suggestions ?? config?.suggestions ?? []
850
+ }
851
+ ) : null,
852
+ conversation?.status === "bot" && messages.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "wakflo-chat__actions", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
853
+ "button",
854
+ {
855
+ className: "wakflo-chat__link",
856
+ onClick: () => {
857
+ state.handover();
858
+ },
859
+ type: "button",
860
+ children: "Talk to a person"
861
+ }
862
+ ) }) : null,
863
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
864
+ Composer,
865
+ {
866
+ inputRef: input,
867
+ onSend: send,
868
+ placeholder: props.placeholder ?? placeholderFor(title)
869
+ }
870
+ )
871
+ ]
872
+ }
873
+ ) : null,
874
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
875
+ "button",
876
+ {
877
+ "aria-controls": open ? panelId : void 0,
878
+ "aria-expanded": open,
879
+ className: "wakflo-chat__launcher",
880
+ onClick: () => setOpen((o) => !o),
881
+ ref: launcher,
882
+ type: "button",
883
+ children: [
884
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { "aria-hidden": "true", className: "wakflo-chat__spark", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Spark, {}) }),
885
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { children: title }),
886
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { "aria-hidden": "true", className: "wakflo-chat__kbd", children: mac ? "\u2318J" : "Ctrl J" })
887
+ ]
888
+ }
889
+ )
890
+ ]
891
+ }
892
+ );
893
+ }
894
+ // Annotate the CommonJS export names for ESM import in node:
895
+ 0 && (module.exports = {
896
+ PublicError,
897
+ WakfloChat,
898
+ contactFields,
899
+ useWakfloChat
900
+ });