@cognitiondesk/widget 1.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/README.md ADDED
@@ -0,0 +1,101 @@
1
+ # @cognitiondesk/widget
2
+
3
+ Embed a CognitionDesk AI chat widget into any website with a single API key.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @cognitiondesk/widget
9
+ ```
10
+
11
+ ## Quick start β€” React
12
+
13
+ ```jsx
14
+ import { CognitionDeskWidget } from '@cognitiondesk/widget/react';
15
+
16
+ export default function App() {
17
+ return (
18
+ <>
19
+ {/* your app */}
20
+ <CognitionDeskWidget
21
+ apiKey="YOUR_API_KEY"
22
+ assistantId="YOUR_ASSISTANT_ID" // optional
23
+ theme="light" // 'light' | 'dark' | 'auto'
24
+ primaryColor="#2563eb"
25
+ botName="Support Bot"
26
+ welcomeMessage="Hello! How can I help you today?"
27
+ />
28
+ </>
29
+ );
30
+ }
31
+ ```
32
+
33
+ ## Quick start β€” Vanilla JS
34
+
35
+ ```js
36
+ import { CognitionDeskWidget } from '@cognitiondesk/widget';
37
+
38
+ const widget = new CognitionDeskWidget({
39
+ apiKey: 'YOUR_API_KEY',
40
+ assistantId: 'YOUR_ASSISTANT_ID',
41
+ });
42
+ widget.mount(); // appends to document.body
43
+ ```
44
+
45
+ ## Script tag (CDN)
46
+
47
+ ```html
48
+ <!-- Auto-init via data attributes -->
49
+ <script
50
+ src="https://cdn.jsdelivr.net/npm/@cognitiondesk/widget/dist/widget.umd.cjs"
51
+ data-api-key="YOUR_API_KEY"
52
+ data-assistant-id="YOUR_ASSISTANT_ID"
53
+ data-theme="light"
54
+ ></script>
55
+
56
+ <!-- Or manual init -->
57
+ <script src="https://cdn.jsdelivr.net/npm/@cognitiondesk/widget/dist/widget.umd.cjs"></script>
58
+ <script>
59
+ CognitionDesk.init({ apiKey: 'YOUR_API_KEY' });
60
+ </script>
61
+ ```
62
+
63
+ ## API Keys
64
+
65
+ Generate and manage API keys in your [CognitionDesk dashboard](https://app.cognitiondesk.com/dashboard/api-keys).
66
+
67
+ Each API key is scoped to your account and used to:
68
+ - Authenticate widget requests to the AI backend
69
+ - Track usage against your plan quotas
70
+ - Associate conversations with the correct assistant
71
+
72
+ ## Configuration options
73
+
74
+ | Prop | Type | Default | Description |
75
+ |---|---|---|---|
76
+ | `apiKey` | `string` | **required** | Your CognitionDesk API key |
77
+ | `assistantId` | `string` | `undefined` | Specific assistant to use (uses account default otherwise) |
78
+ | `theme` | `'light'β”‚'dark'β”‚'auto'` | `'light'` | Color scheme |
79
+ | `primaryColor` | `string` | `'#2563eb'` | Brand accent color (CSS color) |
80
+ | `botName` | `string` | `'AI Assistant'` | Name shown in the widget header |
81
+ | `botEmoji` | `string` | `'πŸ€–'` | Avatar emoji shown in the header |
82
+ | `welcomeMessage` | `string` | `'Hello! How can I help you today?'` | First message shown to the user |
83
+ | `placeholder` | `string` | `'Type a message…'` | Input placeholder |
84
+ | `defaultOpen` | `boolean` | `false` | Open the widget on load *(React only)* |
85
+ | `backendUrl` | `string` | auto | Override backend URL (self-hosted setups) |
86
+
87
+ ## Widget methods (vanilla JS)
88
+
89
+ ```js
90
+ const widget = new CognitionDeskWidget({ apiKey: '...' });
91
+ widget.mount(); // mount to DOM
92
+ widget.open(); // programmatically open
93
+ widget.close(); // close
94
+ widget.toggle(); // toggle open/close
95
+ widget.clearHistory(); // reset conversation
96
+ widget.unmount(); // remove from DOM
97
+ ```
98
+
99
+ ## License
100
+
101
+ MIT
@@ -0,0 +1,576 @@
1
+ import { jsx as C } from "react/jsx-runtime";
2
+ import { forwardRef as H, useRef as y, useImperativeHandle as T, useEffect as k } from "react";
3
+ const L = "https://mounaji-backendv3.onrender.com", N = `
4
+ :host {
5
+ all: initial;
6
+ font-family: system-ui, sans-serif;
7
+ --cd-offset: clamp(12px, 4vw, 24px);
8
+ --cd-launcher-size: clamp(56px, 14vw, 64px);
9
+ --cd-launcher-gap: 12px;
10
+ --cd-viewport-height: 100vh;
11
+ --cd-safe-top: env(safe-area-inset-top, 0px);
12
+ --cd-safe-right: env(safe-area-inset-right, 0px);
13
+ --cd-safe-bottom: env(safe-area-inset-bottom, 0px);
14
+ --cd-safe-left: env(safe-area-inset-left, 0px);
15
+ }
16
+
17
+ .cd-root {
18
+ position: fixed;
19
+ inset: 0;
20
+ pointer-events: none;
21
+ z-index: 2147483000;
22
+ }
23
+
24
+ .cd-root > * {
25
+ pointer-events: auto;
26
+ }
27
+
28
+ .cd-widget-btn {
29
+ position: fixed;
30
+ bottom: calc(var(--cd-offset) + var(--cd-safe-bottom));
31
+ right: calc(var(--cd-offset) + var(--cd-safe-right));
32
+ z-index: 2147483647;
33
+ width: var(--cd-launcher-size);
34
+ height: var(--cd-launcher-size);
35
+ border-radius: 50%;
36
+ background: var(--cd-primary, #2563eb);
37
+ color: #fff;
38
+ border: none;
39
+ cursor: pointer;
40
+ display: flex;
41
+ align-items: center;
42
+ justify-content: center;
43
+ box-shadow: 0 4px 20px rgba(37,99,235,.45);
44
+ transition: transform .2s, box-shadow .2s;
45
+ touch-action: manipulation;
46
+ }
47
+ .cd-widget-btn:hover { transform: scale(1.08); box-shadow: 0 6px 24px rgba(37,99,235,.55); }
48
+ .cd-widget-btn svg { width: 26px; height: 26px; }
49
+
50
+ .cd-panel {
51
+ position: fixed;
52
+ bottom: calc(var(--cd-offset) + var(--cd-safe-bottom) + var(--cd-launcher-size) + var(--cd-launcher-gap));
53
+ right: calc(var(--cd-offset) + var(--cd-safe-right));
54
+ z-index: 2147483646;
55
+ width: min(380px, calc(100vw - (var(--cd-offset) * 2) - var(--cd-safe-left) - var(--cd-safe-right)));
56
+ height: min(560px, calc(var(--cd-viewport-height) - (var(--cd-offset) * 2) - var(--cd-safe-top) - var(--cd-safe-bottom) - var(--cd-launcher-size) - var(--cd-launcher-gap)));
57
+ max-height: calc(var(--cd-viewport-height) - (var(--cd-offset) * 2) - var(--cd-safe-top) - var(--cd-safe-bottom));
58
+ background: #fff;
59
+ border-radius: 16px;
60
+ box-shadow: 0 12px 40px rgba(0,0,0,.18);
61
+ display: flex;
62
+ flex-direction: column;
63
+ overflow: hidden;
64
+ transform: scale(.96) translateY(8px);
65
+ opacity: 0;
66
+ pointer-events: none;
67
+ transition: opacity .2s, transform .2s;
68
+ overscroll-behavior: contain;
69
+ }
70
+ .cd-panel.open {
71
+ transform: scale(1) translateY(0);
72
+ opacity: 1;
73
+ pointer-events: all;
74
+ }
75
+
76
+ .cd-header {
77
+ background: var(--cd-primary, #2563eb);
78
+ color: #fff;
79
+ padding: 14px 16px;
80
+ display: flex;
81
+ align-items: center;
82
+ gap: 10px;
83
+ flex-shrink: 0;
84
+ }
85
+ .cd-header-avatar {
86
+ width: 36px; height: 36px; border-radius: 50%;
87
+ background: rgba(255,255,255,.25);
88
+ display: flex; align-items: center; justify-content: center;
89
+ font-size: 18px;
90
+ }
91
+ .cd-header-info { flex: 1; min-width: 0; }
92
+ .cd-header-name { font-size: 14px; font-weight: 600; }
93
+ .cd-header-status { font-size: 11px; opacity: .85; display: flex; align-items: center; gap: 4px; }
94
+ .cd-status-dot { width: 7px; height: 7px; border-radius: 50%; background: #4ade80; }
95
+ .cd-close-btn {
96
+ background: none; border: none; color: rgba(255,255,255,.75);
97
+ cursor: pointer; padding: 4px; border-radius: 6px;
98
+ display: flex; align-items: center; justify-content: center;
99
+ }
100
+ .cd-close-btn:hover { color: #fff; background: rgba(255,255,255,.15); }
101
+ .cd-close-btn svg { width: 18px; height: 18px; }
102
+
103
+ .cd-messages {
104
+ flex: 1;
105
+ overflow-y: auto;
106
+ padding: 16px;
107
+ display: flex;
108
+ flex-direction: column;
109
+ gap: 12px;
110
+ background: #f8fafc;
111
+ }
112
+ .cd-msg {
113
+ max-width: 78%;
114
+ padding: 10px 13px;
115
+ border-radius: 14px;
116
+ font-size: 13.5px;
117
+ line-height: 1.5;
118
+ word-break: break-word;
119
+ }
120
+ .cd-msg.user {
121
+ align-self: flex-end;
122
+ background: var(--cd-primary, #2563eb);
123
+ color: #fff;
124
+ border-bottom-right-radius: 4px;
125
+ }
126
+ .cd-msg.assistant {
127
+ align-self: flex-start;
128
+ background: #fff;
129
+ color: #1e293b;
130
+ border-bottom-left-radius: 4px;
131
+ box-shadow: 0 1px 4px rgba(0,0,0,.08);
132
+ }
133
+ .cd-msg.error {
134
+ align-self: flex-start;
135
+ background: #fef2f2;
136
+ color: #b91c1c;
137
+ border-bottom-left-radius: 4px;
138
+ }
139
+ .cd-typing { display: flex; gap: 4px; align-items: center; padding: 4px 0; }
140
+ .cd-typing span {
141
+ width: 7px; height: 7px; background: #94a3b8; border-radius: 50%;
142
+ animation: cd-bounce .9s infinite;
143
+ }
144
+ .cd-typing span:nth-child(2) { animation-delay: .15s; }
145
+ .cd-typing span:nth-child(3) { animation-delay: .3s; }
146
+ @keyframes cd-bounce {
147
+ 0%,60%,100% { transform: translateY(0); }
148
+ 30% { transform: translateY(-5px); }
149
+ }
150
+
151
+ .cd-input-area {
152
+ border-top: 1px solid #e2e8f0;
153
+ padding: 12px;
154
+ padding-bottom: calc(12px + (var(--cd-safe-bottom) * 0.35));
155
+ display: flex;
156
+ gap: 8px;
157
+ align-items: flex-end;
158
+ background: #fff;
159
+ flex-shrink: 0;
160
+ }
161
+ .cd-textarea {
162
+ flex: 1;
163
+ border: 1px solid #e2e8f0;
164
+ border-radius: 10px;
165
+ padding: 9px 12px;
166
+ font-size: 13.5px;
167
+ font-family: inherit;
168
+ resize: none;
169
+ outline: none;
170
+ max-height: 120px;
171
+ line-height: 1.5;
172
+ background: #f8fafc;
173
+ color: #1e293b;
174
+ transition: border-color .15s;
175
+ }
176
+ .cd-textarea:focus { border-color: var(--cd-primary, #2563eb); background: #fff; }
177
+ .cd-send-btn {
178
+ width: 36px; height: 36px;
179
+ background: var(--cd-primary, #2563eb);
180
+ color: #fff;
181
+ border: none;
182
+ border-radius: 10px;
183
+ cursor: pointer;
184
+ display: flex; align-items: center; justify-content: center;
185
+ flex-shrink: 0;
186
+ transition: opacity .15s;
187
+ }
188
+ .cd-send-btn:disabled { opacity: .45; cursor: not-allowed; }
189
+ .cd-send-btn svg { width: 16px; height: 16px; }
190
+
191
+ .cd-powered {
192
+ text-align: center;
193
+ font-size: 10px;
194
+ color: #94a3b8;
195
+ padding: 6px 0;
196
+ background: #fff;
197
+ flex-shrink: 0;
198
+ }
199
+ .cd-powered a { color: #94a3b8; text-decoration: none; }
200
+ .cd-powered a:hover { color: #64748b; }
201
+
202
+ /* Dark theme */
203
+ .cd-dark .cd-panel { background: #1e293b; }
204
+ .cd-dark .cd-messages { background: #0f172a; }
205
+ .cd-dark .cd-msg.assistant { background: #1e293b; color: #f1f5f9; box-shadow: 0 1px 4px rgba(0,0,0,.3); }
206
+ .cd-dark .cd-input-area { background: #1e293b; border-color: #334155; }
207
+ .cd-dark .cd-textarea { background: #0f172a; border-color: #334155; color: #f1f5f9; }
208
+ .cd-dark .cd-textarea:focus { border-color: var(--cd-primary, #3b82f6); }
209
+ .cd-dark .cd-powered { background: #1e293b; }
210
+
211
+ @media (max-width: 640px) {
212
+ .cd-panel {
213
+ left: calc(var(--cd-offset) + var(--cd-safe-left));
214
+ right: calc(var(--cd-offset) + var(--cd-safe-right));
215
+ width: auto;
216
+ height: min(540px, calc(var(--cd-viewport-height) - (var(--cd-offset) * 2) - var(--cd-safe-top) - var(--cd-safe-bottom) - 12px));
217
+ }
218
+ }
219
+
220
+ @media (max-width: 480px) {
221
+ .cd-panel {
222
+ top: var(--cd-safe-top);
223
+ right: 0;
224
+ bottom: 0;
225
+ left: 0;
226
+ width: auto;
227
+ height: calc(var(--cd-viewport-height) - var(--cd-safe-top));
228
+ max-height: calc(var(--cd-viewport-height) - var(--cd-safe-top));
229
+ border-radius: 18px 18px 0 0;
230
+ }
231
+
232
+ .cd-header {
233
+ padding: 16px;
234
+ }
235
+
236
+ .cd-messages {
237
+ padding: 14px;
238
+ }
239
+
240
+ .cd-input-area {
241
+ padding: 10px;
242
+ padding-bottom: calc(10px + var(--cd-safe-bottom));
243
+ }
244
+
245
+ .cd-textarea {
246
+ font-size: 16px;
247
+ }
248
+ }
249
+ `, w = {
250
+ chat: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',
251
+ close: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',
252
+ send: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>'
253
+ };
254
+ function I() {
255
+ return "cd_" + Math.random().toString(36).slice(2) + Date.now().toString(36);
256
+ }
257
+ let S = class {
258
+ constructor(e = {}) {
259
+ if (!e.apiKey) throw new Error("[CognitionDesk] apiKey is required");
260
+ this._cfg = {
261
+ apiKey: e.apiKey,
262
+ widgetId: e.widgetId || null,
263
+ assistantId: e.assistantId || null,
264
+ backendUrl: e.backendUrl || L,
265
+ primaryColor: e.primaryColor || "#2563eb",
266
+ theme: e.theme || "light",
267
+ // 'light' | 'dark' | 'auto'
268
+ botName: e.botName || "AI Assistant",
269
+ botEmoji: e.botEmoji || "πŸ€–",
270
+ welcomeMessage: e.welcomeMessage || "Hello! How can I help you today?",
271
+ placeholder: e.placeholder || "Type a message…",
272
+ position: e.position || "bottom-right",
273
+ streaming: e.streaming !== !1
274
+ // default: true
275
+ }, this._sessionId = I(), this._messages = [], this._open = !1, this._loading = !1, this._container = null, this._shadow = null, this._panel = null, this._messagesEl = null, this._textarea = null, this._sendBtn = null, this._viewportHandler = null;
276
+ }
277
+ // ── Public API ──────────────────────────────────────────────────────────────
278
+ /**
279
+ * Mount the widget.
280
+ * If `widgetId` was provided, fetches the server-side config first (async).
281
+ * Returns a Promise so callers can await full initialisation.
282
+ */
283
+ mount(e) {
284
+ const t = () => {
285
+ const a = e || document.body;
286
+ this._container = document.createElement("div"), this._container.setAttribute("data-cognitiondesk", ""), a.appendChild(this._container), this._shadow = this._container.attachShadow({ mode: "open" });
287
+ const s = document.createElement("style");
288
+ s.textContent = N, this._shadow.appendChild(s), this._buildDOM(), this._applyTheme(), this._syncViewportMetrics(), this._bindViewportMetrics(), this._bindEvents(), this._cfg.welcomeMessage && this._appendMessage("assistant", this._cfg.welcomeMessage, !1);
289
+ };
290
+ return this._cfg.widgetId ? this._fetchWidgetConfig().then(() => t()).catch(() => t()) : (t(), Promise.resolve(this));
291
+ }
292
+ /**
293
+ * Fetch public widget config from the platform and merge into this._cfg.
294
+ * Only fields not already overridden by the constructor are applied.
295
+ */
296
+ async _fetchWidgetConfig() {
297
+ var t;
298
+ const e = `${this._cfg.backendUrl}/platforms/web-widget/public/${this._cfg.widgetId}`;
299
+ try {
300
+ const a = await fetch(e);
301
+ if (!a.ok) return;
302
+ const { config: s } = await a.json();
303
+ if (!s) return;
304
+ s.botName && !this._userSet("botName") && (this._cfg.botName = s.botName), s.welcomeMessage && !this._userSet("welcomeMessage") && (this._cfg.welcomeMessage = s.welcomeMessage), s.primaryColor && !this._userSet("primaryColor") && (this._cfg.primaryColor = s.primaryColor), s.placeholder && !this._userSet("placeholder") && (this._cfg.placeholder = s.placeholder), s.assistantId && !this._cfg.assistantId && (this._cfg.assistantId = s.assistantId), (t = s.avatar) != null && t.value && !this._userSet("botEmoji") && (this._cfg.botEmoji = s.avatar.value);
305
+ } catch {
306
+ }
307
+ }
308
+ // eslint-disable-next-line no-unused-vars
309
+ _userSet(e) {
310
+ return !1;
311
+ }
312
+ unmount() {
313
+ this._unbindViewportMetrics(), this._container && (this._container.remove(), this._container = null);
314
+ }
315
+ open() {
316
+ var e, t;
317
+ this._open = !0, this._syncViewportMetrics(), (e = this._panel) == null || e.classList.add("open"), (t = this._textarea) == null || t.focus();
318
+ }
319
+ close() {
320
+ var e;
321
+ this._open = !1, (e = this._panel) == null || e.classList.remove("open");
322
+ }
323
+ toggle() {
324
+ this._open ? this.close() : this.open();
325
+ }
326
+ clearHistory() {
327
+ this._messages = [], this._messagesEl && (this._messagesEl.innerHTML = ""), this._cfg.welcomeMessage && this._appendMessage("assistant", this._cfg.welcomeMessage);
328
+ }
329
+ // ── DOM ─────────────────────────────────────────────────────────────────────
330
+ _buildDOM() {
331
+ const e = document.createElement("div");
332
+ e.className = "cd-root";
333
+ const t = document.createElement("button");
334
+ t.className = "cd-widget-btn", t.innerHTML = w.chat, t.setAttribute("aria-label", "Open chat"), t.style.setProperty("--cd-primary", this._cfg.primaryColor), this._toggleBtn = t;
335
+ const a = document.createElement("div");
336
+ a.className = "cd-panel", this._panel = a;
337
+ const s = document.createElement("div");
338
+ s.className = "cd-header", s.innerHTML = `
339
+ <div class="cd-header-avatar">${this._cfg.botEmoji}</div>
340
+ <div class="cd-header-info">
341
+ <div class="cd-header-name">${this._escHtml(this._cfg.botName)}</div>
342
+ <div class="cd-header-status">
343
+ <span class="cd-status-dot"></span> Online
344
+ </div>
345
+ </div>
346
+ `;
347
+ const o = document.createElement("button");
348
+ o.className = "cd-close-btn", o.innerHTML = w.close, o.setAttribute("aria-label", "Close chat"), s.appendChild(o), this._closeBtn = o;
349
+ const r = document.createElement("div");
350
+ r.className = "cd-messages", r.setAttribute("role", "log"), r.setAttribute("aria-live", "polite"), this._messagesEl = r;
351
+ const n = document.createElement("div");
352
+ n.className = "cd-input-area";
353
+ const d = document.createElement("textarea");
354
+ d.className = "cd-textarea", d.rows = 1, d.placeholder = this._cfg.placeholder, this._textarea = d;
355
+ const c = document.createElement("button");
356
+ c.className = "cd-send-btn", c.innerHTML = w.send, c.setAttribute("aria-label", "Send"), this._sendBtn = c, n.appendChild(d), n.appendChild(c);
357
+ const l = document.createElement("div");
358
+ l.className = "cd-powered", l.innerHTML = 'Powered by <a href="https://cognitiondesk.com" target="_blank" rel="noopener">CognitionDesk</a>', a.appendChild(s), a.appendChild(r), a.appendChild(n), a.appendChild(l), e.appendChild(t), e.appendChild(a), this._shadow.appendChild(e), this._root = e;
359
+ }
360
+ _applyTheme() {
361
+ var t, a, s;
362
+ (this._cfg.theme === "auto" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : this._cfg.theme) === "dark" && ((t = this._root) == null || t.classList.add("cd-dark")), (a = this._root) == null || a.style.setProperty("--cd-primary", this._cfg.primaryColor), (s = this._panel) == null || s.style.setProperty("--cd-primary", this._cfg.primaryColor);
363
+ }
364
+ // ── Events ──────────────────────────────────────────────────────────────────
365
+ _bindEvents() {
366
+ this._toggleBtn.addEventListener("click", () => this.toggle()), this._closeBtn.addEventListener("click", () => this.close()), this._sendBtn.addEventListener("click", () => this._sendMessage()), this._textarea.addEventListener("keydown", (e) => {
367
+ e.key === "Enter" && !e.shiftKey && (e.preventDefault(), this._sendMessage());
368
+ }), this._textarea.addEventListener("input", () => {
369
+ this._textarea.style.height = "auto", this._textarea.style.height = Math.min(this._textarea.scrollHeight, 120) + "px";
370
+ }), this._textarea.addEventListener("focus", () => {
371
+ this._syncViewportMetrics();
372
+ });
373
+ }
374
+ _bindViewportMetrics() {
375
+ this._viewportHandler || (this._viewportHandler = () => this._syncViewportMetrics(), window.addEventListener("resize", this._viewportHandler, { passive: !0 }), window.addEventListener("orientationchange", this._viewportHandler), window.visualViewport && (window.visualViewport.addEventListener("resize", this._viewportHandler), window.visualViewport.addEventListener("scroll", this._viewportHandler)));
376
+ }
377
+ _unbindViewportMetrics() {
378
+ this._viewportHandler && (window.removeEventListener("resize", this._viewportHandler), window.removeEventListener("orientationchange", this._viewportHandler), window.visualViewport && (window.visualViewport.removeEventListener("resize", this._viewportHandler), window.visualViewport.removeEventListener("scroll", this._viewportHandler)), this._viewportHandler = null);
379
+ }
380
+ _syncViewportMetrics() {
381
+ const e = this._root || this._container;
382
+ if (!e) return;
383
+ const t = window.visualViewport, a = t ? t.height : window.innerHeight;
384
+ e.style.setProperty("--cd-viewport-height", `${Math.round(a)}px`);
385
+ }
386
+ // ── Chat ────────────────────────────────────────────────────────────────────
387
+ async _sendMessage() {
388
+ const e = this._textarea.value.trim();
389
+ if (!(!e || this._loading)) {
390
+ this._textarea.value = "", this._textarea.style.height = "auto", this._loading = !0, this._sendBtn.disabled = !0, this._messages.push({ role: "user", content: e }), this._appendMessage("user", e, !1);
391
+ try {
392
+ if (this._cfg.streaming)
393
+ await this._callApiStream();
394
+ else {
395
+ const t = this._showTyping(), a = await this._callApi();
396
+ this._removeTyping(t), this._messages.push({ role: "assistant", content: a }), this._appendMessage("assistant", a, !0);
397
+ }
398
+ } catch (t) {
399
+ this._appendMessage("error", "Sorry, something went wrong. Please try again.", !1), console.error("[CognitionDesk]", t);
400
+ } finally {
401
+ this._loading = !1, this._sendBtn.disabled = !1, this._textarea.focus();
402
+ }
403
+ }
404
+ }
405
+ _buildRequestBody() {
406
+ return {
407
+ messages: this._messages,
408
+ assistantId: this._cfg.assistantId || void 0,
409
+ userContext: {
410
+ sessionId: this._sessionId,
411
+ assistantId: this._cfg.assistantId || void 0,
412
+ widgetId: this._cfg.widgetId || void 0,
413
+ platform: "cognitiondesk-widget"
414
+ }
415
+ };
416
+ }
417
+ /** Streaming path β€” uses SSE endpoint */
418
+ async _callApiStream() {
419
+ const e = `${this._cfg.backendUrl}/chat-apiKeyAuth/stream`, t = await fetch(e, {
420
+ method: "POST",
421
+ headers: { "Content-Type": "application/json", "x-api-key": this._cfg.apiKey },
422
+ body: JSON.stringify({ ...this._buildRequestBody(), stream: !0 })
423
+ });
424
+ if (!t.ok) {
425
+ const d = await t.json().catch(() => ({}));
426
+ throw new Error(d.message || `HTTP ${t.status}`);
427
+ }
428
+ const a = document.createElement("div");
429
+ a.className = "cd-msg assistant", a.innerHTML = '<div class="cd-typing"><span></span><span></span><span></span></div>', this._messagesEl.appendChild(a), this._scrollToBottom();
430
+ const s = t.body.getReader(), o = new TextDecoder();
431
+ let r = "", n = !1;
432
+ try {
433
+ for (; ; ) {
434
+ const { done: d, value: c } = await s.read();
435
+ if (d) break;
436
+ const l = o.decode(c, { stream: !0 });
437
+ for (const g of l.split(`
438
+ `)) {
439
+ if (!g.startsWith("data: ")) continue;
440
+ const f = g.slice(6).trim();
441
+ if (f === "[DONE]") break;
442
+ let h;
443
+ try {
444
+ h = JSON.parse(f);
445
+ } catch {
446
+ continue;
447
+ }
448
+ h.type === "content" && h.data && (n || (a.innerHTML = "", n = !0), r += h.data, a.innerHTML = this._renderMarkdown(r), this._scrollToBottom());
449
+ }
450
+ }
451
+ } finally {
452
+ s.releaseLock();
453
+ }
454
+ n || (a.innerHTML = this._renderMarkdown("No response")), r && this._messages.push({ role: "assistant", content: r });
455
+ }
456
+ /** Non-streaming fallback path */
457
+ async _callApi() {
458
+ var s, o, r;
459
+ const e = `${this._cfg.backendUrl}/chat-apiKeyAuth/chat`, t = await fetch(e, {
460
+ method: "POST",
461
+ headers: { "Content-Type": "application/json", "x-api-key": this._cfg.apiKey },
462
+ body: JSON.stringify(this._buildRequestBody())
463
+ });
464
+ if (!t.ok) {
465
+ const n = await t.json().catch(() => ({}));
466
+ throw new Error(n.message || `HTTP ${t.status}`);
467
+ }
468
+ const a = await t.json();
469
+ return a.response || a.message || a.content || ((r = (o = (s = a.choices) == null ? void 0 : s[0]) == null ? void 0 : o.message) == null ? void 0 : r.content) || "No response";
470
+ }
471
+ // ── DOM helpers ─────────────────────────────────────────────────────────────
472
+ _appendMessage(e, t, a = !0) {
473
+ const s = document.createElement("div");
474
+ s.className = `cd-msg ${e}`, a && e !== "user" ? s.innerHTML = this._renderMarkdown(t) : s.textContent = t, this._messagesEl.appendChild(s), this._scrollToBottom();
475
+ }
476
+ /** Minimal, safe markdown β†’ HTML renderer (no dependencies). */
477
+ _renderMarkdown(e) {
478
+ if (!e) return "";
479
+ let t = this._escHtml(e);
480
+ return t = t.replace(
481
+ /```[\w]*\n?([\s\S]*?)```/g,
482
+ (a, s) => `<pre style="background:#0f172a;color:#e2e8f0;padding:10px;border-radius:6px;font-size:12px;overflow-x:auto;margin:6px 0;white-space:pre-wrap">${s.trim()}</pre>`
483
+ ), t = t.replace(/`([^`]+)`/g, '<code style="background:rgba(0,0,0,.08);padding:1px 5px;border-radius:4px;font-size:.9em">$1</code>'), t = t.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>"), t = t.replace(/__([^_]+)__/g, "<strong>$1</strong>"), t = t.replace(/\*([^*]+)\*/g, "<em>$1</em>"), t = t.replace(/_([^_]+)_/g, "<em>$1</em>"), t = t.replace(
484
+ /\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,
485
+ '<a href="$2" target="_blank" rel="noopener" style="color:var(--cd-primary,#2563eb)">$1</a>'
486
+ ), t = t.replace(/\n/g, "<br>"), t;
487
+ }
488
+ _showTyping() {
489
+ const e = document.createElement("div");
490
+ return e.className = "cd-msg assistant", e.innerHTML = '<div class="cd-typing"><span></span><span></span><span></span></div>', this._messagesEl.appendChild(e), this._scrollToBottom(), e;
491
+ }
492
+ _removeTyping(e) {
493
+ e == null || e.remove();
494
+ }
495
+ _scrollToBottom() {
496
+ this._messagesEl && (this._messagesEl.scrollTop = this._messagesEl.scrollHeight);
497
+ }
498
+ _escHtml(e) {
499
+ return String(e).replace(/[&<>"']/g, (t) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[t]);
500
+ }
501
+ };
502
+ const D = H(function(e, t) {
503
+ const {
504
+ apiKey: a,
505
+ widgetId: s,
506
+ assistantId: o,
507
+ theme: r = "light",
508
+ primaryColor: n = "#2563eb",
509
+ botName: d = "AI Assistant",
510
+ botEmoji: c = "πŸ€–",
511
+ welcomeMessage: l = "Hello! How can I help you today?",
512
+ placeholder: g = "Type a message…",
513
+ defaultOpen: f = !1,
514
+ streaming: h = !0,
515
+ backendUrl: x,
516
+ onOpen: m,
517
+ onClose: u
518
+ } = e, p = y(null), v = y(null);
519
+ return T(t, () => ({
520
+ open: () => {
521
+ var i;
522
+ return (i = p.current) == null ? void 0 : i.open();
523
+ },
524
+ close: () => {
525
+ var i;
526
+ return (i = p.current) == null ? void 0 : i.close();
527
+ },
528
+ toggle: () => {
529
+ var i;
530
+ return (i = p.current) == null ? void 0 : i.toggle();
531
+ },
532
+ clearHistory: () => {
533
+ var i;
534
+ return (i = p.current) == null ? void 0 : i.clearHistory();
535
+ }
536
+ }), []), k(() => {
537
+ if (!a) {
538
+ console.error("[CognitionDesk] apiKey prop is required");
539
+ return;
540
+ }
541
+ const i = new S({
542
+ apiKey: a,
543
+ widgetId: s,
544
+ assistantId: o,
545
+ theme: r,
546
+ primaryColor: n,
547
+ botName: d,
548
+ botEmoji: c,
549
+ welcomeMessage: l,
550
+ placeholder: g,
551
+ streaming: h,
552
+ ...x ? { backendUrl: x } : {}
553
+ });
554
+ if (m || u) {
555
+ const _ = i.open.bind(i), M = i.close.bind(i);
556
+ i.open = (...b) => {
557
+ _(...b), m == null || m();
558
+ }, i.close = (...b) => {
559
+ M(...b), u == null || u();
560
+ };
561
+ }
562
+ return Promise.resolve(i.mount(v.current)).then(() => {
563
+ p.current = i, f && i.open();
564
+ }), () => {
565
+ i.unmount(), p.current = null;
566
+ };
567
+ }, [a, s, o]), k(() => {
568
+ var _;
569
+ const i = p.current;
570
+ i && (i._cfg.theme = r, i._cfg.primaryColor = n, (_ = i._applyTheme) == null || _.call(i));
571
+ }, [r, n]), /* @__PURE__ */ C("div", { ref: v, "data-cognitiondesk-root": "" });
572
+ });
573
+ export {
574
+ D as CognitionDeskWidget,
575
+ S as CognitionDeskWidgetCore
576
+ };