@spilki/widget 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.
@@ -0,0 +1,616 @@
1
+ const I = `
2
+ <style>
3
+ :host {
4
+ all: initial;
5
+ position: fixed;
6
+ z-index: 2147483000;
7
+ }
8
+ button {
9
+ all: unset;
10
+ display: inline-flex;
11
+ align-items: center;
12
+ justify-content: center;
13
+ width: 56px;
14
+ height: 56px;
15
+ border-radius: 999px;
16
+ cursor: pointer;
17
+ background: var(--spilki-accent);
18
+ color: #fff;
19
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
20
+ transition: transform 0.18s ease, box-shadow 0.18s ease;
21
+ }
22
+ button:focus-visible {
23
+ outline: 2px solid #fff;
24
+ outline-offset: 3px;
25
+ }
26
+ button:hover {
27
+ transform: translateY(-1px);
28
+ box-shadow: 0 12px 30px rgba(0, 0, 0, 0.25);
29
+ }
30
+ .icon {
31
+ width: 28px;
32
+ height: 28px;
33
+ }
34
+ .icon svg {
35
+ width: 100%;
36
+ height: 100%;
37
+ }
38
+ </style>
39
+ <button type="button" aria-label="Open chat">
40
+ <span class="icon" aria-hidden="true">
41
+ <svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
42
+ <path d="M5 6a3 3 0 0 1 3-3h16a3 3 0 0 1 3 3v12a3 3 0 0 1-3 3H14l-5 6v-6H8a3 3 0 0 1-3-3V6Z" fill="currentColor"/>
43
+ </svg>
44
+ </span>
45
+ </button>
46
+ `;
47
+ function T(r) {
48
+ const e = document.createElement("div");
49
+ e.setAttribute("part", "bubble-root"), e.style.setProperty("--spilki-accent", r.color), e.style.position = "fixed", e.style.bottom = "24px", e.style[r.position === "bottom-right" ? "right" : "left"] = "24px";
50
+ const t = e.attachShadow({ mode: "open" });
51
+ t.innerHTML = I;
52
+ const s = t.querySelector("button");
53
+ return s.addEventListener("click", () => r.onClick()), {
54
+ element: e,
55
+ mount() {
56
+ document.body.appendChild(e);
57
+ },
58
+ destroy() {
59
+ e.remove();
60
+ },
61
+ setOpen(o) {
62
+ s.setAttribute("aria-expanded", String(o));
63
+ }
64
+ };
65
+ }
66
+ const O = ':host{--spilki-bg-light: #ffffff;--spilki-bg-dark: #0f172a;--spilki-text-light: #0f172a;--spilki-text-dark: #f8fafc;--spilki-border-light: rgba(15, 23, 42, .1);--spilki-border-dark: rgba(148, 163, 184, .25);--spilki-shadow: 0 10px 40px rgba(15, 23, 42, .2);--spilki-radius: 16px;--spilki-font: "Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;color:inherit;font-family:var(--spilki-font)}.wrapper{width:100%;height:100%;display:flex;flex-direction:column;background:var(--spilki-surface);color:var(--spilki-text);border-radius:var(--spilki-radius);box-shadow:var(--spilki-shadow);border:1px solid var(--spilki-border);overflow:hidden}header{display:flex;align-items:center;justify-content:space-between;padding:.75rem 1rem;background:var(--spilki-surface);border-bottom:1px solid var(--spilki-border)}header h1{font-size:1rem;margin:0;display:flex;align-items:center;gap:.5rem}header button.close{border:none;background:transparent;color:inherit;font-size:1.25rem;cursor:pointer}header .status-dot{width:10px;height:10px;border-radius:999px;background:var(--spilki-accent)}.messages{flex:1;overflow-y:auto;padding:1rem;display:flex;flex-direction:column;gap:.5rem}.message{display:flex;flex-direction:column;gap:.25rem;max-width:85%;line-height:1.4;word-wrap:break-word;overflow-wrap:anywhere;white-space:pre-wrap}.message.user{align-self:flex-end;text-align:right}.message .bubble{padding:.6rem .8rem;border-radius:1rem;background:#6366f126}.message.user .bubble{background:var(--spilki-accent);color:#fff}.message.bot .bubble{background:#94a3b826}.input-area{display:flex;align-items:flex-end;gap:.5rem;padding:.75rem 1rem;border-top:1px solid var(--spilki-border)}.input-area textarea{flex:1;resize:none;min-height:2.5rem;max-height:6rem;border-radius:.75rem;border:1px solid var(--spilki-border);padding:.6rem .75rem;font-family:inherit;font-size:.95rem;background:var(--spilki-surface);color:var(--spilki-text)}.input-area button{border:none;border-radius:999px;padding:.6rem 1.1rem;background:var(--spilki-accent);color:#fff;font-weight:600;cursor:pointer}.typing{font-size:.75rem;color:#94a3b8e6;padding:0 1rem .75rem}.offline{font-size:.8rem;padding:0 1rem;color:#f97316}:host([data-theme="dark"]){--spilki-surface: var(--spilki-bg-dark);--spilki-text: var(--spilki-text-dark);--spilki-border: var(--spilki-border-dark)}:host([data-theme="light"]){--spilki-surface: var(--spilki-bg-light);--spilki-text: var(--spilki-text-light);--spilki-border: var(--spilki-border-light)}:host([data-theme="dark"]) .message .bubble{background:#94a3b81f}:host([data-theme="dark"]) .message.bot .bubble{background:#6366f126}:host([data-theme="dark"]) .input-area textarea{background:#0f172ad9}.messages::-webkit-scrollbar,.input-area textarea::-webkit-scrollbar{width:6px}.messages::-webkit-scrollbar-track,.input-area textarea::-webkit-scrollbar-track{background:transparent}.messages::-webkit-scrollbar-thumb,.input-area textarea::-webkit-scrollbar-thumb{background:#94a3b84d;border-radius:999px}.messages::-webkit-scrollbar-thumb:hover,.input-area textarea::-webkit-scrollbar-thumb:hover{background:#94a3b880}:host([data-theme="dark"]) .messages::-webkit-scrollbar-thumb,:host([data-theme="dark"]) .input-area textarea::-webkit-scrollbar-thumb{background:#fff3}:host([data-theme="dark"]) .messages::-webkit-scrollbar-thumb:hover,:host([data-theme="dark"]) .input-area textarea::-webkit-scrollbar-thumb:hover{background:#ffffff59}.messages{scroll-behavior:smooth}';
67
+ class M {
68
+ constructor(e) {
69
+ this.options = e, this.focusable = [], this.open = !1, this.host = document.createElement("div"), this.host.setAttribute("part", "panel-root"), this.host.style.position = "fixed", this.host.style.bottom = "96px", this.host.style[e.position === "bottom-right" ? "right" : "left"] = "24px", this.host.style.width = "360px", this.host.style.maxWidth = "calc(100vw - 32px)", this.host.style.height = "520px", this.host.style.display = "none", this.host.style.zIndex = "2147483001", this.shadow = this.host.attachShadow({ mode: "open" }), this.shadow.innerHTML = `
70
+ <style>${O}</style>
71
+ <div class="wrapper" role="dialog" aria-modal="true" aria-label="${e.i18n.title}">
72
+ <header>
73
+ <h1><span class="status-dot" aria-hidden="true"></span>${e.i18n.title}</h1>
74
+ <button class="close" type="button" aria-label="Close">×</button>
75
+ </header>
76
+ <div class="messages" part="messages"></div>
77
+ <div class="typing" hidden>${e.i18n.typing}</div>
78
+ <div class="offline" hidden>${e.i18n.offline}</div>
79
+ <div class="input-area">
80
+ <textarea rows="2" placeholder="${e.i18n.placeholder}" aria-label="${e.i18n.placeholder}"></textarea>
81
+ <button type="button">${e.i18n.sendLabel}</button>
82
+ </div>
83
+ </div>
84
+ `, this.host.dataset.theme = e.theme, this.host.style.setProperty("--spilki-accent", e.color), this.messagesEl = this.shadow.querySelector(".messages"), this.typingEl = this.shadow.querySelector(".typing"), this.input = this.shadow.querySelector("textarea"), this.offlineEl = this.shadow.querySelector(".offline"), this.sendButton = this.shadow.querySelector(".input-area button"), this.shadow.querySelector("header .close").addEventListener("click", () => this.options.onClose()), this.sendButton.addEventListener("click", () => this.send()), this.input.addEventListener("keydown", (s) => {
85
+ s.key === "Enter" && !s.shiftKey ? (s.preventDefault(), this.send()) : s.key === "Escape" && this.options.onClose();
86
+ }), this.shadow.addEventListener("keydown", (s) => {
87
+ const i = s;
88
+ i.key === "Escape" && this.options.onClose(), i.key === "Tab" && this.trapFocus(i);
89
+ }), this.shadow.addEventListener("focusin", () => this.collectFocusable()), this.collectFocusable();
90
+ }
91
+ mount() {
92
+ document.body.appendChild(this.host);
93
+ }
94
+ destroy() {
95
+ this.host.remove();
96
+ }
97
+ show() {
98
+ this.open || (this.open = !0, this.host.style.display = "block", this.focusInput());
99
+ }
100
+ hide() {
101
+ this.open && (this.open = !1, this.host.style.display = "none");
102
+ }
103
+ focusInput() {
104
+ queueMicrotask(() => {
105
+ this.input.focus();
106
+ });
107
+ }
108
+ updateTheme(e) {
109
+ this.host.dataset.theme = e;
110
+ }
111
+ updateMessages(e) {
112
+ this.messagesEl.innerHTML = "", e.forEach((t) => {
113
+ const s = document.createElement("div");
114
+ s.className = `message ${t.author}`, s.setAttribute("data-author", t.author);
115
+ const i = document.createElement("div");
116
+ i.className = "bubble", i.textContent = t.text, s.appendChild(i), this.messagesEl.appendChild(s);
117
+ }), this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
118
+ }
119
+ appendMessage(e) {
120
+ const t = document.createElement("div");
121
+ t.className = `message ${e.author}`, t.setAttribute("data-author", e.author);
122
+ const s = document.createElement("div");
123
+ s.className = "bubble", s.textContent = e.text, t.appendChild(s), this.messagesEl.appendChild(t), this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
124
+ }
125
+ setTyping(e) {
126
+ this.typingEl.toggleAttribute("hidden", !e);
127
+ }
128
+ setOffline(e) {
129
+ this.offlineEl.toggleAttribute("hidden", !e);
130
+ }
131
+ clearInput() {
132
+ this.input.value = "", this.input.dispatchEvent(new Event("input"));
133
+ }
134
+ send() {
135
+ const e = this.input.value.trim();
136
+ e && (this.options.onSend(e), this.clearInput());
137
+ }
138
+ collectFocusable() {
139
+ const e = this.shadow.querySelectorAll(
140
+ 'button, textarea, [href], [tabindex]:not([tabindex="-1"])'
141
+ );
142
+ this.focusable.length = 0, e.forEach((t) => {
143
+ t.hasAttribute("disabled") || this.focusable.push(t);
144
+ });
145
+ }
146
+ trapFocus(e) {
147
+ if (this.focusable.length === 0) return;
148
+ const t = this.focusable[0], s = this.focusable[this.focusable.length - 1], i = this.shadow.activeElement;
149
+ e.shiftKey && i === t ? (e.preventDefault(), s.focus()) : !e.shiftKey && i === s && (e.preventDefault(), t.focus());
150
+ }
151
+ }
152
+ const C = "https://api.spilki.ai", g = {
153
+ welcome: "Hi! I'm your assistant.",
154
+ placeholder: "Type a message…",
155
+ sendLabel: "Send",
156
+ typing: "Assistant is typing…",
157
+ offline: "Unable to connect. Please try again later.",
158
+ title: "Spilki Assistant"
159
+ }, c = {
160
+ apiBase: C,
161
+ position: "bottom-right",
162
+ theme: "auto",
163
+ color: "#6366f1",
164
+ welcome: g.welcome,
165
+ persist: !0,
166
+ i18n: g
167
+ };
168
+ function A(r) {
169
+ var t, s, i, o, a, l, p;
170
+ const e = { ...g, ...(t = r.i18n) != null ? t : {} };
171
+ return {
172
+ ...c,
173
+ ...r,
174
+ apiBase: (s = r.apiBase) != null ? s : c.apiBase,
175
+ i18n: e,
176
+ welcome: (i = r.welcome) != null ? i : e.welcome,
177
+ position: (o = r.position) != null ? o : c.position,
178
+ theme: (a = r.theme) != null ? a : c.theme,
179
+ color: (l = r.color) != null ? l : c.color,
180
+ persist: (p = r.persist) != null ? p : c.persist
181
+ };
182
+ }
183
+ function $(r = "msg") {
184
+ return typeof crypto != "undefined" && crypto.randomUUID ? crypto.randomUUID() : `${r}-${Math.random().toString(16).slice(2)}`;
185
+ }
186
+ function W() {
187
+ var r, e;
188
+ return (e = (r = window.matchMedia) == null ? void 0 : r.call(window, "(prefers-color-scheme: dark)").matches) != null ? e : !1;
189
+ }
190
+ function y(r) {
191
+ return r === "light" || r === "dark" ? r : W() ? "dark" : "light";
192
+ }
193
+ function u(r, e = 30) {
194
+ return r.slice(-e);
195
+ }
196
+ function L(r) {
197
+ if (!r || r.length === 0) return;
198
+ const e = window.location.origin;
199
+ r.includes(e) || console.warn(
200
+ `SpilkiWidget: current origin ${e} not in allowedOriginsHint: ${r.join(", ")}`
201
+ );
202
+ }
203
+ const d = 1500, x = 8e3;
204
+ class B {
205
+ constructor(e, t) {
206
+ this.sessionId = null, this.currentKind = null, this.stopped = !1, this.backoff = d, this.options = e, this.handlers = t;
207
+ }
208
+ get kind() {
209
+ return this.currentKind;
210
+ }
211
+ get activeSession() {
212
+ var e, t;
213
+ return (t = (e = this.sessionId) != null ? e : this.options.sessionId) != null ? t : null;
214
+ }
215
+ async connect() {
216
+ var a, l;
217
+ this.stopped = !1;
218
+ const e = `${this.options.apiBase.replace(/\/$/, "")}/widget/connect`, t = (l = (a = this.sessionId) != null ? a : this.options.sessionId) != null ? l : void 0, s = {
219
+ organisationId: this.options.org,
220
+ assistantId: this.options.assistant,
221
+ sessionId: t,
222
+ userAgent: typeof navigator != "undefined" ? navigator.userAgent : "",
223
+ referrer: typeof document != "undefined" ? document.referrer : "",
224
+ origin: typeof window != "undefined" ? window.location.origin : ""
225
+ }, i = await fetch(e, {
226
+ method: "POST",
227
+ headers: {
228
+ "Content-Type": "application/json",
229
+ ...this.options.token ? { Authorization: `Bearer ${this.options.token}` } : {}
230
+ },
231
+ body: JSON.stringify(s)
232
+ });
233
+ if (!i.ok)
234
+ throw new Error(`SpilkiWidget: connect failed (${i.status})`);
235
+ const o = await i.json();
236
+ return this.sessionId = o.sessionId, this.options.sessionId = o.sessionId, this.backoff = d, await this.startTransport(o), o;
237
+ }
238
+ async send(e) {
239
+ var o, a;
240
+ const t = {
241
+ sessionId: (a = (o = this.sessionId) != null ? o : this.options.sessionId) != null ? a : "",
242
+ text: e
243
+ };
244
+ if (!t.sessionId)
245
+ throw new Error("SpilkiWidget: missing session id");
246
+ if (this.currentKind === "ws" && this.ws && this.ws.readyState === WebSocket.OPEN) {
247
+ this.ws.send(JSON.stringify({ type: "message", payload: t }));
248
+ return;
249
+ }
250
+ const s = `${this.options.apiBase.replace(/\/$/, "")}/widget/message`, i = await fetch(s, {
251
+ method: "POST",
252
+ headers: {
253
+ "Content-Type": "application/json",
254
+ ...this.options.token ? { Authorization: `Bearer ${this.options.token}` } : {}
255
+ },
256
+ body: JSON.stringify(t)
257
+ });
258
+ if (!i.ok)
259
+ throw new Error(`SpilkiWidget: send failed (${i.status})`);
260
+ }
261
+ stop() {
262
+ this.stopped = !0, this.backoff = d, this.ws && (this.ws.close(), this.ws = void 0), this.sse && (this.sse.close(), this.sse = void 0), this.pollTimer && (clearTimeout(this.pollTimer), this.pollTimer = void 0), this.currentKind = null;
263
+ }
264
+ async startTransport(e) {
265
+ if (this.stopped) return;
266
+ const t = [];
267
+ e.wsUrl && t.push(() => this.startWs(e.wsUrl)), e.sseUrl && t.push(() => this.startSse(e.sseUrl)), e.pollUrl && t.push(() => this.startPoll(e.pollUrl));
268
+ for (const s of t)
269
+ try {
270
+ await s();
271
+ return;
272
+ } catch (i) {
273
+ this.handlers.onError(i);
274
+ }
275
+ throw new Error("SpilkiWidget: unable to establish transport");
276
+ }
277
+ startWs(e) {
278
+ return new Promise((t, s) => {
279
+ try {
280
+ const i = new WebSocket(e);
281
+ this.ws = i, i.addEventListener("open", () => {
282
+ if (this.stopped) {
283
+ i.close();
284
+ return;
285
+ }
286
+ this.currentKind = "ws", this.handlers.onOpen("ws"), this.backoff = d, t();
287
+ }), i.addEventListener("message", (o) => this.handleIncoming(o.data)), i.addEventListener("close", () => {
288
+ this.stopped || this.retryFallback("ws");
289
+ }), i.addEventListener("error", () => {
290
+ this.handlers.onError(new Error("SpilkiWidget: websocket error")), i.readyState !== WebSocket.OPEN && s(new Error("WebSocket failed"));
291
+ });
292
+ } catch (i) {
293
+ s(i);
294
+ }
295
+ });
296
+ }
297
+ startSse(e) {
298
+ return new Promise((t, s) => {
299
+ if (typeof EventSource == "undefined") {
300
+ s(new Error("SSE not supported"));
301
+ return;
302
+ }
303
+ const i = new EventSource(e);
304
+ this.sse = i;
305
+ let o = !1;
306
+ i.addEventListener("open", () => {
307
+ if (o = !0, this.stopped) {
308
+ i.close();
309
+ return;
310
+ }
311
+ this.currentKind = "sse", this.handlers.onOpen("sse"), this.backoff = d, t();
312
+ }), i.addEventListener("message", (a) => this.handleIncoming(a.data)), i.addEventListener("error", () => {
313
+ if (!o) {
314
+ s(new Error("SSE failed"));
315
+ return;
316
+ }
317
+ this.handlers.onError(new Error("SpilkiWidget: SSE error")), !this.stopped && this.retryFallback("sse");
318
+ });
319
+ });
320
+ }
321
+ async startPoll(e) {
322
+ this.currentKind = "poll", this.handlers.onOpen("poll"), this.backoff = d;
323
+ const t = async () => {
324
+ if (!this.stopped)
325
+ try {
326
+ const s = await fetch(e);
327
+ if (!s.ok) throw new Error(`Poll failed ${s.status}`);
328
+ const i = await s.json();
329
+ u(i).forEach((o) => this.handlers.onMessage(o)), this.backoff = d;
330
+ } catch (s) {
331
+ this.handlers.onError(s), this.backoff = Math.min(this.backoff * 1.5, x);
332
+ } finally {
333
+ this.stopped || (this.pollTimer = window.setTimeout(t, this.backoff));
334
+ }
335
+ };
336
+ await t();
337
+ }
338
+ retryFallback(e) {
339
+ this.stopped || (this.stop(), this.backoff = Math.min(this.backoff * 1.5, x), setTimeout(() => {
340
+ this.handlers.onError(new Error(`SpilkiWidget: retrying after ${e}`)), this.connect().catch((t) => this.handlers.onError(t));
341
+ }, this.backoff));
342
+ }
343
+ handleIncoming(e) {
344
+ try {
345
+ const t = JSON.parse(e);
346
+ if (Array.isArray(t)) {
347
+ t.forEach((s) => this.dispatchIncoming(s));
348
+ return;
349
+ }
350
+ this.dispatchIncoming(t);
351
+ } catch {
352
+ const t = {
353
+ id: `${Date.now()}`,
354
+ author: "bot",
355
+ text: e,
356
+ ts: Date.now()
357
+ };
358
+ this.handlers.onMessage(t);
359
+ }
360
+ }
361
+ dispatchIncoming(e) {
362
+ var t;
363
+ if ("type" in e) {
364
+ e.type === "message" ? this.handlers.onMessage(e.payload) : e.type === "typing" && this.handlers.onTyping(!!((t = e.payload) != null && t.active));
365
+ return;
366
+ }
367
+ this.handlers.onMessage(e);
368
+ }
369
+ }
370
+ const f = 30;
371
+ class U {
372
+ constructor(e, t, s) {
373
+ this.org = e, this.assistant = t, this.listeners = /* @__PURE__ */ new Set(), this.state = {
374
+ isOpen: !1,
375
+ isTyping: !1,
376
+ isConnected: !1,
377
+ messages: []
378
+ }, this.historyKey = `spilki-history:${e}:${t}`, this.sessionKey = `spilki-session:${e}:${t}`, this.persist = s.persist, this.state.messages = this.loadMessages();
379
+ }
380
+ get snapshot() {
381
+ return { ...this.state, messages: [...this.state.messages] };
382
+ }
383
+ subscribe(e) {
384
+ return this.listeners.add(e), () => this.listeners.delete(e);
385
+ }
386
+ open() {
387
+ this.state.isOpen || (this.state.isOpen = !0, this.emit());
388
+ }
389
+ close() {
390
+ this.state.isOpen && (this.state.isOpen = !1, this.emit());
391
+ }
392
+ setTyping(e) {
393
+ this.state.isTyping !== e && (this.state.isTyping = e, this.emit());
394
+ }
395
+ setConnected(e) {
396
+ this.state.isConnected !== e && (this.state.isConnected = e, this.emit());
397
+ }
398
+ addMessage(e) {
399
+ var s, i;
400
+ const t = {
401
+ id: (s = e.id) != null ? s : $("msg"),
402
+ ts: (i = e.ts) != null ? i : Date.now(),
403
+ author: e.author,
404
+ text: e.text
405
+ };
406
+ return this.state.messages = u([...this.state.messages, t], f), this.persistMessages(), this.emit(), t;
407
+ }
408
+ setMessages(e) {
409
+ this.state.messages = u(e, f), this.persistMessages(), this.emit();
410
+ }
411
+ clearMessages() {
412
+ this.state.messages = [], this.persistMessages(), this.emit();
413
+ }
414
+ get sessionId() {
415
+ if (!this.persist) return null;
416
+ try {
417
+ return localStorage.getItem(this.sessionKey);
418
+ } catch {
419
+ return null;
420
+ }
421
+ }
422
+ persistSession(e) {
423
+ if (this.persist)
424
+ try {
425
+ localStorage.setItem(this.sessionKey, e);
426
+ } catch (t) {
427
+ console.warn("SpilkiWidget: Unable to persist session", t);
428
+ }
429
+ }
430
+ clearSession() {
431
+ if (this.persist)
432
+ try {
433
+ localStorage.removeItem(this.sessionKey);
434
+ } catch (e) {
435
+ console.warn("SpilkiWidget: Unable to clear session", e);
436
+ }
437
+ }
438
+ emit() {
439
+ this.listeners.forEach((e) => e());
440
+ }
441
+ persistMessages() {
442
+ if (this.persist)
443
+ try {
444
+ localStorage.setItem(this.historyKey, JSON.stringify(this.state.messages));
445
+ } catch (e) {
446
+ console.warn("SpilkiWidget: Unable to persist messages", e);
447
+ }
448
+ }
449
+ loadMessages() {
450
+ if (!this.persist) return [];
451
+ try {
452
+ const e = localStorage.getItem(this.historyKey);
453
+ if (!e) return [];
454
+ const t = JSON.parse(e);
455
+ return Array.isArray(t) ? u(t, f) : [];
456
+ } catch {
457
+ return [];
458
+ }
459
+ }
460
+ }
461
+ function K(r) {
462
+ const e = r.replace(/-/g, "+").replace(/_/g, "/"), t = e.padEnd(e.length + (4 - e.length % 4) % 4, "=");
463
+ if (typeof atob == "function")
464
+ return decodeURIComponent(
465
+ Array.prototype.map.call(atob(t), (i) => `%${`00${i.charCodeAt(0).toString(16)}`.slice(-2)}`).join("")
466
+ );
467
+ const s = globalThis.Buffer;
468
+ if (s)
469
+ return s.from(t, "base64").toString("utf8");
470
+ throw new Error("SpilkiWidget: no base64 decoder available");
471
+ }
472
+ function P(r) {
473
+ if (!r) return null;
474
+ const e = r.split(".");
475
+ if (e.length < 2) return null;
476
+ try {
477
+ const t = K(e[1]);
478
+ return JSON.parse(t);
479
+ } catch (t) {
480
+ return console.error("SpilkiWidget: unable to parse JWT", t), null;
481
+ }
482
+ }
483
+ function D(r) {
484
+ const e = P(r);
485
+ if (!(e != null && e.exp)) return !1;
486
+ const t = Math.floor(Date.now() / 1e3);
487
+ return e.exp < t;
488
+ }
489
+ const N = {
490
+ onOpen() {
491
+ },
492
+ onClose() {
493
+ },
494
+ onMessage() {
495
+ },
496
+ onError() {
497
+ },
498
+ onTransportChange() {
499
+ }
500
+ };
501
+ function v(r) {
502
+ var m, k, w;
503
+ if (!r.org || !r.assistant)
504
+ throw new Error("SpilkiWidget: org and assistant are required");
505
+ const e = A(r);
506
+ if (e.token && D(e.token))
507
+ throw new Error("SpilkiWidget: JWT token has expired");
508
+ L(e.allowedOriginsHint);
509
+ const t = { ...N, ...(m = e.hooks) != null ? m : {} }, s = new U(e.org, e.assistant, { persist: e.persist }), i = T({
510
+ color: e.color,
511
+ position: (k = e.position) != null ? k : "bottom-right",
512
+ onClick: () => {
513
+ s.snapshot.isOpen ? (s.close(), t.onClose()) : (s.open(), t.onOpen());
514
+ }
515
+ }), o = new M({
516
+ color: e.color,
517
+ theme: y(e.theme),
518
+ position: (w = e.position) != null ? w : "bottom-right",
519
+ i18n: e.i18n,
520
+ onClose: () => {
521
+ s.close(), t.onClose();
522
+ },
523
+ onSend: (n) => {
524
+ const h = s.addMessage({ author: "user", text: n });
525
+ o.appendMessage(h), a.send(n).catch((S) => {
526
+ t.onError(S), s.setConnected(!1), o.setOffline(!0);
527
+ });
528
+ }
529
+ }), a = new B(
530
+ {
531
+ apiBase: e.apiBase,
532
+ token: e.token,
533
+ org: e.org,
534
+ assistant: e.assistant,
535
+ sessionId: s.sessionId
536
+ },
537
+ {
538
+ onOpen(n) {
539
+ b.transport = n, t.onTransportChange(n), s.setConnected(!0), o.setOffline(!1);
540
+ },
541
+ onMessage(n) {
542
+ const h = s.addMessage(n);
543
+ o.appendMessage(h), t.onMessage(h);
544
+ },
545
+ onTyping(n) {
546
+ s.setTyping(n);
547
+ },
548
+ onError(n) {
549
+ t.onError(n), s.setConnected(!1), s.snapshot.isOpen && o.setOffline(!0);
550
+ }
551
+ }
552
+ );
553
+ i.mount(), o.mount();
554
+ const l = s.snapshot.messages;
555
+ if (l.length === 0 && e.welcome) {
556
+ const n = {
557
+ id: "welcome",
558
+ author: "bot",
559
+ text: e.welcome,
560
+ ts: Date.now()
561
+ };
562
+ s.addMessage(n), o.appendMessage(n);
563
+ } else
564
+ o.updateMessages(l);
565
+ const p = s.subscribe(() => {
566
+ const n = s.snapshot;
567
+ i.setOpen(n.isOpen), o.setTyping(n.isTyping), o.setOffline(!n.isConnected), o.updateTheme(y(e.theme)), n.isOpen ? o.show() : o.hide();
568
+ });
569
+ a.connect().then((n) => {
570
+ var h;
571
+ e.persist && s.persistSession(n.sessionId), s.setConnected(!0), t.onTransportChange((h = a.kind) != null ? h : "ws");
572
+ }).catch((n) => {
573
+ t.onError(n), s.setConnected(!1), o.setOffline(!0);
574
+ });
575
+ const b = {
576
+ transport: null,
577
+ open() {
578
+ s.open(), t.onOpen();
579
+ },
580
+ close() {
581
+ s.close(), t.onClose();
582
+ },
583
+ destroy() {
584
+ p(), a.stop(), i.destroy(), o.destroy();
585
+ }
586
+ };
587
+ return b;
588
+ }
589
+ function E() {
590
+ var i, o;
591
+ if (typeof document == "undefined") return;
592
+ const r = document.currentScript;
593
+ if (!r) return;
594
+ const e = r.dataset;
595
+ if (e.autoinit === "false") return;
596
+ const t = e.org, s = e.assistant;
597
+ if (!t || !s) {
598
+ console.error("SpilkiWidget: data-org and data-assistant are required for auto init");
599
+ return;
600
+ }
601
+ v({
602
+ org: t,
603
+ assistant: s,
604
+ token: e.token,
605
+ apiBase: e.apiBase,
606
+ position: (i = e.position) != null ? i : void 0,
607
+ theme: (o = e.theme) != null ? o : void 0
608
+ });
609
+ }
610
+ if (typeof window != "undefined") {
611
+ const r = window;
612
+ r.SpilkiWidget = r.SpilkiWidget || {}, r.SpilkiWidget.init = (e) => v(e);
613
+ }
614
+ E();
615
+ E();
616
+ //# sourceMappingURL=bootstrap.es.js.map