@kilichat/vue 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.js ADDED
@@ -0,0 +1,790 @@
1
+ import { Comment as e, Fragment as t, cloneVNode as n, computed as r, createBlock as i, createCommentVNode as a, createElementBlock as o, createElementVNode as s, createTextVNode as c, createVNode as l, defineComponent as u, inject as d, normalizeClass as f, normalizeStyle as p, onBeforeUnmount as m, onMounted as h, openBlock as g, provide as _, reactive as v, ref as y, renderList as b, renderSlot as x, shallowRef as S, toDisplayString as C, unref as w, watch as T, withCtx as E } from "vue";
2
+ import { ArrowLeft as ee, ChevronRight as te, MessageSquarePlus as ne, Paperclip as re, Send as ie, Smile as ae } from "@lucide/vue";
3
+ import { clsx as D } from "clsx";
4
+ import { twMerge as oe } from "tailwind-merge";
5
+ import { cva as se } from "class-variance-authority";
6
+ import ce from "axios";
7
+ import { io as O } from "socket.io-client";
8
+ import le from "@scaleway/random-name";
9
+ // src/lib/storage-keys.ts
10
+ var k = {
11
+ AccessTokenExp: "atexp",
12
+ JwtAccessToken: "at",
13
+ JwtRefreshToken: "rt",
14
+ User: "u"
15
+ }, A = { ActiveChat: "ac" }, j = Symbol("KiliAppState");
16
+ function ue() {
17
+ let e = v({
18
+ accessToken: null,
19
+ chats: [],
20
+ messages: [],
21
+ refreshToken: null,
22
+ user: null,
23
+ appendMessage(t) {
24
+ let n = e.messages.filter((e) => String(e.id) !== String(t.id));
25
+ e.messages = [...n, t];
26
+ },
27
+ setAccessToken(t) {
28
+ localStorage.setItem(k.JwtAccessToken, t), e.accessToken = t;
29
+ },
30
+ updateChat(t) {
31
+ e.chats = e.chats.map((e) => String(e.id) === String(t.id) ? t : e);
32
+ },
33
+ setChats(t) {
34
+ e.chats = t;
35
+ },
36
+ setMessages(t) {
37
+ e.messages = t;
38
+ },
39
+ setRefreshToken(t) {
40
+ localStorage.setItem(k.JwtRefreshToken, t), e.refreshToken = t;
41
+ },
42
+ setUser(t) {
43
+ localStorage.setItem(k.User, JSON.stringify(t)), e.user = t;
44
+ }
45
+ });
46
+ return e;
47
+ }
48
+ function de() {
49
+ let e = ue();
50
+ return _(j, e), e;
51
+ }
52
+ var M = () => {
53
+ let e = d(j, null);
54
+ if (!e) throw Error("useApp can only be called from inside AppStateProvider");
55
+ return e;
56
+ }, fe = /* @__PURE__ */ u({
57
+ __name: "AppStateProvider",
58
+ setup(e) {
59
+ return de(), (e, t) => x(e.$slots, "default");
60
+ }
61
+ });
62
+ // src/lib/utils.ts
63
+ function N(...e) {
64
+ return oe(D(e));
65
+ }
66
+ function P(e) {
67
+ if (!e) return "CS";
68
+ let [t, n] = e.split(" "), r = t?.substring(0, 1) ?? "", i = n?.substring(0, 1) ?? "";
69
+ return r === "" && i === "" ? "CS" : `${r.toUpperCase()}${i.toUpperCase()}`;
70
+ }
71
+ function pe(e, t) {
72
+ let n = e?.substring(0, 1) ?? "", r = t?.substring(0, 1) ?? "";
73
+ return n === "" && r === "" ? "CS" : `${n.toUpperCase()}${r.toUpperCase()}`;
74
+ }
75
+ // src/components/widget/InitialsAvatar.vue
76
+ var F = /* @__PURE__ */ u({
77
+ name: "InitialsAvatar",
78
+ __name: "InitialsAvatar",
79
+ props: {
80
+ initials: {},
81
+ size: { default: "md" },
82
+ tone: { default: "brand" },
83
+ class: { type: [
84
+ Boolean,
85
+ null,
86
+ String,
87
+ Object,
88
+ Array
89
+ ] }
90
+ },
91
+ setup(e) {
92
+ let t = e;
93
+ return (e, n) => (g(), o("span", { class: f(w(N)("inline-flex shrink-0 items-center justify-center rounded-full font-heading font-semibold tracking-tight", t.size === "sm" && "size-7 text-[11px]", t.size === "md" && "size-9 text-xs", t.size === "lg" && "size-12 text-sm", t.tone === "brand" && "bg-primary/15 text-primary", t.tone === "sage" && "bg-sage/20 text-forest", t.tone === "muted" && "bg-muted text-muted-foreground", t.class)) }, C(t.initials), 3));
94
+ }
95
+ }), I = se("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium cursor-pointer transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 disabled:cursor-not-allowed [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", {
96
+ variants: {
97
+ variant: {
98
+ default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
99
+ destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
100
+ outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
101
+ secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
102
+ ghost: "hover:bg-accent hover:text-accent-foreground",
103
+ link: "text-primary underline-offset-4 hover:underline"
104
+ },
105
+ size: {
106
+ default: "h-9 px-4 py-2",
107
+ sm: "h-8 rounded-md px-3 text-xs",
108
+ lg: "h-10 rounded-md px-8",
109
+ icon: "h-9 w-9"
110
+ }
111
+ },
112
+ defaultVariants: {
113
+ variant: "default",
114
+ size: "default"
115
+ }
116
+ });
117
+ // src/components/ui/slot.ts
118
+ function L(n) {
119
+ for (let r of n) if (r.type !== e) {
120
+ if (r.type === t && Array.isArray(r.children)) {
121
+ let e = L(r.children);
122
+ if (e) return e;
123
+ } else return r;
124
+ }
125
+ return null;
126
+ }
127
+ var R = u({
128
+ name: "Slot",
129
+ inheritAttrs: !1,
130
+ setup(e, { slots: t, attrs: r }) {
131
+ return () => {
132
+ let e = L(t.default?.() ?? []);
133
+ return e ? n(e, r, !0) : null;
134
+ };
135
+ }
136
+ }), z = /* @__PURE__ */ u({
137
+ name: "Button",
138
+ __name: "Button",
139
+ props: {
140
+ variant: {},
141
+ size: {},
142
+ asChild: {
143
+ type: Boolean,
144
+ default: !1
145
+ },
146
+ class: { type: [
147
+ Boolean,
148
+ null,
149
+ String,
150
+ Object,
151
+ Array
152
+ ] }
153
+ },
154
+ setup(e) {
155
+ let t = e, n = r(() => N(I({
156
+ variant: t.variant,
157
+ size: t.size,
158
+ className: t.class
159
+ })));
160
+ return (e, r) => t.asChild ? (g(), i(w(R), {
161
+ key: 0,
162
+ class: f(n.value)
163
+ }, {
164
+ default: E(() => [x(e.$slots, "default")]),
165
+ _: 3
166
+ }, 8, ["class"])) : (g(), o("button", {
167
+ key: 1,
168
+ class: f(n.value)
169
+ }, [x(e.$slots, "default")], 2));
170
+ }
171
+ }), B = {
172
+ name: "Kili",
173
+ greeting: "Hi there",
174
+ subline: "Ask us anything, or share your feedback. We usually reply in a few minutes.",
175
+ replyTime: "Typically replies in a few minutes"
176
+ }, me = {
177
+ name: "You",
178
+ initials: "YO"
179
+ }, V = [
180
+ {
181
+ id: "a-mara",
182
+ name: "Mara Okafor",
183
+ initials: "MO",
184
+ role: "Customer Support"
185
+ },
186
+ {
187
+ id: "a-devon",
188
+ name: "Devon Reyes",
189
+ initials: "DR",
190
+ role: "Billing Specialist"
191
+ },
192
+ {
193
+ id: "a-bot",
194
+ name: "Kili Team",
195
+ initials: "KT",
196
+ role: "Support Team"
197
+ }
198
+ ], H = (e) => (/* @__PURE__ */ new Date(Date.now() - e * 36e5)).toISOString(), U = (e, t = 0) => (/* @__PURE__ */ new Date(Date.now() - e * 864e5 - t * 36e5)).toISOString(), he = [{
199
+ id: "c-1",
200
+ subject: "Trouble syncing my orders",
201
+ agentId: "a-mara",
202
+ messages: [
203
+ {
204
+ id: "m-1",
205
+ kind: "customer",
206
+ body: "Hey — my orders stopped syncing this morning. Nothing new has come through since about 8am.",
207
+ at: H(5)
208
+ },
209
+ {
210
+ id: "m-2",
211
+ kind: "agent",
212
+ authorId: "a-mara",
213
+ body: "Thanks for flagging that! I can see the sync queue backed up on our side. I've re-queued your account now.",
214
+ at: H(4.6)
215
+ },
216
+ {
217
+ id: "m-3",
218
+ kind: "customer",
219
+ body: "Great, I can see a few coming in now. How long until it catches up fully?",
220
+ at: H(4.2)
221
+ },
222
+ {
223
+ id: "m-4",
224
+ kind: "agent",
225
+ authorId: "a-mara",
226
+ body: "Should be fully caught up within the hour. I'll keep an eye on it and let you know if anything stalls again.",
227
+ at: H(4)
228
+ }
229
+ ]
230
+ }, {
231
+ id: "c-2",
232
+ subject: "Invoice for August",
233
+ agentId: "a-devon",
234
+ messages: [
235
+ {
236
+ id: "m-5",
237
+ kind: "customer",
238
+ body: "Could you resend the August invoice? I can't find it in my inbox.",
239
+ at: U(3, 2)
240
+ },
241
+ {
242
+ id: "m-6",
243
+ kind: "agent",
244
+ authorId: "a-devon",
245
+ body: "Just sent it over to the billing email on file. Let me know if it doesn't land in the next few minutes.",
246
+ at: U(3, 1)
247
+ },
248
+ {
249
+ id: "m-7",
250
+ kind: "customer",
251
+ body: "Got it, thank you!",
252
+ at: U(3)
253
+ }
254
+ ],
255
+ closed: !0
256
+ }], ge = [
257
+ "Thanks for reaching out! Let me take a look at that for you.",
258
+ "Good question — I'm checking with the team and will come right back to you.",
259
+ "I've made a note of this on your account. Anything else I can help with?",
260
+ "That should be sorted now. Give it a refresh and let me know how it looks."
261
+ ], _e = 0;
262
+ function ve() {
263
+ let e = ge[_e % ge.length];
264
+ return _e += 1, e;
265
+ }
266
+ function ye(e) {
267
+ return V.find((t) => t.id === e) ?? V[2];
268
+ }
269
+ // src/lib/widget-format.ts
270
+ function W(e) {
271
+ return e ? new Date(e).toLocaleTimeString([], {
272
+ hour: "numeric",
273
+ minute: "2-digit"
274
+ }) : (/* @__PURE__ */ new Date()).toLocaleTimeString([], {
275
+ hour: "numeric",
276
+ minute: "2-digit"
277
+ });
278
+ }
279
+ function G(e) {
280
+ if (!e) return (/* @__PURE__ */ new Date()).toLocaleDateString([], {
281
+ weekday: "long",
282
+ month: "short",
283
+ day: "numeric"
284
+ });
285
+ let t = new Date(e), n = /* @__PURE__ */ new Date(), r = /* @__PURE__ */ new Date(Date.now() - 864e5), i = (e, t) => e.toDateString() === t.toDateString();
286
+ return i(t, n) ? "Today" : i(t, r) ? "Yesterday" : t.toLocaleDateString([], {
287
+ weekday: "long",
288
+ month: "short",
289
+ day: "numeric"
290
+ });
291
+ }
292
+ function be(e) {
293
+ let t = Date.now() - new Date(e).getTime(), n = Math.round(t / 6e4);
294
+ if (n < 1) return "just now";
295
+ if (n < 60) return `${n}m ago`;
296
+ let r = Math.round(n / 60);
297
+ if (r < 24) return `${r}h ago`;
298
+ let i = Math.round(r / 24);
299
+ return i < 7 ? `${i}d ago` : new Date(e).toLocaleDateString([], {
300
+ month: "short",
301
+ day: "numeric"
302
+ });
303
+ }
304
+ // src/components/widget/ChatHome.vue?vue&type=script&setup=true&lang.ts
305
+ var xe = { class: "flex min-h-0 flex-1 flex-col" }, Se = { class: "bg-brand-gradient px-6 pt-10 pb-12 text-primary-foreground sm:px-10 sm:pt-14" }, Ce = { class: "mx-auto w-full max-w-2xl" }, we = { class: "font-heading text-sm font-semibold tracking-wide opacity-90" }, Te = { class: "mt-4 font-heading text-3xl font-semibold sm:text-4xl" }, Ee = { class: "mt-2 max-w-md text-sm opacity-90 sm:text-base" }, De = { class: "min-h-0 flex-1 overflow-y-auto scrollbar-thin px-4 pt-6 pb-10 sm:px-10" }, Oe = { class: "mx-auto w-full max-w-2xl space-y-3" }, ke = { class: "grid size-10 shrink-0 place-items-center rounded-full bg-primary/15 text-primary" }, Ae = { class: "min-w-0 flex-1" }, je = { class: "block text-xs text-muted-foreground" }, Me = { class: "space-y-2" }, Ne = ["onClick"], Pe = { class: "min-w-0 flex-1" }, Fe = { class: "flex items-center justify-between gap-2" }, Ie = { class: "truncate font-heading text-sm font-semibold" }, Le = { class: "shrink-0 text-[11px] text-muted-foreground" }, Re = { class: "mt-0.5 block truncate text-xs text-muted-foreground" }, ze = {
306
+ key: 0,
307
+ class: "mt-2 inline-flex rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground"
308
+ }, Be = { class: "pt-6 text-center" }, Ve = /* @__PURE__ */ u({
309
+ name: "ChatHome",
310
+ __name: "ChatHome",
311
+ props: { chats: {} },
312
+ emits: ["open", "startNew"],
313
+ setup(e, { emit: n }) {
314
+ let r = n;
315
+ function i(e) {
316
+ return e.title ?? e.summary ?? e.lastMessagePreview?.substring(0, 30) ?? "Open conversation";
317
+ }
318
+ function u(e) {
319
+ let t = e.lastMessagePreview;
320
+ return t ? `${e.lastMessageSenderAccountType === "staff" ? e.assignedStaffFullName?.split(" ")[0] ?? "CS" : "You"}: ${t}` : "No messages yet";
321
+ }
322
+ return (n, d) => (g(), o("div", xe, [s("header", Se, [s("div", Ce, [
323
+ s("p", we, C(w(B).name), 1),
324
+ s("h1", Te, C(w(B).greeting), 1),
325
+ s("p", Ee, C(w(B).subline), 1)
326
+ ])]), s("div", De, [s("div", Oe, [
327
+ s("button", {
328
+ type: "button",
329
+ class: "flex w-full items-center gap-3 rounded-2xl border border-border bg-card p-4 text-left shadow-soft transition-colors hover:bg-accent/40",
330
+ onClick: d[0] ||= (e) => r("startNew")
331
+ }, [
332
+ s("span", ke, [l(w(ne), { class: "size-5" })]),
333
+ s("span", Ae, [d[1] ||= s("span", { class: "block font-heading text-sm font-semibold" }, "Start a conversation", -1), s("span", je, C(w(B).replyTime), 1)]),
334
+ l(w(te), { class: "size-4 shrink-0 text-muted-foreground" })
335
+ ]),
336
+ e.chats.length > 0 ? (g(), o(t, { key: 0 }, [d[2] ||= s("p", { class: "px-1 pt-4 text-xs font-medium tracking-wide text-muted-foreground uppercase" }, " Your conversations ", -1), s("ul", Me, [(g(!0), o(t, null, b(e.chats, (e) => (g(), o("li", { key: e.id }, [s("button", {
337
+ type: "button",
338
+ class: "flex w-full items-start gap-3 rounded-2xl border border-border bg-card p-4 text-left transition-colors hover:bg-accent/40",
339
+ onClick: (t) => r("open", e)
340
+ }, [l(F, {
341
+ initials: w(P)(e.assignedStaffFullName ?? ""),
342
+ size: "md",
343
+ tone: "sage"
344
+ }, null, 8, ["initials"]), s("span", Pe, [
345
+ s("span", Fe, [s("span", Ie, C(i(e)), 1), s("span", Le, C(e.lastMessagePreview ? w(be)(e.lastMessageSentAt ?? e.updatedAt) : ""), 1)]),
346
+ s("span", Re, C(u(e)), 1),
347
+ e.closedAt ? (g(), o("span", ze, " Closed ")) : a("", !0)
348
+ ])], 8, Ne)]))), 128))])], 64)) : a("", !0),
349
+ s("div", Be, [l(z, {
350
+ variant: "ghost",
351
+ size: "sm",
352
+ class: "text-xs text-muted-foreground",
353
+ onClick: () => {}
354
+ }, {
355
+ default: E(() => [...d[3] ||= [c(" Can't find what you need? Message us ", -1)]]),
356
+ _: 1
357
+ })])
358
+ ])])]));
359
+ }
360
+ }), He = ["value"], Ue = /* @__PURE__ */ u({
361
+ name: "Textarea",
362
+ __name: "Textarea",
363
+ props: {
364
+ modelValue: {},
365
+ class: { type: [
366
+ Boolean,
367
+ null,
368
+ String,
369
+ Object,
370
+ Array
371
+ ] }
372
+ },
373
+ emits: ["update:modelValue"],
374
+ setup(e, { emit: t }) {
375
+ let n = e, r = t;
376
+ return (e, t) => (g(), o("textarea", {
377
+ class: f(w(N)("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm", n.class)),
378
+ value: n.modelValue,
379
+ onInput: t[0] ||= (e) => r("update:modelValue", e.target.value)
380
+ }, null, 42, He));
381
+ }
382
+ }), K = null;
383
+ function q(e) {
384
+ K = e;
385
+ }
386
+ function J() {
387
+ if (!K) throw Error("Kili SDK is not configured. Render <KiliChat :config=\"...\" /> or call configureKili() first.");
388
+ return K;
389
+ }
390
+ function We() {
391
+ let e = J();
392
+ return e.socketBaseUrl ?? e.apiBaseUrl;
393
+ }
394
+ // src/lib/http.ts
395
+ var Y = ce.create();
396
+ Y.interceptors.request.use((e) => {
397
+ let t = J();
398
+ e.baseURL = t.apiBaseUrl, e.headers["Api-Key"] = t.apiKey, e.headers["Api-Secret"] = t.apiSecret;
399
+ let n = localStorage.getItem(k.JwtAccessToken);
400
+ return n && (e.headers.Authorization = `Bearer ${n}`), e;
401
+ });
402
+ // src/services/chat.service.ts
403
+ var X = {
404
+ async getAllChats(e) {
405
+ return (await Y.get(`/chats?customerId=${e}`)).data.data;
406
+ },
407
+ async getChatMessages(e) {
408
+ return (await Y.get(`/chats/${e}/messages`)).data.data;
409
+ },
410
+ async startChat() {
411
+ return (await Y.post("/chats", { initiationChannel: "web_widget" })).data.data;
412
+ },
413
+ async sendMessage() {},
414
+ async markMessageAsRead() {}
415
+ }, Ge = { class: "flex min-h-0 flex-1 flex-col bg-surface" }, Ke = { class: "border-b border-border bg-card px-4 py-3 sm:px-6" }, qe = { class: "mx-auto flex w-full max-w-2xl items-center gap-3" }, Je = { class: "min-w-0 flex-1" }, Ye = { class: "truncate font-heading text-sm font-semibold" }, Xe = { class: "truncate text-xs text-muted-foreground" }, Ze = { class: "min-h-0 flex-1 overflow-y-auto scrollbar-thin px-4 py-6 sm:px-6" }, Qe = { class: "mx-auto w-full max-w-2xl space-y-4" }, $e = {
416
+ key: 0,
417
+ class: "rounded-2xl border border-dashed border-border bg-card/60 p-6 text-center"
418
+ }, et = { class: "mt-3 font-heading text-sm font-semibold" }, tt = {
419
+ key: 0,
420
+ class: "flex items-center gap-3"
421
+ }, nt = { class: "text-[11px] text-muted-foreground" }, rt = {
422
+ key: 1,
423
+ class: "flex max-w-[80%] items-end gap-2"
424
+ }, it = { class: "rounded-2xl rounded-bl-sm border border-border bg-card px-4 py-2.5" }, at = { class: "text-sm whitespace-pre-wrap" }, ot = { class: "mt-1 text-[11px] text-muted-foreground" }, st = {
425
+ key: 2,
426
+ class: "ml-auto flex max-w-[80%] flex-row-reverse items-end gap-2"
427
+ }, ct = { class: "rounded-2xl rounded-br-sm bg-primary px-4 py-2.5 text-primary-foreground" }, lt = { class: "text-sm whitespace-pre-wrap" }, ut = { class: "mt-1 text-[11px] opacity-80" }, dt = {
428
+ key: 1,
429
+ class: "flex max-w-[80%] items-end gap-2"
430
+ }, ft = { class: "flex items-center gap-1 rounded-2xl rounded-bl-sm border border-border bg-card px-4 py-3" }, pt = { class: "border-t border-border bg-card px-4 py-3 sm:px-6" }, mt = { class: "mx-auto w-full max-w-2xl" }, ht = { class: "flex items-end gap-2" }, gt = { class: "mt-2 flex items-center gap-2 text-muted-foreground" }, _t = /* @__PURE__ */ u({
431
+ name: "ChatThread",
432
+ __name: "ChatThread",
433
+ props: {
434
+ chat: {},
435
+ draft: {},
436
+ typing: { type: Boolean }
437
+ },
438
+ emits: [
439
+ "update:draft",
440
+ "send",
441
+ "back",
442
+ "textfieldFocus",
443
+ "textfieldBlur"
444
+ ],
445
+ setup(e, { emit: n }) {
446
+ let i = e, c = n, u = y(null), d = M(), f = r(() => P(i.chat.assignedStaffFullName)), m = r(() => P(i.chat.customerFullName)), _ = r(() => i.chat.assignedStaffFullName?.split(" ")[0]), v = async () => {
447
+ let e = await X.getChatMessages(i.chat.id);
448
+ d.setMessages(e.data);
449
+ }, x = () => {
450
+ u.value?.scrollIntoView({
451
+ behavior: "smooth",
452
+ block: "end"
453
+ });
454
+ };
455
+ T(() => [d.messages.length, i.typing], x, { flush: "post" }), h(() => {
456
+ x(), v();
457
+ });
458
+ function S(e) {
459
+ let t = d.messages[e], n = d.messages[e - 1];
460
+ return !n || G(n.sentAt) !== G(t?.sentAt);
461
+ }
462
+ let te = () => crypto.randomUUID();
463
+ function ne(e) {
464
+ e.key === "Enter" && !e.shiftKey && (e.preventDefault(), c("send"));
465
+ }
466
+ let D = [
467
+ "0ms",
468
+ "150ms",
469
+ "300ms"
470
+ ];
471
+ return (e, n) => (g(), o("div", Ge, [
472
+ s("header", Ke, [s("div", qe, [
473
+ l(z, {
474
+ variant: "ghost",
475
+ size: "icon",
476
+ class: "size-8 shrink-0",
477
+ "aria-label": "Back",
478
+ onClick: n[0] ||= (e) => c("back")
479
+ }, {
480
+ default: E(() => [l(w(ee), { class: "size-4" })]),
481
+ _: 1
482
+ }),
483
+ l(F, {
484
+ initials: f.value,
485
+ size: "md",
486
+ tone: "sage"
487
+ }, null, 8, ["initials"]),
488
+ s("div", Je, [s("p", Ye, C(i.chat.assignedStaffFullName), 1), s("p", Xe, C(i.typing ? `${_.value} is typing…` : w(B).replyTime), 1)])
489
+ ])]),
490
+ s("div", Ze, [s("div", Qe, [
491
+ w(d).messages.length ? (g(), o("div", $e, [
492
+ l(F, {
493
+ initials: w(P)(i.chat.assignedStaffFullName),
494
+ size: "lg",
495
+ tone: "sage",
496
+ class: "mx-auto"
497
+ }, null, 8, ["initials"]),
498
+ s("p", et, "Say hello to " + C(_.value), 1),
499
+ n[5] ||= s("p", { class: "mt-1 text-xs text-muted-foreground" }, " Describe what you need help with and we'll take it from there. ", -1)
500
+ ])) : a("", !0),
501
+ (g(!0), o(t, null, b(w(d).messages, (e, t) => (g(), o("div", {
502
+ key: te(),
503
+ class: "space-y-4"
504
+ }, [S(t) ? (g(), o("div", tt, [
505
+ n[6] ||= s("span", { class: "h-px flex-1 bg-border" }, null, -1),
506
+ s("span", nt, C(w(G)(e.sentAt)), 1),
507
+ n[7] ||= s("span", { class: "h-px flex-1 bg-border" }, null, -1)
508
+ ])) : a("", !0), e.senderAccountType === "staff" ? (g(), o("div", rt, [l(F, {
509
+ initials: w(pe)(e.senderFirstName, e.senderLastName),
510
+ size: "sm",
511
+ tone: "sage"
512
+ }, null, 8, ["initials"]), s("div", it, [s("p", at, C(e.content), 1), s("p", ot, C(e.senderFirstName) + " · " + C(w(W)(e.sentAt)), 1)])])) : (g(), o("div", st, [l(F, {
513
+ initials: m.value,
514
+ size: "sm",
515
+ tone: "muted"
516
+ }, null, 8, ["initials"]), s("div", ct, [s("p", lt, C(e.content), 1), s("p", ut, C(w(W)(e.sentAt)) + " · Sent", 1)])]))]))), 128)),
517
+ i.typing ? (g(), o("div", dt, [l(F, {
518
+ initials: f.value,
519
+ size: "sm",
520
+ tone: "sage"
521
+ }, null, 8, ["initials"]), s("div", ft, [(g(), o(t, null, b(D, (e) => s("span", {
522
+ key: e,
523
+ class: "size-1.5 animate-bounce rounded-full bg-muted-foreground/60",
524
+ style: p({ animationDelay: e })
525
+ }, null, 4)), 64))])])) : a("", !0),
526
+ s("div", {
527
+ ref_key: "bottomRef",
528
+ ref: u
529
+ }, null, 512)
530
+ ])]),
531
+ s("div", pt, [s("div", mt, [s("div", ht, [l(Ue, {
532
+ "model-value": i.draft,
533
+ placeholder: "Write a message…",
534
+ "aria-label": "Write a message",
535
+ class: "max-h-40 min-h-[44px] flex-1 resize-none bg-background text-sm",
536
+ "onUpdate:modelValue": n[1] ||= (e) => c("update:draft", e),
537
+ onKeydown: ne,
538
+ onFocus: n[2] ||= (e) => c("textfieldFocus"),
539
+ onBlur: n[3] ||= (e) => c("textfieldBlur")
540
+ }, null, 8, ["model-value"]), l(z, {
541
+ size: "icon",
542
+ class: "size-10 shrink-0",
543
+ disabled: !i.draft.trim(),
544
+ "aria-label": "Send",
545
+ onClick: n[4] ||= (e) => c("send")
546
+ }, {
547
+ default: E(() => [l(w(ie), { class: "size-4" })]),
548
+ _: 1
549
+ }, 8, ["disabled"])]), s("div", gt, [
550
+ l(w(re), {
551
+ class: "size-4",
552
+ "aria-hidden": "true"
553
+ }),
554
+ l(w(ae), {
555
+ class: "size-4",
556
+ "aria-hidden": "true"
557
+ }),
558
+ n[8] ||= s("span", { class: "ml-auto text-[11px]" }, "Enter to send · Shift + Enter for a new line", -1)
559
+ ])])])
560
+ ]));
561
+ }
562
+ }), Z = Object.freeze({
563
+ Connection: "connection",
564
+ Disconnect: "disconnect",
565
+ Error: "error",
566
+ AssignChat: "assign_chat",
567
+ ChatAction: "chat_action",
568
+ ChatAssigned: "chat_assigned",
569
+ ChatDeassigned: "chat_deassigned",
570
+ ChatStarted: "chat_started",
571
+ ChatUpdated: "chat_updated",
572
+ ChatWindowClosed: "chat_window_closed",
573
+ ChatWindowOpened: "chat_window_opened",
574
+ CloseChat: "close_chat",
575
+ InternalNote: "internal_note",
576
+ JoinAllUnclosedChatRooms: "join_all_unclosed_chat_rooms",
577
+ JoinChatRoom: "join_chat_room",
578
+ JoinedChatRoom: "joined_chat_room",
579
+ LeaveRoom: "leave_room",
580
+ MarkMsgAsRead: "mark_msg_as_read",
581
+ Message: "message",
582
+ MessageDelivered: "message_delivered",
583
+ NewMention: "new_mention",
584
+ PrioritizeChat: "prioritize_chat",
585
+ RefetchChats: "refetch_chats",
586
+ ReopenChat: "reopen_chat",
587
+ RefetchChatCounts: "refetch_chat_counts",
588
+ SnoozeChat: "snooze_chat",
589
+ StartChat: "start_chat"
590
+ }), vt = {
591
+ key: 0,
592
+ class: "kili-root flex h-dvh w-full flex-col overflow-hidden bg-background"
593
+ }, yt = /* @__PURE__ */ u({
594
+ name: "ChatWidget",
595
+ __name: "ChatWidget",
596
+ setup(e) {
597
+ let t = y(""), n = y(!1), r = [], s = M(), c = y(null), l = { current: null }, u = (e) => {
598
+ let t = sessionStorage.getItem(A.ActiveChat);
599
+ if (!t) return;
600
+ let n = JSON.parse(t);
601
+ e.chatId == n.id && s?.appendMessage(e);
602
+ }, d = (e) => {
603
+ switch (e.action) {
604
+ case "typing.started":
605
+ n.value = !0;
606
+ break;
607
+ case "typing.stopped": n.value = !1;
608
+ }
609
+ }, f = async (e) => {
610
+ let t = JSON.parse(localStorage.getItem(k.User));
611
+ if (e.customerId != t.id) {
612
+ console.log("chat created by a different cstomer");
613
+ return;
614
+ }
615
+ l.current?.emit(Z.JoinChatRoom, e.id);
616
+ let n = await X.getAllChats(t.id);
617
+ s?.setChats(n.data), h(e);
618
+ }, p = (e) => {
619
+ let t = sessionStorage.getItem(A.ActiveChat);
620
+ if (!t) return;
621
+ let n = JSON.parse(t);
622
+ n && n.id === e.id && (c.value = e);
623
+ }, h = (e) => {
624
+ c.value = e, e ? sessionStorage.setItem(A.ActiveChat, JSON.stringify(e)) : sessionStorage.removeItem(A.ActiveChat);
625
+ };
626
+ m(() => {
627
+ r.forEach(clearTimeout);
628
+ }), T(() => [s.user, s.accessToken], () => {
629
+ if (!s || !s.user || !s.accessToken || l.current) return;
630
+ let e = O(We(), { extraHeaders: {
631
+ "Api-Key": J().apiKey,
632
+ "Api-Secret": J().apiSecret,
633
+ Authorization: `Bearer ${s.accessToken}`
634
+ } });
635
+ e.on("connect", () => {
636
+ console.log("socket connected"), e.emit(Z.JoinAllUnclosedChatRooms), e.on(Z.ChatAction, d), e.on(Z.ChatStarted, f), e.on(Z.ChatUpdated, p), e.on(Z.MessageDelivered, u);
637
+ }), e.on(Z.Disconnect, () => {
638
+ console.log("socket disconnected");
639
+ }), e.on(Z.Error, (t) => {
640
+ console.log(e.id, "has an error", t);
641
+ }), l.current = e;
642
+ }, { immediate: !0 });
643
+ let _ = () => {
644
+ if (!c.value) return;
645
+ let e = s?.user ?? JSON.parse(localStorage.getItem(k.User)), n = {
646
+ chatId: Number(c.value.id),
647
+ content: t.value.trim(),
648
+ senderEmail: e.email,
649
+ senderId: e.id,
650
+ sentAt: (/* @__PURE__ */ new Date()).toISOString(),
651
+ senderAccountType: "CUSTOMER",
652
+ senderFirstName: e.firstName,
653
+ senderLastName: e.lastName,
654
+ type: "TEXT"
655
+ };
656
+ l.current.emit(Z.ChatAction, {
657
+ action: "typing.stopped",
658
+ chatId: c.value.id
659
+ }), l.current.emit(Z.Message, n), t.value = "";
660
+ }, v = () => {
661
+ l?.current?.emit(Z.StartChat, { initiationChannel: "web_widget" }), t.value = "";
662
+ }, b = () => {
663
+ h(null), n.value = !1;
664
+ }, x = () => {
665
+ l.current?.emit(Z.ChatAction, {
666
+ action: "typing.stopped",
667
+ chatId: c.value?.id
668
+ });
669
+ }, S = () => {
670
+ l.current?.emit(Z.ChatAction, {
671
+ action: "typing.started",
672
+ chatId: c.value?.id
673
+ });
674
+ }, C = (e) => {
675
+ h(e), t.value = "";
676
+ };
677
+ return (e, r) => w(s) ? (g(), o("div", vt, [c.value ? (g(), i(_t, {
678
+ key: 0,
679
+ draft: t.value,
680
+ "onUpdate:draft": r[0] ||= (e) => t.value = e,
681
+ chat: c.value,
682
+ typing: n.value,
683
+ onSend: _,
684
+ onBack: b,
685
+ onTextfieldBlur: x,
686
+ onTextfieldFocus: S
687
+ }, null, 8, [
688
+ "draft",
689
+ "chat",
690
+ "typing"
691
+ ])) : (g(), i(Ve, {
692
+ key: 1,
693
+ chats: w(s).chats,
694
+ onOpen: C,
695
+ onStartNew: v
696
+ }, null, 8, ["chats"]))])) : a("", !0);
697
+ }
698
+ }), Q = {
699
+ async createCustomer() {
700
+ let e = localStorage.getItem(k.User);
701
+ if (e) return JSON.parse(e);
702
+ let [t, n] = le("", " ").split(" "), r = await Y.post("/customers", {
703
+ city: "Denver",
704
+ country: "united states",
705
+ device: "iPhone 17 pro",
706
+ email: `${t}.${n}@kili.africa`,
707
+ firstName: t,
708
+ id: crypto.randomUUID(),
709
+ lastName: n,
710
+ phoneCountryCode: "1",
711
+ phoneNumberSuffix: "1234567",
712
+ state: "Colorado"
713
+ });
714
+ return console.dir({ createdCustomer: r.data }, { depth: null }), localStorage.setItem(k.User, JSON.stringify(r.data.data)), r.data.data;
715
+ },
716
+ async registerCustomer() {
717
+ let e = localStorage.getItem(k.User), t = JSON.parse(e), n = await Y.put("/customers", {
718
+ id: t.userId,
719
+ email: t.email
720
+ });
721
+ return localStorage.setItem(k.JwtAccessToken, n.data.data.accessToken), localStorage.setItem(k.AccessTokenExp, n.data.data.expiresAt), n.data.data;
722
+ },
723
+ async setCustomerHmac() {
724
+ let e = localStorage.getItem(k.User), t = JSON.parse(e), n = crypto.randomUUID();
725
+ await Y.patch(`/customers/${t.userId}/hmac`, { hmac: n });
726
+ }
727
+ }, bt = /* @__PURE__ */ u({
728
+ name: "KiliChatBootstrap",
729
+ __name: "KiliChatBootstrap",
730
+ setup(e) {
731
+ let t = M(), n = async () => {
732
+ let e = await Q.createCustomer();
733
+ await Q.setCustomerHmac();
734
+ let n = await Q.registerCustomer();
735
+ t?.setUser(e), t?.setAccessToken(n.accessToken);
736
+ let r = await X.getAllChats(e.id);
737
+ t?.setChats(r.data);
738
+ };
739
+ return h(() => {
740
+ n();
741
+ }), (e, t) => (g(), i(yt));
742
+ }
743
+ }), xt = /* @__PURE__ */ u({
744
+ name: "KiliChat",
745
+ __name: "KiliChat",
746
+ props: { config: {} },
747
+ setup(e) {
748
+ let t = e;
749
+ return q(t.config), T(() => t.config, (e) => q(e), { deep: !0 }), (e, t) => (g(), i(fe, null, {
750
+ default: E(() => [l(bt)]),
751
+ _: 1
752
+ }));
753
+ }
754
+ }), $ = Symbol("KiliSocket");
755
+ function St() {
756
+ return d($, null);
757
+ }
758
+ // src/context/SocketProvider.vue
759
+ var Ct = /* @__PURE__ */ u({
760
+ __name: "SocketProvider",
761
+ setup(e) {
762
+ let t = S(null), n = d(j, null);
763
+ return T(() => [n?.user, n?.accessToken], () => {
764
+ if (!n || !n.user || !n.accessToken || t.value) return;
765
+ let e = O(We(), { extraHeaders: {
766
+ "Api-Key": J().apiKey,
767
+ "Api-Secret": J().apiSecret,
768
+ Authorization: `Bearer ${n.accessToken}`
769
+ } });
770
+ e.on("connect", () => {
771
+ console.log(e.id, "connected to the socket"), e.emit(Z.JoinAllUnclosedChatRooms), e.on(Z.JoinedChatRoom, (e) => console.log("joined chat room", e));
772
+ }), e.on(Z.Disconnect, () => {
773
+ console.log(e.id, "has disconnected from the socket");
774
+ }), e.on(Z.Error, (t) => {
775
+ console.log(e.id, "has an error", t);
776
+ }), t.value = e;
777
+ }, { immediate: !0 }), _($, t), (e, t) => x(e.$slots, "default");
778
+ }
779
+ }), wt = 768;
780
+ function Tt() {
781
+ let e = y(void 0), t = null, n = () => {
782
+ e.value = window.innerWidth < wt;
783
+ };
784
+ return h(() => {
785
+ t = window.matchMedia("(max-width: 767px)"), t.addEventListener("change", n), e.value = window.innerWidth < wt;
786
+ }), m(() => t?.removeEventListener("change", n)), r(() => !!e.value);
787
+ }
788
+ export { j as AppStateContext, fe as AppStateProvider, z as Button, Ve as ChatHome, _t as ChatThread, yt as ChatWidget, F as InitialsAvatar, xt as KiliChat, k as LocalStorageKeys, A as SessionStorageKeys, R as Slot, $ as SocketContext, Z as SocketEvent, Ct as SocketProvider, Ue as Textarea, ye as agentById, V as agents, B as brand, I as buttonVariants, X as chatService, W as clockTime, N as cn, q as configureKili, Q as coreService, ue as createAppState, me as customer, G as dayLabel, P as getInitialsFromFullName, pe as getInitialsFromNames, J as getKiliConfig, Y as http, ve as nextCannedReply, de as provideAppState, be as relativeTime, he as seedConversations, M as useApp, Tt as useIsMobile, St as useSocket };
789
+
790
+ //# sourceMappingURL=index.js.map