copilot-chat-widget 0.1.24 → 0.1.26

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 CHANGED
@@ -13,10 +13,13 @@ yarn add copilot-chat-widget
13
13
  ```js
14
14
  import { loadCopilotChatWidget } from "copilot-chat-widget";
15
15
 
16
- loadCopilotChatWidget({
17
- });
18
- ```
19
- `loadCopilotChatWidget` fetches widget config from `/api/chat-widget/config` and mounts the chat bubble.
16
+ loadCopilotChatWidget({
17
+ token: "YOUR_WIDGET_TOKEN",
18
+ // optional: baseUrl if backend is on a different origin
19
+ // baseUrl: "https://your-backend-domain"
20
+ });
21
+ ```
22
+ `loadCopilotChatWidget` injects the standalone script (`chat-widget.min.js`) and bootstraps the widget using the provided `token`.
20
23
 
21
24
  ### React/Next.js example
22
25
  ```jsx
@@ -24,10 +27,12 @@ import { useEffect } from "react";
24
27
  import { loadCopilotChatWidget } from "copilot-chat-widget";
25
28
 
26
29
  export default function Page() {
27
- useEffect(() => {
28
- loadCopilotChatWidget({
29
- });
30
- }, []);
30
+ useEffect(() => {
31
+ loadCopilotChatWidget({
32
+ token: process.env.NEXT_PUBLIC_CHAT_WIDGET_TOKEN,
33
+ baseUrl: process.env.NEXT_PUBLIC_WIDGET_BASE_URL // optional override if backend is another origin
34
+ });
35
+ }, []);
31
36
 
32
37
  return <main>Your page content</main>;
33
38
  }
@@ -35,14 +40,20 @@ export default function Page() {
35
40
 
36
41
  ## Usage (script tag)
37
42
  ```html
38
- <script
39
- src="https://cdn.example.com/chat-widget.min.js"
40
- ></script>
41
- ```
42
- - `data-autoload="false"`: if you want to insert the script but call `window.CopilotChat.init()` manually.
43
-
44
- ## Configuration
45
- - `autoload` (boolean): set `false` to defer bootstrap and call `window.CopilotChat.load()` yourself.
43
+ <script
44
+ src="https://cdn.example.com/chat-widget.min.js"
45
+ data-token="YOUR_WIDGET_TOKEN"
46
+ data-base-url="https://your-backend-domain" <!-- optional if backend is another origin -->
47
+ ></script>
48
+ ```
49
+ - `data-token`: required.
50
+ - `data-base-url`: optional override; if omitted, the widget uses the build-time default `WIDGET_BASE_URL`, then falls back to the script/page origin.
51
+ - `data-autoload="false"`: if you want to insert the script but call `window.CopilotChat.init()` manually.
52
+
53
+ ## Configuration
54
+ - `token` (string, required): widget token.
55
+ - `baseUrl` (string): backend host serving `/api/chat-widget/config`. Needed when the embedding page is on a different origin. If omitted, the widget uses `WIDGET_BASE_URL` (injected at build) then falls back to the script/page origin.
56
+ - `autoload` (boolean): set `false` to defer bootstrap and call `window.CopilotChat.load()` yourself.
46
57
 
47
58
  Runtime controls (after script loads):
48
59
  ```js
@@ -1,7 +1,7 @@
1
- (function(){"use strict";(()=>{if(typeof window>"u"||typeof document>"u"||window.__copilotWidgetLoaded)return;window.__copilotWidgetLoaded=!0;const S="http://localhost:3000",b=64,f=720,x=document.currentScript,k=e=>{document.readyState==="complete"||document.readyState==="interactive"?setTimeout(e,0):document.addEventListener("DOMContentLoaded",e)},y=()=>x||Array.from(document.querySelectorAll("script")).reverse().find(o=>o.src&&o.src.includes("chat-widget"))||null,T=({iframeUrl:e,launcherIcon:p})=>{const o=document.querySelector("[data-copilot-widget-root]");o&&o.remove();const c=d=>{const i=document.querySelector("[data-copilot-checkout-toast]");i&&i.remove();const a=document.createElement("div");a.setAttribute("data-copilot-checkout-toast","true"),a.innerText=d,Object.assign(a.style,{position:"fixed",top:"20px",left:"50%",transform:"translateX(-50%)",padding:"12px 16px",background:"#0f172a",color:"white",borderRadius:"12px",boxShadow:"0 8px 24px rgba(0,0,0,0.25)",zIndex:2147483647,fontSize:"14px",fontWeight:"600",maxWidth:"420px",lineHeight:"1.4",textAlign:"center"}),document.body.appendChild(a),setTimeout(()=>{a.remove()},4500)},m=document.createElement("div");m.setAttribute("data-copilot-widget-root","true");const h=m.attachShadow({mode:"open"});document.body.appendChild(m);const t=document.createElement("button");t.type="button",t.setAttribute("aria-label","Open Copilot chat"),t.innerHTML=`
1
+ (function(){"use strict";(()=>{if(typeof window>"u"||typeof document>"u"||window.__copilotWidgetLoaded)return;window.__copilotWidgetLoaded=!0;const T="http://localhost:3000",b=64,y=720,x=document.currentScript,k=t=>{if(!t?.src)return{};try{const s=new URL(t.src,window.location.href),n={};return s.searchParams.forEach((l,c)=>{n[c]=l}),n}catch(s){return console.warn("[CopilotChat] Failed to parse script query params:",s),{}}},I=t=>{document.readyState==="complete"||document.readyState==="interactive"?setTimeout(t,0):document.addEventListener("DOMContentLoaded",t)},v=()=>x||Array.from(document.querySelectorAll("script")).reverse().find(n=>n.dataset?.token||n.src&&n.src.includes("chat-widget"))||null,U=({iframeUrl:t,launcherIcon:s})=>{const n=document.querySelector("[data-copilot-widget-root]");n&&n.remove();const l=w=>{const a=document.querySelector("[data-copilot-checkout-toast]");a&&a.remove();const h=document.createElement("div");h.setAttribute("data-copilot-checkout-toast","true"),h.innerText=w,Object.assign(h.style,{position:"fixed",top:"20px",left:"50%",transform:"translateX(-50%)",padding:"12px 16px",background:"#0f172a",color:"white",borderRadius:"12px",boxShadow:"0 8px 24px rgba(0,0,0,0.25)",zIndex:2147483647,fontSize:"14px",fontWeight:"600",maxWidth:"420px",lineHeight:"1.4",textAlign:"center"}),document.body.appendChild(h),setTimeout(()=>{h.remove()},4500)},c=document.createElement("div");c.setAttribute("data-copilot-widget-root","true");const C=c.attachShadow({mode:"open"});document.body.appendChild(c);const e=document.createElement("button");e.type="button",e.setAttribute("aria-label","Open Copilot chat"),e.innerHTML=`
2
2
  <img
3
- src="${p}"
3
+ src="${s}"
4
4
  alt="Copilot chat launcher"
5
5
  style="width: 38px; height: 38px; object-fit: contain; border-radius: 50%; pointer-events: none;"
6
6
  />
7
- `,Object.assign(t.style,{position:"fixed",bottom:"24px",right:"24px",width:`${b}px`,height:`${b}px`,borderRadius:"50%",border:"none",background:"linear-gradient(135deg, #0078ff, #00c6ff)",color:"white",cursor:"pointer",zIndex:999998,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 6px 14px rgba(0,0,0,0.25)",transition:"all 0.25s ease"}),t.onmouseover=()=>{t.style.transform="scale(1.12)",t.style.boxShadow="0 10px 25px rgba(0,0,0,0.3)"},t.onmouseout=()=>{t.style.transform="scale(1)",t.style.boxShadow="0 6px 14px rgba(0,0,0,0.25)"};const n=document.createElement("div");n.setAttribute("data-copilot-widget-root","true"),Object.assign(n.style,{display:"none",position:"fixed",bottom:`${b+36}px`,right:"24px",zIndex:"999999",transformOrigin:"bottom right",transform:"scale(0.8) translateY(20px)",opacity:"0",transition:"all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55)"});const l=document.createElement("div"),E=document.createElement("div"),v=document.createElement("div");Object.assign(l.style,{position:"absolute",bottom:"-14px",right:"28px",width:"30px",height:"20px",pointerEvents:"none",display:"none",zIndex:"1"}),Object.assign(E.style,{position:"absolute",bottom:"0",left:"0",right:"0",margin:"0 auto",width:"0",height:"0",borderLeft:"15px solid transparent",borderRight:"15px solid transparent",borderTop:"15px solid rgba(15,23,42,0.1)"}),Object.assign(v.style,{position:"absolute",bottom:"2px",left:"0",right:"0",margin:"0 auto",width:"0",height:"0",borderLeft:"13px solid transparent",borderRight:"13px solid transparent",borderTop:"13px solid white",boxShadow:"0 6px 16px rgba(15,23,42,0.12)",borderRadius:"2px"}),l.appendChild(E),l.appendChild(v);const u=document.createElement("div");Object.assign(u.style,{width:`${f}px`,maxWidth:"calc(100vw - 48px)",height:`${Math.min(f,Math.max(320,window.innerHeight-140))}px`,maxHeight:"calc(100vh - 150px)",borderRadius:"20px",background:"white",border:"1px solid rgba(15,23,42,0.12)",boxShadow:"0 18px 45px rgba(15,23,42,0.16)",overflow:"hidden"}),h.appendChild(u);const r=document.createElement("iframe");r.src=e,r.title="Copilot chat widget",r.allow="clipboard-read; clipboard-write; microphone; camera; display-capture",r.setAttribute("scrolling","no"),Object.assign(r.style,{width:"100%",height:"100%",border:"none",display:"block",background:"transparent",overflow:"hidden"}),h.appendChild(u),u.appendChild(r),n.appendChild(l),n.appendChild(u),document.body.appendChild(t),document.body.appendChild(n);let s=!1;const w=()=>{s&&(s=!1,n.style.opacity="0",n.style.transform="scale(0.8) translateY(20px)",l.style.display="none",setTimeout(()=>{n.style.display="none"},250),t.style.transform="scale(1)")},O=d=>{const{data:i,source:a}=d||{};if(i?.type){if(i.type==="CART_CHECKOUT"&&a===r.contentWindow){console.log("[CopilotChat] Received checkout payload from widget:",i),c("Checkout message received from chat widget. Check console for payload.");return}if(i.type==="WIDGET_READY"&&a===r.contentWindow){r.contentWindow.postMessage({type:"INIT_WIDGET"},"*");return}i.type==="CHAT_CLOSED"&&w()}};t.onclick=d=>{d.stopPropagation(),s=!s,s?(n.style.display="block",l.style.display="block",requestAnimationFrame(()=>{n.style.opacity="1",n.style.transform="scale(1) translateY(0)"}),r.contentWindow&&r.contentWindow.postMessage({type:"CHAT_OPENED"},"*")):w()},window.addEventListener("message",O),document.addEventListener("click",d=>{const i=d.target;i&&s&&!n.contains(i)&&i!==t&&w()});const g={close:w,open:()=>{s||t.click()}};return window.CopilotChat=window.CopilotChat||{},window.CopilotChat.close=g.close,window.CopilotChat.open=g.open,window.CopilotChat.controls=g,g},I=e=>{console.error(`[CopilotChat] ${e}`)},A=()=>{const e=y();return e?(e.dataset||{}).autoload!=="false":!1},C=async(e={})=>{e.scriptEl||y();const p=S;try{const o=await fetch(`${p}/api/chat-widget/config`,{credentials:"omit",mode:"cors"});if(!o.ok)throw new Error(`Server responded with ${o.status}`);const c=await o.json();if(!c?.iframeUrl||!c?.launcherIcon)throw new Error("Received incomplete widget configuration from server.");return window.CopilotChat=window.CopilotChat||{},window.CopilotChat.init=(h={})=>{const t={iframeUrl:h.iframeUrl||c.iframeUrl,launcherIcon:h.launcherIcon||c.launcherIcon};return T(t)},window.CopilotChat.init(e)}catch(o){return I(o instanceof Error?o.message:"Unknown error during widget bootstrap."),null}};A()&&k(()=>{C()}),window.CopilotChat=window.CopilotChat||{},window.CopilotChat.load=C})()})();
7
+ `,Object.assign(e.style,{position:"fixed",bottom:"24px",right:"24px",width:`${b}px`,height:`${b}px`,borderRadius:"50%",border:"none",background:"linear-gradient(135deg, #0078ff, #00c6ff)",color:"white",cursor:"pointer",zIndex:999998,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 6px 14px rgba(0,0,0,0.25)",transition:"all 0.25s ease"}),e.onmouseover=()=>{e.style.transform="scale(1.12)",e.style.boxShadow="0 10px 25px rgba(0,0,0,0.3)"},e.onmouseout=()=>{e.style.transform="scale(1)",e.style.boxShadow="0 6px 14px rgba(0,0,0,0.25)"};const i=document.createElement("div");i.setAttribute("data-copilot-widget-root","true"),Object.assign(i.style,{display:"none",position:"fixed",bottom:`${b+36}px`,right:"24px",zIndex:"999999",transformOrigin:"bottom right",transform:"scale(0.8) translateY(20px)",opacity:"0",transition:"all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55)"});const o=document.createElement("div"),r=document.createElement("div"),m=document.createElement("div");Object.assign(o.style,{position:"absolute",bottom:"-14px",right:"28px",width:"30px",height:"20px",pointerEvents:"none",display:"none",zIndex:"1"}),Object.assign(r.style,{position:"absolute",bottom:"0",left:"0",right:"0",margin:"0 auto",width:"0",height:"0",borderLeft:"15px solid transparent",borderRight:"15px solid transparent",borderTop:"15px solid rgba(15,23,42,0.1)"}),Object.assign(m.style,{position:"absolute",bottom:"2px",left:"0",right:"0",margin:"0 auto",width:"0",height:"0",borderLeft:"13px solid transparent",borderRight:"13px solid transparent",borderTop:"13px solid white",boxShadow:"0 6px 16px rgba(15,23,42,0.12)",borderRadius:"2px"}),o.appendChild(r),o.appendChild(m);const p=document.createElement("div");Object.assign(p.style,{width:`${y}px`,maxWidth:"calc(100vw - 48px)",height:`${Math.min(y,Math.max(320,window.innerHeight-140))}px`,maxHeight:"calc(100vh - 150px)",borderRadius:"20px",background:"white",border:"1px solid rgba(15,23,42,0.12)",boxShadow:"0 18px 45px rgba(15,23,42,0.16)",overflow:"hidden"}),C.appendChild(p);const d=document.createElement("iframe");d.src=t,d.title="Copilot chat widget",d.allow="clipboard-read; clipboard-write; microphone; camera; display-capture",d.setAttribute("scrolling","no"),Object.assign(d.style,{width:"100%",height:"100%",border:"none",display:"block",background:"transparent",overflow:"hidden"}),C.appendChild(p),p.appendChild(d),i.appendChild(o),i.appendChild(p),document.body.appendChild(e),document.body.appendChild(i);let u=!1;const f=()=>{u&&(u=!1,i.style.opacity="0",i.style.transform="scale(0.8) translateY(20px)",o.style.display="none",setTimeout(()=>{i.style.display="none"},250),e.style.transform="scale(1)")},O=w=>{const{data:a,source:h}=w||{};if(a?.type){if(a.type==="CART_CHECKOUT"&&h===d.contentWindow){console.log("[CopilotChat] Received checkout payload from widget:",a),l("Checkout message received from chat widget. Check console for payload.");return}if(a.type==="WIDGET_READY"&&h===d.contentWindow){d.contentWindow.postMessage({type:"INIT_WIDGET"},"*");return}a.type==="CHAT_CLOSED"&&f()}};e.onclick=w=>{w.stopPropagation(),u=!u,u?(i.style.display="block",o.style.display="block",requestAnimationFrame(()=>{i.style.opacity="1",i.style.transform="scale(1) translateY(0)"})):f()},window.addEventListener("message",O),document.addEventListener("click",w=>{const a=w.target;a&&u&&!i.contains(a)&&a!==e&&f()});const g={close:f,open:()=>{u||e.click()}};return window.CopilotChat=window.CopilotChat||{},window.CopilotChat.close=g.close,window.CopilotChat.open=g.open,window.CopilotChat.controls=g,g},E=t=>{console.error(`[CopilotChat] ${t}`)},A=()=>{const t=v();if(!t)return!1;const s=k(t),n=t.dataset||{},l=n.token||s.token,c=typeof window<"u"&&window.CopilotChatConfig&&window.CopilotChatConfig.token;return(l||c)&&n.autoload!=="false"},S=async(t={})=>{const s=t.scriptEl||v(),n=window.CopilotChatConfig||{},l=s?.dataset||{},c=k(s),e=(()=>{const o=t.token||n.token||l.token||c.token;if(o)return o;try{const r=window.localStorage.getItem("copilotChatToken");if(r)return r}catch{}if(typeof window<"u"&&typeof window.prompt=="function"){const r=window.prompt("Enter your Copilot Chat token:");if(r){try{window.localStorage.setItem("copilotChatToken",r)}catch{}return r}}return null})();if(!e)return E("Missing token (provide via init config, window.CopilotChatConfig.token, or data-token attribute)."),null;const i=t.baseUrl||n.baseUrl||l.baseUrl||c.baseUrl||T;try{const o=await fetch(`${i}/api/chat-widget/config?token=${encodeURIComponent(e)}`,{credentials:"omit",mode:"cors"});if(!o.ok)throw new Error(`Server responded with ${o.status}`);const r=await o.json();if(!r?.iframeUrl||!r?.launcherIcon)throw new Error("Received incomplete widget configuration from server.");return window.CopilotChat=window.CopilotChat||{},window.CopilotChat.init=(p={})=>{const d={iframeUrl:p.iframeUrl||r.iframeUrl,launcherIcon:p.launcherIcon||r.launcherIcon};return U(d)},window.CopilotChat.init(t)}catch(o){return E(o instanceof Error?o.message:"Unknown error during widget bootstrap."),null}};A()&&I(()=>{S()}),window.CopilotChat=window.CopilotChat||{},window.CopilotChat.load=S})()})();
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const v="http://localhost:3000",m=64,y=720,T=({iframeUrl:b,launcherIcon:u})=>{const i=document.querySelector("[data-copilot-widget-root]");i&&i.remove();const d=s=>{const o=document.querySelector("[data-copilot-checkout-toast]");o&&o.remove();const r=document.createElement("div");r.setAttribute("data-copilot-checkout-toast","true"),r.innerText=s,Object.assign(r.style,{position:"fixed",top:"20px",left:"50%",transform:"translateX(-50%)",padding:"12px 16px",background:"#0f172a",color:"white",borderRadius:"12px",boxShadow:"0 8px 24px rgba(0,0,0,0.25)",zIndex:2147483647,fontSize:"14px",fontWeight:"600",maxWidth:"420px",lineHeight:"1.4",textAlign:"center"}),document.body.appendChild(r),setTimeout(()=>{r.remove()},4500)},g=document.createElement("div");g.setAttribute("data-copilot-widget-root","true");const x=g.attachShadow({mode:"open"});document.body.appendChild(g);const t=document.createElement("button");t.type="button",t.setAttribute("aria-label","Open Copilot chat"),t.innerHTML=`
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k="http://localhost:3000",w=64,C=720,E=({iframeUrl:u,launcherIcon:g})=>{const d=document.querySelector("[data-copilot-widget-root]");d&&d.remove();const c=s=>{const o=document.querySelector("[data-copilot-checkout-toast]");o&&o.remove();const r=document.createElement("div");r.setAttribute("data-copilot-checkout-toast","true"),r.innerText=s,Object.assign(r.style,{position:"fixed",top:"20px",left:"50%",transform:"translateX(-50%)",padding:"12px 16px",background:"#0f172a",color:"white",borderRadius:"12px",boxShadow:"0 8px 24px rgba(0,0,0,0.25)",zIndex:2147483647,fontSize:"14px",fontWeight:"600",maxWidth:"420px",lineHeight:"1.4",textAlign:"center"}),document.body.appendChild(r),setTimeout(()=>{r.remove()},4500)},p=document.createElement("div");p.setAttribute("data-copilot-widget-root","true");const n=p.attachShadow({mode:"open"});document.body.appendChild(p);const t=document.createElement("button");t.type="button",t.setAttribute("aria-label","Open Copilot chat"),t.innerHTML=`
2
2
  <img
3
- src="${u}"
3
+ src="${g}"
4
4
  alt="Copilot chat launcher"
5
5
  style="width: 38px; height: 38px; object-fit: contain; border-radius: 50%; pointer-events: none;"
6
6
  />
7
- `,Object.assign(t.style,{position:"fixed",bottom:"24px",right:"24px",width:`${m}px`,height:`${m}px`,borderRadius:"50%",border:"none",background:"linear-gradient(135deg, #0078ff, #00c6ff)",color:"white",cursor:"pointer",zIndex:999998,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 6px 14px rgba(0,0,0,0.25)",transition:"all 0.25s ease"}),t.onmouseover=()=>{t.style.transform="scale(1.12)",t.style.boxShadow="0 10px 25px rgba(0,0,0,0.3)"},t.onmouseout=()=>{t.style.transform="scale(1)",t.style.boxShadow="0 6px 14px rgba(0,0,0,0.25)"};const e=document.createElement("div");e.setAttribute("data-copilot-widget-root","true"),Object.assign(e.style,{display:"none",position:"fixed",bottom:`${m+36}px`,right:"24px",zIndex:"999999",transformOrigin:"bottom right",transform:"scale(0.8) translateY(20px)",opacity:"0",transition:"all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55)"});const l=document.createElement("div"),f=document.createElement("div"),w=document.createElement("div");Object.assign(l.style,{position:"absolute",bottom:"-14px",right:"28px",width:"30px",height:"20px",pointerEvents:"none",display:"none",zIndex:"1"}),Object.assign(f.style,{position:"absolute",bottom:"0",left:"0",right:"0",margin:"0 auto",width:"0",height:"0",borderLeft:"15px solid transparent",borderRight:"15px solid transparent",borderTop:"15px solid rgba(15,23,42,0.1)"}),Object.assign(w.style,{position:"absolute",bottom:"2px",left:"0",right:"0",margin:"0 auto",width:"0",height:"0",borderLeft:"13px solid transparent",borderRight:"13px solid transparent",borderTop:"13px solid white",boxShadow:"0 6px 16px rgba(15,23,42,0.12)",borderRadius:"2px"}),l.appendChild(f),l.appendChild(w);const c=document.createElement("div");Object.assign(c.style,{width:`${y}px`,maxWidth:"calc(100vw - 48px)",height:`${Math.min(y,Math.max(320,window.innerHeight-140))}px`,maxHeight:"calc(100vh - 150px)",borderRadius:"20px",background:"white",border:"1px solid rgba(15,23,42,0.12)",boxShadow:"0 18px 45px rgba(15,23,42,0.16)",overflow:"hidden"}),x.appendChild(c);const n=document.createElement("iframe");n.src=b,n.title="Copilot chat widget",n.allow="clipboard-read; clipboard-write; microphone; camera; display-capture",n.setAttribute("scrolling","no"),Object.assign(n.style,{width:"100%",height:"100%",border:"none",display:"block",background:"transparent",overflow:"hidden"}),x.appendChild(c),c.appendChild(n),e.appendChild(l),e.appendChild(c),document.body.appendChild(t),document.body.appendChild(e);let a=!1;const p=()=>{a&&(a=!1,e.style.opacity="0",e.style.transform="scale(0.8) translateY(20px)",l.style.display="none",setTimeout(()=>{e.style.display="none"},250),t.style.transform="scale(1)")},E=s=>{const{data:o,source:r}=s||{};if(o?.type){if(o.type==="CART_CHECKOUT"&&r===n.contentWindow){console.log("[CopilotChat] Received checkout payload from widget:",o),d("Checkout message received from chat widget. Check console for payload.");return}if(o.type==="WIDGET_READY"&&r===n.contentWindow){n.contentWindow.postMessage({type:"INIT_WIDGET"},"*");return}o.type==="CHAT_CLOSED"&&p()}};window.addEventListener("message",E),t.onclick=s=>{s.stopPropagation(),a=!a,a?(e.style.display="block",l.style.display="block",requestAnimationFrame(()=>{e.style.opacity="1",e.style.transform="scale(1) translateY(0)"}),n.contentWindow&&n.contentWindow.postMessage({type:"CHAT_OPENED"},"*")):p()},document.addEventListener("click",s=>{const o=s.target;o&&a&&!e.contains(o)&&o!==t&&p()});const h={close:p,open:()=>{a||t.click()}};return window.CopilotChat=window.CopilotChat||{},window.CopilotChat.close=h.close,window.CopilotChat.open=h.open,window.CopilotChat.controls=h,h};async function C(){if(typeof window>"u"||typeof document>"u")return null;const u=`${v.replace(/\/$/,"")}/api/chat-widget/config`;try{const i=await fetch(u,{credentials:"omit",mode:"cors"});if(!i.ok)throw new Error(`Server responded with ${i.status}`);const d=await i.json();if(!d?.iframeUrl||!d?.launcherIcon)throw new Error("Received incomplete widget configuration from server.");return T({iframeUrl:d.iframeUrl,launcherIcon:d.launcherIcon})}catch(i){return console.error("[CopilotChat] Error during widget bootstrap:",i instanceof Error?i.message:i),null}}exports.default=C;exports.loadCopilotChatWidget=C;
7
+ `,Object.assign(t.style,{position:"fixed",bottom:"24px",right:"24px",width:`${w}px`,height:`${w}px`,borderRadius:"50%",border:"none",background:"linear-gradient(135deg, #0078ff, #00c6ff)",color:"white",cursor:"pointer",zIndex:999998,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 6px 14px rgba(0,0,0,0.25)",transition:"all 0.25s ease"}),t.onmouseover=()=>{t.style.transform="scale(1.12)",t.style.boxShadow="0 10px 25px rgba(0,0,0,0.3)"},t.onmouseout=()=>{t.style.transform="scale(1)",t.style.boxShadow="0 6px 14px rgba(0,0,0,0.25)"};const e=document.createElement("div");e.setAttribute("data-copilot-widget-root","true"),Object.assign(e.style,{display:"none",position:"fixed",bottom:`${w+36}px`,right:"24px",zIndex:"999999",transformOrigin:"bottom right",transform:"scale(0.8) translateY(20px)",opacity:"0",transition:"all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55)"});const l=document.createElement("div"),f=document.createElement("div"),x=document.createElement("div");Object.assign(l.style,{position:"absolute",bottom:"-14px",right:"28px",width:"30px",height:"20px",pointerEvents:"none",display:"none",zIndex:"1"}),Object.assign(f.style,{position:"absolute",bottom:"0",left:"0",right:"0",margin:"0 auto",width:"0",height:"0",borderLeft:"15px solid transparent",borderRight:"15px solid transparent",borderTop:"15px solid rgba(15,23,42,0.1)"}),Object.assign(x.style,{position:"absolute",bottom:"2px",left:"0",right:"0",margin:"0 auto",width:"0",height:"0",borderLeft:"13px solid transparent",borderRight:"13px solid transparent",borderTop:"13px solid white",boxShadow:"0 6px 16px rgba(15,23,42,0.12)",borderRadius:"2px"}),l.appendChild(f),l.appendChild(x);const h=document.createElement("div");Object.assign(h.style,{width:`${C}px`,maxWidth:"calc(100vw - 48px)",height:`${Math.min(C,Math.max(320,window.innerHeight-140))}px`,maxHeight:"calc(100vh - 150px)",borderRadius:"20px",background:"white",border:"1px solid rgba(15,23,42,0.12)",boxShadow:"0 18px 45px rgba(15,23,42,0.16)",overflow:"hidden"}),n.appendChild(h);const i=document.createElement("iframe");i.src=u,i.title="Copilot chat widget",i.allow="clipboard-read; clipboard-write; microphone; camera; display-capture",i.setAttribute("scrolling","no"),Object.assign(i.style,{width:"100%",height:"100%",border:"none",display:"block",background:"transparent",overflow:"hidden"}),n.appendChild(h),h.appendChild(i),e.appendChild(l),e.appendChild(h),document.body.appendChild(t),document.body.appendChild(e);let a=!1;const m=()=>{a&&(a=!1,e.style.opacity="0",e.style.transform="scale(0.8) translateY(20px)",l.style.display="none",setTimeout(()=>{e.style.display="none"},250),t.style.transform="scale(1)")},v=s=>{const{data:o,source:r}=s||{};if(o?.type){if(o.type==="CART_CHECKOUT"&&r===i.contentWindow){console.log("[CopilotChat] Received checkout payload from widget:",o),c("Checkout message received from chat widget. Check console for payload."),c("Data:");return}if(o.type==="WIDGET_READY"&&r===i.contentWindow){i.contentWindow.postMessage({type:"INIT_WIDGET"},"*");return}o.type==="CHAT_CLOSED"&&m()}};window.addEventListener("message",v),t.onclick=s=>{s.stopPropagation(),a=!a,a?(e.style.display="block",l.style.display="block",requestAnimationFrame(()=>{e.style.opacity="1",e.style.transform="scale(1) translateY(0)"})):m()},document.addEventListener("click",s=>{const o=s.target;o&&a&&!e.contains(o)&&o!==t&&m()});const b={close:m,open:()=>{a||t.click()}};return window.CopilotChat=window.CopilotChat||{},window.CopilotChat.close=b.close,window.CopilotChat.open=b.open,window.CopilotChat.controls=b,b};async function y(u={}){if(typeof window>"u"||typeof document>"u")return null;const g=window.CopilotChatConfig||{},d=u.token||g.token||typeof window<"u"&&window.localStorage?.getItem("copilotChatToken")||null;if(!d)return console.error("[CopilotChat] Missing token (provide via loadCopilotChatWidget({ token }) or window.CopilotChatConfig.token)."),null;const c=u.baseUrl||g.baseUrl||k,p=`${c.replace(/\/$/,"")}/api/chat-widget/config?token=${encodeURIComponent(d)}`;try{const n=await fetch(p,{credentials:"omit",mode:"cors"});if(!n.ok)throw new Error(`Server responded with ${n.status}`);const t=await n.json();if(!t?.iframeUrl||!t?.launcherIcon)throw new Error("Received incomplete widget configuration from server.");return window.CopilotChat=window.CopilotChat||{},window.CopilotChat.token=d,window.CopilotChat.baseUrl=c,E({iframeUrl:t.iframeUrl,launcherIcon:t.launcherIcon})}catch(n){return console.error("[CopilotChat] Error during widget bootstrap:",n instanceof Error?n.message:n),null}}exports.default=y;exports.loadCopilotChatWidget=y;
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- const y = "http://localhost:3000";
2
- const C = ({ iframeUrl: m, launcherIcon: u }) => {
3
- const i = document.querySelector("[data-copilot-widget-root]");
4
- i && i.remove();
5
- const d = (s) => {
1
+ const C = "http://localhost:3000";
2
+ const y = ({ iframeUrl: u, launcherIcon: g }) => {
3
+ const d = document.querySelector("[data-copilot-widget-root]");
4
+ d && d.remove();
5
+ const c = (s) => {
6
6
  const o = document.querySelector("[data-copilot-checkout-toast]");
7
7
  o && o.remove();
8
8
  const r = document.createElement("div");
@@ -25,14 +25,14 @@ const C = ({ iframeUrl: m, launcherIcon: u }) => {
25
25
  }), document.body.appendChild(r), setTimeout(() => {
26
26
  r.remove();
27
27
  }, 4500);
28
- }, g = document.createElement("div");
29
- g.setAttribute("data-copilot-widget-root", "true");
30
- const b = g.attachShadow({ mode: "open" });
31
- document.body.appendChild(g);
28
+ }, p = document.createElement("div");
29
+ p.setAttribute("data-copilot-widget-root", "true");
30
+ const n = p.attachShadow({ mode: "open" });
31
+ document.body.appendChild(p);
32
32
  const t = document.createElement("button");
33
33
  t.type = "button", t.setAttribute("aria-label", "Open Copilot chat"), t.innerHTML = `
34
34
  <img
35
- src="${u}"
35
+ src="${g}"
36
36
  alt="Copilot chat launcher"
37
37
  style="width: 38px; height: 38px; object-fit: contain; border-radius: 50%; pointer-events: none;"
38
38
  />
@@ -70,8 +70,8 @@ const C = ({ iframeUrl: m, launcherIcon: u }) => {
70
70
  opacity: "0",
71
71
  transition: "all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55)"
72
72
  });
73
- const c = document.createElement("div"), x = document.createElement("div"), f = document.createElement("div");
74
- Object.assign(c.style, {
73
+ const l = document.createElement("div"), b = document.createElement("div"), f = document.createElement("div");
74
+ Object.assign(l.style, {
75
75
  position: "absolute",
76
76
  bottom: "-14px",
77
77
  right: "28px",
@@ -80,7 +80,7 @@ const C = ({ iframeUrl: m, launcherIcon: u }) => {
80
80
  pointerEvents: "none",
81
81
  display: "none",
82
82
  zIndex: "1"
83
- }), Object.assign(x.style, {
83
+ }), Object.assign(b.style, {
84
84
  position: "absolute",
85
85
  bottom: "0",
86
86
  left: "0",
@@ -104,9 +104,9 @@ const C = ({ iframeUrl: m, launcherIcon: u }) => {
104
104
  borderTop: "13px solid white",
105
105
  boxShadow: "0 6px 16px rgba(15,23,42,0.12)",
106
106
  borderRadius: "2px"
107
- }), c.appendChild(x), c.appendChild(f);
108
- const l = document.createElement("div");
109
- Object.assign(l.style, {
107
+ }), l.appendChild(b), l.appendChild(f);
108
+ const h = document.createElement("div");
109
+ Object.assign(h.style, {
110
110
  width: "720px",
111
111
  maxWidth: "calc(100vw - 48px)",
112
112
  height: `${Math.min(720, Math.max(320, window.innerHeight - 140))}px`,
@@ -116,73 +116,80 @@ const C = ({ iframeUrl: m, launcherIcon: u }) => {
116
116
  border: "1px solid rgba(15,23,42,0.12)",
117
117
  boxShadow: "0 18px 45px rgba(15,23,42,0.16)",
118
118
  overflow: "hidden"
119
- }), b.appendChild(l);
120
- const n = document.createElement("iframe");
121
- n.src = m, n.title = "Copilot chat widget", n.allow = "clipboard-read; clipboard-write; microphone; camera; display-capture", n.setAttribute("scrolling", "no"), Object.assign(n.style, {
119
+ }), n.appendChild(h);
120
+ const i = document.createElement("iframe");
121
+ i.src = u, i.title = "Copilot chat widget", i.allow = "clipboard-read; clipboard-write; microphone; camera; display-capture", i.setAttribute("scrolling", "no"), Object.assign(i.style, {
122
122
  width: "100%",
123
123
  height: "100%",
124
124
  border: "none",
125
125
  display: "block",
126
126
  background: "transparent",
127
127
  overflow: "hidden"
128
- }), b.appendChild(l), l.appendChild(n), e.appendChild(c), e.appendChild(l), document.body.appendChild(t), document.body.appendChild(e);
128
+ }), n.appendChild(h), h.appendChild(i), e.appendChild(l), e.appendChild(h), document.body.appendChild(t), document.body.appendChild(e);
129
129
  let a = !1;
130
- const p = () => {
131
- a && (a = !1, e.style.opacity = "0", e.style.transform = "scale(0.8) translateY(20px)", c.style.display = "none", setTimeout(() => {
130
+ const m = () => {
131
+ a && (a = !1, e.style.opacity = "0", e.style.transform = "scale(0.8) translateY(20px)", l.style.display = "none", setTimeout(() => {
132
132
  e.style.display = "none";
133
133
  }, 250), t.style.transform = "scale(1)");
134
- }, w = (s) => {
134
+ }, x = (s) => {
135
135
  const { data: o, source: r } = s || {};
136
136
  if (o?.type) {
137
- if (o.type === "CART_CHECKOUT" && r === n.contentWindow) {
138
- console.log("[CopilotChat] Received checkout payload from widget:", o), d("Checkout message received from chat widget. Check console for payload.");
137
+ if (o.type === "CART_CHECKOUT" && r === i.contentWindow) {
138
+ console.log("[CopilotChat] Received checkout payload from widget:", o), c("Checkout message received from chat widget. Check console for payload."), c("Data:");
139
139
  return;
140
140
  }
141
- if (o.type === "WIDGET_READY" && r === n.contentWindow) {
142
- n.contentWindow.postMessage({ type: "INIT_WIDGET" }, "*");
141
+ if (o.type === "WIDGET_READY" && r === i.contentWindow) {
142
+ i.contentWindow.postMessage({ type: "INIT_WIDGET" }, "*");
143
143
  return;
144
144
  }
145
- o.type === "CHAT_CLOSED" && p();
145
+ o.type === "CHAT_CLOSED" && m();
146
146
  }
147
147
  };
148
- window.addEventListener("message", w), t.onclick = (s) => {
149
- s.stopPropagation(), a = !a, a ? (e.style.display = "block", c.style.display = "block", requestAnimationFrame(() => {
148
+ window.addEventListener("message", x), t.onclick = (s) => {
149
+ s.stopPropagation(), a = !a, a ? (e.style.display = "block", l.style.display = "block", requestAnimationFrame(() => {
150
150
  e.style.opacity = "1", e.style.transform = "scale(1) translateY(0)";
151
- }), n.contentWindow && n.contentWindow.postMessage({ type: "CHAT_OPENED" }, "*")) : p();
151
+ })) : m();
152
152
  }, document.addEventListener("click", (s) => {
153
153
  const o = s.target;
154
- o && a && !e.contains(o) && o !== t && p();
154
+ o && a && !e.contains(o) && o !== t && m();
155
155
  });
156
- const h = {
157
- close: p,
156
+ const w = {
157
+ close: m,
158
158
  open: () => {
159
159
  a || t.click();
160
160
  }
161
161
  };
162
- return window.CopilotChat = window.CopilotChat || {}, window.CopilotChat.close = h.close, window.CopilotChat.open = h.open, window.CopilotChat.controls = h, h;
162
+ return window.CopilotChat = window.CopilotChat || {}, window.CopilotChat.close = w.close, window.CopilotChat.open = w.open, window.CopilotChat.controls = w, w;
163
163
  };
164
- async function E() {
164
+ async function E(u = {}) {
165
165
  if (typeof window > "u" || typeof document > "u")
166
166
  return null;
167
- const u = `${y.replace(/\/$/, "")}/api/chat-widget/config`;
167
+ const g = window.CopilotChatConfig || {}, d = u.token || g.token || typeof window < "u" && window.localStorage?.getItem("copilotChatToken") || null;
168
+ if (!d)
169
+ return console.error(
170
+ "[CopilotChat] Missing token (provide via loadCopilotChatWidget({ token }) or window.CopilotChatConfig.token)."
171
+ ), null;
172
+ const c = u.baseUrl || g.baseUrl || C, p = `${c.replace(/\/$/, "")}/api/chat-widget/config?token=${encodeURIComponent(
173
+ d
174
+ )}`;
168
175
  try {
169
- const i = await fetch(u, {
176
+ const n = await fetch(p, {
170
177
  credentials: "omit",
171
178
  mode: "cors"
172
179
  });
173
- if (!i.ok)
174
- throw new Error(`Server responded with ${i.status}`);
175
- const d = await i.json();
176
- if (!d?.iframeUrl || !d?.launcherIcon)
180
+ if (!n.ok)
181
+ throw new Error(`Server responded with ${n.status}`);
182
+ const t = await n.json();
183
+ if (!t?.iframeUrl || !t?.launcherIcon)
177
184
  throw new Error("Received incomplete widget configuration from server.");
178
- return C({
179
- iframeUrl: d.iframeUrl,
180
- launcherIcon: d.launcherIcon
185
+ return window.CopilotChat = window.CopilotChat || {}, window.CopilotChat.token = d, window.CopilotChat.baseUrl = c, y({
186
+ iframeUrl: t.iframeUrl,
187
+ launcherIcon: t.launcherIcon
181
188
  });
182
- } catch (i) {
189
+ } catch (n) {
183
190
  return console.error(
184
191
  "[CopilotChat] Error during widget bootstrap:",
185
- i instanceof Error ? i.message : i
192
+ n instanceof Error ? n.message : n
186
193
  ), null;
187
194
  }
188
195
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "copilot-chat-widget",
3
- "version": "0.1.24",
3
+ "version": "0.1.26",
4
4
  "description": "Embeddable Copilot chat widget that can be loaded via NPM or a script tag.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
package/src/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
- export interface CopilotChatOptions {
2
- autoload?: boolean;
3
- }
1
+ export interface CopilotChatOptions {
2
+ token: string;
3
+ autoload?: boolean;
4
+ baseUrl?: string;
5
+ }
4
6
 
5
7
  export function loadCopilotChatWidget(options: CopilotChatOptions): unknown;
6
8
  export default loadCopilotChatWidget;
package/src/index.js CHANGED
@@ -210,6 +210,8 @@ const buildWidget = ({ iframeUrl, launcherIcon }) => {
210
210
  if (data.type === "CART_CHECKOUT" && source === iframe.contentWindow) {
211
211
  console.log("[CopilotChat] Received checkout payload from widget:", data);
212
212
  showCheckoutToast("Checkout message received from chat widget. Check console for payload.");
213
+ showCheckoutToast("Data:",data);
214
+
213
215
  return;
214
216
  }
215
217
 
@@ -235,9 +237,6 @@ const buildWidget = ({ iframeUrl, launcherIcon }) => {
235
237
  container.style.opacity = "1";
236
238
  container.style.transform = "scale(1) translateY(0)";
237
239
  });
238
- if (iframe.contentWindow) {
239
- iframe.contentWindow.postMessage({ type: "CHAT_OPENED" }, "*");
240
- }
241
240
  } else {
242
241
  closeChat();
243
242
  }
@@ -268,22 +267,43 @@ const buildWidget = ({ iframeUrl, launcherIcon }) => {
268
267
  return controls;
269
268
  };
270
269
 
271
- export async function loadCopilotChatWidget() {
270
+ export async function loadCopilotChatWidget(options = {}) {
272
271
  if (typeof window === "undefined" || typeof document === "undefined") {
273
272
  return null;
274
273
  }
275
274
 
275
+ const globalConfig = window.CopilotChatConfig || {};
276
+ const token =
277
+ options.token ||
278
+ globalConfig.token ||
279
+ (typeof window !== "undefined"
280
+ ? window.localStorage?.getItem("copilotChatToken") || null
281
+ : null);
282
+
283
+ if (!token) {
284
+ console.error(
285
+ "[CopilotChat] Missing token (provide via loadCopilotChatWidget({ token }) or window.CopilotChatConfig.token)."
286
+ );
287
+ return null;
288
+ }
289
+
276
290
  const baseUrl =
291
+ options.baseUrl ||
292
+ globalConfig.baseUrl ||
277
293
  BUILD_BASE_URL ||
278
294
  (typeof window !== "undefined" && window.location?.origin) ||
279
295
  null;
280
296
 
281
297
  if (!baseUrl) {
282
- console.error("[CopilotChat] Unable to resolve widget base URL.");
298
+ console.error(
299
+ "[CopilotChat] Missing baseUrl (set via loadCopilotChatWidget({ baseUrl }), window.CopilotChatConfig.baseUrl, or WIDGET_BASE_URL)."
300
+ );
283
301
  return null;
284
302
  }
285
303
 
286
- const url = `${baseUrl.replace(/\/$/, "")}/api/chat-widget/config`;
304
+ const url = `${baseUrl.replace(/\/$/, "")}/api/chat-widget/config?token=${encodeURIComponent(
305
+ token
306
+ )}`;
287
307
 
288
308
  try {
289
309
  const response = await fetch(url, {
@@ -300,6 +320,10 @@ export async function loadCopilotChatWidget() {
300
320
  throw new Error("Received incomplete widget configuration from server.");
301
321
  }
302
322
 
323
+ window.CopilotChat = window.CopilotChat || {};
324
+ window.CopilotChat.token = token;
325
+ window.CopilotChat.baseUrl = baseUrl;
326
+
303
327
  return buildWidget({
304
328
  iframeUrl: remoteConfig.iframeUrl,
305
329
  launcherIcon: remoteConfig.launcherIcon,
@@ -11,6 +11,21 @@
11
11
  const IFRAME_SIZE = 720;
12
12
  const embeddingScript = document.currentScript;
13
13
 
14
+ const readQueryConfig = (scriptEl) => {
15
+ if (!scriptEl?.src) return {};
16
+ try {
17
+ const url = new URL(scriptEl.src, window.location.href);
18
+ const params = {};
19
+ url.searchParams.forEach((value, key) => {
20
+ params[key] = value;
21
+ });
22
+ return params;
23
+ } catch (error) {
24
+ console.warn("[CopilotChat] Failed to parse script query params:", error);
25
+ return {};
26
+ }
27
+ };
28
+
14
29
  const ready = (fn) => {
15
30
  if (document.readyState === "complete" || document.readyState === "interactive") {
16
31
  setTimeout(fn, 0);
@@ -30,15 +45,15 @@
30
45
  }
31
46
  };
32
47
 
33
- const resolveEmbeddingScript = () => {
34
- if (embeddingScript) {
35
- return embeddingScript;
36
- }
37
-
38
- const scripts = Array.from(document.querySelectorAll("script"));
39
- const candidate = scripts
40
- .reverse()
41
- .find((script) => script.src && script.src.includes("chat-widget"));
48
+ const resolveEmbeddingScript = () => {
49
+ if (embeddingScript) {
50
+ return embeddingScript;
51
+ }
52
+
53
+ const scripts = Array.from(document.querySelectorAll("script"));
54
+ const candidate = scripts
55
+ .reverse()
56
+ .find((script) => script.dataset?.token || (script.src && script.src.includes("chat-widget")));
42
57
 
43
58
  return candidate || null;
44
59
  };
@@ -261,23 +276,20 @@
261
276
  }
262
277
  };
263
278
 
264
- btn.onclick = (event) => {
265
- event.stopPropagation();
266
- isOpen = !isOpen;
267
- if (isOpen) {
268
- container.style.display = "block";
269
- arrow.style.display = "block";
270
- requestAnimationFrame(() => {
271
- container.style.opacity = "1";
272
- container.style.transform = "scale(1) translateY(0)";
273
- });
274
- if (iframe.contentWindow) {
275
- iframe.contentWindow.postMessage({ type: "CHAT_OPENED" }, "*");
276
- }
277
- } else {
278
- closeChat();
279
- }
280
- };
279
+ btn.onclick = (event) => {
280
+ event.stopPropagation();
281
+ isOpen = !isOpen;
282
+ if (isOpen) {
283
+ container.style.display = "block";
284
+ arrow.style.display = "block";
285
+ requestAnimationFrame(() => {
286
+ container.style.opacity = "1";
287
+ container.style.transform = "scale(1) translateY(0)";
288
+ });
289
+ } else {
290
+ closeChat();
291
+ }
292
+ };
281
293
 
282
294
  window.addEventListener("message", handleWidgetMessage);
283
295
 
@@ -313,16 +325,59 @@
313
325
  const shouldAutoBootstrapFromScript = () => {
314
326
  const scriptEl = resolveEmbeddingScript();
315
327
  if (!scriptEl) return false;
328
+ const queryConfig = readQueryConfig(scriptEl);
316
329
  const dataset = scriptEl.dataset || {};
317
- return dataset.autoload !== "false";
330
+ const hasTokenHint = dataset.token || queryConfig.token;
331
+ const hasGlobalToken = typeof window !== "undefined" && window.CopilotChatConfig && window.CopilotChatConfig.token;
332
+ return (hasTokenHint || hasGlobalToken) && dataset.autoload !== "false";
318
333
  };
319
334
 
320
- const initCopilotChatWidget = async (config = {}) => {
321
- const scriptEl = config.scriptEl || resolveEmbeddingScript();
322
-
323
- const baseUrl =
324
- BUILD_BASE_URL ||
325
- inferBaseUrlFromScript(scriptEl) ||
335
+ const initCopilotChatWidget = async (config = {}) => {
336
+ const scriptEl = config.scriptEl || resolveEmbeddingScript();
337
+ const globalConfig = window.CopilotChatConfig || {};
338
+ const datasetConfig = scriptEl?.dataset || {};
339
+ const queryConfig = readQueryConfig(scriptEl);
340
+
341
+ const resolveToken = () => {
342
+ const fromConfig = config.token || globalConfig.token || datasetConfig.token || queryConfig.token;
343
+ if (fromConfig) return fromConfig;
344
+
345
+ try {
346
+ const stored = window.localStorage.getItem("copilotChatToken");
347
+ if (stored) return stored;
348
+ } catch (error) {
349
+ // ignore storage errors
350
+ }
351
+
352
+ if (typeof window !== "undefined" && typeof window.prompt === "function") {
353
+ const entered = window.prompt("Enter your Copilot Chat token:");
354
+ if (entered) {
355
+ try {
356
+ window.localStorage.setItem("copilotChatToken", entered);
357
+ } catch (error) {
358
+ // ignore storage errors
359
+ }
360
+ return entered;
361
+ }
362
+ }
363
+
364
+ return null;
365
+ };
366
+
367
+ const token = resolveToken();
368
+
369
+ if (!token) {
370
+ handleError("Missing token (provide via init config, window.CopilotChatConfig.token, or data-token attribute).");
371
+ return null;
372
+ }
373
+
374
+ const baseUrl =
375
+ config.baseUrl ||
376
+ globalConfig.baseUrl ||
377
+ datasetConfig.baseUrl ||
378
+ queryConfig.baseUrl ||
379
+ BUILD_BASE_URL ||
380
+ inferBaseUrlFromScript(scriptEl) ||
326
381
  (typeof window !== "undefined" && window.location?.origin) ||
327
382
  null;
328
383
 
@@ -332,7 +387,7 @@
332
387
  }
333
388
 
334
389
  try {
335
- const response = await fetch(`${baseUrl}/api/chat-widget/config`, {
390
+ const response = await fetch(`${baseUrl}/api/chat-widget/config?token=${encodeURIComponent(token)}`, {
336
391
  credentials: "omit",
337
392
  mode: "cors",
338
393
  });