@robylon/web-react-sdk 1.1.28-staging.8 → 1.1.29

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.
Files changed (120) hide show
  1. package/README.md +443 -32
  2. package/dist/cjs/index.js +1 -1215
  3. package/dist/cjs/index.js.map +1 -1
  4. package/dist/cjs/types/components/ChatbotContainer/ChatbotContainer.d.ts +15 -0
  5. package/dist/cjs/types/components/ChatbotContainer/index.d.ts +1 -0
  6. package/dist/cjs/types/components/ChatbotFloatingButton.d.ts +3 -0
  7. package/dist/cjs/types/components/ChatbotIframe.d.ts +2 -0
  8. package/dist/cjs/types/components/RobylonChatbot.d.ts +3 -0
  9. package/dist/cjs/types/config.d.ts +1 -1
  10. package/dist/cjs/types/constants/fontStyles.d.ts +2 -0
  11. package/dist/cjs/types/core/api.d.ts +6 -54
  12. package/dist/cjs/types/core/config.d.ts +34 -0
  13. package/dist/cjs/types/core/events.d.ts +22 -0
  14. package/dist/cjs/types/core/index.d.ts +4 -0
  15. package/dist/cjs/types/core/state.d.ts +34 -0
  16. package/dist/cjs/types/index.d.ts +5 -9
  17. package/dist/cjs/types/types.d.ts +34 -9
  18. package/dist/cjs/types/utils/fetchData.d.ts +16 -0
  19. package/dist/cjs/types/vanilla/components/ChatbotContainer.d.ts +45 -0
  20. package/dist/cjs/types/vanilla/components/ChatbotFloatingButton.d.ts +72 -0
  21. package/dist/cjs/types/vanilla/components/ChatbotIframe.d.ts +73 -0
  22. package/dist/cjs/types/vanilla/index.d.ts +18 -29
  23. package/dist/esm/index.js +1 -1208
  24. package/dist/esm/index.js.map +1 -1
  25. package/dist/esm/types/components/ChatbotContainer/ChatbotContainer.d.ts +15 -0
  26. package/dist/esm/types/components/ChatbotContainer/index.d.ts +1 -0
  27. package/dist/esm/types/components/ChatbotFloatingButton.d.ts +3 -0
  28. package/dist/esm/types/components/ChatbotIframe.d.ts +2 -0
  29. package/dist/esm/types/components/RobylonChatbot.d.ts +3 -0
  30. package/dist/esm/types/config.d.ts +1 -1
  31. package/dist/esm/types/constants/fontStyles.d.ts +2 -0
  32. package/dist/esm/types/core/api.d.ts +6 -54
  33. package/dist/esm/types/core/config.d.ts +34 -0
  34. package/dist/esm/types/core/events.d.ts +22 -0
  35. package/dist/esm/types/core/index.d.ts +4 -0
  36. package/dist/esm/types/core/state.d.ts +34 -0
  37. package/dist/esm/types/index.d.ts +5 -9
  38. package/dist/esm/types/types.d.ts +34 -9
  39. package/dist/esm/types/utils/fetchData.d.ts +16 -0
  40. package/dist/esm/types/vanilla/components/ChatbotContainer.d.ts +45 -0
  41. package/dist/esm/types/vanilla/components/ChatbotFloatingButton.d.ts +72 -0
  42. package/dist/esm/types/vanilla/components/ChatbotIframe.d.ts +73 -0
  43. package/dist/esm/types/vanilla/index.d.ts +18 -29
  44. package/dist/index.d.ts +115 -57
  45. package/dist/umd/robylon-chatbot.js +2 -0
  46. package/dist/umd/robylon-chatbot.js.map +1 -0
  47. package/dist/umd/types/components/ChatbotContainer/ChatbotContainer.d.ts +15 -0
  48. package/dist/umd/types/components/ChatbotContainer/index.d.ts +1 -0
  49. package/dist/umd/types/components/ChatbotFloatingButton.d.ts +3 -0
  50. package/dist/umd/types/components/ChatbotIframe.d.ts +2 -0
  51. package/dist/umd/types/components/RobylonChatbot.d.ts +3 -0
  52. package/dist/umd/types/config.d.ts +1 -1
  53. package/dist/umd/types/constants/fontStyles.d.ts +2 -0
  54. package/dist/umd/types/core/api.d.ts +6 -54
  55. package/dist/umd/types/core/config.d.ts +34 -0
  56. package/dist/umd/types/core/events.d.ts +22 -0
  57. package/dist/umd/types/core/index.d.ts +4 -0
  58. package/dist/umd/types/core/state.d.ts +34 -0
  59. package/dist/umd/types/index.d.ts +5 -9
  60. package/dist/umd/types/types.d.ts +34 -9
  61. package/dist/umd/types/utils/fetchData.d.ts +16 -0
  62. package/dist/umd/types/vanilla/components/ChatbotContainer.d.ts +45 -0
  63. package/dist/umd/types/vanilla/components/ChatbotFloatingButton.d.ts +72 -0
  64. package/dist/umd/types/vanilla/components/ChatbotIframe.d.ts +73 -0
  65. package/dist/umd/types/vanilla/index.d.ts +18 -29
  66. package/package.json +30 -85
  67. package/dist/cjs/legacy.js +0 -2
  68. package/dist/cjs/legacy.js.map +0 -1
  69. package/dist/cjs/react.js +0 -2
  70. package/dist/cjs/react.js.map +0 -1
  71. package/dist/cjs/types/core/chatbotEmbed.d.ts +0 -59
  72. package/dist/cjs/types/core/utils/color.d.ts +0 -1
  73. package/dist/cjs/types/core/utils/cookies.d.ts +0 -30
  74. package/dist/cjs/types/core/utils/environment.d.ts +0 -19
  75. package/dist/cjs/types/core/utils/logger.d.ts +0 -37
  76. package/dist/cjs/types/core/utils/system.d.ts +0 -22
  77. package/dist/cjs/types/index.legacy.d.ts +0 -7
  78. package/dist/cjs/types/index.react.d.ts +0 -9
  79. package/dist/cjs/types/index.vanilla.d.ts +0 -32
  80. package/dist/cjs/types/react/components/Chatbot.d.ts +0 -34
  81. package/dist/cjs/types/react/components/ErrorBoundary.d.ts +0 -18
  82. package/dist/cjs/types/types/config.d.ts +0 -33
  83. package/dist/cjs/types/types/index.d.ts +0 -16
  84. package/dist/esm/legacy.js +0 -2
  85. package/dist/esm/legacy.js.map +0 -1
  86. package/dist/esm/react.js +0 -2
  87. package/dist/esm/react.js.map +0 -1
  88. package/dist/esm/types/core/chatbotEmbed.d.ts +0 -59
  89. package/dist/esm/types/core/utils/color.d.ts +0 -1
  90. package/dist/esm/types/core/utils/cookies.d.ts +0 -30
  91. package/dist/esm/types/core/utils/environment.d.ts +0 -19
  92. package/dist/esm/types/core/utils/logger.d.ts +0 -37
  93. package/dist/esm/types/core/utils/system.d.ts +0 -22
  94. package/dist/esm/types/index.legacy.d.ts +0 -7
  95. package/dist/esm/types/index.react.d.ts +0 -9
  96. package/dist/esm/types/index.vanilla.d.ts +0 -32
  97. package/dist/esm/types/react/components/Chatbot.d.ts +0 -34
  98. package/dist/esm/types/react/components/ErrorBoundary.d.ts +0 -18
  99. package/dist/esm/types/types/config.d.ts +0 -33
  100. package/dist/esm/types/types/index.d.ts +0 -16
  101. package/dist/legacy.d.ts +0 -160
  102. package/dist/react.d.ts +0 -49
  103. package/dist/umd/robylon.js +0 -1230
  104. package/dist/umd/robylon.js.map +0 -1
  105. package/dist/umd/robylon.min.js +0 -2
  106. package/dist/umd/robylon.min.js.map +0 -1
  107. package/dist/umd/types/core/chatbotEmbed.d.ts +0 -59
  108. package/dist/umd/types/core/utils/color.d.ts +0 -1
  109. package/dist/umd/types/core/utils/cookies.d.ts +0 -30
  110. package/dist/umd/types/core/utils/environment.d.ts +0 -19
  111. package/dist/umd/types/core/utils/logger.d.ts +0 -37
  112. package/dist/umd/types/core/utils/system.d.ts +0 -22
  113. package/dist/umd/types/index.legacy.d.ts +0 -7
  114. package/dist/umd/types/index.react.d.ts +0 -9
  115. package/dist/umd/types/index.vanilla.d.ts +0 -32
  116. package/dist/umd/types/react/components/Chatbot.d.ts +0 -34
  117. package/dist/umd/types/react/components/ErrorBoundary.d.ts +0 -18
  118. package/dist/umd/types/types/config.d.ts +0 -33
  119. package/dist/umd/types/types/index.d.ts +0 -16
  120. package/dist/vite-compat.js +0 -76
package/dist/esm/index.js CHANGED
@@ -1,1209 +1,2 @@
1
- /******************************************************************************
2
- Copyright (c) Microsoft Corporation.
3
-
4
- Permission to use, copy, modify, and/or distribute this software for any
5
- purpose with or without fee is hereby granted.
6
-
7
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
- PERFORMANCE OF THIS SOFTWARE.
14
- ***************************************************************************** */
15
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
16
-
17
- var extendStatics = function(d, b) {
18
- extendStatics = Object.setPrototypeOf ||
19
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
21
- return extendStatics(d, b);
22
- };
23
-
24
- function __extends(d, b) {
25
- if (typeof b !== "function" && b !== null)
26
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
27
- extendStatics(d, b);
28
- function __() { this.constructor = d; }
29
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30
- }
31
-
32
- var __assign = function() {
33
- __assign = Object.assign || function __assign(t) {
34
- for (var s, i = 1, n = arguments.length; i < n; i++) {
35
- s = arguments[i];
36
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
37
- }
38
- return t;
39
- };
40
- return __assign.apply(this, arguments);
41
- };
42
-
43
- function __awaiter(thisArg, _arguments, P, generator) {
44
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
45
- return new (P || (P = Promise))(function (resolve, reject) {
46
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
47
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
48
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
49
- step((generator = generator.apply(thisArg, _arguments || [])).next());
50
- });
51
- }
52
-
53
- function __generator(thisArg, body) {
54
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
55
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
56
- function verb(n) { return function (v) { return step([n, v]); }; }
57
- function step(op) {
58
- if (f) throw new TypeError("Generator is already executing.");
59
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
60
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
61
- if (y = 0, t) op = [op[0] & 2, t.value];
62
- switch (op[0]) {
63
- case 0: case 1: t = op; break;
64
- case 4: _.label++; return { value: op[1], done: false };
65
- case 5: _.label++; y = op[1]; op = [0]; continue;
66
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
67
- default:
68
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
69
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
70
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
71
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
72
- if (t[2]) _.ops.pop();
73
- _.trys.pop(); continue;
74
- }
75
- op = body.call(thisArg, _);
76
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
77
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
78
- }
79
- }
80
-
81
- function __spreadArray(to, from, pack) {
82
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
83
- if (ar || !(i in from)) {
84
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
85
- ar[i] = from[i];
86
- }
87
- }
88
- return to.concat(ar || Array.prototype.slice.call(from));
89
- }
90
-
91
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
92
- var e = new Error(message);
93
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
94
- };
95
-
96
- var getBestFontColor = function (backgroundColor, contrastThreshold) {
97
- if (contrastThreshold === void 0) { contrastThreshold = 0.5; }
98
- var whiteShade = "#FFFFFF"; // Light white shade
99
- var blackShade = "#0E0E0F"; // Dark black shade
100
- // Function to convert hex to RGB
101
- var hexToRgb = function (hex) {
102
- var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
103
- hex = hex.replace(shorthandRegex, function (m, r, g, b) { return r + r + g + g + b + b; });
104
- var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
105
- return result
106
- ? {
107
- r: parseInt(result[1], 16),
108
- g: parseInt(result[2], 16),
109
- b: parseInt(result[3], 16),
110
- }
111
- : { r: 0, g: 0, b: 0 };
112
- };
113
- // Function to calculate luminance
114
- var luminance = function (r, g, b) {
115
- var a = [r, g, b].map(function (v) {
116
- v /= 255;
117
- return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
118
- });
119
- return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
120
- };
121
- var _a = hexToRgb(backgroundColor), r = _a.r, g = _a.g, b = _a.b;
122
- var bgLuminance = luminance(r, g, b);
123
- return bgLuminance > contrastThreshold ? blackShade : whiteShade;
124
- };
125
-
126
- /**
127
- * Cookie and storage utility functions
128
- */
129
- /**
130
- * Generates a UUID v4 string
131
- */
132
- var generateUUID = function () {
133
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
134
- var r = (Math.random() * 16) | 0, v = c === "x" ? r : (r & 0x3) | 0x8;
135
- return v.toString(16);
136
- });
137
- };
138
- /**
139
- * Gets a cookie by name
140
- */
141
- var getCookie = function (name) {
142
- var _a;
143
- if (typeof document === "undefined")
144
- return undefined;
145
- var value = "; ".concat(document.cookie);
146
- var parts = value.split("; ".concat(name, "="));
147
- if (parts.length === 2)
148
- return (_a = parts.pop()) === null || _a === void 0 ? void 0 : _a.split(";").shift();
149
- return undefined;
150
- };
151
- /**
152
- * Sets a cookie with expiration in days
153
- */
154
- var setCookie = function (name, value, days) {
155
- if (typeof document === "undefined")
156
- return;
157
- var expires = new Date();
158
- expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
159
- document.cookie = "".concat(name, "=").concat(value, ";expires=").concat(expires.toUTCString(), ";path=/");
160
- };
161
- /**
162
- * Gets all localStorage as a JSON string
163
- */
164
- var getLocalStorage = function () {
165
- if (typeof localStorage === "undefined")
166
- return "{}";
167
- try {
168
- return JSON.stringify(localStorage);
169
- }
170
- catch (e) {
171
- console.error("Error stringifying localStorage:", e);
172
- return "{}";
173
- }
174
- };
175
- /**
176
- * Gets all sessionStorage as a JSON string
177
- */
178
- var getSessionStorage = function () {
179
- if (typeof sessionStorage === "undefined")
180
- return "{}";
181
- try {
182
- return JSON.stringify(sessionStorage);
183
- }
184
- catch (e) {
185
- console.error("Error stringifying sessionStorage:", e);
186
- return "{}";
187
- }
188
- };
189
- /**
190
- * Gets all cookies as an array of objects
191
- */
192
- var getCookies = function (isTeachmint) {
193
- if (typeof document === "undefined")
194
- return [];
195
- try {
196
- // Note: The teachmint specific code has been simplified for the core library
197
- // If specific implementations are needed, they should be handled in the application layer
198
- var cookieStr = document.cookie;
199
- if (cookieStr === "")
200
- return [];
201
- var cookies = cookieStr.split(";").map(function (cookie) {
202
- var _a = cookie.split("="), name = _a[0], rest = _a.slice(1);
203
- var value = rest.join("=").trim();
204
- name = name.trim();
205
- return {
206
- name: name,
207
- value: value ? decodeURIComponent(value) : "",
208
- };
209
- });
210
- return cookies;
211
- }
212
- catch (e) {
213
- console.error("Error processing cookies:", e);
214
- return [];
215
- }
216
- };
217
-
218
- /**
219
- * Core ChatbotEmbed class - provides the main functionality for both React and vanilla JS implementations
220
- */
221
- var ChatbotEmbed = /** @class */ (function () {
222
- function ChatbotEmbed(config) {
223
- var _this = this;
224
- this.logoContainer = null;
225
- this.iframe = null;
226
- this.bubblePromptContainer = null;
227
- this.chatBtnImage = null;
228
- this.eventHandlers = new Map();
229
- this.isInitialized = false;
230
- this.onMessageListener = function (event) {
231
- if (event.origin === _this.config.domain) {
232
- if (event.data === "closeChatbot") {
233
- _this.closeIframe();
234
- _this.emit("CHATBOT_CLOSED");
235
- return;
236
- }
237
- // Handle structured events
238
- if (typeof event.data === "object" && event.data !== null) {
239
- // Handle specific event types
240
- if (event.data.type === "CHATBOT_LOADED") {
241
- _this.emit("CHATBOT_LOADED", event.data);
242
- }
243
- else if (event.data.type === "CHAT_INITIALIZED") {
244
- _this.emit("CHAT_INITIALIZED", event.data);
245
- }
246
- else if (event.data.type === "CHAT_INITIALIZATION_FAILED") {
247
- _this.emit("CHAT_INITIALIZATION_FAILED", event.data);
248
- }
249
- else if (event.data.type === "SESSION_REFRESHED") {
250
- _this.emit("SESSION_REFRESHED", event.data);
251
- }
252
- else if (event.data.type === "CHATBOT_TOKEN_EXHAUSTED") {
253
- _this.emit("CHATBOT_TOKEN_EXHAUSTED", event.data);
254
- }
255
- }
256
- // Special commands
257
- if (event.data === "captureSessionData") {
258
- _this.handleCaptureSessionData();
259
- }
260
- if (event.data === "expand") {
261
- _this.adjustIframeWidth();
262
- if (_this.iframe) {
263
- _this.iframe.style.height = "calc(100vh - 120px)";
264
- _this.iframe.style.bottom = "86px";
265
- }
266
- }
267
- if (event.data === "collapse") {
268
- if (_this.iframe) {
269
- _this.iframe.style.width = "26%";
270
- _this.iframe.style.height = "calc(100vh - 32px - 10vh)";
271
- _this.iframe.style.bottom = "86px";
272
- _this.iframe.style.top = "auto";
273
- }
274
- }
275
- }
276
- };
277
- this.config = config;
278
- // Normalize the config
279
- if (typeof this.config.userId === "number") {
280
- this.config.userId = String(this.config.userId);
281
- }
282
- if (this.validateConfig()) {
283
- this.init();
284
- this.setupEventListeners();
285
- this.isInitialized = true;
286
- }
287
- }
288
- // Public API methods
289
- ChatbotEmbed.prototype.show = function () {
290
- if (!this.isInitialized || !this.iframe)
291
- return;
292
- this.showIframe();
293
- this.emit("CHATBOT_OPENED");
294
- };
295
- ChatbotEmbed.prototype.hide = function () {
296
- if (!this.isInitialized || !this.iframe)
297
- return;
298
- this.closeIframe();
299
- this.emit("CHATBOT_CLOSED");
300
- };
301
- ChatbotEmbed.prototype.toggle = function () {
302
- if (!this.isInitialized)
303
- return;
304
- if (this.iframe && this.iframe.style.display === "none") {
305
- this.show();
306
- }
307
- else {
308
- this.hide();
309
- }
310
- };
311
- ChatbotEmbed.prototype.updateConfig = function (newConfig) {
312
- var _a;
313
- this.config = __assign(__assign({}, this.config), newConfig);
314
- // Update UI if needed
315
- if (newConfig.brand_colour && this.logoContainer) {
316
- this.logoContainer.style.backgroundColor = newConfig.brand_colour;
317
- this.logoContainer.style.color = getBestFontColor(newConfig.brand_colour);
318
- }
319
- if (newConfig.image_url && this.logoContainer) {
320
- this.loadImage(this.logoContainer);
321
- }
322
- // Update user profile in iframe if it's visible
323
- if (newConfig.userProfile &&
324
- this.iframe &&
325
- this.iframe.style.display === "block") {
326
- (_a = this.iframe.contentWindow) === null || _a === void 0 ? void 0 : _a.postMessage({
327
- action: "updateUserProfile",
328
- user_profile: newConfig.userProfile,
329
- }, this.config.domain);
330
- }
331
- };
332
- // Event system
333
- ChatbotEmbed.prototype.on = function (eventName, callback) {
334
- var _a;
335
- if (!this.eventHandlers.has(eventName)) {
336
- this.eventHandlers.set(eventName, []);
337
- }
338
- (_a = this.eventHandlers.get(eventName)) === null || _a === void 0 ? void 0 : _a.push(callback);
339
- };
340
- ChatbotEmbed.prototype.off = function (eventName, callback) {
341
- if (!this.eventHandlers.has(eventName))
342
- return;
343
- var handlers = this.eventHandlers.get(eventName) || [];
344
- var index = handlers.indexOf(callback);
345
- if (index !== -1) {
346
- handlers.splice(index, 1);
347
- }
348
- };
349
- ChatbotEmbed.prototype.emit = function (eventType, data) {
350
- var event = {
351
- type: eventType,
352
- timestamp: Date.now(),
353
- data: data,
354
- };
355
- // Call specific event handlers
356
- var handlers = this.eventHandlers.get(eventType) || [];
357
- handlers.forEach(function (handler) { return handler(event); });
358
- // Call wildcard handlers
359
- var wildcardHandlers = this.eventHandlers.get("*") || [];
360
- wildcardHandlers.forEach(function (handler) { return handler(event); });
361
- };
362
- // Cleanup
363
- ChatbotEmbed.prototype.destroy = function () {
364
- // Remove DOM elements
365
- if (this.iframe) {
366
- document.body.removeChild(this.iframe);
367
- this.iframe = null;
368
- }
369
- if (this.logoContainer) {
370
- document.body.removeChild(this.logoContainer);
371
- this.logoContainer = null;
372
- }
373
- if (this.bubblePromptContainer) {
374
- document.body.removeChild(this.bubblePromptContainer);
375
- this.bubblePromptContainer = null;
376
- }
377
- // Remove event listeners
378
- window === null || window === void 0 ? void 0 : window.removeEventListener("message", this.onMessageListener);
379
- // Clear event handlers
380
- this.eventHandlers.clear();
381
- this.isInitialized = false;
382
- };
383
- // Private methods
384
- ChatbotEmbed.prototype.validateConfig = function () {
385
- if (!this.config.chatbotId) {
386
- console.error("ChatbotEmbed: Missing required chatbotId");
387
- return false;
388
- }
389
- return true;
390
- };
391
- ChatbotEmbed.prototype.setupEventListeners = function () {
392
- window === null || window === void 0 ? void 0 : window.addEventListener("message", this.onMessageListener);
393
- };
394
- ChatbotEmbed.prototype.init = function () {
395
- this.createIframe();
396
- this.createFloatingButton();
397
- };
398
- ChatbotEmbed.prototype.createFloatingButton = function () {
399
- var _this = this;
400
- var div = document.createElement("div");
401
- div.classList.add("message-bubble-container");
402
- Object.assign(div.style, {
403
- position: "fixed",
404
- bottom: "1.5rem",
405
- right: "1.5rem",
406
- zIndex: "1000",
407
- width: "48px",
408
- height: "48px",
409
- display: "flex",
410
- flexDirection: "column-reverse",
411
- backgroundColor: this.config.brand_colour,
412
- color: getBestFontColor(this.config.brand_colour),
413
- borderRadius: "50%",
414
- alignItems: "center",
415
- justifyContent: "center",
416
- cursor: "pointer",
417
- overflow: "hidden",
418
- });
419
- document.body.appendChild(div);
420
- this.logoContainer = div;
421
- this.loadImage(this.logoContainer);
422
- this.createChatBubblContainer();
423
- this.logoContainer.addEventListener("click", this.toggleIframe.bind(this));
424
- // Emit button loaded event
425
- setTimeout(function () {
426
- _this.emit("CHATBOT_BUTTON_LOADED");
427
- }, 0);
428
- };
429
- ChatbotEmbed.prototype.createChatBubblContainer = function () {
430
- var _this = this;
431
- var _a;
432
- var chatbaseContainer = document.createElement("div");
433
- chatbaseContainer.id = "chatbase-message-bubbles";
434
- Object.assign(chatbaseContainer.style, {
435
- position: "fixed",
436
- bottom: "80px",
437
- borderRadius: "10px",
438
- fontFamily: "sans-serif",
439
- fontSize: "16px",
440
- zIndex: "2147483644",
441
- cursor: "pointer",
442
- flexDirection: "column",
443
- gap: "50px",
444
- maxWidth: "70vw",
445
- display: "block",
446
- right: "1rem",
447
- left: "unset",
448
- });
449
- var closeButton = document.createElement("div");
450
- closeButton.classList.add("close-btn");
451
- closeButton.textContent = "✕";
452
- Object.assign(closeButton.style, {
453
- position: "absolute",
454
- top: "-7px",
455
- right: "-7px",
456
- fontWeight: "bold",
457
- display: "none",
458
- justifyContent: "center",
459
- alignItems: "center",
460
- zIndex: "2147483643",
461
- width: "22px",
462
- height: "22px",
463
- borderRadius: "50%",
464
- textAlign: "center",
465
- fontSize: "12px",
466
- cursor: "pointer",
467
- backgroundColor: "rgb(224, 224, 224)",
468
- color: "black",
469
- boxShadow: "rgba(150, 150, 150, 0.15) 0px 6px 24px 0px, rgba(150, 150, 150, 0.15) 0px 0px 0px 1px",
470
- });
471
- var prompts = ((_a = this.config.chat_interface_config) === null || _a === void 0 ? void 0 : _a.chat_bubble_prompts) || [];
472
- prompts.forEach(function (prompt) {
473
- var messageBubble = _this.createMessageBubble(prompt);
474
- chatbaseContainer.appendChild(messageBubble);
475
- });
476
- chatbaseContainer.appendChild(closeButton);
477
- document.body.appendChild(chatbaseContainer);
478
- };
479
- ChatbotEmbed.prototype.createMessageBubble = function (message) {
480
- var bubble = document.createElement("div");
481
- this.bubblePromptContainer = bubble;
482
- Object.assign(bubble.style, {
483
- display: "flex",
484
- position: "relative",
485
- justifyContent: "flex-end",
486
- });
487
- var messageContent = document.createElement("div");
488
- messageContent.classList.add("message");
489
- messageContent.textContent = message;
490
- Object.assign(messageContent.style, {
491
- backgroundColor: "white",
492
- color: "black",
493
- boxShadow: "rgba(150, 150, 150, 0.2) 0px 10px 30px 0px, rgba(150, 150, 150, 0.2) 0px 0px 0px 1px",
494
- borderRadius: "10px",
495
- padding: "8px 5px",
496
- margin: "8px",
497
- fontSize: "14px",
498
- opacity: "1",
499
- transform: "scale(1)",
500
- transition: "opacity 0.5s ease 0s, transform 0.5s ease 0s",
501
- });
502
- var closeButton = document.createElement("button");
503
- closeButton.innerHTML = "&times;";
504
- Object.assign(closeButton.style, {
505
- position: "absolute",
506
- top: "1px",
507
- left: "-3px",
508
- width: "20px",
509
- height: "20px",
510
- borderRadius: "50%",
511
- backgroundColor: "#fff",
512
- color: "#000",
513
- border: "none",
514
- cursor: "pointer",
515
- display: "flex",
516
- alignItems: "center",
517
- justifyContent: "center",
518
- boxShadow: "0 2px 5px rgba(0,0,0,0.2)",
519
- fontSize: "14px",
520
- lineHeight: "1",
521
- padding: "0",
522
- zIndex: "100",
523
- });
524
- closeButton.addEventListener("click", function () {
525
- bubble.remove();
526
- });
527
- bubble.appendChild(closeButton);
528
- bubble.appendChild(messageContent);
529
- return bubble;
530
- };
531
- ChatbotEmbed.prototype.createIframe = function () {
532
- var _this = this;
533
- var iframe = document.createElement("iframe");
534
- Object.assign(iframe.style, {
535
- position: "fixed",
536
- right: "32px",
537
- bottom: "86px",
538
- minWidth: "400px",
539
- width: "26%",
540
- maxWidth: "560px",
541
- top: "auto",
542
- maxHeight: "45rem",
543
- height: "calc(100vh - 3rem - 10vh)",
544
- zIndex: "20000000",
545
- border: "none",
546
- boxShadow: "0px 0px 40px 0px rgba(14, 14, 15, 0.24)",
547
- transformOrigin: "bottom right",
548
- transition: "transform 0.3s ease-out",
549
- borderRadius: "1rem",
550
- display: "none",
551
- });
552
- iframe.src = "".concat(this.config.domain, "/chatbot-plugin?id=").concat(this.config.chatbotId);
553
- document.body.appendChild(iframe);
554
- this.iframe = iframe;
555
- // Media Query Handling
556
- var applyStylesBasedOnScreenWidth = function () {
557
- if ((window === null || window === void 0 ? void 0 : window.innerWidth) < 560) {
558
- // Styles for screen width below 560px
559
- Object.assign(iframe.style, {
560
- width: "100vw",
561
- minWidth: "300px",
562
- right: "0",
563
- bottom: "0",
564
- height: "100vh",
565
- flexDirection: "column",
566
- flexGrow: "1",
567
- borderRadius: "0",
568
- top: "0",
569
- maxHeight: "100%",
570
- });
571
- }
572
- else {
573
- // Styles for screen width above 560px
574
- Object.assign(iframe.style, {
575
- width: "26%",
576
- maxWidth: "560px",
577
- minWidth: "400px",
578
- right: "32px",
579
- bottom: "86px",
580
- height: "calc(100vh - 3rem - 10vh)",
581
- borderRadius: "1rem",
582
- top: "auto",
583
- maxHeight: "45rem",
584
- });
585
- }
586
- };
587
- applyStylesBasedOnScreenWidth();
588
- // Set up window resize handler
589
- window === null || window === void 0 ? void 0 : window.addEventListener("resize", applyStylesBasedOnScreenWidth);
590
- // Set up iframe load handler
591
- iframe.addEventListener("load", function () {
592
- var _a, _b, _c, _d;
593
- if (!_this.iframe)
594
- return;
595
- var targetOrigin = new URL(_this.iframe.src).origin || _this.config.domain;
596
- (_a = iframe.contentWindow) === null || _a === void 0 ? void 0 : _a.postMessage({ domain: (_b = window === null || window === void 0 ? void 0 : window.location) === null || _b === void 0 ? void 0 : _b.hostname, name: "checkDomain" }, targetOrigin);
597
- (_c = iframe.contentWindow) === null || _c === void 0 ? void 0 : _c.postMessage({
598
- domain: (_d = window === null || window === void 0 ? void 0 : window.location) === null || _d === void 0 ? void 0 : _d.hostname,
599
- action: "registerUserId",
600
- data: {
601
- userId: _this.config.userId,
602
- token: _this.config.token,
603
- userProfile: _this.config.userProfile,
604
- isAnonymous: _this.config.isAnonymous,
605
- },
606
- }, targetOrigin);
607
- });
608
- };
609
- ChatbotEmbed.prototype.loadImage = function (containerElement) {
610
- var image = document.createElement("img");
611
- image.src = this.config.image_url || "".concat(this.config.domain, "/chatbubble.png");
612
- image.alt = "Chat";
613
- Object.assign(image.style, {
614
- zIndex: "1000",
615
- cursor: "pointer",
616
- borderRadius: "50%",
617
- objectFit: "cover",
618
- width: "100%",
619
- height: "100%",
620
- });
621
- this.chatBtnImage = image;
622
- containerElement.innerHTML = ""; // Clear any existing content
623
- containerElement.appendChild(image);
624
- };
625
- ChatbotEmbed.prototype.loadSvgInline = function (containerElement) {
626
- var svgChevronDown = "\n<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <g id=\"Chevron_Down\">\n <path id=\"Vector\" d=\"M19 9L12 16L5 9\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n </g>\n</svg>\n";
627
- // Create a temporary container to insert the SVG content
628
- var tempDiv = document.createElement("div");
629
- tempDiv.innerHTML = svgChevronDown;
630
- // Find the <svg> element
631
- var svgElement = tempDiv.querySelector("svg");
632
- // Clear the existing content in the container and inject the SVG
633
- containerElement.innerHTML = ""; // Clear any existing content
634
- if (svgElement) {
635
- containerElement.appendChild(svgElement);
636
- }
637
- };
638
- ChatbotEmbed.prototype.toggleIcon = function (containerElement, iframe) {
639
- if (iframe.style.display === "block") {
640
- // Load the SVG Chevron Down when iframe is visible
641
- this.loadSvgInline(containerElement);
642
- }
643
- else {
644
- // Load the image when iframe is hidden
645
- this.loadImage(containerElement);
646
- }
647
- };
648
- ChatbotEmbed.prototype.toggleIframe = function () {
649
- if (!this.iframe || !this.logoContainer || !this.chatBtnImage)
650
- return;
651
- if (this.iframe.style.display === "none") {
652
- this.showIframe();
653
- this.emit("CHATBOT_BUTTON_CLICKED");
654
- this.emit("CHATBOT_OPENED");
655
- }
656
- else {
657
- this.closeIframe();
658
- this.emit("CHATBOT_CLOSED");
659
- }
660
- };
661
- ChatbotEmbed.prototype.showIframe = function () {
662
- var _a;
663
- if (!this.iframe || !this.logoContainer || !this.chatBtnImage)
664
- return;
665
- var targetOrigin = new URL(this.iframe.src).origin || this.config.domain;
666
- this.iframe.style.display = "block";
667
- (_a = this.iframe.contentWindow) === null || _a === void 0 ? void 0 : _a.postMessage({
668
- domain: window === null || window === void 0 ? void 0 : window.location.hostname,
669
- name: "openFrame",
670
- }, targetOrigin);
671
- this.toggleIcon(this.logoContainer, this.iframe);
672
- this.chatBtnImage.style.objectFit = "none";
673
- if (this.bubblePromptContainer) {
674
- this.bubblePromptContainer.style.display = "none";
675
- }
676
- };
677
- ChatbotEmbed.prototype.closeIframe = function () {
678
- if (!this.iframe || !this.logoContainer || !this.chatBtnImage)
679
- return;
680
- this.iframe.style.display = "none";
681
- this.toggleIcon(this.logoContainer, this.iframe);
682
- this.chatBtnImage.style.objectFit = "cover";
683
- };
684
- ChatbotEmbed.prototype.adjustIframeWidth = function () {
685
- if (!this.iframe)
686
- return;
687
- var screenWidth = window === null || window === void 0 ? void 0 : window.innerWidth;
688
- if (screenWidth < 832) {
689
- this.iframe.style.width = "".concat(screenWidth - 64, "px");
690
- }
691
- else {
692
- this.iframe.style.width = "800px";
693
- }
694
- };
695
- ChatbotEmbed.prototype.handleCaptureSessionData = function () {
696
- var _a, _b;
697
- if (!this.iframe)
698
- return;
699
- var data = {
700
- cookies: getCookies(), // TODO: Handle the isTeachmint parameter better
701
- localStorage: getLocalStorage(),
702
- sessionStorage: getSessionStorage(),
703
- action: "capturedSessionData",
704
- domain_name: (_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 ? void 0 : _a.hostname,
705
- user_profile: this.config.userProfile,
706
- };
707
- (_b = this.iframe.contentWindow) === null || _b === void 0 ? void 0 : _b.postMessage(data, this.config.domain || "*");
708
- };
709
- return ChatbotEmbed;
710
- }());
711
-
712
- /**
713
- * Environment configuration for the SDK
714
- */
715
- // Get current environment from build-time
716
- var NODE_ENV = "staging" ;
717
- // Default configuration values based on environment
718
- var DEFAULT_CONFIG = {
719
- // Default URLs for each environment
720
- copilotUrl: {
721
- development: "https://dev.robylon.ai",
722
- staging: "https://staging.d2s3wsqyyond1h.amplifyapp.com",
723
- production: "https://app.robylon.ai",
724
- },
725
- environment: NODE_ENV,
726
- apiUrl: {
727
- development: "https://dev-api.robylon.ai",
728
- staging: "https://stage-api.robylon.ai",
729
- production: "https://api.robylon.ai",
730
- },
731
- };
732
- // Store custom config values
733
- var customConfig = {};
734
- /**
735
- * Set custom environment configuration
736
- */
737
- var setEnvironmentConfig = function (config) {
738
- customConfig = __assign(__assign({}, customConfig), config);
739
- };
740
- /**
741
- * Gets environment configuration with defaults
742
- */
743
- var getEnvironmentConfig = function () {
744
- // Determine current environment
745
- var environment = customConfig.environment || NODE_ENV;
746
- // Ensure we pick URLs appropriate for the current environment
747
- var envType = environment === "staging"
748
- ? "staging"
749
- : environment === "development"
750
- ? "development"
751
- : "production";
752
- // Get default values for current environment
753
- var defaultCopilotUrl = DEFAULT_CONFIG.copilotUrl[envType];
754
- var defaultApiUrl = DEFAULT_CONFIG.apiUrl[envType];
755
- return {
756
- copilotUrl: customConfig.copilotUrl || defaultCopilotUrl,
757
- environment: environment,
758
- apiUrl: customConfig.apiUrl || defaultApiUrl,
759
- };
760
- };
761
-
762
- /**
763
- * Simple logger class with configurable log level
764
- */
765
- var Logger = /** @class */ (function () {
766
- function Logger() {
767
- this.level = "info";
768
- this.isEnabled = true;
769
- }
770
- /**
771
- * Set the log level
772
- */
773
- Logger.prototype.setLevel = function (level) {
774
- this.level = level;
775
- };
776
- /**
777
- * Enable or disable logging
778
- */
779
- Logger.prototype.setEnabled = function (enabled) {
780
- this.isEnabled = enabled;
781
- };
782
- /**
783
- * Log debug level messages
784
- */
785
- Logger.prototype.debug = function () {
786
- var args = [];
787
- for (var _i = 0; _i < arguments.length; _i++) {
788
- args[_i] = arguments[_i];
789
- }
790
- if (!this.isEnabled || this.level === "none")
791
- return;
792
- if (["debug"].includes(this.level)) {
793
- console.debug.apply(console, __spreadArray(["[Robylon Debug]"], args, false));
794
- }
795
- };
796
- /**
797
- * Log informational messages
798
- */
799
- Logger.prototype.log = function () {
800
- var args = [];
801
- for (var _i = 0; _i < arguments.length; _i++) {
802
- args[_i] = arguments[_i];
803
- }
804
- if (!this.isEnabled || this.level === "none")
805
- return;
806
- if (["debug", "info"].includes(this.level)) {
807
- console.log.apply(console, __spreadArray(["[Robylon]"], args, false));
808
- }
809
- };
810
- /**
811
- * Log warning messages
812
- */
813
- Logger.prototype.warn = function () {
814
- var args = [];
815
- for (var _i = 0; _i < arguments.length; _i++) {
816
- args[_i] = arguments[_i];
817
- }
818
- if (!this.isEnabled || this.level === "none")
819
- return;
820
- if (["debug", "info", "warn"].includes(this.level)) {
821
- console.warn.apply(console, __spreadArray(["[Robylon Warn]"], args, false));
822
- }
823
- };
824
- /**
825
- * Log error messages
826
- */
827
- Logger.prototype.error = function () {
828
- var args = [];
829
- for (var _i = 0; _i < arguments.length; _i++) {
830
- args[_i] = arguments[_i];
831
- }
832
- if (!this.isEnabled || this.level === "none")
833
- return;
834
- if (["debug", "info", "warn", "error"].includes(this.level)) {
835
- console.error.apply(console, __spreadArray(["[Robylon Error]"], args, false));
836
- }
837
- };
838
- return Logger;
839
- }());
840
- /**
841
- * Singleton logger instance
842
- */
843
- var logger = new Logger();
844
-
845
- /**
846
- * Error codes for API operations
847
- */
848
- var ApiErrorCode;
849
- (function (ApiErrorCode) {
850
- ApiErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR";
851
- ApiErrorCode["API_REQUEST_FAILED"] = "API_REQUEST_FAILED";
852
- ApiErrorCode["INVALID_RESPONSE"] = "INVALID_RESPONSE";
853
- ApiErrorCode["MISSING_API_KEY"] = "MISSING_API_KEY";
854
- })(ApiErrorCode || (ApiErrorCode = {}));
855
- /**
856
- * API error class for better error handling
857
- */
858
- var ApiError = /** @class */ (function (_super) {
859
- __extends(ApiError, _super);
860
- function ApiError(message, code, context) {
861
- if (context === void 0) { context = {}; }
862
- var _this = _super.call(this, message) || this;
863
- _this.name = "ApiError";
864
- _this.code = code;
865
- _this.context = context;
866
- return _this;
867
- }
868
- return ApiError;
869
- }(Error));
870
- /**
871
- * Fetch chatbot configuration from API
872
- */
873
- var fetchChatbotConfig = function (chatbotId, userId, token) { return __awaiter(void 0, void 0, void 0, function () {
874
- var apiUrl, endpointUrl, payload, response, errorText, data, error_1;
875
- var _a;
876
- return __generator(this, function (_b) {
877
- switch (_b.label) {
878
- case 0:
879
- if (!chatbotId) {
880
- throw new ApiError("Missing required API key", ApiErrorCode.MISSING_API_KEY, { chatbotId: chatbotId });
881
- }
882
- apiUrl = getEnvironmentConfig().apiUrl;
883
- endpointUrl = "".concat(apiUrl, "/chat/chatbot/get/");
884
- payload = {
885
- client_user_id: userId,
886
- org_id: chatbotId,
887
- token: token || undefined,
888
- extra_info: {},
889
- };
890
- _b.label = 1;
891
- case 1:
892
- _b.trys.push([1, 6, , 7]);
893
- logger.log("Fetching chatbot config from ".concat(endpointUrl));
894
- return [4 /*yield*/, fetch(endpointUrl, {
895
- method: "POST",
896
- headers: {
897
- "Content-Type": "application/json",
898
- },
899
- body: JSON.stringify(payload),
900
- })];
901
- case 2:
902
- response = _b.sent();
903
- if (!!response.ok) return [3 /*break*/, 4];
904
- return [4 /*yield*/, response.text()];
905
- case 3:
906
- errorText = _b.sent();
907
- throw new ApiError("API request failed with status ".concat(response.status, ": ").concat(errorText), ApiErrorCode.API_REQUEST_FAILED, {
908
- statusCode: response.status,
909
- errorText: errorText,
910
- payload: payload,
911
- });
912
- case 4: return [4 /*yield*/, response.json()];
913
- case 5:
914
- data = _b.sent();
915
- // Validate the response structure
916
- if (!((_a = data === null || data === void 0 ? void 0 : data.user) === null || _a === void 0 ? void 0 : _a.org_info)) {
917
- throw new ApiError("Invalid API response: missing required fields", ApiErrorCode.INVALID_RESPONSE, {
918
- missingFields: ["user", "org_info"],
919
- responseData: data,
920
- });
921
- }
922
- return [2 /*return*/, data];
923
- case 6:
924
- error_1 = _b.sent();
925
- // If it's already an ApiError, just rethrow it
926
- if (error_1 instanceof ApiError) {
927
- throw error_1;
928
- }
929
- // Otherwise wrap in a generic network error
930
- throw new ApiError("Network error: ".concat(error_1 instanceof Error ? error_1.message : String(error_1)), ApiErrorCode.NETWORK_ERROR, {
931
- chatbotId: chatbotId,
932
- userId: userId,
933
- apiUrl: apiUrl,
934
- originalError: error_1,
935
- timestamp: Date.now(),
936
- });
937
- case 7: return [2 /*return*/];
938
- }
939
- });
940
- }); };
941
-
942
- /**
943
- * System information detection utilities
944
- */
945
- // Define the SDK version - this will be updated by the build process
946
- var SDK_VERSION = "1.0.0";
947
- /**
948
- * Detect the operating system from the user agent
949
- */
950
- var detectOS = function () {
951
- var _a;
952
- if (typeof navigator === "undefined")
953
- return "Unknown";
954
- return (((_a = navigator.userAgentData) === null || _a === void 0 ? void 0 : _a.platform) ||
955
- (/Windows|Mac|Linux|Android|iOS/.exec(navigator.userAgent) || [
956
- "Unknown",
957
- ])[0]);
958
- };
959
- /**
960
- * Detect the browser from the user agent
961
- */
962
- var detectBrowser = function () {
963
- var _a;
964
- if (typeof navigator === "undefined")
965
- return "Unknown";
966
- // Try to get the most relevant brand from userAgentData
967
- if ((_a = navigator.userAgentData) === null || _a === void 0 ? void 0 : _a.brands) {
968
- var brands = navigator.userAgentData.brands;
969
- // Look for known browsers in order of preference
970
- var knownBrands = ["Chrome", "Firefox", "Safari", "Edge", "Opera"];
971
- for (var _i = 0, brands_1 = brands; _i < brands_1.length; _i++) {
972
- var brand = brands_1[_i];
973
- if (knownBrands.includes(brand.brand)) {
974
- return brand.brand;
975
- }
976
- }
977
- }
978
- // Fallback to userAgent parsing
979
- return (/Chrome|Firefox|Safari|Edge|Opera/.exec(navigator.userAgent) || [
980
- "Unknown",
981
- ])[0];
982
- };
983
- /**
984
- * Detect the device type from the user agent
985
- */
986
- var detectDevice = function () {
987
- if (typeof navigator === "undefined")
988
- return "Unknown";
989
- var userAgent = navigator.userAgent.toLowerCase();
990
- if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(userAgent)) {
991
- return "tablet";
992
- }
993
- if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(userAgent)) {
994
- return "mobile";
995
- }
996
- return "desktop";
997
- };
998
- /**
999
- * Get the screen dimensions
1000
- */
1001
- var getScreenSize = function () {
1002
- var _a, _b, _c, _d;
1003
- if (typeof window === "undefined" || typeof document === "undefined") {
1004
- return { width: 0, height: 0 };
1005
- }
1006
- return {
1007
- width: (window === null || window === void 0 ? void 0 : window.innerWidth) ||
1008
- ((_a = document === null || document === void 0 ? void 0 : document.documentElement) === null || _a === void 0 ? void 0 : _a.clientWidth) ||
1009
- ((_b = document === null || document === void 0 ? void 0 : document.body) === null || _b === void 0 ? void 0 : _b.clientWidth) ||
1010
- 0,
1011
- height: (window === null || window === void 0 ? void 0 : window.innerHeight) ||
1012
- ((_c = document === null || document === void 0 ? void 0 : document.documentElement) === null || _c === void 0 ? void 0 : _c.clientHeight) ||
1013
- ((_d = document === null || document === void 0 ? void 0 : document.body) === null || _d === void 0 ? void 0 : _d.clientHeight) ||
1014
- 0,
1015
- };
1016
- };
1017
- /**
1018
- * Get complete system information
1019
- */
1020
- var getSystemInfo = function () {
1021
- return {
1022
- platform: "web",
1023
- os: detectOS(),
1024
- browser: detectBrowser(),
1025
- sdk_version: SDK_VERSION,
1026
- device: detectDevice(),
1027
- screen_size: getScreenSize(),
1028
- };
1029
- };
1030
-
1031
- /**
1032
- * Initialize the SDK with custom environment settings
1033
- * @internal This is primarily for internal use and advanced debugging.
1034
- * Normal users should not need to call this function.
1035
- */
1036
- function init(config) {
1037
- // For internal SDK initialization - not intended for general user use
1038
- // We prioritize built-in environment settings based on NODE_ENV
1039
- // Get current environment from build-time
1040
- var currentEnv = "staging" ;
1041
- // Default environment-specific API URLs
1042
- var defaultApiUrls = {
1043
- development: "https://dev-api.robylon.ai",
1044
- staging: "https://stage-api.robylon.ai",
1045
- production: "https://api.robylon.ai",
1046
- };
1047
- // Default environment-specific Copilot URLs
1048
- var defaultCopilotUrls = {
1049
- development: "https://dev.robylon.ai",
1050
- staging: "https://staging.d2s3wsqyyond1h.amplifyapp.com",
1051
- production: "https://app.robylon.ai",
1052
- };
1053
- // Only override with user values in non-production environments or if explicitly allowed
1054
- var isProduction = currentEnv === "production";
1055
- config.allowProductionOverride === "true" && isProduction;
1056
- {
1057
- // Use environment-specific defaults as fallbacks
1058
- var configWithDefaults = __assign(__assign({}, config), { apiUrl: config.apiUrl ||
1059
- defaultApiUrls[currentEnv], copilotUrl: config.copilotUrl ||
1060
- defaultCopilotUrls[currentEnv], environment: config.environment || currentEnv });
1061
- setEnvironmentConfig(configWithDefaults);
1062
- logger.log("Robylon SDK environment initialized with custom config", configWithDefaults);
1063
- }
1064
- }
1065
- /**
1066
- * Create a new Robylon chatbot instance
1067
- */
1068
- function create(config) {
1069
- return __awaiter(this, void 0, void 0, function () {
1070
- var userId, isAnonymous, systemInfo_1, apiResponse, userProfile, chatbotConfig, chatbotEmbed_1, error_1;
1071
- var _a, _b, _c, _d, _e, _f, _g;
1072
- return __generator(this, function (_h) {
1073
- switch (_h.label) {
1074
- case 0:
1075
- if (!config.api_key) {
1076
- throw new Error("api_key is required to create a chatbot instance");
1077
- }
1078
- _h.label = 1;
1079
- case 1:
1080
- _h.trys.push([1, 3, , 4]);
1081
- userId = config.user_id;
1082
- isAnonymous = false;
1083
- // Handle anonymous users
1084
- if (!userId) {
1085
- userId = getCookie("rblyn_anon") || generateUUID();
1086
- setCookie("rblyn_anon", String(userId), 365);
1087
- isAnonymous = true;
1088
- }
1089
- systemInfo_1 = getSystemInfo();
1090
- return [4 /*yield*/, fetchChatbotConfig(config.api_key, userId, config.user_token)];
1091
- case 2:
1092
- apiResponse = _h.sent();
1093
- userProfile = __assign(__assign({}, systemInfo_1), config.user_profile);
1094
- chatbotConfig = {
1095
- chatbotId: config.api_key,
1096
- userId: userId,
1097
- token: config.user_token,
1098
- isAnonymous: isAnonymous,
1099
- domain: getEnvironmentConfig().copilotUrl,
1100
- brand_colour: ((_b = (_a = apiResponse.user.org_info.brand_config) === null || _a === void 0 ? void 0 : _a.colors) === null || _b === void 0 ? void 0 : _b.brand_color) ||
1101
- "#6a26cd",
1102
- image_url: ((_d = (_c = apiResponse.user.org_info) === null || _c === void 0 ? void 0 : _c.brand_config) === null || _d === void 0 ? void 0 : _d.launcher_logo_url) || "",
1103
- userProfile: userProfile,
1104
- chat_interface_config: {
1105
- chat_bubble_prompts: [],
1106
- display_name: ((_e = apiResponse.user.org_info.brand_config) === null || _e === void 0 ? void 0 : _e.display_name) || "",
1107
- welcome_message: ((_f = apiResponse.user.org_info.brand_config) === null || _f === void 0 ? void 0 : _f.welcome_message) ||
1108
- "Hey! What can we help you with today?",
1109
- redirect_url: ((_g = apiResponse.user.org_info.brand_config) === null || _g === void 0 ? void 0 : _g.redirect_url) || "",
1110
- },
1111
- };
1112
- chatbotEmbed_1 = new ChatbotEmbed(chatbotConfig);
1113
- // Set up event handler
1114
- if (config.onEvent) {
1115
- chatbotEmbed_1.on("*", config.onEvent);
1116
- }
1117
- // Return public API
1118
- return [2 /*return*/, {
1119
- show: function () { return chatbotEmbed_1.show(); },
1120
- hide: function () { return chatbotEmbed_1.hide(); },
1121
- toggle: function () { return chatbotEmbed_1.toggle(); },
1122
- update: function (newConfig) {
1123
- // Handle profile updates
1124
- if (newConfig.user_profile) {
1125
- chatbotEmbed_1.updateConfig({
1126
- userProfile: __assign(__assign({}, systemInfo_1), newConfig.user_profile),
1127
- });
1128
- }
1129
- // Handle user_id updates
1130
- if (newConfig.user_id !== undefined) {
1131
- chatbotEmbed_1.updateConfig({
1132
- userId: newConfig.user_id ? String(newConfig.user_id) : null,
1133
- });
1134
- }
1135
- // Handle token updates
1136
- if (newConfig.user_token !== undefined) {
1137
- chatbotEmbed_1.updateConfig({
1138
- token: newConfig.user_token,
1139
- });
1140
- }
1141
- },
1142
- destroy: function () { return chatbotEmbed_1.destroy(); },
1143
- }];
1144
- case 3:
1145
- error_1 = _h.sent();
1146
- logger.error("Failed to create chatbot instance:", error_1);
1147
- if (error_1 instanceof ApiError) {
1148
- throw new Error("Robylon SDK initialization failed: ".concat(error_1.message, " (").concat(error_1.code, ")"));
1149
- }
1150
- throw new Error("Robylon SDK initialization failed: ".concat(error_1 instanceof Error ? error_1.message : String(error_1)));
1151
- case 4: return [2 /*return*/];
1152
- }
1153
- });
1154
- });
1155
- }
1156
-
1157
- // Conditionally import React components to avoid errors in environments without React
1158
- var RobylonChatbot = null;
1159
- // Try to import React components, but don't fail if React is not available
1160
- try {
1161
- // Import React components
1162
- var ReactImports = require("./react/components/Chatbot");
1163
- RobylonChatbot = ReactImports.default || ReactImports.Chatbot;
1164
- }
1165
- catch (e) {
1166
- // React not available, provide a placeholder
1167
- RobylonChatbot = function () {
1168
- throw new Error("React is required to use the Chatbot component");
1169
- };
1170
- }
1171
- // Export the Chatbot component for compatibility if available
1172
- var Chatbot = RobylonChatbot;
1173
- // Expose the public API
1174
- var Robylon = {
1175
- /**
1176
- * Create a new Robylon chatbot instance
1177
- */
1178
- create: create,
1179
- /**
1180
- * Initialize the SDK with custom environment settings
1181
- */
1182
- init: init,
1183
- /**
1184
- * The Chatbot React component
1185
- */
1186
- Chatbot: RobylonChatbot,
1187
- /**
1188
- * Configure logging
1189
- */
1190
- logging: {
1191
- /**
1192
- * Enable or disable logging
1193
- */
1194
- setEnabled: function (enabled) { return logger.setEnabled(enabled); },
1195
- /**
1196
- * Set log level
1197
- */
1198
- setLevel: function (level) {
1199
- return logger.setLevel(level);
1200
- },
1201
- },
1202
- };
1203
- // For UMD/global environments
1204
- if (typeof window !== "undefined") {
1205
- window.Robylon = Robylon;
1206
- }
1207
-
1208
- export { Chatbot, create, Robylon as default, init };
1
+ import e,{memo as t,useRef as n,useState as i,useEffect as o,useCallback as r,Component as a,useMemo as s}from"react";var l=function(e,t){return l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},l(e,t)};var c,d,u,p=function(){return p=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},p.apply(this,arguments)};function f(e,t,n,i){return new(n||(n=Promise))((function(o,r){function a(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}l((i=i.apply(e,t||[])).next())}))}function h(e,t){var n,i,o,r={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(l){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(r=0)),r;)try{if(n=1,i&&(o=2&s[0]?i.return:s[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,s[1])).done)return o;switch(i=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return r.label++,{value:s[1],done:!1};case 5:r.label++,i=s[1],s=[0];continue;case 7:s=r.ops.pop(),r.trys.pop();continue;default:if(!(o=r.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){r=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){r.label=s[1];break}if(6===s[0]&&r.label<o[1]){r.label=o[1],o=s;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(s);break}o[2]&&r.ops.pop(),r.trys.pop();continue}s=t.call(e,r)}catch(e){s=[6,e],i=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,l])}}}"function"==typeof SuppressedError&&SuppressedError,function(e){e.WIDGET="WIDGET",e.POPOVER="POPOVER",e.EMBED="EMBED"}(c||(c={})),function(e){e.RIGHT="Right",e.LEFT="Left"}(d||(d={})),function(e){e.TEXT="TEXT",e.IMAGE="IMAGE",e.TEXTUAL_IMAGE="TEXTUAL_IMAGE"}(u||(u={}));var g=function(e,t){void 0===t&&(t=.5);var n=function(e){e=e.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(function(e,t,n,i){return t+t+n+n+i+i}));var t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:{r:0,g:0,b:0}}(e),i=function(e,t,n){var i=[e,t,n].map((function(e){return(e/=255)<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}));return.2126*i[0]+.7152*i[1]+.0722*i[2]}(n.r,n.g,n.b);return i>t?"#0E0E0F":"#FFFFFF"},m={log:function(){},error:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.error.apply(console,e)},warn:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.warn.apply(console,e)},info:function(){}};m.log("Raw API_URL:","https://api.robylon.ai");var v={copilotUrl:"https://chatbot.robylon.ai",environment:"production",apiUrl:"https://api.robylon.ai"};m.log("CONFIG",v);var b,w,y=function(){return"undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement},E=function(){return{copilotUrl:v.copilotUrl||"https://app.robylon.ai",environment:v.environment||"production",apiUrl:v.apiUrl||"https://app.robylon.ai"}};!function(e){e.CHATBOT_BUTTON_LOADED="CHATBOT_BUTTON_LOADED",e.CHATBOT_BUTTON_CLICKED="CHATBOT_BUTTON_CLICKED",e.CHATBOT_OPENED="CHATBOT_OPENED",e.CHATBOT_CLOSED="CHATBOT_CLOSED",e.CHATBOT_APP_READY="CHATBOT_APP_READY",e.CHATBOT_LOADED="CHATBOT_LOADED",e.CHAT_INITIALIZED="CHAT_INITIALIZED",e.SESSION_REFRESHED="SESSION_REFRESHED",e.CHAT_INITIALIZATION_FAILED="CHAT_INITIALIZATION_FAILED"}(b||(b={})),function(e){e.CHAT_MOVED="CHAT_MOVED",e.CHATBOT_TOKEN_EXHAUSTED="CHATBOT_TOKEN_EXHAUSTED"}(w||(w={}));var _,I="system-ui, Inter, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'",x="21px",T=t((function(t){var r,a,s,l,c,d,f,h=t.config,v=t.toggleIframe,w=t.isIframeVisible,y=t.onEvent,_=t.onInternalEvent,T=t.position,C=t.sideSpacing,S=t.bottomSpacing,O=n(null),A=E().copilotUrl,R=i(!1),D=R[0],k=R[1];o((function(){var e=function(){var e=(null===window||void 0===window?void 0:window.innerWidth)<560;k(e)};return e(),window.addEventListener("resize",e),function(){window.removeEventListener("resize",e)}}),[]),o((function(){O.current&&requestAnimationFrame((function(){null==y||y({type:b.CHATBOT_BUTTON_LOADED,timestamp:Date.now()}),_(b.CHATBOT_BUTTON_LOADED)}))}),[y,_]);var L={zIndex:1e3,display:"flex",flexDirection:"column-reverse",alignItems:"center",justifyContent:"center",cursor:"pointer",overflow:"hidden",marginTop:"16px",boxSizing:"border-box"};h.launcher_type===u.IMAGE&&(L.width="48px",L.height="48px",L.borderRadius="50%",L.backgroundColor=h.brand_colour);var z=T||(null===(s=h.interface_properties)||void 0===s?void 0:s.position)||"Right",N=null!==(c=null!=C?C:null===(l=h.interface_properties)||void 0===l?void 0:l.side_spacing)&&void 0!==c?c:20,M=null!==(f=null!=S?S:null===(d=h.interface_properties)||void 0===d?void 0:d.bottom_spacing)&&void 0!==f?f:20,H=p(p({},L),((r={position:void 0,bottom:"0",borderRadius:(null==h?void 0:h.launcher_type)&&(null==h?void 0:h.launcher_type)!==u.IMAGE?"9999px":"50%"})[z.toLowerCase()]="0",r)),B=p(p({},L),((a={position:"fixed",bottom:"".concat(M,"px"),borderRadius:(null==h?void 0:h.launcher_type)&&(null==h?void 0:h.launcher_type)!==u.IMAGE?"9999px":"50%"})[z.toLowerCase()]="".concat(N,"px"),a)),j=D?B:H;o((function(){m.log("Screen width changed, isMobile:",D,"Style:",j)}),[D,j]),m.log("config in floating button",h);return e.createElement("div",{ref:O,className:"message-bubble-container",style:p(p({},j),{transition:"transform 0.2s cubic-bezier(0.2, 1.27, 0.29, 0.97)",transform:w?"scale(0.85)":"scale(1)"}),onClick:v},function(){switch(h.launcher_type){case u.TEXT:return function(){var t;return e.createElement("div",{style:{width:"fit-content",maxWidth:"160px",height:"40px",borderRadius:"9999px",backgroundColor:h.brand_colour,display:"flex",alignItems:"center",padding:"9px 20px",boxShadow:"0px 0px 16px 0px rgba(0, 0, 0, 0.24)",boxSizing:"border-box",fontFamily:I,lineHeight:x}},e.createElement("div",{style:{flex:1,minWidth:0}},e.createElement("p",{style:{margin:0,color:g(h.brand_colour),fontSize:"0.875rem",fontWeight:600,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontFamily:I,lineHeight:x,WebkitFontSmoothing:"antialiased",textRendering:"optimizeLegibility",textSizeAdjust:"100%"}},null===(t=h.launcher_properties)||void 0===t?void 0:t.text)))}();case u.TEXTUAL_IMAGE:return function(){var t,n,i;return e.createElement("div",{style:{maxWidth:"13rem",width:"fit-content",height:"40px",borderRadius:"9999px",backgroundColor:h.brand_colour,display:"flex",alignItems:"center",paddingLeft:"20px",paddingRight:0,paddingTop:"9px",paddingBottom:"9px",boxShadow:"0px 0px 16px 0px rgba(0, 0, 0, 0.24)",gap:"8px",boxSizing:"border-box",fontFamily:I,lineHeight:x}},e.createElement("div",{style:{flex:1,minWidth:0}},e.createElement("p",{style:{margin:0,color:g(h.brand_colour),fontSize:"0.875rem",fontWeight:600,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontFamily:I,lineHeight:x,WebkitFontSmoothing:"antialiased",textRendering:"optimizeLegibility",textSizeAdjust:"100%"}},null===(t=h.launcher_properties)||void 0===t?void 0:t.text)),e.createElement("div",{style:{width:"40px",height:"40px",borderRadius:"9999px",overflow:"hidden",position:"relative",flexShrink:0}},e.createElement("img",{src:(null==h?void 0:h.launcher_type)?(null===(i=null===(n=null==h?void 0:h.images)||void 0===n?void 0:n.launcher_image_url)||void 0===i?void 0:i.url)||"".concat(A,"/chatbubble.png"):(null==h?void 0:h.image_url)||"".concat(A,"/chatbubble.png"),alt:"Chat",style:{width:"100%",height:"100%",objectFit:"cover"}})))}();case u.IMAGE:default:return function(){var t,n;return w?e.createElement("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},e.createElement("g",{id:"Chevron_Down"},e.createElement("path",{id:"Vector",d:"M19 9L12 16L5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}))):e.createElement("img",{src:(null==h?void 0:h.launcher_type)?(null===(n=null===(t=null==h?void 0:h.images)||void 0===t?void 0:t.launcher_image_url)||void 0===n?void 0:n.url)||"".concat(A,"/chatbubble.png"):(null==h?void 0:h.image_url)||"".concat(A,"/chatbubble.png"),alt:"Chat",style:{zIndex:1e3,cursor:"pointer",borderRadius:"50%",objectFit:"cover",width:"100%",height:"100%",boxSizing:"border-box"}})}()}}())})),C=function(){var e;return(null===(e=navigator.userAgentData)||void 0===e?void 0:e.platform)||(/Windows|Mac|Linux|Android|iOS/.exec(navigator.userAgent)||["Unknown"])[0]},S=function(){var e;if(null===(e=navigator.userAgentData)||void 0===e?void 0:e.brands)for(var t=["Chrome","Firefox","Safari","Edge","Opera"],n=0,i=navigator.userAgentData.brands;n<i.length;n++){var o=i[n];if(t.includes(o.brand))return o.brand}return(/Chrome|Firefox|Safari|Edge|Opera/.exec(navigator.userAgent)||["Unknown"])[0]},O=function(){var e,t,n,i;return{width:(null===window||void 0===window?void 0:window.innerWidth)||(null===(e=null===document||void 0===document?void 0:document.documentElement)||void 0===e?void 0:e.clientWidth)||(null===(t=null===document||void 0===document?void 0:document.body)||void 0===t?void 0:t.clientWidth),height:(null===window||void 0===window?void 0:window.innerHeight)||(null===(n=null===document||void 0===document?void 0:document.documentElement)||void 0===n?void 0:n.clientHeight)||(null===(i=null===document||void 0===document?void 0:document.body)||void 0===i?void 0:i.clientHeight)}},A=function(){return{platform:"web",os:C(),browser:S(),sdk_version:"1.1.29",device:(e=navigator.userAgent.toLowerCase(),/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(e)?"tablet":/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(e)?"mobile":"desktop"),screen_size:O()};var e};!function(e){e.ERROR="ERROR",e.INFO="INFO"}(_||(_={}));var R,D=["@robylon/web-react-sdk","node_modules/@robylon/web-react-sdk/"],k=function(e){var t=e.filename,n=e.stack,i=e.message;return!!(t||n||i)&&D.some((function(e){return(null==t?void 0:t.includes(e))||(null==n?void 0:n.includes(e))||(null==i?void 0:i.includes(e))}))},L=function(){function e(){var e=this;this.apiKey="",this.userId=null,this.preInitQueue=[],this.isInitialized=!1,this.handleWindowError=function(t){var n,i={filename:t.filename,stack:null===(n=t.error)||void 0===n?void 0:n.stack,message:t.message};k(i)&&e.trackError(t.error||t.message,"GlobalErrorHandler",{filename:t.filename,lineNo:t.lineno,colNo:t.colno})},this.handleUnhandledRejection=function(t){var n,i,o={stack:null===(n=t.reason)||void 0===n?void 0:n.stack,message:(null===(i=t.reason)||void 0===i?void 0:i.message)||String(t.reason)};k(o)&&e.trackError(t.reason||"Unhandled Promise Rejection","GlobalPromiseHandler",{reason:t.reason})},this.setupGlobalHandlers()}return e.prototype.setupGlobalHandlers=function(){y()&&(null===window||void 0===window||window.addEventListener("error",null==this?void 0:this.handleWindowError),null===window||void 0===window||window.addEventListener("unhandledrejection",this.handleUnhandledRejection))},e.prototype.cleanup=function(){y()&&(null===window||void 0===window||window.removeEventListener("error",null==this?void 0:this.handleWindowError),null===window||void 0===window||window.removeEventListener("unhandledrejection",this.handleUnhandledRejection))},e.getInstance=function(){return e.instance||(e.instance=new e),e.instance},e.prototype.initialize=function(e,t){void 0===t&&(t=null);try{if(this.preInitQueue.length>0){var n={org_id:"UNINITALIZED",event_data:{message:"SDK Initialization Failed: Required parameter 'api_key' is ".concat(void 0===e?"undefined":null===e?"null":""===e?"empty string":"invalid: ".concat(e)),componentName:"ErrorTrackingService",additionalInfo:{preInitError:!0,apiKey:e,userId:t,timestamp:Date.now()},timestamp:Date.now()},metadata:A(),event_type:_.ERROR,user_id:t};this.sendLog(n).catch(console.error)}this.apiKey=e,this.userId=t,this.isInitialized=!0,this.processPreInitQueue()}catch(n){m.error("Error during ErrorTrackingService initialization:",n),this.preInitQueue.push({error:n instanceof Error?n:new Error(String(n)),componentName:"ErrorTrackingService",additionalInfo:{apiKey:e,userId:t}})}},e.prototype.processPreInitQueue=function(){return f(this,void 0,void 0,(function(){var e,t,n;return h(this,(function(i){switch(i.label){case 0:if(!this.preInitQueue.length)return[2];m.info("Processing ".concat(this.preInitQueue.length," pre-initialization errors")),e=0,t=this.preInitQueue,i.label=1;case 1:return e<t.length?(n=t[e],[4,this.trackError(n.error,n.componentName,p(p({},n.additionalInfo),{preInitError:!0}))]):[3,4];case 2:i.sent(),i.label=3;case 3:return e++,[3,1];case 4:return this.preInitQueue=[],[2]}}))}))},e.prototype.sendLog=function(e){return f(this,void 0,void 0,(function(){var t,n,i,o,r,a;return h(this,(function(s){switch(s.label){case 0:return s.trys.push([0,4,,5]),t=E().apiUrl,[4,fetch("".concat(t,"/users/sdk/record-logs/"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})];case 1:return(n=s.sent()).ok?[3,3]:(o=(i=m).error,r=["Failed to send error log:"],[4,n.text()]);case 2:o.apply(i,r.concat([s.sent()])),s.label=3;case 3:return[3,5];case 4:return a=s.sent(),m.error("Error sending log:",a),[3,5];case 5:return[2]}}))}))},e.prototype.trackError=function(e,t,n){return f(this,void 0,void 0,(function(){var i,o,r;return h(this,(function(a){switch(a.label){case 0:if(this.isInitialized)return[3,5];i={org_id:"UNINITALIZED",event_data:{message:e instanceof Error?e.message:e,stack:e instanceof Error?e.stack:void 0,componentName:t,additionalInfo:p(p({},n),{preInitError:!0,timestamp:Date.now()}),timestamp:Date.now()},metadata:A(),event_type:_.ERROR,user_id:this.userId},a.label=1;case 1:return a.trys.push([1,3,,4]),[4,this.sendLog(i)];case 2:return a.sent(),[3,4];case 3:return a.sent(),this.preInitQueue.push({error:e,componentName:t,additionalInfo:n}),m.warn("Error tracked before initialization, queuing:",e),[3,4];case 4:return[2];case 5:return o={message:e instanceof Error?e.message:e,stack:e instanceof Error?e.stack:void 0,componentName:t,additionalInfo:p(p({},n),{timestamp:Date.now()}),timestamp:Date.now()},r={org_id:this.apiKey||"UNINITALIZED",event_data:o,metadata:A(),event_type:_.ERROR,user_id:this.userId},[4,this.sendLog(r)];case 6:return a.sent(),[2]}}))}))},e.prototype.trackInfo=function(e,t,n){return f(this,void 0,void 0,(function(){var i,o;return h(this,(function(r){switch(r.label){case 0:return this.apiKey?(i={message:e,componentName:t,additionalInfo:n,timestamp:Date.now()},o={org_id:this.apiKey,event_data:i,metadata:A(),event_type:_.INFO,user_id:this.userId},[4,this.sendLog(o)]):(m.error("Error tracking not initialized"),[2]);case 1:return r.sent(),[2]}}))}))},e}(),z=L.getInstance(),N="MISSING_API_KEY",M="INVALID_API_KEY",H="CONFIG_FETCH_FAILED",B="SDK_INIT_FAILED",j="ERROR_TRACKING_INIT_FAILED",F="API_REQUEST_FAILED",U="NETWORK_ERROR",W="INVALID_RESPONSE",P="IFRAME_LOAD_FAILED",V="COOKIE_ACCESS_ERROR",G="COMPONENT_RENDER_ERROR",K="INITIALIZATION_ERROR",J="API_ERROR",Z="RUNTIME_ERROR",Y="COMPONENT_ERROR",Q=((R={})[N]=function(e){return"SDK Initialization Failed: Required parameter 'api_key' is ".concat(void 0===e?"undefined":null===e?"null":""===e?"empty string":"invalid: ".concat(e),". A valid API key string is required to initialize the SDK.")},R[M]=function(e){return"SDK Initialization Failed: Provided API key '".concat(e,"' is invalid. API key must be a non-empty string in UUID format.")},R[H]=function(e){return"Failed to fetch chatbot configuration: ".concat(e.statusCode?"Server responded with status ".concat(e.statusCode):"Could not reach server").concat(e.error?". Error: ".concat(e.error):"")},R[F]=function(e,t,n){return"API Request Failed: Server responded with status ".concat(e," for ").concat(n?"endpoint ".concat(n):"request"," - ").concat(t)},R[U]=function(e){return"Network Error: Failed to communicate with server".concat(e.url?" at ".concat(e.url):"").concat(e.error?" - ".concat(e.error):"")},R[P]=function(e){return"Failed to load chatbot interface".concat(e.src?" from ".concat(e.src):"").concat(e.error?". Error: ".concat(e.error):"")},R[W]=function(e){return"Invalid API Response: Missing required fields in response data: ".concat(e.join(", "))},R[j]=function(e){return"Error Tracking Service initialization failed".concat(e.apiKey?" for API key ".concat(e.apiKey):"").concat(e.error?". Error: ".concat(e.error):"")},R[B]=function(e){return"SDK Initialization Failed: ".concat(e.reason||"Could not initialize the chatbot SDK").concat(e.config?". Attempted initialization with config: ".concat(JSON.stringify(e.config,null,2)):"")},R[V]=function(e,t){return"Cookie Access Error: Failed to ".concat(e).concat(t?" cookie '".concat(t,"'"):" cookies",". This may affect user session persistence.")},R[G]=function(e){return"React Component Error: ".concat(e.component||"Unknown component"," failed to render. Error: ").concat(e.error).concat(e.stack?"\nComponent Stack: ".concat(e.stack):"")},R),X=t((function(t){var i,a,s,l,c=t.config,d=t.isVisible,u=t.onClose,p=t.onEvent,f=t.onInternalEvent,h=t.position,g=t.bottomSpacing,m=n(null),v=n(!1),y=n(!1),_=h||(null===(i=c.interface_properties)||void 0===i?void 0:i.position)||"Right",I=null!==(s=null!=g?g:null===(a=c.interface_properties)||void 0===a?void 0:a.bottom_spacing)&&void 0!==s?s:20,x=r((function(){var e,t=m.current;if(t){var n=((e={width:(null===window||void 0===window?void 0:window.innerWidth)<560?"100vw":"26%",minWidth:(null===window||void 0===window?void 0:window.innerWidth)<560?"300px":"400px",height:(null===window||void 0===window?void 0:window.innerWidth)<560?"100vh":"calc(100vh - 2rem - 10vh - ".concat(I,"px)"),borderRadius:(null===window||void 0===window?void 0:window.innerWidth)<560?"0":"1rem",position:(null===window||void 0===window?void 0:window.innerWidth)<560?"fixed":"",maxHeight:(null===window||void 0===window?void 0:window.innerWidth)<560?"100%":"50rem",top:(null===window||void 0===window?void 0:window.innerWidth)<560?"0":"calc(10vh - 32px)"})[_.toLowerCase()]=(null===window||void 0===window?void 0:window.innerWidth)<560?"0":void 0,e.flexDirection=(null===window||void 0===window?void 0:window.innerWidth)<560?"column":void 0,e.flexGrow=(null===window||void 0===window?void 0:window.innerWidth)<560?"1":void 0,e);Object.assign(t.style,n)}}),[I,_]);return o((function(){var e=m.current;if(e&&!v.current){var t=E().copilotUrl;Object.assign(e.style,{zIndex:"20000000",border:"none",boxShadow:"0px 0px 40px 0px rgba(14, 14, 15, 0.24)",transformOrigin:"bottom ".concat(_.toLowerCase()),transition:"transform 0.2s cubic-bezier(0.2, 1.27, 0.29, 0.97), opacity 0.15s ease-out",transform:"scale(0.3) translate3d(0,40px,0)",opacity:"0",display:"none"}),e.src="".concat(t,"/chatbot-plugin?id=").concat(c.chatbotId),v.current=!0,x();var n=function(){var n,i,o=new URL(e.src).origin||t;null===(n=e.contentWindow)||void 0===n||n.postMessage({domain:null===(i=null===window||void 0===window?void 0:window.location)||void 0===i?void 0:i.hostname,name:"checkDomain"},o)};return e.addEventListener("load",n),function(){return e.removeEventListener("load",n)}}}),[c.chatbotId,null===(l=c.interface_properties)||void 0===l?void 0:l.position,x]),o((function(){var e,t,n,i,o,r=m.current;if(r&&v.current){var a=(null===(e=c.interface_properties)||void 0===e?void 0:e.position)||"Right";if(d?(Object.assign(r.style,{transform:"scale(0.3) translate3d(0,40px,0)",opacity:"0",display:"block"}),r.getBoundingClientRect(),setTimeout((function(){Object.assign(r.style,{transform:"scale(1) translate3d(0,0,0)",opacity:"1",transition:"transform 0.2s cubic-bezier(0.2, 1.27, 0.29, 0.97), opacity 0.15s ease-out"})}),20)):(r.style.transition="none",r.getBoundingClientRect(),Object.assign(r.style,{opacity:"0",transform:"scale(0.3) translate3d(".concat((a.toLowerCase(),"0"),",40px,0)"),transition:"transform 0.2s cubic-bezier(0.2, 1.27, 0.29, 0.97), opacity 0.15s ease-out"}),setTimeout((function(){!d&&r&&(r.style.display="none")}),200)),r.contentWindow&&d){var s=E().copilotUrl;null===(t=null==r?void 0:r.contentWindow)||void 0===t||t.postMessage({domain:null===(n=null===window||void 0===window?void 0:window.location)||void 0===n?void 0:n.hostname,name:"openFrame"},s),(null==y?void 0:y.current)||(null===(i=r.contentWindow)||void 0===i||i.postMessage({domain:null===(o=null===window||void 0===window?void 0:window.location)||void 0===o?void 0:o.hostname,action:"registerUserId",data:{userId:null==c?void 0:c.userId,token:null==c?void 0:c.token,userProfile:null==c?void 0:c.userProfile,isAnonymous:null==c?void 0:c.isAnonymous}},s),y.current=!0)}}}),[d,c.userId,c.token,c.userProfile]),o((function(){if(m.current&&v.current){var e=E().copilotUrl;d&&(null==p||p({type:b.CHATBOT_OPENED,timestamp:Date.now()}),f(b.CHATBOT_OPENED));var t=function(t){var n,i,o,r,a,s,l;if(t.origin===e){if("closeChatbot"===t.data)return void u();if("CHATBOT_TOKEN_EXHAUSTED"===(null===(n=t.data)||void 0===n?void 0:n.type))return void f(w.CHATBOT_TOKEN_EXHAUSTED);"CHATBOT_LOADED"===(null===(i=t.data)||void 0===i?void 0:i.type)&&(null==p||p({type:b.CHATBOT_LOADED,timestamp:Date.now()}),f(b.CHATBOT_LOADED)),"CHAT_INITIALIZED"===(null===(o=t.data)||void 0===o?void 0:o.type)&&(null==p||p({type:b.CHAT_INITIALIZED,timestamp:Date.now()}),f(b.CHAT_INITIALIZED)),"CHAT_INITIALIZATION_FAILED"===(null===(r=t.data)||void 0===r?void 0:r.type)&&(null==p||p({type:b.CHAT_INITIALIZATION_FAILED,timestamp:Date.now()}),f(b.CHAT_INITIALIZATION_FAILED,{error:null===(a=t.data)||void 0===a?void 0:a.error})),"SESSION_REFRESHED"===(null===(s=t.data)||void 0===s?void 0:s.type)&&(null==p||p({type:b.SESSION_REFRESHED,timestamp:Date.now()}),f(b.SESSION_REFRESHED)),"CHAT_MOVED"===(null===(l=t.data)||void 0===l?void 0:l.type)&&f(w.CHAT_MOVED,{from:t.data.from,to:t.data.to,trigger:t.data.trigger})}};return null===window||void 0===window||window.addEventListener("message",t),function(){return null===window||void 0===window?void 0:window.removeEventListener("message",t)}}}),[u,p,f,c.chatbotId,d]),o((function(){var e=m.current;if(e&&v.current){var t=function(){z.trackError(new Error(Q[P]({src:e.src,error:"Failed to load iframe"})),"ChatbotIframe",{errorCode:P,errorType:Z,context:{config:c,iframeUrl:e.src,timestamp:Date.now()}})};return e.addEventListener("error",t),function(){return e.removeEventListener("error",t)}}}),[c]),o((function(){var e;if(m.current&&c&&d){var t=m.current,n=E().copilotUrl;null===(e=t.contentWindow)||void 0===e||e.postMessage({action:"updateUserProfile",user_profile:c.userProfile},n)}}),[c.userProfile,d]),e.createElement("iframe",{ref:m,id:"chat-iframe-rbyln",style:{display:"none"}})})),q=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.state={hasError:!1},t}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}l(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}(t,e),t.getDerivedStateFromError=function(e){return{hasError:!0}},t.prototype.componentDidCatch=function(e,t){z.trackError(new Error(Q[G]({component:this.props.componentName||void 0,error:e.message,stack:t.componentStack})),this.props.componentName||void 0,{errorCode:G,errorType:Y,context:{originalError:e,componentStack:t.componentStack,timestamp:Date.now()}})},t.prototype.render=function(){return this.state.hasError?null:this.props.children},t}(a),$=function(e,t,n){return f(void 0,void 0,void 0,(function(){var i,o,r,a,s,l,c,d;return h(this,(function(u){switch(u.label){case 0:i=E().apiUrl,o="".concat(i,"/chat/chatbot/get/"),m.log("endpointUrl",o),r={client_user_id:t,org_id:e,token:n||void 0,extra_info:{}},u.label=1;case 1:return u.trys.push([1,6,,7]),[4,fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})];case 2:return(a=u.sent()).ok?[3,4]:[4,a.text()];case 3:throw s=u.sent(),new Error(Q[F](a.status,s));case 4:return[4,a.json()];case 5:if(l=u.sent(),!(null===(d=null==l?void 0:l.user)||void 0===d?void 0:d.org_info))throw new Error(Q[W](["user","org_info"]));return[2,l];case 6:throw c=u.sent(),z.trackError(c instanceof Error?c:new Error(Q[U]({error:String(c)})),"fetchChatbotConfig",{errorCode:c instanceof Error&&c.message.includes("API Request Failed")?F:U,errorType:J,context:{chatbotId:e,userId:t,apiUrl:i,statusCode:c instanceof Response?c.status:void 0,timestamp:Date.now(),requestPayload:{client_user_id:t,org_id:e}}}),c;case 7:return[2]}}))}))},ee=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))},te=function(e){var t,n="; ".concat(document.cookie).split("; ".concat(e,"="));if(2===n.length)return null===(t=n.pop())||void 0===t?void 0:t.split(";").shift()},ne=function(e,t,n){var i=new Date;i.setTime(i.getTime()+24*n*60*60*1e3),document.cookie="".concat(e,"=").concat(t,";expires=").concat(i.toUTCString(),";path=/")},ie=function(e){var t=e?"USER_DATA=%7B%22attributes%22%3A%5B%7B%22key%22%3A%22USER_ATTRIBUTE_USER_EMAIL%22%2C%22value%22%3A%22dinesh.goel%40robylon.ai%22%7D%2C%7B%22key%22%3A%22USER_ATTRIBUTE_UNIQUE_ID%22%2C%22value%22%3A%2266011f2c28d1787d13c6c796%22%7D%5D%2C%22subscribedToOldSdk%22%3Afalse%2C%22deviceUuid%22%3A%2226c02feb-2664-451d-8469-9cf1378547c6%22%2C%22deviceAdded%22%3Atrue%7D; _ga_3YS9P6ZDWX=GS1.1.1715252584.3.1.1715258696.39.0.0; _ga_V4J24F7YF9=GS1.1.1715273274.2.0.1715273274.0.0.0; city_name=Bengaluru; lang_code=en-in; cookieConcent=A; _gcl_au=1.1.343275043.1717154298; _clck=43guwd%7C2%7Cfmi%7C0%7C1561; _gid=GA1.2.1423066649.1718210058; moe_uuid=26c02feb-2664-451d-8469-9cf1378547c6; _ga_6RM65PWEZY=GS1.1.1718210058.18.1.1718211647.60.0.0; _ga=GA1.1.689213983.1712737672; AMP_MKTG_fe4beb374f=JTdCJTIycmVmZXJyZXIlMjIlM0ElMjJodHRwcyUzQSUyRiUyRmFjY291bnRzLnRlYWNobWludC5jb20lMkYlMjIlMkMlMjJyZWZlcnJpbmdfZG9tYWluJTIyJTNBJTIyYWNjb3VudHMudGVhY2htaW50LmNvbSUyMiU3RA==; AMP_fe4beb374f=JTdCJTIyZGV2aWNlSWQlMjIlM0ElMjI0MWMxMTljZC03YzVjLTRiYTctYTUzZS1mYTgzMjRlYjc0OWUlMjIlMkMlMjJ1c2VySWQlMjIlM0ElMjIxZjI2ODAwOC01OGYxLTQwYTItYjQ0Ni1mYmQ5N2E0NDQyYTAlMjIlMkMlMjJzZXNzaW9uSWQlMjIlM0ExNzE4MjEzMzEwOTc3JTJDJTIyb3B0T3V0JTIyJTNBZmFsc2UlMkMlMjJsYXN0RXZlbnRUaW1lJTIyJTNBMTcxODIxMzMxMDk4MSUyQyUyMmxhc3RFdmVudElkJTIyJTNBMTQlN0Q=; _ga_3YS9P6ZDWX=GS1.1.1718211637.26.1.1718213441.60.0.0; SESSION=%7B%22sessionKey%22%3A%22e4d76f52-9053-4277-99a4-f1ba667fd5f2%22%2C%22sessionStartTime%22%3A%222024-06-12T16%3A34%3A19.047Z%22%2C%22sessionMaxTime%22%3A1800%2C%22customIdentifiersToTrack%22%3A%5B%5D%2C%22sessionExpiryTime%22%3A1718215247464%2C%22numberOfSessions%22%3A17%7D":document.cookie;return t=t.split(";").map((function(e){var t=e.split("="),n=t[0],i=t.slice(1).join("=").trim();return{name:n=n.trim(),value:i?decodeURIComponent(i):""}})),t},oe=function(){function e(e){this.logoContainer=null,this.iframe=null,this.bubblePromptContainer=null,this.chatBtnImage=null,this.config=e,this.validateDomain()&&this.init(),null===window||void 0===window||window.addEventListener("message",this.onCloseListener.bind(this),!1)}return e.prototype.onCloseListener=function(e){e.origin===this.config.domain&&"closeChatbot"===e.data&&this.closeIframe()},e.prototype.validateDomain=function(){var e,t=this.config.domain,n=null===(e=null===window||void 0===window?void 0:window.location)||void 0===e?void 0:e.origin;return m.log("expectedDomain, to current domain",t,n,t===n),t===n},e.prototype.createChatBubblContainer=function(){var e,t=this,n=document.createElement("div");n.id="chatbase-message-bubbles",Object.assign(n.style,{position:"fixed",bottom:"80px",borderRadius:"10px",fontFamily:"sans-serif",fontSize:"16px",zIndex:"2147483644",cursor:"pointer",flexDirection:"column",gap:"50px",maxWidth:"70vw",display:"block",right:"1rem",left:"unset"});var i=document.createElement("div");i.classList.add("close-btn"),i.textContent="✕",Object.assign(i.style,{position:"absolute",top:"-7px",right:"-7px",fontWeight:"bold",display:"none",justifyContent:"center",alignItems:"center",zIndex:"2147483643",width:"22px",height:"22px",borderRadius:"50%",textAlign:"center",fontSize:"12px",cursor:"pointer",backgroundColor:"rgb(224, 224, 224)",color:"black",boxShadow:"rgba(150, 150, 150, 0.15) 0px 6px 24px 0px, rgba(150, 150, 150, 0.15) 0px 0px 0px 1px"}),((null===(e=this.config.chat_interface_config)||void 0===e?void 0:e.chat_bubble_prompts)||[]).forEach((function(e){var i=t.createMessageBubble(e);n.appendChild(i)})),n.appendChild(i),document.body.appendChild(n)},e.prototype.createMessageBubble=function(e){var t=document.createElement("div");this.bubblePromptContainer=t,Object.assign(t.style,{display:"flex",position:"relative",justifyContent:"flex-end"});var n=document.createElement("div");n.classList.add("message"),n.textContent=e,Object.assign(n.style,{backgroundColor:"white",color:"black",boxShadow:"rgba(150, 150, 150, 0.2) 0px 10px 30px 0px, rgba(150, 150, 150, 0.2) 0px 0px 0px 1px",borderRadius:"10px",padding:"8px 5px",margin:"8px",fontSize:"14px",opacity:"1",transform:"scale(1)",transition:"opacity 0.5s ease 0s, transform 0.5s ease 0s"});var i=document.createElement("button");return i.innerHTML="&times;",Object.assign(i.style,{position:"absolute",top:"1px",left:"-3px",width:"20px",height:"20px",borderRadius:"50%",backgroundColor:"#fff",color:"#000",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 2px 5px rgba(0,0,0,0.2)",fontSize:"14px",lineHeight:"1",padding:"0",zIndex:"100"}),i.addEventListener("click",(function(){t.remove()})),t.appendChild(i),t.appendChild(n),t},e.prototype.createFloatingButton=function(){var e=document.createElement("div");e.classList.add("message-bubble-container"),Object.assign(e.style,{position:"fixed",bottom:"1.5rem",right:"1.5rem",zIndex:"1000",width:"48px",height:"48px",display:"flex",flexDirection:"column-reverse",backgroundColor:this.config.brand_colour,color:g(this.config.brand_colour),borderRadius:"50%",alignItems:"center",justifyContent:"center",cursor:"pointer",overflow:"hidden"}),document.body.appendChild(e),this.logoContainer=e,this.loadImage(this.logoContainer),this.createChatBubblContainer(),this.logoContainer.addEventListener("click",this.toggleIframe.bind(this))},e.prototype.loadImage=function(e){var t,n,i=document.createElement("img");i.src=this.config.launcher_type?(null===(n=null===(t=this.config.images)||void 0===t?void 0:t.launcher_image_url)||void 0===n?void 0:n.url)||"".concat(this.config.domain,"/chatbubble.png"):this.config.image_url||"".concat(this.config.domain,"/chatbubble.png"),i.alt="Chat",Object.assign(i.style,{zIndex:"1000",cursor:"pointer",borderRadius:"50%",objectFit:"cover"}),this.chatBtnImage=i,e.innerHTML="",e.appendChild(i)},e.prototype.createIframe=function(){var e=this;m.log("RobylonConfig?.domain====>",this.config.domain);var t=document.createElement("iframe");Object.assign(t.style,{position:"fixed",right:"32px",bottom:"86px",minWidth:"400px",width:"26%",maxWidth:"800px",top:"calc(10vh - 32px)",maxHeight:"45rem",height:"calc(100vh - 3rem - 10vh)",zIndex:"20000000",border:"none",boxShadow:"0px 0px 40px 0px rgba(14, 14, 15, 0.24)",transformOrigin:"bottom right",transition:"transform 0.3s ease-out",borderRadius:"1rem",display:"none"}),t.src="".concat(this.config.domain,"/chatbot-plugin?id=").concat(this.config.chatbotId),m.log("iframe.src====>",t.src),document.body.appendChild(t),this.iframe=t;var n=function(){(null===window||void 0===window?void 0:window.innerWidth)<560?Object.assign(t.style,{width:"100vw",minWidth:"300px",right:"0",bottom:"0",height:"100vh",flexDirection:"column",flexGrow:"1",borderRadius:"0",top:"0",maxHeight:"100%"}):Object.assign(t.style,{width:"26%",minWidth:"400px",right:"32px",bottom:"86px",height:"calc(100vh - 3rem - 10vh)",borderRadius:"1rem",top:"calc(10vh - 32px)",maxHeight:"45rem"})};n(),null===window||void 0===window||window.addEventListener("resize",n),t.addEventListener("load",(function(){var n,i,o,r;if(e.iframe){var a=new URL(e.iframe.src).origin||e.config.domain;null===(n=t.contentWindow)||void 0===n||n.postMessage({domain:null===(i=null===window||void 0===window?void 0:window.location)||void 0===i?void 0:i.hostname,name:"checkDomain"},a),null===(o=t.contentWindow)||void 0===o||o.postMessage({domain:null===(r=null===window||void 0===window?void 0:window.location)||void 0===r?void 0:r.hostname,action:"registerUserId",data:{userId:e.config.userId,token:e.config.token,userProfile:e.config.userProfile}},a)}})),null===window||void 0===window||window.addEventListener("message",(function(n){var i,o;if(n.origin===e.config.domain){if("captureSessionData"===n.data){var r="66b33d16-5b38-4693-8772-1a1bd7dd412d"===e.config.chatbotId,a={cookies:ie(r),localStorage:JSON.stringify(localStorage),sessionStorage:JSON.stringify(sessionStorage),action:"capturedSessionData",domain_name:null===(i=null===window||void 0===window?void 0:window.location)||void 0===i?void 0:i.hostname};null===(o=t.contentWindow)||void 0===o||o.postMessage(a,e.config.domain||"*")}"expand"===n.data&&(e.adjustIframeWidth(),t.style.height="calc(100vh - 120px)",t.style.bottom="86px"),"collapse"===n.data&&Object.assign(t.style,{width:"26%",height:"calc(100vh - 32px - 10vh)",bottom:"86px",top:"calc(32px + 10vh)"})}}))},e.prototype.adjustIframeWidth=function(){if(this.iframe){var e=null===window||void 0===window?void 0:window.innerWidth;m.log("screenWidth",e),this.iframe.style.width=e<832?"".concat(e-64,"px"):"800px"}},e.prototype.loadSvgInline=function(e){var t=document.createElement("div");t.innerHTML='\n<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <g id="Chevron_Down">\n <path id="Vector" d="M19 9L12 16L5 9" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </g>\n</svg>\n';var n=t.querySelector("svg");e.innerHTML="",n&&e.appendChild(n)},e.prototype.toggleIcon=function(e,t){"block"===t.style.display?this.loadSvgInline(e):this.loadImage(e)},e.prototype.toggleIframe=function(){var e;if(m.log("toggleIframe",this.iframe,this.logoContainer,this.chatBtnImage),this.iframe&&this.logoContainer&&this.chatBtnImage){var t=new URL(this.iframe.src).origin||this.config.domain;m.log("toggleIframe"),null===(e=this.iframe.contentWindow)||void 0===e||e.postMessage({domain:null===window||void 0===window?void 0:window.location.hostname,name:"none"===this.iframe.style.display?"openFrame":"closeFrame"},t),this.iframe.style.display="none"===this.iframe.style.display?"block":"none",this.toggleIcon(this.logoContainer,this.iframe),this.chatBtnImage.style.objectFit="block"===this.iframe.style.display?"none":"cover",this.bubblePromptContainer&&(this.bubblePromptContainer.style.display="none"),m.log("this.bubblePromptContainer",this.bubblePromptContainer)}},e.prototype.closeIframe=function(){this.iframe&&this.logoContainer&&this.chatBtnImage&&(this.iframe.style.display="none",this.toggleIcon(this.logoContainer,this.iframe),this.chatBtnImage.style.objectFit="cover")},e.prototype.init=function(){this.createIframe(),this.createFloatingButton()},e}(),re=function(e,t,n){if(e.chatbotId&&e.userId)try{new oe(e);t(!0),m.log("Robylon SDK initialized successfully.")}catch(e){n(e instanceof Error?e.message:"Failed to initialize SDK")}else n("Incomplete configuration for SDK initialization.")},ae=function(e){var t=s((function(){return function(e){return{api_key:String(e.api_key||""),user_id:e.user_id?String(e.user_id):null,user_token:e.user_token?String(e.user_token):void 0,user_profile:e.user_profile||{}}}(e)}),[e.api_key,e.user_id,e.user_token,JSON.stringify(e.user_profile)]),n=i({isInitialized:!1,isInitializing:!1,error:null,chatbotConfig:null,isIframeVisible:!1}),a=n[0],l=n[1],g=s((function(){var e=["email","name","mobile","platform","OS","browser","sdk_version","device","screen_size","is_test_user"];return t.user_profile?Object.fromEntries(Object.entries(t.user_profile).filter((function(t){var n=t[0];return e.includes(n)})).map((function(e){var t=e[0],n=e[1];return"boolean"==typeof n||"number"==typeof n?[t,n]:[t,String(n)]}))):{}}),[JSON.stringify(t.user_profile)]),m=r((function(e){l((function(t){return p(p({},t),e)}))}),[]),v=r((function(){return f(void 0,void 0,void 0,(function(){var e,n,i,o,r,a,s,l,f,v,b,w,y,E,_,I,x,T,C,S,O,R,D,k,L,M,H,j,F,U;return h(this,(function(h){switch(h.label){case 0:if(!t.api_key)return z.trackError(new Error(Q[N](t.api_key)),"useChatbotState",{errorCode:N,errorType:K,context:{timestamp:Date.now()}}),[2];m({isInitializing:!0}),h.label=1;case 1:return h.trys.push([1,4,5,6]),e=t.user_id||void 0,n=!1,e||(e=te("rblyn_anon")||ee(),ne("rblyn_anon",e,365),n=!0),[4,$(t.api_key,e,t.user_token)];case 2:return i=h.sent(),o=A(),r=p(p({},o),g),a={chatbotId:t.api_key,userId:e,token:t.user_token,isAnonymous:n,domain:"",brand_colour:(null===(v=null===(f=i.user.org_info.brand_config)||void 0===f?void 0:f.colors)||void 0===v?void 0:v.brand_color)||"",image_url:(null===(w=null===(b=i.user.org_info)||void 0===b?void 0:b.brand_config)||void 0===w?void 0:w.launcher_logo_url)||"",userProfile:r,chat_interface_config:{chat_bubble_prompts:[],display_name:(null===(y=i.user.org_info.brand_config)||void 0===y?void 0:y.display_name)||"",welcome_message:(null===(E=i.user.org_info.brand_config)||void 0===E?void 0:E.welcome_message)||"Hey! What can we help you with today?",redirect_url:(null===(_=i.user.org_info.brand_config)||void 0===_?void 0:_.redirect_url)||""},interface_properties:{position:(null===(x=null===(I=i.user.org_info.brand_config)||void 0===I?void 0:I.interface_properties)||void 0===x?void 0:x.position)||d.RIGHT,side_spacing:null!==(S=null===(C=null===(T=i.user.org_info.brand_config)||void 0===T?void 0:T.interface_properties)||void 0===C?void 0:C.side_spacing)&&void 0!==S?S:20,bottom_spacing:null!==(D=null===(R=null===(O=i.user.org_info.brand_config)||void 0===O?void 0:O.interface_properties)||void 0===R?void 0:R.bottom_spacing)&&void 0!==D?D:20},interface_type:(null===(k=i.user.org_info.brand_config)||void 0===k?void 0:k.interface_type)||c.WIDGET,launcher_type:(null===(L=i.user.org_info.brand_config)||void 0===L?void 0:L.launcher_type)||u.IMAGE,launcher_properties:{text:(null===(H=null===(M=i.user.org_info.brand_config)||void 0===M?void 0:M.launcher_properties)||void 0===H?void 0:H.text)||""},images:{launcher_image_url:{url:(null===(U=null===(F=null===(j=i.user.org_info.brand_config)||void 0===j?void 0:j.images)||void 0===F?void 0:F.launcher_image_url)||void 0===U?void 0:U.url)||""}}},[4,new Promise((function(e,t){re(a,(function(){m({isInitialized:!0,chatbotConfig:a}),e()}),(function(e){t(e)}))}))];case 3:return h.sent(),[3,6];case 4:return s=h.sent(),l=s instanceof Error?s.message:"Failed to initialize chatbot",m({error:l}),z.trackError(s instanceof Error?s:new Error(l),"useChatbotState",{errorCode:B,errorType:K,context:{timestamp:Date.now()}}),[3,6];case 5:return m({isInitializing:!1}),[7];case 6:return[2]}}))}))}),[t.api_key,t.user_id,t.user_token]);o((function(){t.api_key&&v()}),[v]),o((function(){a.chatbotConfig&&l((function(e){return p(p({},e),{chatbotConfig:p(p({},e.chatbotConfig),{userProfile:p(p({},A()),g)})})}))}),[g]);var b=r((function(){l((function(e){return p(p({},e),{isIframeVisible:!e.isIframeVisible})}))}),[]),w=r((function(){m({isIframeVisible:!1})}),[]);return p(p({},a),{toggleIframeVisibility:b,closeIframe:w})},se=function(e){var t=e.api_key,n=e.chatbotConfig,i=e.user_profile,o=e.onEvent,a=s((function(){return{isAnonymous:(null==n?void 0:n.isAnonymous)||!1,userId:(null==n?void 0:n.userId)||""}}),[null==n?void 0:n.isAnonymous,null==n?void 0:n.userId]),l=s((function(){return i||{}}),[JSON.stringify(i)]),c=r((function(e){for(var n=[],i=1;i<arguments.length;i++)n[i-1]=arguments[i];return f(void 0,function(e,t,n){if(n||2===arguments.length)for(var i,o=0,r=t.length;o<r;o++)!i&&o in t||(i||(i=Array.prototype.slice.call(t,0,o)),i[o]=t[o]);return e.concat(i||Array.prototype.slice.call(t))}([e],n,!0),void 0,(function(e,n){var i,o,r,s,c,d,u;return void 0===n&&(n={}),h(this,(function(f){switch(f.label){case 0:if(!t)return[2];f.label=1;case 1:return f.trys.push([1,3,,4]),i=E().apiUrl,o=A(),r=p({trigger_time:Date.now(),channel:"CHATBOT",launch_url:(null===(u=null===window||void 0===window?void 0:window.location)||void 0===u?void 0:u.href)||"",org_id:t,client_user_id:a.isAnonymous?"Anonymous":String(a.userId),event_type:e,user_profile:l},n),s={org_id:t,event_data:r,metadata:p({timestamp:Date.now()},o),event_type:"INFO",user_id:a.userId},[4,fetch("".concat(i,"/users/sdk/record-logs/"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})];case 2:if(!(c=f.sent()).ok)throw new Error("Failed to send internal event: ".concat(c.statusText));return[3,4];case 3:return d=f.sent(),m.error("Failed to send internal event:",d),[3,4];case 4:return[2]}}))}))}),[t,a]);return{emitEvent:r((function(e,t){var n=Date.now();e!==b.CHATBOT_BUTTON_CLICKED&&e!==b.CHATBOT_CLOSED&&e!==b.CHATBOT_OPENED||(o&&o({type:e,timestamp:n,data:t}),c(e,{timestamp:n}))}),[o,c]),onInternalEvent:c}},le=function(t){var n,r,a,s,l,c,d,u=t.children,f=t.config,h=t.position,g=t.sideSpacing,v=t.bottomSpacing,b=i(!1),w=b[0],y=b[1];o((function(){var e=function(){var e=(null===window||void 0===window?void 0:window.innerWidth)<560;y(e)};return e(),window.addEventListener("resize",e),function(){window.removeEventListener("resize",e)}}),[]);var E=h||(null===(a=f.interface_properties)||void 0===a?void 0:a.position)||"Right",_=null!==(l=null!=g?g:null===(s=f.interface_properties)||void 0===s?void 0:s.side_spacing)&&void 0!==l?l:20,I=null!==(d=null!=v?v:null===(c=f.interface_properties)||void 0===c?void 0:c.bottom_spacing)&&void 0!==d?d:20;m.log("config",f,E,_);var x={position:"fixed",zIndex:1e3,display:"flex",flexDirection:"column"},T=p(p({},x),((n={bottom:"".concat(I,"px")})[E.toLowerCase()]="".concat(null!=_?_:20,"px"),n.alignItems="Right"===E?"flex-end":"flex-start",n.top=void 0,n["Right"===E?"left":"right"]=void 0,n)),C=p(p({},x),((r={top:0})[E.toLowerCase()]="".concat(null!=_?_:20,"px"),r.alignItems="center",r.bottom=void 0,r["Right"===E?"left":"right"]=void 0,r)),S=w?C:T;return o((function(){console.log("Container screen width changed, isMobile:",w,"Style:",S)}),[w,S]),e.createElement("div",{className:"robylon-chatbot-container",style:S},u)},ce=t((function(t){var n=t.api_key,i=t.user_id,a=t.user_token,l=t.user_profile,c=t.onEvent,d=t.position,u=t.sideSpacing,f=t.bottomSpacing,h="string"==typeof u?""===u||isNaN(Number(u))?void 0:Number(u):u,g="string"==typeof f?""===f||isNaN(Number(f))?void 0:Number(f):f,v="string"==typeof d?"left"===d.toLowerCase()?"Left":"right"===d.toLowerCase()?"Right":void 0:d;o((function(){}));var w=s((function(){return{api_key:n,user_id:i,user_token:a,user_profile:l}}),[n,i,a,l]),y=r((function(e){null==c||c(e)}),[c]),E=ae(w),_=E.isInitialized,I=E.error,x=E.chatbotConfig,C=E.isIframeVisible,S=E.toggleIframeVisibility,O=E.closeIframe,A=s((function(){return{api_key:n,user_profile:w.user_profile,onEvent:y,chatbotConfig:x?{isAnonymous:x.isAnonymous,userId:x.userId}:null}}),[n,w.user_profile,y,null==x?void 0:x.isAnonymous,null==x?void 0:x.userId]),R=se(p({},A)),D=R.emitEvent,k=R.onInternalEvent;o((function(){if(n)try{z.initialize(n,i)}catch(e){z.trackError(e instanceof Error?e:new Error(String(e)),"RobylonChatbot",{errorCode:j,errorType:K,context:{timestamp:Date.now()}})}else z.trackError(new Error(Q[N](n)),"RobylonChatbot",{errorCode:N,errorType:K,context:{timestamp:Date.now()}})}),[n,i]);var L=r((function(){O(),D(b.CHATBOT_CLOSED)}),[O,D]),M=r((function(){S(),D(C?b.CHATBOT_CLOSED:b.CHATBOT_BUTTON_CLICKED)}),[S,D,C]),H=s((function(){return{config:x,toggleIframe:M,isIframeVisible:C,onEvent:y,onInternalEvent:k,position:v,sideSpacing:h,bottomSpacing:g}}),[x,M,C,y,k,v,h,g]);m.log("floatingButtonProps",H);var B=s((function(){return{config:x,isVisible:C,onClose:L,onEvent:y,onInternalEvent:k,position:v,bottomSpacing:g}}),[x,C,L,y,k,v,g]);return n&&!I&&x?e.createElement(q,{componentName:"RobylonChatbot"},_?e.createElement(le,{config:x,position:v,sideSpacing:h,bottomSpacing:g},e.createElement(q,{componentName:"ChatbotIframe"},e.createElement(X,p({},B))),e.createElement(q,{componentName:"ChatbotFloatingButton"},e.createElement(T,p({},H)))):null):null}),(function(e,t){return e.api_key===t.api_key&&e.user_id===t.user_id&&e.user_token===t.user_token&&JSON.stringify(e.user_profile)===JSON.stringify(t.user_profile)&&e.position===t.position&&e.sideSpacing===t.sideSpacing&&e.bottomSpacing===t.bottomSpacing&&!0})),de=function(e){var t=i({isLoading:!0,isInitialized:!1,error:null}),n=t[0],r=t[1],a=function(e){r((function(t){return p(p({},t),{isInitialized:e})}))},s=function(e){r((function(t){return p(p({},t),{error:e})}))};return o((function(){!function(){try{re(e,a,s)}catch(e){r((function(t){return p(p({},t),{error:e instanceof Error?e.message:"Failed to initialize SDK",isLoading:!1})}))}}()}),[e.chatbotId,e.userId]),n},ue=function(){function e(e){this.resizeObserver=null,this.config=e,this.buttonElement=document.createElement("div"),this.handleResizeFunction=this.handleResize.bind(this),this.render(),this.mount(),this.setupResizeListener()}return e.prototype.render=function(){var e=this;E().copilotUrl;var t=this.config,n=t.config,i={zIndex:"1000",display:"flex",flexDirection:"column-reverse",alignItems:"center",justifyContent:"center",cursor:"pointer",overflow:"hidden",marginTop:"16px",transition:"transform 0.2s cubic-bezier(0.2, 1.27, 0.29, 0.97)",transform:t.isIframeVisible?"scale(0.85)":"scale(1)",fontFamily:I};n.launcher_type===u.IMAGE&&Object.assign(i,{width:"48px",height:"48px",borderRadius:"50%",backgroundColor:n.brand_colour}),this.applyResponsiveStyles(i),this.buttonElement.className="message-bubble-container",this.buttonElement.innerHTML="",this.buttonElement.appendChild(this.createLauncherElement()),this.buttonElement.onclick=function(){e.config.toggleIframe()}},e.prototype.createLauncherElement=function(){var e,t,n=this.config,i=n.config,o=n.isIframeVisible,r=E().copilotUrl;switch(console.log("config in floating button",i),i.launcher_type){case u.TEXT:return this.createTextLauncher();case u.TEXTUAL_IMAGE:return this.createTextualImageLauncher();case u.IMAGE:default:if(o){var a=document.createElement("div");return a.innerHTML='\n <svg\n width="24"\n height="24"\n viewBox="0 0 24 24"\n fill="none"\n xmlns="http://www.w3.org/2000/svg"\n >\n <path\n d="M19 9L12 16L5 9"\n stroke="currentColor"\n stroke-width="1.5"\n stroke-linecap="round"\n stroke-linejoin="round"\n />\n </svg>\n ',a}var s=document.createElement("img");return s.src=i.launcher_type?(null===(t=null===(e=i.images)||void 0===e?void 0:e.launcher_image_url)||void 0===t?void 0:t.url)||"".concat(r,"/chatbubble.png"):i.image_url||"".concat(r,"/chatbubble.png"),s.alt="Chat",Object.assign(s.style,{zIndex:"1000",cursor:"pointer",borderRadius:"50%",objectFit:"cover",width:"100%",height:"100%",boxSizing:"border-box"}),s}},e.prototype.createTextLauncher=function(){var e=this.config.config,t=e.brand_colour,n=e.launcher_properties,i=document.createElement("div");Object.assign(i.style,{width:"fit-content",maxWidth:"160px",height:"40px",borderRadius:"9999px",backgroundColor:t,display:"flex",alignItems:"center",padding:"9px 20px",boxShadow:"0px 0px 16px 0px rgba(0, 0, 0, 0.24)",boxSizing:"border-box"});var o=document.createElement("div");Object.assign(o.style,{flex:"1",minWidth:"0"});var r=document.createElement("p");return Object.assign(r.style,{margin:"0",color:g(t),fontSize:"0.875rem",fontWeight:"600",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",lineHeight:x,fontFamily:I,WebkitFontSmoothing:"antialiased",textRendering:"optimizeLegibility",textSizeAdjust:"100%"}),r.textContent=(null==n?void 0:n.text)||"",o.appendChild(r),i.appendChild(o),i},e.prototype.createTextualImageLauncher=function(){var e,t,n,i,o,r,a=E().copilotUrl,s=this.config.config,l=s.brand_colour,c=s.launcher_properties,d=s.image_url,u=document.createElement("div");Object.assign(u.style,{maxWidth:"13rem",width:"fit-content",height:"40px",borderRadius:"9999px",backgroundColor:l,display:"flex",alignItems:"center",paddingLeft:"20px",paddingRight:"0",paddingTop:"9px",paddingBottom:"9px",boxShadow:"0px 0px 16px 0px rgba(0, 0, 0, 0.24)",gap:"8px",boxSizing:"border-box"});var p=document.createElement("div");Object.assign(p.style,{flex:"1",minWidth:"0"});var f=document.createElement("p");Object.assign(f.style,{margin:"0",color:g(l),fontSize:"0.875rem",fontWeight:"600",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",lineHeight:x,fontFamily:I,WebkitFontSmoothing:"antialiased",textRendering:"optimizeLegibility",textSizeAdjust:"100%"}),f.textContent=(null==c?void 0:c.text)||"";var h=document.createElement("div");Object.assign(h.style,{width:"40px",height:"40px",borderRadius:"9999px",overflow:"hidden",position:"relative",flexShrink:"0"});var m=document.createElement("img");return m.src=(null===(t=null===(e=null==this?void 0:this.config)||void 0===e?void 0:e.config)||void 0===t?void 0:t.launcher_type)?(null===(r=null===(o=null===(i=null===(n=null==this?void 0:this.config)||void 0===n?void 0:n.config)||void 0===i?void 0:i.images)||void 0===o?void 0:o.launcher_image_url)||void 0===r?void 0:r.url)||"".concat(a,"/chatbubble.png"):d||"".concat(a,"/chatbubble.png"),m.alt="Chat",Object.assign(m.style,{width:"100%",height:"100%",objectFit:"cover"}),p.appendChild(f),h.appendChild(m),u.appendChild(p),u.appendChild(h),u},e.prototype.applyResponsiveStyles=function(e){var t,n,i,o,r,a,s,l,c,d=(null===window||void 0===window?void 0:window.innerWidth)<560,u=this.config.config,f=this.config.position||(null===(i=u.interface_properties)||void 0===i?void 0:i.position)||"Right",h=null!==(a=null!==(o=this.config.sideSpacing)&&void 0!==o?o:null===(r=u.interface_properties)||void 0===r?void 0:r.side_spacing)&&void 0!==a?a:20,g=null!==(c=null!==(s=this.config.bottomSpacing)&&void 0!==s?s:null===(l=u.interface_properties)||void 0===l?void 0:l.bottom_spacing)&&void 0!==c?c:20;this.buttonElement.style.position="",this.buttonElement.style.bottom="",this.buttonElement.style.right="",this.buttonElement.style.left="";var m=p(p({},e),d?((t={position:"fixed",bottom:"".concat(g,"px")})[f.toLowerCase()]="".concat(h,"px"),t):((n={position:"fixed",bottom:"".concat(g,"px")})[f.toLowerCase()]="".concat(h,"px"),n));Object.assign(this.buttonElement.style,m)},e.prototype.handleResize=function(){var e={zIndex:"1000",display:"flex",flexDirection:"column-reverse",alignItems:"center",justifyContent:"center",cursor:"pointer",overflow:"hidden",marginTop:"16px",borderRadius:this.config.config.launcher_type&&this.config.config.launcher_type!==u.IMAGE?"9999px":"50%",boxSizing:"border-box"};this.config.config.launcher_type===u.IMAGE&&Object.assign(e,{width:"48px",height:"48px",borderRadius:"50%",backgroundColor:this.config.config.brand_colour}),this.applyResponsiveStyles(e)},e.prototype.setupResizeListener=function(){"undefined"!=typeof ResizeObserver?(this.resizeObserver=new ResizeObserver(this.handleResizeFunction),this.resizeObserver.observe(document.body)):window.addEventListener("resize",this.handleResizeFunction)},e.prototype.getElement=function(){return this.buttonElement},e.prototype.mount=function(){var e=this;requestAnimationFrame((function(){var t,n;null===(n=(t=e.config).onEvent)||void 0===n||n.call(t,{type:b.CHATBOT_BUTTON_LOADED,timestamp:Date.now()}),e.config.onInternalEvent(b.CHATBOT_BUTTON_LOADED)}))},e.prototype.update=function(e){this.config.isIframeVisible,this.config=p(p({},this.config),e),this.buttonElement.style.transform=this.config.isIframeVisible?"scale(0.85)":"scale(1)",this.render()},e.prototype.destroy=function(){this.resizeObserver?(this.resizeObserver.disconnect(),this.resizeObserver=null):window.removeEventListener("resize",this.handleResizeFunction),this.buttonElement&&this.buttonElement.parentNode&&this.buttonElement.parentNode.removeChild(this.buttonElement)},e}(),pe=function(){function e(e){var t=this;this.isInitialized=!1,this.hasRegistered=!1,this.handleMessage=function(e){var n,i,o,r,a,s,l,c,d,u,p,f,h,g,m,v=E().copilotUrl;if(e.origin===v){if("closeChatbot"===e.data)return void t.config.onClose();if("CHATBOT_TOKEN_EXHAUSTED"===(null===(n=e.data)||void 0===n?void 0:n.type))return void t.config.onInternalEvent(w.CHATBOT_TOKEN_EXHAUSTED);"CHATBOT_LOADED"===(null===(i=e.data)||void 0===i?void 0:i.type)&&(null===(r=(o=t.config).onEvent)||void 0===r||r.call(o,{type:b.CHATBOT_LOADED,timestamp:Date.now()}),t.config.onInternalEvent(b.CHATBOT_LOADED)),"CHAT_INITIALIZED"===(null===(a=e.data)||void 0===a?void 0:a.type)&&(null===(l=(s=t.config).onEvent)||void 0===l||l.call(s,{type:b.CHAT_INITIALIZED,timestamp:Date.now()}),t.config.onInternalEvent(b.CHAT_INITIALIZED)),"CHAT_INITIALIZATION_FAILED"===(null===(c=e.data)||void 0===c?void 0:c.type)&&(null===(u=(d=t.config).onEvent)||void 0===u||u.call(d,{type:b.CHAT_INITIALIZATION_FAILED,timestamp:Date.now()}),t.config.onInternalEvent(b.CHAT_INITIALIZATION_FAILED,{error:null===(p=e.data)||void 0===p?void 0:p.error})),"SESSION_REFRESHED"===(null===(f=e.data)||void 0===f?void 0:f.type)&&(null===(g=(h=t.config).onEvent)||void 0===g||g.call(h,{type:b.SESSION_REFRESHED,timestamp:Date.now()}),t.config.onInternalEvent(b.SESSION_REFRESHED)),"CHAT_MOVED"===(null===(m=e.data)||void 0===m?void 0:m.type)&&t.config.onInternalEvent(w.CHAT_MOVED,{from:e.data.from,to:e.data.to,trigger:e.data.trigger})}},this.config=e,this.iframeElement=document.createElement("iframe"),this.iframeElement.id="chat-iframe-rbyln",this.resizeHandler=this.applyResponsiveStyles.bind(this),this.render(),this.initialize(),this.setupEventListeners()}return e.prototype.getElement=function(){return this.iframeElement},e.prototype.render=function(){var e,t=this.config.position||(null===(e=this.config.config.interface_properties)||void 0===e?void 0:e.position)||"Right";Object.assign(this.iframeElement.style,{zIndex:"20000000",border:"none",boxShadow:"0px 0px 40px 0px rgba(14, 14, 15, 0.24)",transformOrigin:"bottom ".concat(t.toLowerCase()),transition:"transform 0.2s cubic-bezier(0.2, 1.27, 0.29, 0.97), opacity 0.15s ease-out",transform:"scale(0.3) translate3d(0,40px,0)",opacity:"0",display:"none"}),this.applyResponsiveStyles()},e.prototype.applyResponsiveStyles=function(){var e,t,n,i,o,r;if(this.iframeElement){var a=this.config.position||(null===(n=this.config.config.interface_properties)||void 0===n?void 0:n.position)||"Right",s=null!==(r=null!==(i=this.config.bottomSpacing)&&void 0!==i?i:null===(o=this.config.config.interface_properties)||void 0===o?void 0:o.bottom_spacing)&&void 0!==r?r:20;window.innerWidth<560?Object.assign(this.iframeElement.style,((e={width:"100vw",minWidth:"300px"})[a.toLowerCase()]="0",e.bottom="0",e.height="100vh",e.flexDirection="column",e.flexGrow="1",e.borderRadius="0",e.top="0",e.maxHeight="100%",e.position="fixed",e)):Object.assign(this.iframeElement.style,((t={width:"26%",minWidth:"400px",height:"calc(100vh - 2rem - 10vh - ".concat(s,"px)"),borderRadius:"1rem",top:"calc(10vh - 32px)",maxHeight:"50rem",position:""})[a.toLowerCase()]=void 0,t))}},e.prototype.initialize=function(){var e=this;if(!this.isInitialized){var t=E().copilotUrl;this.iframeElement.src="".concat(t,"/chatbot-plugin?id=").concat(this.config.config.chatbotId),this.isInitialized=!0,this.iframeElement.addEventListener("load",(function(){var n,i,o=new URL(e.iframeElement.src).origin||t;null===(n=e.iframeElement.contentWindow)||void 0===n||n.postMessage({domain:null===(i=null===window||void 0===window?void 0:window.location)||void 0===i?void 0:i.hostname,name:"checkDomain"},o)}))}},e.prototype.setupEventListeners=function(){var e=this;window.addEventListener("resize",this.resizeHandler),this.iframeElement.addEventListener("error",(function(){z.trackError(new Error(Q[P]({src:e.iframeElement.src,error:"Failed to load iframe"})),"ChatbotIframe",{errorCode:P,errorType:Z,context:{config:e.config.config,iframeUrl:e.iframeElement.src,timestamp:Date.now()}})})),window.addEventListener("message",this.handleMessage)},e.prototype.updateVisibility=function(e){var t,n,i,o,r,a,s,l,c,d=this;this.config.isVisible=e;var u=this.config.position||(null===(t=this.config.config.interface_properties)||void 0===t?void 0:t.position)||"Right";if(e?(this.iframeElement.style.display="block",this.iframeElement.getBoundingClientRect(),this.iframeElement.style.opacity="1",this.iframeElement.style.transform="scale(1) translate3d(0,0,0)"):(this.iframeElement.style.opacity="0",this.iframeElement.style.transform="scale(0.3) translate3d(".concat((u.toLowerCase(),"0"),",40px,0)"),setTimeout((function(){d.config.isVisible||(d.iframeElement.style.display="none")}),200)),this.iframeElement.contentWindow&&e){var p=E().copilotUrl,f=new URL(this.iframeElement.src).origin||p;this.iframeElement.contentWindow.postMessage({domain:null===(n=null===window||void 0===window?void 0:window.location)||void 0===n?void 0:n.hostname,name:"openFrame"},f),this.hasRegistered||(this.iframeElement.contentWindow.postMessage({domain:null===(i=null===window||void 0===window?void 0:window.location)||void 0===i?void 0:i.hostname,action:"registerUserId",data:{userId:null===(o=this.config.config)||void 0===o?void 0:o.userId,token:null===(r=this.config.config)||void 0===r?void 0:r.token,userProfile:null===(a=this.config.config)||void 0===a?void 0:a.userProfile,isAnonymous:null===(s=this.config.config)||void 0===s?void 0:s.isAnonymous}},f),this.hasRegistered=!0),null===(c=(l=this.config).onEvent)||void 0===c||c.call(l,{type:b.CHATBOT_OPENED,timestamp:Date.now()}),this.config.onInternalEvent(b.CHATBOT_OPENED)}},e.prototype.update=function(e){var t=this.config.isVisible;if(this.config=p(p({},this.config),e),t!==this.config.isVisible&&this.updateVisibility(this.config.isVisible),this.iframeElement.contentWindow&&this.config.isVisible){var n=E().copilotUrl;this.iframeElement.contentWindow.postMessage({action:"updateUserProfile",user_profile:this.config.config.userProfile},n)}},e.prototype.destroy=function(){window.removeEventListener("resize",this.resizeHandler),window.removeEventListener("message",this.handleMessage),this.iframeElement&&this.iframeElement.parentNode&&this.iframeElement.parentNode.removeChild(this.iframeElement)},e}(),fe=function(){function e(e,t,n,i){this.resizeObserver=null,this.containerElement=document.createElement("div"),this.handleResizeFunction=this.handleResize.bind(this),this.config={config:e,position:t,sideSpacing:n,bottomSpacing:i},this.render(),this.mount(),this.setupResizeListener()}return e.prototype.render=function(){this.applyStyles(),this.containerElement.className="robylon-chatbot-container"},e.prototype.applyStyles=function(){var e,t,n,i,o,r,a,s,l,c=(null===window||void 0===window?void 0:window.innerWidth)<560,d=this.config.position||(null===(n=this.config.config.interface_properties)||void 0===n?void 0:n.position)||"Right",u=null!==(r=null!==(i=this.config.sideSpacing)&&void 0!==i?i:null===(o=this.config.config.interface_properties)||void 0===o?void 0:o.side_spacing)&&void 0!==r?r:20,f=null!==(l=null!==(a=this.config.bottomSpacing)&&void 0!==a?a:null===(s=this.config.config.interface_properties)||void 0===s?void 0:s.bottom_spacing)&&void 0!==l?l:20;this.containerElement.style.position="",this.containerElement.style.top="",this.containerElement.style.bottom="",this.containerElement.style.right="",this.containerElement.style.left="",this.containerElement.style.alignItems="";var h={position:"fixed",zIndex:"1000",display:"flex",flexDirection:"column"},g=p(p({},h),((e={bottom:"".concat(f,"px")})[d.toLowerCase()]="".concat(u,"px"),e.alignItems="Right"===d?"flex-end":"flex-start",e)),m=p(p({},h),((t={top:"0"})[d.toLowerCase()]="".concat(u,"px"),t.alignItems="center",t));Object.assign(this.containerElement.style,c?m:g)},e.prototype.handleResize=function(){this.applyStyles()},e.prototype.setupResizeListener=function(){"undefined"!=typeof ResizeObserver?(this.resizeObserver=new ResizeObserver(this.handleResizeFunction),this.resizeObserver.observe(document.body)):window.addEventListener("resize",this.handleResizeFunction)},e.prototype.mount=function(){document.body.appendChild(this.containerElement)},e.prototype.getElement=function(){return this.containerElement},e.prototype.destroy=function(){this.resizeObserver?(this.resizeObserver.disconnect(),this.resizeObserver=null):window.removeEventListener("resize",this.handleResizeFunction),this.containerElement&&this.containerElement.parentNode&&this.containerElement.parentNode.removeChild(this.containerElement)},e}(),he=function(e,t,n){return f(void 0,void 0,void 0,(function(){var i,o,r,a,s,l,c,d;return h(this,(function(u){switch(u.label){case 0:return u.trys.push([0,5,,6]),i=E().apiUrl,o="".concat(i,"/chat/chatbot/get/"),m.log("endpointUrl",o),r={client_user_id:t||null,org_id:e,token:n||void 0,extra_info:{}},[4,fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})];case 1:return(a=u.sent()).ok?[3,3]:[4,a.text()];case 2:throw s=u.sent(),new Error(Q[F](a.status,s));case 3:return[4,a.json()];case 4:if(l=u.sent(),!(null===(d=null==l?void 0:l.user)||void 0===d?void 0:d.org_info))throw new Error(Q[W](["user","org_info"]));return[2,l];case 5:throw c=u.sent(),z.trackError(c instanceof Error?c:new Error(Q[U]({error:String(c)})),"fetchChatbotConfig",{errorCode:c instanceof Error&&c.message.includes("API Request Failed")?F:U,errorType:J,context:{apiKey:e,userId:t,timestamp:Date.now()}}),c;case 6:return[2]}}))}))},ge=function(e){return f(void 0,void 0,void 0,(function(){var t,n,i,o,r,a,s,l,f,g,m,v,b,w,y,E,_,I,x,T,C,S,O,R,D,k,L;return h(this,(function(h){switch(h.label){case 0:return t=function(e){return{api_key:String(e.api_key||""),user_id:e.user_id?String(e.user_id):null,user_token:e.user_token?String(e.user_token):void 0,user_profile:e.user_profile||{}}}(e),n=t.user_id||void 0,i=!1,n||(n=te("rblyn_anon")||ee(),ne("rblyn_anon",n,365),i=!0),[4,he(t.api_key,n,t.user_token)];case 1:return o=h.sent(),r=A(),z=t.user_profile,a=z?Object.fromEntries(Object.entries(z).map((function(e){var t=e[0],n=e[1];return"boolean"==typeof n||"number"==typeof n?[t,n]:[t,String(n)]}))):{},s=p(p({},r),a),[2,{chatbotId:t.api_key,userId:n,token:t.user_token,isAnonymous:i,domain:"",brand_colour:(null===(f=null===(l=o.user.org_info.brand_config)||void 0===l?void 0:l.colors)||void 0===f?void 0:f.brand_color)||"",image_url:(null===(m=null===(g=o.user.org_info)||void 0===g?void 0:g.brand_config)||void 0===m?void 0:m.launcher_logo_url)||"",userProfile:s,chat_interface_config:{chat_bubble_prompts:[],display_name:(null===(v=o.user.org_info.brand_config)||void 0===v?void 0:v.display_name)||"",welcome_message:(null===(b=o.user.org_info.brand_config)||void 0===b?void 0:b.welcome_message)||"Hey! What can we help you with today?",redirect_url:(null===(w=o.user.org_info.brand_config)||void 0===w?void 0:w.redirect_url)||""},launcher_type:(null===(y=o.user.org_info.brand_config)||void 0===y?void 0:y.launcher_type)||u.IMAGE,launcher_properties:{text:(null===(_=null===(E=o.user.org_info.brand_config)||void 0===E?void 0:E.launcher_properties)||void 0===_?void 0:_.text)||""},images:{launcher_image_url:{url:(null===(T=null===(x=null===(I=o.user.org_info.brand_config)||void 0===I?void 0:I.images)||void 0===x?void 0:x.launcher_image_url)||void 0===T?void 0:T.url)||""}},interface_properties:{position:(null===(S=null===(C=o.user.org_info.brand_config)||void 0===C?void 0:C.interface_properties)||void 0===S?void 0:S.position)||d.RIGHT,side_spacing:(null===(R=null===(O=o.user.org_info.brand_config)||void 0===O?void 0:O.interface_properties)||void 0===R?void 0:R.side_spacing)||20,bottom_spacing:(null===(k=null===(D=o.user.org_info.brand_config)||void 0===D?void 0:D.interface_properties)||void 0===k?void 0:k.bottom_spacing)||20},interface_type:(null===(L=o.user.org_info.brand_config)||void 0===L?void 0:L.interface_type)||c.WIDGET}]}var z}))}))},me=function(e){e.api_key,e.user_profile;var t=e.onEvent;e.chatbotConfig;return{emit:function(e,n){var i={type:e,timestamp:Date.now(),data:n};null==t||t(i)},onInternalEvent:function(e,t){}}},ve=function(){function e(e){var t=this;this.container=null,this.floatingButton=null,this.iframe=null,this.isDestroyed=!1,this.handleStateChange=function(e){if(!t.isDestroyed){var n=e.isInitialized,i=e.error,o=e.chatbotConfig,r=e.isIframeVisible;if(!i&&o&&n){if(t.eventEmitter=me({api_key:t.config.api_key,user_profile:t.config.user_profile,onEvent:t.config.onEvent,chatbotConfig:{isAnonymous:o.isAnonymous,userId:o.userId}}),t.container||(t.container=new fe(o,t.config.position,t.config.sideSpacing,t.config.bottomSpacing)),t.iframe)t.iframe.update({config:o,isVisible:r,position:t.config.position,bottomSpacing:t.config.bottomSpacing});else if(t.iframe=new pe({config:o,isVisible:r,onClose:t.handleClose,onEvent:t.config.onEvent,onInternalEvent:t.eventEmitter.onInternalEvent,position:t.config.position,bottomSpacing:t.config.bottomSpacing}),t.iframe.getElement&&"function"==typeof t.iframe.getElement){var a=t.iframe.getElement();a&&t.container&&t.container.getElement().prepend(a)}if(t.floatingButton)t.floatingButton.update({config:o,isIframeVisible:r,position:t.config.position,sideSpacing:t.config.sideSpacing,bottomSpacing:t.config.bottomSpacing});else if(t.floatingButton=new ue({config:o,toggleIframe:t.toggleIframe,isIframeVisible:r,onEvent:t.config.onEvent,onInternalEvent:t.eventEmitter.onInternalEvent,position:t.config.position,sideSpacing:t.config.sideSpacing,bottomSpacing:t.config.bottomSpacing}),t.floatingButton.getElement&&"function"==typeof t.floatingButton.getElement){var s=t.floatingButton.getElement();s&&t.container&&t.container.getElement().appendChild(s)}}}},this.toggleIframe=function(){var e=t.stateManager.getState();t.stateManager.toggleIframeVisibility(),t.eventEmitter.emit(e.isIframeVisible?b.CHATBOT_CLOSED:b.CHATBOT_BUTTON_CLICKED)},this.handleClose=function(){t.stateManager.closeIframe(),t.eventEmitter.emit(b.CHATBOT_CLOSED)};var n,i,o,r,a=p(p({},e),{position:"string"==typeof e.position?"left"===e.position.toLowerCase()?"Left":"right"===e.position.toLowerCase()?"Right":void 0:void 0,sideSpacing:"string"==typeof e.sideSpacing?""===e.sideSpacing||isNaN(Number(e.sideSpacing))?void 0:Number(e.sideSpacing):e.sideSpacing,bottomSpacing:"string"==typeof e.bottomSpacing?""===e.bottomSpacing||isNaN(Number(e.bottomSpacing))?void 0:Number(e.bottomSpacing):e.bottomSpacing});if(this.config=a,!e.api_key)throw z.trackError(new Error(Q[N](e.api_key)),"RobylonChatbot",{errorCode:N,errorType:K,context:{timestamp:Date.now()}}),new Error("API key is required");try{z.initialize(e.api_key,e.user_id)}catch(e){z.trackError(e instanceof Error?e:new Error(String(e)),"RobylonChatbot",{errorCode:j,errorType:K,context:{timestamp:Date.now()}})}this.stateManager=(n={api_key:e.api_key,user_id:e.user_id,user_token:e.user_token,user_profile:e.user_profile},i={isInitialized:!1,isInitializing:!1,error:null,chatbotConfig:null,isIframeVisible:!1},o=[],{getState:function(){return i},initialize:function(){return f(void 0,void 0,void 0,(function(){var e,t,i;return h(this,(function(o){switch(o.label){case 0:if(!n.api_key)return z.trackError(new Error(Q[N](n.api_key)),"ChatbotStateManager",{errorCode:N,errorType:K,context:{timestamp:Date.now()}}),[2];r({isInitializing:!0}),o.label=1;case 1:return o.trys.push([1,4,5,6]),[4,ge(n)];case 2:return e=o.sent(),[4,new Promise((function(t,n){re(e,(function(){r({isInitialized:!0,chatbotConfig:e}),t()}),(function(e){n(e)}))}))];case 3:return o.sent(),[3,6];case 4:return t=o.sent(),i=t instanceof Error?t.message:"Failed to initialize chatbot",r({error:i}),z.trackError(t instanceof Error?t:new Error(i),"ChatbotStateManager",{errorCode:B,errorType:K,context:{timestamp:Date.now()}}),[3,6];case 5:return r({isInitializing:!1}),[7];case 6:return[2]}}))}))},toggleIframeVisibility:function(){r({isIframeVisible:!i.isIframeVisible})},closeIframe:function(){r({isIframeVisible:!1})},updateState:r=function(e){i=p(p({},i),e),o.forEach((function(e){return e(i)}))},subscribe:function(e){return o.push(e),function(){var t=o.indexOf(e);t>-1&&o.splice(t,1)}},unsubscribe:function(e){var t=o.indexOf(e);t>-1&&o.splice(t,1)}}),this.eventEmitter=me({api_key:e.api_key,user_profile:e.user_profile,onEvent:e.onEvent,chatbotConfig:null}),this.initialize()}return e.prototype.initialize=function(){return f(this,void 0,void 0,(function(){var e;return h(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this.stateManager.initialize()];case 1:return t.sent(),this.stateManager.subscribe(this.handleStateChange),this.handleStateChange(this.stateManager.getState()),[3,3];case 2:return e=t.sent(),z.trackError(e instanceof Error?e:new Error(String(e)),"RobylonChatbot.initialize",{errorCode:B,errorType:K,context:{timestamp:Date.now()}}),[3,3];case 3:return[2]}}))}))},e.prototype.show=function(){this.stateManager.getState().isIframeVisible||(this.stateManager.toggleIframeVisibility(),this.eventEmitter.emit(b.CHATBOT_BUTTON_CLICKED))},e.prototype.hide=function(){this.stateManager.getState().isIframeVisible&&(this.stateManager.closeIframe(),this.eventEmitter.emit(b.CHATBOT_CLOSED))},e.prototype.toggle=function(){this.toggleIframe()},e.prototype.destroy=function(){this.isDestroyed=!0,this.floatingButton&&(this.floatingButton.destroy(),this.floatingButton=null),this.iframe&&(this.iframe.destroy(),this.iframe=null),this.container&&(this.container.destroy(),this.container=null),this.stateManager.unsubscribe(this.handleStateChange)},e.prototype.getState=function(){return this.stateManager.getState().isInitialized?"initialized":"uninitialized"},e}();function be(e){return new ve(e)}"undefined"!=typeof window&&function(){if("undefined"!=typeof window){var e=window.RobylonChatbot;if(e&&Array.isArray(e.q)){var t=null;e.q.forEach((function(e){var n=e[0];if("init"===n){var i=e[1]||{};t=be(i)}else t&&"function"==typeof t[n]&&t[n]()})),window.RobylonChatbot=function(e){for(var n,i=[],o=1;o<arguments.length;o++)i[o-1]=arguments[o];return"init"===e?t=be(i[0]||{}):t&&"function"==typeof t[e]?(n=t)[e].apply(n,i):void 0},window.RobylonChatbot.getState=function(){return"initialized"}}}}();var we={create:be,getState:function(){return"initialized"}};export{ce as Chatbot,c as ChatbotInterfaceType,u as LauncherType,we as RobylonChatbot,d as WidgetPositionEnums,de as useChatbot};
1209
2
  //# sourceMappingURL=index.js.map