@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.
@@ -0,0 +1,256 @@
1
+ (function(d,l){typeof exports=="object"&&typeof module<"u"?l(exports):typeof define=="function"&&define.amd?define(["exports"],l):(d=typeof globalThis<"u"?globalThis:d||self,l(d.CognitionDeskWidget={}))})(this,function(d){"use strict";const l="https://mounaji-backendv3.onrender.com",_=`
2
+ :host {
3
+ all: initial;
4
+ font-family: system-ui, sans-serif;
5
+ --cd-offset: clamp(12px, 4vw, 24px);
6
+ --cd-launcher-size: clamp(56px, 14vw, 64px);
7
+ --cd-launcher-gap: 12px;
8
+ --cd-viewport-height: 100vh;
9
+ --cd-safe-top: env(safe-area-inset-top, 0px);
10
+ --cd-safe-right: env(safe-area-inset-right, 0px);
11
+ --cd-safe-bottom: env(safe-area-inset-bottom, 0px);
12
+ --cd-safe-left: env(safe-area-inset-left, 0px);
13
+ }
14
+
15
+ .cd-root {
16
+ position: fixed;
17
+ inset: 0;
18
+ pointer-events: none;
19
+ z-index: 2147483000;
20
+ }
21
+
22
+ .cd-root > * {
23
+ pointer-events: auto;
24
+ }
25
+
26
+ .cd-widget-btn {
27
+ position: fixed;
28
+ bottom: calc(var(--cd-offset) + var(--cd-safe-bottom));
29
+ right: calc(var(--cd-offset) + var(--cd-safe-right));
30
+ z-index: 2147483647;
31
+ width: var(--cd-launcher-size);
32
+ height: var(--cd-launcher-size);
33
+ border-radius: 50%;
34
+ background: var(--cd-primary, #2563eb);
35
+ color: #fff;
36
+ border: none;
37
+ cursor: pointer;
38
+ display: flex;
39
+ align-items: center;
40
+ justify-content: center;
41
+ box-shadow: 0 4px 20px rgba(37,99,235,.45);
42
+ transition: transform .2s, box-shadow .2s;
43
+ touch-action: manipulation;
44
+ }
45
+ .cd-widget-btn:hover { transform: scale(1.08); box-shadow: 0 6px 24px rgba(37,99,235,.55); }
46
+ .cd-widget-btn svg { width: 26px; height: 26px; }
47
+
48
+ .cd-panel {
49
+ position: fixed;
50
+ bottom: calc(var(--cd-offset) + var(--cd-safe-bottom) + var(--cd-launcher-size) + var(--cd-launcher-gap));
51
+ right: calc(var(--cd-offset) + var(--cd-safe-right));
52
+ z-index: 2147483646;
53
+ width: min(380px, calc(100vw - (var(--cd-offset) * 2) - var(--cd-safe-left) - var(--cd-safe-right)));
54
+ 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)));
55
+ max-height: calc(var(--cd-viewport-height) - (var(--cd-offset) * 2) - var(--cd-safe-top) - var(--cd-safe-bottom));
56
+ background: #fff;
57
+ border-radius: 16px;
58
+ box-shadow: 0 12px 40px rgba(0,0,0,.18);
59
+ display: flex;
60
+ flex-direction: column;
61
+ overflow: hidden;
62
+ transform: scale(.96) translateY(8px);
63
+ opacity: 0;
64
+ pointer-events: none;
65
+ transition: opacity .2s, transform .2s;
66
+ overscroll-behavior: contain;
67
+ }
68
+ .cd-panel.open {
69
+ transform: scale(1) translateY(0);
70
+ opacity: 1;
71
+ pointer-events: all;
72
+ }
73
+
74
+ .cd-header {
75
+ background: var(--cd-primary, #2563eb);
76
+ color: #fff;
77
+ padding: 14px 16px;
78
+ display: flex;
79
+ align-items: center;
80
+ gap: 10px;
81
+ flex-shrink: 0;
82
+ }
83
+ .cd-header-avatar {
84
+ width: 36px; height: 36px; border-radius: 50%;
85
+ background: rgba(255,255,255,.25);
86
+ display: flex; align-items: center; justify-content: center;
87
+ font-size: 18px;
88
+ }
89
+ .cd-header-info { flex: 1; min-width: 0; }
90
+ .cd-header-name { font-size: 14px; font-weight: 600; }
91
+ .cd-header-status { font-size: 11px; opacity: .85; display: flex; align-items: center; gap: 4px; }
92
+ .cd-status-dot { width: 7px; height: 7px; border-radius: 50%; background: #4ade80; }
93
+ .cd-close-btn {
94
+ background: none; border: none; color: rgba(255,255,255,.75);
95
+ cursor: pointer; padding: 4px; border-radius: 6px;
96
+ display: flex; align-items: center; justify-content: center;
97
+ }
98
+ .cd-close-btn:hover { color: #fff; background: rgba(255,255,255,.15); }
99
+ .cd-close-btn svg { width: 18px; height: 18px; }
100
+
101
+ .cd-messages {
102
+ flex: 1;
103
+ overflow-y: auto;
104
+ padding: 16px;
105
+ display: flex;
106
+ flex-direction: column;
107
+ gap: 12px;
108
+ background: #f8fafc;
109
+ }
110
+ .cd-msg {
111
+ max-width: 78%;
112
+ padding: 10px 13px;
113
+ border-radius: 14px;
114
+ font-size: 13.5px;
115
+ line-height: 1.5;
116
+ word-break: break-word;
117
+ }
118
+ .cd-msg.user {
119
+ align-self: flex-end;
120
+ background: var(--cd-primary, #2563eb);
121
+ color: #fff;
122
+ border-bottom-right-radius: 4px;
123
+ }
124
+ .cd-msg.assistant {
125
+ align-self: flex-start;
126
+ background: #fff;
127
+ color: #1e293b;
128
+ border-bottom-left-radius: 4px;
129
+ box-shadow: 0 1px 4px rgba(0,0,0,.08);
130
+ }
131
+ .cd-msg.error {
132
+ align-self: flex-start;
133
+ background: #fef2f2;
134
+ color: #b91c1c;
135
+ border-bottom-left-radius: 4px;
136
+ }
137
+ .cd-typing { display: flex; gap: 4px; align-items: center; padding: 4px 0; }
138
+ .cd-typing span {
139
+ width: 7px; height: 7px; background: #94a3b8; border-radius: 50%;
140
+ animation: cd-bounce .9s infinite;
141
+ }
142
+ .cd-typing span:nth-child(2) { animation-delay: .15s; }
143
+ .cd-typing span:nth-child(3) { animation-delay: .3s; }
144
+ @keyframes cd-bounce {
145
+ 0%,60%,100% { transform: translateY(0); }
146
+ 30% { transform: translateY(-5px); }
147
+ }
148
+
149
+ .cd-input-area {
150
+ border-top: 1px solid #e2e8f0;
151
+ padding: 12px;
152
+ padding-bottom: calc(12px + (var(--cd-safe-bottom) * 0.35));
153
+ display: flex;
154
+ gap: 8px;
155
+ align-items: flex-end;
156
+ background: #fff;
157
+ flex-shrink: 0;
158
+ }
159
+ .cd-textarea {
160
+ flex: 1;
161
+ border: 1px solid #e2e8f0;
162
+ border-radius: 10px;
163
+ padding: 9px 12px;
164
+ font-size: 13.5px;
165
+ font-family: inherit;
166
+ resize: none;
167
+ outline: none;
168
+ max-height: 120px;
169
+ line-height: 1.5;
170
+ background: #f8fafc;
171
+ color: #1e293b;
172
+ transition: border-color .15s;
173
+ }
174
+ .cd-textarea:focus { border-color: var(--cd-primary, #2563eb); background: #fff; }
175
+ .cd-send-btn {
176
+ width: 36px; height: 36px;
177
+ background: var(--cd-primary, #2563eb);
178
+ color: #fff;
179
+ border: none;
180
+ border-radius: 10px;
181
+ cursor: pointer;
182
+ display: flex; align-items: center; justify-content: center;
183
+ flex-shrink: 0;
184
+ transition: opacity .15s;
185
+ }
186
+ .cd-send-btn:disabled { opacity: .45; cursor: not-allowed; }
187
+ .cd-send-btn svg { width: 16px; height: 16px; }
188
+
189
+ .cd-powered {
190
+ text-align: center;
191
+ font-size: 10px;
192
+ color: #94a3b8;
193
+ padding: 6px 0;
194
+ background: #fff;
195
+ flex-shrink: 0;
196
+ }
197
+ .cd-powered a { color: #94a3b8; text-decoration: none; }
198
+ .cd-powered a:hover { color: #64748b; }
199
+
200
+ /* Dark theme */
201
+ .cd-dark .cd-panel { background: #1e293b; }
202
+ .cd-dark .cd-messages { background: #0f172a; }
203
+ .cd-dark .cd-msg.assistant { background: #1e293b; color: #f1f5f9; box-shadow: 0 1px 4px rgba(0,0,0,.3); }
204
+ .cd-dark .cd-input-area { background: #1e293b; border-color: #334155; }
205
+ .cd-dark .cd-textarea { background: #0f172a; border-color: #334155; color: #f1f5f9; }
206
+ .cd-dark .cd-textarea:focus { border-color: var(--cd-primary, #3b82f6); }
207
+ .cd-dark .cd-powered { background: #1e293b; }
208
+
209
+ @media (max-width: 640px) {
210
+ .cd-panel {
211
+ left: calc(var(--cd-offset) + var(--cd-safe-left));
212
+ right: calc(var(--cd-offset) + var(--cd-safe-right));
213
+ width: auto;
214
+ height: min(540px, calc(var(--cd-viewport-height) - (var(--cd-offset) * 2) - var(--cd-safe-top) - var(--cd-safe-bottom) - 12px));
215
+ }
216
+ }
217
+
218
+ @media (max-width: 480px) {
219
+ .cd-panel {
220
+ top: var(--cd-safe-top);
221
+ right: 0;
222
+ bottom: 0;
223
+ left: 0;
224
+ width: auto;
225
+ height: calc(var(--cd-viewport-height) - var(--cd-safe-top));
226
+ max-height: calc(var(--cd-viewport-height) - var(--cd-safe-top));
227
+ border-radius: 18px 18px 0 0;
228
+ }
229
+
230
+ .cd-header {
231
+ padding: 16px;
232
+ }
233
+
234
+ .cd-messages {
235
+ padding: 14px;
236
+ }
237
+
238
+ .cd-input-area {
239
+ padding: 10px;
240
+ padding-bottom: calc(10px + var(--cd-safe-bottom));
241
+ }
242
+
243
+ .cd-textarea {
244
+ font-size: 16px;
245
+ }
246
+ }
247
+ `,m={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>',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>',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>'};function w(){return"cd_"+Math.random().toString(36).slice(2)+Date.now().toString(36)}class g{constructor(e={}){if(!e.apiKey)throw new Error("[CognitionDesk] apiKey is required");this._cfg={apiKey:e.apiKey,widgetId:e.widgetId||null,assistantId:e.assistantId||null,backendUrl:e.backendUrl||l,primaryColor:e.primaryColor||"#2563eb",theme:e.theme||"light",botName:e.botName||"AI Assistant",botEmoji:e.botEmoji||"🤖",welcomeMessage:e.welcomeMessage||"Hello! How can I help you today?",placeholder:e.placeholder||"Type a message…",position:e.position||"bottom-right",streaming:e.streaming!==!1},this._sessionId=w(),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}mount(e){const t=()=>{const a=e||document.body;this._container=document.createElement("div"),this._container.setAttribute("data-cognitiondesk",""),a.appendChild(this._container),this._shadow=this._container.attachShadow({mode:"open"});const s=document.createElement("style");s.textContent=_,this._shadow.appendChild(s),this._buildDOM(),this._applyTheme(),this._syncViewportMetrics(),this._bindViewportMetrics(),this._bindEvents(),this._cfg.welcomeMessage&&this._appendMessage("assistant",this._cfg.welcomeMessage,!1)};return this._cfg.widgetId?this._fetchWidgetConfig().then(()=>t()).catch(()=>t()):(t(),Promise.resolve(this))}async _fetchWidgetConfig(){var t;const e=`${this._cfg.backendUrl}/platforms/web-widget/public/${this._cfg.widgetId}`;try{const a=await fetch(e);if(!a.ok)return;const{config:s}=await a.json();if(!s)return;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)}catch{}}_userSet(e){return!1}unmount(){this._unbindViewportMetrics(),this._container&&(this._container.remove(),this._container=null)}open(){var e,t;this._open=!0,this._syncViewportMetrics(),(e=this._panel)==null||e.classList.add("open"),(t=this._textarea)==null||t.focus()}close(){var e;this._open=!1,(e=this._panel)==null||e.classList.remove("open")}toggle(){this._open?this.close():this.open()}clearHistory(){this._messages=[],this._messagesEl&&(this._messagesEl.innerHTML=""),this._cfg.welcomeMessage&&this._appendMessage("assistant",this._cfg.welcomeMessage)}_buildDOM(){const e=document.createElement("div");e.className="cd-root";const t=document.createElement("button");t.className="cd-widget-btn",t.innerHTML=m.chat,t.setAttribute("aria-label","Open chat"),t.style.setProperty("--cd-primary",this._cfg.primaryColor),this._toggleBtn=t;const a=document.createElement("div");a.className="cd-panel",this._panel=a;const s=document.createElement("div");s.className="cd-header",s.innerHTML=`
248
+ <div class="cd-header-avatar">${this._cfg.botEmoji}</div>
249
+ <div class="cd-header-info">
250
+ <div class="cd-header-name">${this._escHtml(this._cfg.botName)}</div>
251
+ <div class="cd-header-status">
252
+ <span class="cd-status-dot"></span> Online
253
+ </div>
254
+ </div>
255
+ `;const r=document.createElement("button");r.className="cd-close-btn",r.innerHTML=m.close,r.setAttribute("aria-label","Close chat"),s.appendChild(r),this._closeBtn=r;const i=document.createElement("div");i.className="cd-messages",i.setAttribute("role","log"),i.setAttribute("aria-live","polite"),this._messagesEl=i;const n=document.createElement("div");n.className="cd-input-area";const o=document.createElement("textarea");o.className="cd-textarea",o.rows=1,o.placeholder=this._cfg.placeholder,this._textarea=o;const c=document.createElement("button");c.className="cd-send-btn",c.innerHTML=m.send,c.setAttribute("aria-label","Send"),this._sendBtn=c,n.appendChild(o),n.appendChild(c);const h=document.createElement("div");h.className="cd-powered",h.innerHTML='Powered by <a href="https://cognitiondesk.com" target="_blank" rel="noopener">CognitionDesk</a>',a.appendChild(s),a.appendChild(i),a.appendChild(n),a.appendChild(h),e.appendChild(t),e.appendChild(a),this._shadow.appendChild(e),this._root=e}_applyTheme(){var t,a,s;(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)}_bindEvents(){this._toggleBtn.addEventListener("click",()=>this.toggle()),this._closeBtn.addEventListener("click",()=>this.close()),this._sendBtn.addEventListener("click",()=>this._sendMessage()),this._textarea.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this._sendMessage())}),this._textarea.addEventListener("input",()=>{this._textarea.style.height="auto",this._textarea.style.height=Math.min(this._textarea.scrollHeight,120)+"px"}),this._textarea.addEventListener("focus",()=>{this._syncViewportMetrics()})}_bindViewportMetrics(){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)))}_unbindViewportMetrics(){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)}_syncViewportMetrics(){const e=this._root||this._container;if(!e)return;const t=window.visualViewport,a=t?t.height:window.innerHeight;e.style.setProperty("--cd-viewport-height",`${Math.round(a)}px`)}async _sendMessage(){const e=this._textarea.value.trim();if(!(!e||this._loading)){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);try{if(this._cfg.streaming)await this._callApiStream();else{const t=this._showTyping(),a=await this._callApi();this._removeTyping(t),this._messages.push({role:"assistant",content:a}),this._appendMessage("assistant",a,!0)}}catch(t){this._appendMessage("error","Sorry, something went wrong. Please try again.",!1),console.error("[CognitionDesk]",t)}finally{this._loading=!1,this._sendBtn.disabled=!1,this._textarea.focus()}}}_buildRequestBody(){return{messages:this._messages,assistantId:this._cfg.assistantId||void 0,userContext:{sessionId:this._sessionId,assistantId:this._cfg.assistantId||void 0,widgetId:this._cfg.widgetId||void 0,platform:"cognitiondesk-widget"}}}async _callApiStream(){const e=`${this._cfg.backendUrl}/chat-apiKeyAuth/stream`,t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this._cfg.apiKey},body:JSON.stringify({...this._buildRequestBody(),stream:!0})});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error(o.message||`HTTP ${t.status}`)}const a=document.createElement("div");a.className="cd-msg assistant",a.innerHTML='<div class="cd-typing"><span></span><span></span><span></span></div>',this._messagesEl.appendChild(a),this._scrollToBottom();const s=t.body.getReader(),r=new TextDecoder;let i="",n=!1;try{for(;;){const{done:o,value:c}=await s.read();if(o)break;const h=r.decode(c,{stream:!0});for(const u of h.split(`
256
+ `)){if(!u.startsWith("data: "))continue;const b=u.slice(6).trim();if(b==="[DONE]")break;let f;try{f=JSON.parse(b)}catch{continue}f.type==="content"&&f.data&&(n||(a.innerHTML="",n=!0),i+=f.data,a.innerHTML=this._renderMarkdown(i),this._scrollToBottom())}}}finally{s.releaseLock()}n||(a.innerHTML=this._renderMarkdown("No response")),i&&this._messages.push({role:"assistant",content:i})}async _callApi(){var s,r,i;const e=`${this._cfg.backendUrl}/chat-apiKeyAuth/chat`,t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this._cfg.apiKey},body:JSON.stringify(this._buildRequestBody())});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.message||`HTTP ${t.status}`)}const a=await t.json();return a.response||a.message||a.content||((i=(r=(s=a.choices)==null?void 0:s[0])==null?void 0:r.message)==null?void 0:i.content)||"No response"}_appendMessage(e,t,a=!0){const s=document.createElement("div");s.className=`cd-msg ${e}`,a&&e!=="user"?s.innerHTML=this._renderMarkdown(t):s.textContent=t,this._messagesEl.appendChild(s),this._scrollToBottom()}_renderMarkdown(e){if(!e)return"";let t=this._escHtml(e);return t=t.replace(/```[\w]*\n?([\s\S]*?)```/g,(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>`),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(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener" style="color:var(--cd-primary,#2563eb)">$1</a>'),t=t.replace(/\n/g,"<br>"),t}_showTyping(){const e=document.createElement("div");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}_removeTyping(e){e==null||e.remove()}_scrollToBottom(){this._messagesEl&&(this._messagesEl.scrollTop=this._messagesEl.scrollHeight)}_escHtml(e){return String(e).replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}}function v(p){const e=new g(p);return e.mount(),e}if(typeof document<"u"){const p=()=>{document.querySelectorAll("script[data-api-key]").forEach(e=>{const t=e.getAttribute("data-api-key");if(!t)return;const a=e.getAttribute("data-widget-id")||void 0,s=e.getAttribute("data-streaming"),r=new g({apiKey:t,widgetId:a,assistantId:e.getAttribute("data-assistant-id")||void 0,theme:e.getAttribute("data-theme")||"light",primaryColor:e.getAttribute("data-primary-color")||"#2563eb",botName:e.getAttribute("data-bot-name")||"AI Assistant",botEmoji:e.getAttribute("data-bot-emoji")||void 0,welcomeMessage:e.getAttribute("data-welcome-message")||void 0,placeholder:e.getAttribute("data-placeholder")||void 0,backendUrl:e.getAttribute("data-backend-url")||void 0,streaming:s===null?!0:s!=="false"});Promise.resolve(r.mount())})};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",p):p()}d.CognitionDeskWidget=g,d.default=g,d.init=v,Object.defineProperties(d,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@cognitiondesk/widget",
3
+ "version": "1.1.0",
4
+ "description": "Embed a CognitionDesk AI chat widget into any website. Authenticate with an API key from your CognitionDesk dashboard.",
5
+ "keywords": ["chat", "widget", "ai", "cognitiondesk", "chatbot", "react", "streaming", "mounaji"],
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "main": "./dist/widget.umd.cjs",
9
+ "module": "./dist/widget.es.js",
10
+ "exports": {
11
+ ".": {
12
+ "import": "./dist/widget.es.js",
13
+ "require": "./dist/widget.umd.cjs"
14
+ },
15
+ "./react": {
16
+ "import": "./dist/react.es.js",
17
+ "require": "./dist/react.umd.cjs"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "src"
23
+ ],
24
+ "scripts": {
25
+ "build": "vite build && vite build --config vite.config.react.js",
26
+ "dev": "vite build --watch"
27
+ },
28
+ "peerDependencies": {
29
+ "react": ">=17.0.0",
30
+ "react-dom": ">=17.0.0"
31
+ },
32
+ "peerDependenciesMeta": {
33
+ "react": { "optional": true },
34
+ "react-dom": { "optional": true }
35
+ },
36
+ "devDependencies": {
37
+ "@vitejs/plugin-react": "^4.2.1",
38
+ "react": "^18.2.0",
39
+ "react-dom": "^18.2.0",
40
+ "vite": "^5.1.0"
41
+ }
42
+ }
package/src/index.js ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * @cognitiondesk/widget — main entry point (vanilla JS / UMD)
3
+ *
4
+ * For React, import from '@cognitiondesk/widget/react' instead.
5
+ */
6
+
7
+ import CognitionDeskWidget from './widget.js';
8
+ export { CognitionDeskWidget };
9
+ export default CognitionDeskWidget;
10
+
11
+ /**
12
+ * Convenience global init — used by the UMD/script-tag build.
13
+ *
14
+ * <script src="widget.umd.js"></script>
15
+ * <script>
16
+ * CognitionDesk.init({ apiKey: 'xxx', assistantId: 'yyy' });
17
+ * </script>
18
+ */
19
+ export function init(config) {
20
+ const w = new CognitionDeskWidget(config);
21
+ w.mount();
22
+ return w;
23
+ }
24
+
25
+ /**
26
+ * Auto-init via data attributes when included as a script tag:
27
+ *
28
+ * <!-- Minimal — config loaded from platform -->
29
+ * <script src="widget.umd.cjs"
30
+ * data-api-key="YOUR_API_KEY"
31
+ * data-widget-id="widget_xxx">
32
+ * </script>
33
+ *
34
+ * <!-- Full inline config -->
35
+ * <script src="widget.umd.cjs"
36
+ * data-api-key="YOUR_API_KEY"
37
+ * data-assistant-id="asst_xxx"
38
+ * data-theme="light"
39
+ * data-primary-color="#2563eb"
40
+ * data-bot-name="Support Bot"
41
+ * data-bot-emoji="🤖"
42
+ * data-welcome-message="Hi! How can I help?"
43
+ * data-placeholder="Type a message…"
44
+ * data-streaming="true"
45
+ * data-backend-url="https://mounaji-backendv3.onrender.com">
46
+ * </script>
47
+ */
48
+ if (typeof document !== 'undefined') {
49
+ const _autoInit = () => {
50
+ document.querySelectorAll('script[data-api-key]').forEach(script => {
51
+ const apiKey = script.getAttribute('data-api-key');
52
+ if (!apiKey) return;
53
+ const widgetId = script.getAttribute('data-widget-id') || undefined;
54
+ const streamingAttr = script.getAttribute('data-streaming');
55
+ const w = new CognitionDeskWidget({
56
+ apiKey,
57
+ widgetId,
58
+ assistantId: script.getAttribute('data-assistant-id') || undefined,
59
+ theme: script.getAttribute('data-theme') || 'light',
60
+ primaryColor: script.getAttribute('data-primary-color') || '#2563eb',
61
+ botName: script.getAttribute('data-bot-name') || 'AI Assistant',
62
+ botEmoji: script.getAttribute('data-bot-emoji') || undefined,
63
+ welcomeMessage: script.getAttribute('data-welcome-message') || undefined,
64
+ placeholder: script.getAttribute('data-placeholder') || undefined,
65
+ backendUrl: script.getAttribute('data-backend-url') || undefined,
66
+ streaming: streamingAttr === null ? true : streamingAttr !== 'false',
67
+ });
68
+ // mount() is async when widgetId is set (fetches remote config first)
69
+ Promise.resolve(w.mount());
70
+ });
71
+ };
72
+
73
+ if (document.readyState === 'loading') {
74
+ document.addEventListener('DOMContentLoaded', _autoInit);
75
+ } else {
76
+ _autoInit();
77
+ }
78
+ }
package/src/react.jsx ADDED
@@ -0,0 +1,114 @@
1
+ /**
2
+ * CognitionDesk React component wrapper.
3
+ *
4
+ * Usage:
5
+ * import { CognitionDeskWidget } from '@cognitiondesk/widget/react';
6
+ *
7
+ * // Minimal — loads config from the platform using widgetId
8
+ * <CognitionDeskWidget apiKey="YOUR_API_KEY" widgetId="widget_xxx" />
9
+ *
10
+ * // Full inline config — no widgetId needed
11
+ * <CognitionDeskWidget
12
+ * apiKey="YOUR_API_KEY"
13
+ * assistantId="assistant-id"
14
+ * theme="light"
15
+ * primaryColor="#2563eb"
16
+ * botName="Support Bot"
17
+ * botEmoji="🤖"
18
+ * welcomeMessage="Hi! How can I help?"
19
+ * placeholder="Type a message…"
20
+ * defaultOpen={false}
21
+ * streaming={true}
22
+ * backendUrl="https://mounaji-backendv3.onrender.com"
23
+ * onOpen={() => console.log('chat opened')}
24
+ * onClose={() => console.log('chat closed')}
25
+ * />
26
+ */
27
+
28
+ import { useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
29
+ import CognitionDeskWidgetCore from './widget.js';
30
+
31
+ export const CognitionDeskWidget = forwardRef(function CognitionDeskWidget(props, ref) {
32
+ const {
33
+ apiKey,
34
+ widgetId,
35
+ assistantId,
36
+ theme = 'light',
37
+ primaryColor = '#2563eb',
38
+ botName = 'AI Assistant',
39
+ botEmoji = '🤖',
40
+ welcomeMessage = 'Hello! How can I help you today?',
41
+ placeholder = 'Type a message…',
42
+ defaultOpen = false,
43
+ streaming = true,
44
+ backendUrl,
45
+ onOpen,
46
+ onClose,
47
+ } = props;
48
+
49
+ const widgetRef = useRef(null);
50
+ const mountRef = useRef(null);
51
+
52
+ // Expose widget API to parent via ref
53
+ useImperativeHandle(ref, () => ({
54
+ open: () => widgetRef.current?.open(),
55
+ close: () => widgetRef.current?.close(),
56
+ toggle: () => widgetRef.current?.toggle(),
57
+ clearHistory: () => widgetRef.current?.clearHistory(),
58
+ }), []);
59
+
60
+ useEffect(() => {
61
+ if (!apiKey) {
62
+ console.error('[CognitionDesk] apiKey prop is required');
63
+ return;
64
+ }
65
+
66
+ const widget = new CognitionDeskWidgetCore({
67
+ apiKey,
68
+ widgetId,
69
+ assistantId,
70
+ theme,
71
+ primaryColor,
72
+ botName,
73
+ botEmoji,
74
+ welcomeMessage,
75
+ placeholder,
76
+ streaming,
77
+ ...(backendUrl ? { backendUrl } : {}),
78
+ });
79
+
80
+ // Patch open/close to fire callbacks
81
+ if (onOpen || onClose) {
82
+ const origOpen = widget.open.bind(widget);
83
+ const origClose = widget.close.bind(widget);
84
+ widget.open = (...a) => { origOpen(...a); onOpen?.(); };
85
+ widget.close = (...a) => { origClose(...a); onClose?.(); };
86
+ }
87
+
88
+ // mount() returns a Promise when widgetId is set
89
+ Promise.resolve(widget.mount(mountRef.current)).then(() => {
90
+ widgetRef.current = widget;
91
+ if (defaultOpen) widget.open();
92
+ });
93
+
94
+ return () => {
95
+ widget.unmount();
96
+ widgetRef.current = null;
97
+ };
98
+ // eslint-disable-next-line react-hooks/exhaustive-deps
99
+ }, [apiKey, widgetId, assistantId]); // re-init only when identity changes
100
+
101
+ // Sync visual-only props without full re-init
102
+ useEffect(() => {
103
+ const w = widgetRef.current;
104
+ if (!w) return;
105
+ w._cfg.theme = theme;
106
+ w._cfg.primaryColor = primaryColor;
107
+ w._applyTheme?.();
108
+ }, [theme, primaryColor]);
109
+
110
+ return <div ref={mountRef} data-cognitiondesk-root="" />;
111
+ });
112
+
113
+ // Also expose the raw class for advanced use
114
+ export { default as CognitionDeskWidgetCore } from './widget.js';