copilot-chat-widget 0.1.0 → 0.1.1

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/src/index.js CHANGED
@@ -1,425 +1,371 @@
1
- const BUTTON_SIZE = 64;
2
- const IFRAME_SIZE = 720;
3
- const embeddingScript = typeof document !== "undefined" ? document.currentScript : null;
4
-
5
- const readQueryConfig = (scriptEl) => {
6
- if (!scriptEl?.src) return {};
7
- try {
8
- const url = new URL(scriptEl.src, typeof window !== "undefined" ? window.location.href : undefined);
9
- const params = {};
10
- url.searchParams.forEach((value, key) => {
11
- params[key] = value;
12
- });
13
- return params;
14
- } catch (error) {
15
- console.warn("[CopilotChat] Failed to parse script query params:", error);
16
- return {};
17
- }
18
- };
19
-
20
- const ready = (fn) => {
21
- if (typeof document === "undefined") return;
22
- if (document.readyState === "complete" || document.readyState === "interactive") {
23
- setTimeout(fn, 0);
24
- } else {
25
- document.addEventListener("DOMContentLoaded", fn);
26
- }
27
- };
28
-
29
- const inferBaseUrlFromScript = (scriptEl) => {
30
- if (!scriptEl?.src || typeof window === "undefined") return null;
31
- try {
32
- const srcUrl = new URL(scriptEl.src, window.location.href);
33
- return `${srcUrl.protocol}//${srcUrl.host}`;
34
- } catch (error) {
35
- console.warn("[CopilotChat] Unable to infer base URL from script source.", error);
36
- return null;
37
- }
38
- };
39
-
40
- const resolveBaseUrl = (scriptEl) => {
41
- // Use the build-time defined base URL from VITE_CHAT_WIDGET_BASE_URL
42
- if (typeof CHAT_WIDGET_BASE_URL !== "undefined") {
43
- return CHAT_WIDGET_BASE_URL;
44
- }
45
-
46
- // Fallback to inferred URL from script
47
- const inferred = inferBaseUrlFromScript(scriptEl);
48
- if (inferred) return inferred;
49
-
50
- // Final fallback to window location
51
- if (typeof window !== "undefined" && window.location?.origin) {
52
- return window.location.origin;
53
- }
54
- return null;
55
- };
56
-
57
- const buildWidget = ({ iframeUrl, launcherIcon }) => {
58
- const existingRoot = document.querySelector("[data-copilot-widget-root]");
59
- if (existingRoot) {
60
- existingRoot.remove();
61
- }
62
-
63
- const showCheckoutToast = (message) => {
64
- const existingToast = document.querySelector("[data-copilot-checkout-toast]");
65
- if (existingToast) {
66
- existingToast.remove();
67
- }
68
-
69
- const toast = document.createElement("div");
70
- toast.setAttribute("data-copilot-checkout-toast", "true");
71
- toast.innerText = message;
72
-
73
- Object.assign(toast.style, {
74
- position: "fixed",
75
- top: "20px",
76
- left: "50%",
77
- transform: "translateX(-50%)",
78
- padding: "12px 16px",
79
- background: "#0f172a",
80
- color: "white",
81
- borderRadius: "12px",
82
- boxShadow: "0 8px 24px rgba(0,0,0,0.25)",
83
- zIndex: 2147483647,
84
- fontSize: "14px",
85
- fontWeight: "600",
86
- maxWidth: "420px",
87
- lineHeight: "1.4",
88
- textAlign: "center",
89
- });
90
-
91
- document.body.appendChild(toast);
92
-
93
- setTimeout(() => {
94
- toast.remove();
95
- }, 4500);
96
- };
97
-
98
- // ---------- Shadow DOM container ----------
99
- const containerHost = document.createElement("div");
100
- containerHost.setAttribute("data-copilot-widget-root", "true");
101
- const shadow = containerHost.attachShadow({ mode: "open" });
102
- document.body.appendChild(containerHost);
103
-
104
- // ---------- Button ----------
105
- const btn = document.createElement("button");
106
- btn.type = "button";
107
- btn.setAttribute("aria-label", "Open Copilot chat");
108
- btn.innerHTML = `
109
- <img
110
- src="${launcherIcon}"
111
- alt="Copilot chat launcher"
112
- style="width: 38px; height: 38px; object-fit: contain; border-radius: 50%; pointer-events: none;"
113
- />
114
- `;
115
-
116
- Object.assign(btn.style, {
117
- position: "fixed",
118
- bottom: "24px",
119
- right: "24px",
120
- width: `${BUTTON_SIZE}px`,
121
- height: `${BUTTON_SIZE}px`,
122
- borderRadius: "50%",
123
- border: "none",
124
- background: "linear-gradient(135deg, #0078ff, #00c6ff)",
125
- color: "white",
126
- cursor: "pointer",
127
- zIndex: 999998,
128
- display: "flex",
129
- alignItems: "center",
130
- justifyContent: "center",
131
- boxShadow: "0 6px 14px rgba(0,0,0,0.25)",
132
- transition: "all 0.25s ease",
133
- });
134
-
135
- btn.onmouseover = () => {
136
- btn.style.transform = "scale(1.12)";
137
- btn.style.boxShadow = "0 10px 25px rgba(0,0,0,0.3)";
138
- };
139
- btn.onmouseout = () => {
140
- btn.style.transform = "scale(1)";
141
- btn.style.boxShadow = "0 6px 14px rgba(0,0,0,0.25)";
142
- };
143
-
144
- const container = document.createElement("div");
145
- container.setAttribute("data-copilot-widget-root", "true");
146
- Object.assign(container.style, {
147
- display: "none",
148
- position: "fixed",
149
- bottom: `${BUTTON_SIZE + 36}px`,
150
- right: "24px",
151
- zIndex: "999999",
152
- transformOrigin: "bottom right",
153
- transform: "scale(0.8) translateY(20px)",
154
- opacity: "0",
155
- transition: "all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55)",
156
- });
157
-
158
- const arrow = document.createElement("div");
159
- const arrowBorder = document.createElement("div");
160
- const arrowFill = document.createElement("div");
161
-
162
- Object.assign(arrow.style, {
163
- position: "absolute",
164
- bottom: "-14px",
165
- right: "28px",
166
- width: "30px",
167
- height: "20px",
168
- pointerEvents: "none",
169
- display: "none",
170
- zIndex: "1",
171
- });
172
-
173
- Object.assign(arrowBorder.style, {
174
- position: "absolute",
175
- bottom: "0",
176
- left: "0",
177
- right: "0",
178
- margin: "0 auto",
179
- width: "0",
180
- height: "0",
181
- borderLeft: "15px solid transparent",
182
- borderRight: "15px solid transparent",
183
- borderTop: "15px solid rgba(15,23,42,0.1)",
184
- });
185
-
186
- Object.assign(arrowFill.style, {
187
- position: "absolute",
188
- bottom: "2px",
189
- left: "0",
190
- right: "0",
191
- margin: "0 auto",
192
- width: "0",
193
- height: "0",
194
- borderLeft: "13px solid transparent",
195
- borderRight: "13px solid transparent",
196
- borderTop: "13px solid white",
197
- boxShadow: "0 6px 16px rgba(15,23,42,0.12)",
198
- borderRadius: "2px",
199
- });
200
-
201
- arrow.appendChild(arrowBorder);
202
- arrow.appendChild(arrowFill);
203
-
204
- const frameWrapper = document.createElement("div");
205
- Object.assign(frameWrapper.style, {
206
- width: `${IFRAME_SIZE}px`,
207
- maxWidth: "calc(100vw - 48px)",
208
- // keep height responsive to viewport to avoid outer scrollbars
209
- height: `${Math.min(IFRAME_SIZE, Math.max(320, window.innerHeight - 140))}px`,
210
- maxHeight: "calc(100vh - 150px)",
211
- borderRadius: "20px",
212
- background: "white",
213
- border: "1px solid rgba(15,23,42,0.12)",
214
- boxShadow: "0 18px 45px rgba(15,23,42,0.16)",
215
- overflow: "hidden",
216
- });
217
- shadow.appendChild(frameWrapper);
218
-
219
- const iframe = document.createElement("iframe");
220
- iframe.src = iframeUrl;
221
- iframe.title = "Copilot chat widget";
222
- iframe.allow = "clipboard-read; clipboard-write; microphone; camera; display-capture";
223
- iframe.setAttribute("scrolling", "no");
224
- Object.assign(iframe.style, {
225
- width: "100%",
226
- height: "100%",
227
- border: "none",
228
- display: "block",
229
- background: "transparent",
230
- overflow: "hidden",
231
- });
232
-
233
- shadow.appendChild(frameWrapper);
234
- frameWrapper.appendChild(iframe);
235
-
236
- container.appendChild(arrow);
237
- container.appendChild(frameWrapper);
238
- document.body.appendChild(btn);
239
- document.body.appendChild(container);
240
-
241
- let isOpen = false;
242
-
243
- const closeChat = () => {
244
- if (!isOpen) return;
245
- isOpen = false;
246
- container.style.opacity = "0";
247
- container.style.transform = "scale(0.8) translateY(20px)";
248
- arrow.style.display = "none";
249
- setTimeout(() => {
250
- container.style.display = "none";
251
- }, 250);
252
- btn.style.transform = "scale(1)";
253
- };
254
-
255
- const handleWidgetMessage = (event) => {
256
- const { data, source } = event || {};
257
- if (!data?.type) return;
258
-
259
- if (data.type === "CART_CHECKOUT" && source === iframe.contentWindow) {
260
- console.log("[CopilotChat] Received checkout payload from widget:", data);
261
- showCheckoutToast("Checkout message received from chat widget. Check console for payload.");
262
- return;
263
- }
264
-
265
- if (data.type === "CHAT_CLOSED") {
266
- closeChat();
267
- }
268
- };
269
-
270
- window.addEventListener("message", handleWidgetMessage);
271
-
272
- btn.onclick = (event) => {
273
- event.stopPropagation();
274
- isOpen = !isOpen;
275
- if (isOpen) {
276
- container.style.display = "block";
277
- arrow.style.display = "block";
278
- requestAnimationFrame(() => {
279
- container.style.opacity = "1";
280
- container.style.transform = "scale(1) translateY(0)";
281
- });
282
- } else {
283
- closeChat();
284
- }
285
- };
286
-
287
- document.addEventListener("click", (event) => {
288
- const target = event.target;
289
- if (!target) return;
290
- if (isOpen && !container.contains(target) && target !== btn) {
291
- closeChat();
292
- }
293
- });
294
-
295
- const controls = {
296
- close: closeChat,
297
- open: () => {
298
- if (!isOpen) {
299
- btn.click();
300
- }
301
- },
302
- };
303
-
304
- window.CopilotChat = window.CopilotChat || {};
305
- window.CopilotChat.close = controls.close;
306
- window.CopilotChat.open = controls.open;
307
- window.CopilotChat.controls = controls;
308
-
309
- return controls;
310
- };
311
-
312
- const handleError = (message) => {
313
- console.error(`[CopilotChat] ${message}`);
314
- };
315
-
316
- export const resolveEmbeddingScript = () => {
317
- if (embeddingScript) {
318
- return embeddingScript;
319
- }
320
-
321
- if (typeof document === "undefined") return null;
322
-
323
- const scripts = Array.from(document.querySelectorAll("script"));
324
- const candidate = scripts
325
- .reverse()
326
- .find((script) => script.dataset?.token || (script.src && script.src.includes("chat-widget")));
327
-
328
- return candidate || null;
329
- };
330
-
331
- const shouldAutoBootstrapFromScript = () => {
332
- if (typeof window === "undefined" || typeof document === "undefined") {
333
- return false;
334
- }
335
- const scriptEl = resolveEmbeddingScript();
336
- if (!scriptEl) return false;
337
- const queryConfig = readQueryConfig(scriptEl);
338
- const dataset = scriptEl.dataset || {};
339
- const hasTokenHint = dataset.token || queryConfig.token;
340
- const hasGlobalToken = typeof window !== "undefined" && window.CopilotChatConfig && window.CopilotChatConfig.token;
341
- return (hasTokenHint || hasGlobalToken) && dataset.autoload !== "false";
342
- };
343
-
344
- export const initCopilotChatWidget = async (config = {}) => {
345
- if (typeof window === "undefined" || typeof document === "undefined") {
346
- handleError("Window or document is not available. This widget runs in browsers only.");
347
- return null;
348
- }
349
-
350
- if (window.__copilotWidgetLoaded && !config.force) {
351
- return window.CopilotChat?.controls || null;
352
- }
353
- window.__copilotWidgetLoaded = true;
354
-
355
- const scriptEl = config.scriptEl || resolveEmbeddingScript();
356
- const globalConfig = window.CopilotChatConfig || {};
357
- const datasetConfig = scriptEl?.dataset || {};
358
- const queryConfig = readQueryConfig(scriptEl);
359
-
360
- const token = config.token || globalConfig.token || datasetConfig.token || queryConfig.token;
361
-
362
- if (!token) {
363
- handleError("Missing token (provide via init config, window.CopilotChatConfig.token, or data-token attribute).");
364
- return null;
365
- }
366
-
367
- const baseUrl = resolveBaseUrl(scriptEl);
368
-
369
- if (!baseUrl) {
370
- handleError("Unable to resolve base URL from embedding script or window.location.");
371
- return null;
372
- }
373
-
374
- try {
375
- const response = await fetch(`${baseUrl}/api/chat-widget/config?token=${encodeURIComponent(token)}`, {
376
- credentials: "omit",
377
- mode: "cors",
378
- });
379
-
380
- if (!response.ok) {
381
- throw new Error(`Server responded with ${response.status}`);
382
- }
383
-
384
- const remoteConfig = await response.json();
385
- if (!remoteConfig?.iframeUrl || !remoteConfig?.launcherIcon) {
386
- throw new Error("Received incomplete widget configuration from server.");
387
- }
388
-
389
- const baseConfig = {
390
- iframeUrl: remoteConfig.iframeUrl,
391
- launcherIcon: remoteConfig.launcherIcon,
392
- };
393
-
394
- window.CopilotChat = window.CopilotChat || {};
395
- window.CopilotChat.init = (overrides = {}) => {
396
- const mergedConfig = {
397
- iframeUrl: overrides.iframeUrl || baseConfig.iframeUrl,
398
- launcherIcon: overrides.launcherIcon || baseConfig.launcherIcon,
399
- };
400
-
401
- return buildWidget(mergedConfig);
402
- };
403
-
404
- const controls = window.CopilotChat.init(config);
405
- return controls;
406
- } catch (error) {
407
- handleError(error instanceof Error ? error.message : "Unknown error during widget bootstrap.");
408
- return null;
409
- }
410
- };
411
-
412
- export const loadCopilotChatWidget = (config = {}) =>
413
- new Promise((resolve) => {
414
- if (typeof document === "undefined") {
415
- resolve(null);
416
- return;
417
- }
418
- ready(() => {
419
- initCopilotChatWidget(config).then(resolve);
420
- });
421
- });
422
-
423
- if (shouldAutoBootstrapFromScript()) {
424
- loadCopilotChatWidget();
425
- }
1
+ (function bootstrap() {
2
+ if (typeof window === "undefined") {
3
+ return;
4
+ }
5
+
6
+ if (window.__copilotWidgetLoaded) {
7
+ return;
8
+ }
9
+ window.__copilotWidgetLoaded = true;
10
+
11
+ const DEFAULT_BASE_URL = CHAT_WIDGET_BASE_URL;
12
+ const BUTTON_SIZE = 64;
13
+ const IFRAME_SIZE = 720;
14
+ const embeddingScript = document.currentScript;
15
+ const ENV_BASE_URL = CHAT_WIDGET_BASE_URL;
16
+
17
+ const readQueryConfig = (scriptEl) => {
18
+ if (!scriptEl?.src) return {};
19
+ try {
20
+ const url = new URL(scriptEl.src, window.location.href);
21
+ const params = {};
22
+ url.searchParams.forEach((value, key) => {
23
+ params[key] = value;
24
+ });
25
+ return params;
26
+ } catch (error) {
27
+ console.warn("[CopilotChat] Failed to parse script query params:", error);
28
+ return {};
29
+ }
30
+ };
31
+
32
+ const ready = (fn) => {
33
+ if (document.readyState === "complete" || document.readyState === "interactive") {
34
+ setTimeout(fn, 0);
35
+ } else {
36
+ document.addEventListener("DOMContentLoaded", fn);
37
+ }
38
+ };
39
+
40
+ const normalizeBaseUrl = (url) => {
41
+ if (!url) return DEFAULT_BASE_URL;
42
+ return url.endsWith("/") ? url.slice(0, -1) : url;
43
+ };
44
+
45
+ const inferBaseUrlFromScript = (scriptEl) => {
46
+ if (!scriptEl?.src) return null;
47
+ try {
48
+ const srcUrl = new URL(scriptEl.src, window.location.href);
49
+ return `${srcUrl.protocol}//${srcUrl.host}`;
50
+ } catch (error) {
51
+ console.warn("[CopilotChat] Unable to infer base URL from script source.", error);
52
+ return null;
53
+ }
54
+ };
55
+
56
+ const buildWidget = ({ iframeUrl, launcherIcon, theme = {} }) => {
57
+ const existingRoot = document.querySelector("[data-copilot-widget-root]");
58
+ if (existingRoot) {
59
+ existingRoot.remove();
60
+ }
61
+
62
+ const { accent = "linear-gradient(135deg, #0078ff, #00c6ff)" } = theme;
63
+
64
+ // ---------- Shadow DOM container ----------
65
+ const containerHost = document.createElement("div");
66
+ containerHost.setAttribute("data-copilot-widget-root", "true");
67
+ const shadow = containerHost.attachShadow({ mode: "open" });
68
+ document.body.appendChild(containerHost);
69
+
70
+ // ---------- Button ----------
71
+ const btn = document.createElement("button");
72
+ btn.type = "button";
73
+ btn.setAttribute("aria-label", "Open Copilot chat");
74
+ btn.innerHTML = `
75
+ <img
76
+ src="${launcherIcon}"
77
+ alt="Copilot chat launcher"
78
+ style="width: 38px; height: 38px; object-fit: contain; border-radius: 50%; pointer-events: none;"
79
+ />
80
+ `;
81
+
82
+ Object.assign(btn.style, {
83
+ position: "fixed",
84
+ bottom: "24px",
85
+ right: "24px",
86
+ width: `${BUTTON_SIZE}px`,
87
+ height: `${BUTTON_SIZE}px`,
88
+ borderRadius: "50%",
89
+ border: "none",
90
+ background: accent,
91
+ color: "white",
92
+ cursor: "pointer",
93
+ zIndex: 999998,
94
+ display: "flex",
95
+ alignItems: "center",
96
+ justifyContent: "center",
97
+ boxShadow: "0 6px 14px rgba(0,0,0,0.25)",
98
+ transition: "all 0.25s ease",
99
+ });
100
+
101
+ btn.onmouseover = () => {
102
+ btn.style.transform = "scale(1.12)";
103
+ btn.style.boxShadow = "0 10px 25px rgba(0,0,0,0.3)";
104
+ };
105
+ btn.onmouseout = () => {
106
+ btn.style.transform = "scale(1)";
107
+ btn.style.boxShadow = "0 6px 14px rgba(0,0,0,0.25)";
108
+ };
109
+
110
+ const container = document.createElement("div");
111
+ container.setAttribute("data-copilot-widget-root", "true");
112
+ Object.assign(container.style, {
113
+ display: "none",
114
+ position: "fixed",
115
+ bottom: `${BUTTON_SIZE + 36}px`,
116
+ right: "24px",
117
+ zIndex: "999999",
118
+ transformOrigin: "bottom right",
119
+ transform: "scale(0.8) translateY(20px)",
120
+ opacity: "0",
121
+ transition: "all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55)",
122
+ });
123
+
124
+ const arrow = document.createElement("div");
125
+ const arrowBorder = document.createElement("div");
126
+ const arrowFill = document.createElement("div");
127
+
128
+ Object.assign(arrow.style, {
129
+ position: "absolute",
130
+ bottom: "-14px",
131
+ right: "28px",
132
+ width: "30px",
133
+ height: "20px",
134
+ pointerEvents: "none",
135
+ display: "none",
136
+ zIndex: "1",
137
+ });
138
+
139
+ Object.assign(arrowBorder.style, {
140
+ position: "absolute",
141
+ bottom: "0",
142
+ left: "0",
143
+ right: "0",
144
+ margin: "0 auto",
145
+ width: "0",
146
+ height: "0",
147
+ borderLeft: "15px solid transparent",
148
+ borderRight: "15px solid transparent",
149
+ borderTop: "15px solid rgba(15,23,42,0.1)",
150
+ });
151
+
152
+ Object.assign(arrowFill.style, {
153
+ position: "absolute",
154
+ bottom: "2px",
155
+ left: "0",
156
+ right: "0",
157
+ margin: "0 auto",
158
+ width: "0",
159
+ height: "0",
160
+ borderLeft: "13px solid transparent",
161
+ borderRight: "13px solid transparent",
162
+ borderTop: "13px solid white",
163
+ boxShadow: "0 6px 16px rgba(15,23,42,0.12)",
164
+ borderRadius: "2px",
165
+ });
166
+
167
+ arrow.appendChild(arrowBorder);
168
+ arrow.appendChild(arrowFill);
169
+
170
+ const frameWrapper = document.createElement("div");
171
+ Object.assign(frameWrapper.style, {
172
+ width: `${IFRAME_SIZE}px`,
173
+ maxWidth: "calc(100vw - 48px)",
174
+ // keep height responsive to viewport to avoid outer scrollbars
175
+ height: `${Math.min(IFRAME_SIZE, Math.max(320, window.innerHeight - 140))}px`,
176
+ maxHeight: "calc(100vh - 150px)",
177
+ borderRadius: "20px",
178
+ background: "white",
179
+ border: "1px solid rgba(15,23,42,0.12)",
180
+ boxShadow: "0 18px 45px rgba(15,23,42,0.16)",
181
+ overflow: "hidden",
182
+ });
183
+ shadow.appendChild(frameWrapper);
184
+
185
+ const iframe = document.createElement("iframe");
186
+ iframe.src = iframeUrl;
187
+ iframe.title = "Copilot chat widget";
188
+ iframe.allow = "clipboard-read; clipboard-write; microphone; camera; display-capture";
189
+ iframe.setAttribute("scrolling", "no");
190
+ Object.assign(iframe.style, {
191
+ width: "100%",
192
+ height: "100%",
193
+ border: "none",
194
+ display: "block",
195
+ background: "transparent",
196
+ overflow: "hidden",
197
+ });
198
+
199
+ shadow.appendChild(frameWrapper);
200
+ frameWrapper.appendChild(iframe);
201
+
202
+ container.appendChild(arrow);
203
+ container.appendChild(frameWrapper);
204
+ document.body.appendChild(btn);
205
+ document.body.appendChild(container);
206
+
207
+
208
+ window.addEventListener("message", (event) => {
209
+ if (event.data?.type === "WIDGET_READY") {
210
+ iframe.contentWindow.postMessage(
211
+ { type: "INIT_WIDGET" },
212
+ "*"
213
+ );
214
+ }
215
+ });
216
+
217
+ let isOpen = false;
218
+
219
+ const closeChat = () => {
220
+ if (!isOpen) return;
221
+ isOpen = false;
222
+ container.style.opacity = "0";
223
+ container.style.transform = "scale(0.8) translateY(20px)";
224
+ arrow.style.display = "none";
225
+ setTimeout(() => {
226
+ container.style.display = "none";
227
+ }, 250);
228
+ btn.style.transform = "scale(1)";
229
+ };
230
+
231
+ btn.onclick = (event) => {
232
+ event.stopPropagation();
233
+ isOpen = !isOpen;
234
+ if (isOpen) {
235
+ container.style.display = "block";
236
+ arrow.style.display = "block";
237
+ requestAnimationFrame(() => {
238
+ container.style.opacity = "1";
239
+ container.style.transform = "scale(1) translateY(0)";
240
+ });
241
+ } else {
242
+ closeChat();
243
+ }
244
+ };
245
+
246
+ window.addEventListener("message", (event) => {
247
+ if (event?.data?.type === "CHAT_CLOSED") {
248
+ closeChat();
249
+ }
250
+ });
251
+
252
+ document.addEventListener("click", (event) => {
253
+ const target = event.target;
254
+ if (!target) return;
255
+ if (isOpen && !container.contains(target) && target !== btn) {
256
+ closeChat();
257
+ }
258
+ });
259
+
260
+ const controls = {
261
+ close: closeChat,
262
+ open: () => {
263
+ if (!isOpen) {
264
+ btn.click();
265
+ }
266
+ },
267
+ };
268
+
269
+ window.CopilotChat = window.CopilotChat || {};
270
+ window.CopilotChat.close = controls.close;
271
+ window.CopilotChat.open = controls.open;
272
+
273
+ return controls;
274
+ };
275
+
276
+ const handleError = (message) => {
277
+ console.error(`[CopilotChat] ${message}`);
278
+ };
279
+
280
+ const resolveEmbeddingScript = () => {
281
+ if (embeddingScript) {
282
+ return embeddingScript;
283
+ }
284
+
285
+ const scripts = Array.from(document.querySelectorAll("script"));
286
+ const candidate = scripts
287
+ .reverse()
288
+ .find((script) => script.dataset?.token || script.src.includes("chat-widget"));
289
+
290
+ return candidate || null;
291
+ };
292
+
293
+ ready(async () => {
294
+ const scriptEl = resolveEmbeddingScript();
295
+ if (!scriptEl) {
296
+ handleError("Unable to locate the embedding script tag on the page.");
297
+ return;
298
+ }
299
+
300
+ const globalConfig = window.CopilotChatConfig || {};
301
+ const datasetConfig = scriptEl.dataset || {};
302
+ const queryConfig = readQueryConfig(scriptEl);
303
+
304
+ const token = globalConfig.token || datasetConfig.token || queryConfig.token;
305
+ if (!token) {
306
+ handleError("Missing token (provide via window.CopilotChatConfig.token or data-token attribute).");
307
+ return;
308
+ }
309
+
310
+ const baseUrl = normalizeBaseUrl(
311
+ ENV_BASE_URL ||
312
+ globalConfig.baseUrl ||
313
+ datasetConfig.baseUrl ||
314
+ queryConfig.baseUrl ||
315
+ inferBaseUrlFromScript(scriptEl)
316
+ );
317
+ const themeAccent =
318
+ (globalConfig.theme && globalConfig.theme.accent) ||
319
+ globalConfig.accent ||
320
+ datasetConfig.themeAccent ||
321
+ queryConfig.themeAccent;
322
+
323
+ try {
324
+ const response = await fetch(`${baseUrl}/api/chat-widget/config?token=${encodeURIComponent(token)}`, {
325
+ credentials: "omit",
326
+ mode: "cors",
327
+ });
328
+
329
+ if (!response.ok) {
330
+ throw new Error(`Server responded with ${response.status}`);
331
+ }
332
+
333
+ const config = await response.json();
334
+ if (!config?.iframeUrl || !config?.launcherIcon) {
335
+ throw new Error("Received incomplete widget configuration from server.");
336
+ }
337
+
338
+ const baseConfig = {
339
+ iframeUrl: config.iframeUrl,
340
+ launcherIcon: config.launcherIcon,
341
+ theme: {
342
+ accent: themeAccent || config.theme?.accent || undefined,
343
+ },
344
+ };
345
+
346
+ window.CopilotChat = window.CopilotChat || {};
347
+ window.CopilotChat.init = (overrides = {}) => {
348
+ const mergedTheme = {
349
+ accent:
350
+ overrides.theme?.accent ||
351
+ overrides.accent ||
352
+ baseConfig.theme.accent ||
353
+ (typeof globalConfig.theme === "object" ? globalConfig.theme.accent : undefined) ||
354
+ globalConfig.accent,
355
+ };
356
+
357
+ const mergedConfig = {
358
+ iframeUrl: overrides.iframeUrl || baseConfig.iframeUrl,
359
+ launcherIcon: overrides.launcherIcon || baseConfig.launcherIcon,
360
+ theme: mergedTheme,
361
+ };
362
+
363
+ return buildWidget(mergedConfig);
364
+ };
365
+
366
+ window.CopilotChat.init(globalConfig);
367
+ } catch (error) {
368
+ handleError(error instanceof Error ? error.message : "Unknown error during widget bootstrap.");
369
+ }
370
+ });
371
+ })();