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