@crestapps/ai-chat-ui 1.0.0-preview-22-preview.2 → 1.0.0-preview-22-preview.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-chat.js +17 -7
- package/dist/ai-chat.min.js +1 -1
- package/dist/chat-interaction.js +11 -5
- package/dist/chat-interaction.min.js +1 -1
- package/dist/chat-widget.css +117 -35
- package/dist/chat-widget.min.css +1 -1
- package/package.json +1 -1
package/dist/ai-chat.js
CHANGED
|
@@ -25,7 +25,6 @@ window.openAIChatManager = function () {
|
|
|
25
25
|
// UI defaults for generated media
|
|
26
26
|
generatedImageAltText: 'Generated Image',
|
|
27
27
|
generatedImageMaxWidth: 400,
|
|
28
|
-
generatedChartMaxWidth: 900,
|
|
29
28
|
downloadImageTitle: 'Download image',
|
|
30
29
|
downloadChartTitle: 'Download chart as image',
|
|
31
30
|
downloadChartButtonText: 'Download',
|
|
@@ -134,8 +133,7 @@ window.openAIChatManager = function () {
|
|
|
134
133
|
// its DOM update to render charts it didn't create itself.
|
|
135
134
|
window.__chartConfigs = window.__chartConfigs || {};
|
|
136
135
|
function createChartHtml(chartId) {
|
|
137
|
-
|
|
138
|
-
return "<div class=\"chart-container\" style=\"position: relative; width: 100%; max-width: ".concat(chartMaxWidth, "px;\">") + "<canvas id=\"".concat(chartId, "\" class=\"img-thumbnail\"></canvas>") + "</div>" + "<div class=\"mt-2\">" + "<button type=\"button\" class=\"btn btn-sm btn-outline-secondary download-chart-btn\" data-chart-id=\"".concat(chartId, "\" title=\"").concat(defaultConfig.downloadChartTitle, "\">") + "<i class=\"fa-solid fa-download\"></i> ".concat(defaultConfig.downloadChartButtonText) + "</button>" + "</div>";
|
|
136
|
+
return "<div class=\"chart-container\" style=\"position: relative; width: 100%; max-width: 560px; min-height: 420px;\">" + "<canvas id=\"".concat(chartId, "\"></canvas>") + "</div>" + "<div class=\"mt-2\">" + "<button type=\"button\" class=\"btn btn-sm btn-outline-secondary download-chart-btn\" data-chart-id=\"".concat(chartId, "\" title=\"").concat(defaultConfig.downloadChartTitle, "\">") + "<i class=\"fa-solid fa-download\"></i> ".concat(defaultConfig.downloadChartButtonText) + "</button>" + "</div>";
|
|
139
137
|
}
|
|
140
138
|
|
|
141
139
|
// Register [chart:{...json...}] as a native marked block extension so the
|
|
@@ -263,25 +261,37 @@ window.openAIChatManager = function () {
|
|
|
263
261
|
function renderChartOnCanvas(chartId, config) {
|
|
264
262
|
var canvas = document.getElementById(chartId);
|
|
265
263
|
if (!canvas) {
|
|
266
|
-
return;
|
|
264
|
+
return false;
|
|
267
265
|
}
|
|
268
266
|
if (typeof Chart === 'undefined') {
|
|
269
267
|
console.warn('Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>).');
|
|
270
|
-
return;
|
|
268
|
+
return false;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// When the canvas is inside a hidden container (e.g., a widget panel with
|
|
272
|
+
// display:none), it has zero dimensions and Chart.js cannot render correctly.
|
|
273
|
+
// Keep the config in __chartConfigs so renderPendingCharts() can retry later
|
|
274
|
+
// once the container becomes visible.
|
|
275
|
+
if (canvas.offsetParent === null) {
|
|
276
|
+
window.__chartConfigs[chartId] = config;
|
|
277
|
+
return false;
|
|
271
278
|
}
|
|
272
279
|
try {
|
|
273
|
-
var _cfg$options;
|
|
280
|
+
var _cfg$options, _cfg$options2, _cfg$options2$aspectR;
|
|
274
281
|
if (canvas._chartInstance) {
|
|
275
282
|
canvas._chartInstance.destroy();
|
|
276
283
|
}
|
|
277
284
|
var cfg = typeof config === 'string' ? JSON.parse(config) : config;
|
|
278
285
|
(_cfg$options = cfg.options) !== null && _cfg$options !== void 0 ? _cfg$options : cfg.options = {};
|
|
279
286
|
cfg.options.responsive = true;
|
|
280
|
-
cfg.options.maintainAspectRatio =
|
|
287
|
+
cfg.options.maintainAspectRatio = true;
|
|
288
|
+
(_cfg$options2$aspectR = (_cfg$options2 = cfg.options).aspectRatio) !== null && _cfg$options2$aspectR !== void 0 ? _cfg$options2$aspectR : _cfg$options2.aspectRatio = 4 / 3;
|
|
281
289
|
canvas._chartInstance = new Chart(canvas, cfg);
|
|
282
290
|
delete window.__chartConfigs[chartId];
|
|
291
|
+
return true;
|
|
283
292
|
} catch (e) {
|
|
284
293
|
console.error('Error creating chart:', e);
|
|
294
|
+
return false;
|
|
285
295
|
}
|
|
286
296
|
}
|
|
287
297
|
|
package/dist/ai-chat.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",o=n.toStringTag||"@@toStringTag";function s(n,i,o,s){var c=i&&i.prototype instanceof r?i:r,l=Object.create(c.prototype);return _regeneratorDefine2(l,"_invoke",function(n,i,o){var s,r,c,l=0,d=o||[],u=!1,h={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return s=t,r=0,c=e,h.n=n,a}};function f(n,i){for(r=n,c=i,t=0;!u&&l&&!o&&t<d.length;t++){var o,s=d[t],f=h.p,m=s[2];n>3?(o=m===i)&&(c=s[(r=s[4])?5:(r=3,3)],s[4]=s[5]=e):s[0]<=f&&((o=n<2&&f<s[1])?(r=0,h.v=i,h.n=s[1]):f<m&&(o=n<3||s[0]>i||i>m)&&(s[4]=n,s[5]=i,h.n=m,r=0))}if(o||n>1)return a;throw u=!0,i}return function(o,d,m){if(l>1)throw TypeError("Generator is already running");for(u&&1===d&&f(d,m),r=d,c=m;(t=r<2?e:c)||!u;){s||(r?r<3?(r>1&&(h.n=-1),f(r,c)):h.n=c:h.v=c);try{if(l=2,s){if(r||(o="next"),t=s[o]){if(!(t=t.call(s,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,r<2&&(r=0)}else 1===r&&(t=s.return)&&t.call(s),r<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),r=1);s=e}else if((t=(u=h.n<0)?c:n.call(i,h))!==a)break}catch(t){s=e,r=1,c=t}finally{l=1}}return{value:t,done:u}}}(n,o,s),!0),l}var a={};function r(){}function c(){}function l(){}t=Object.getPrototypeOf;var d=[][i]?t(t([][i]())):(_regeneratorDefine2(t={},i,function(){return this}),t),u=l.prototype=r.prototype=Object.create(d);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return c.prototype=l,_regeneratorDefine2(u,"constructor",l),_regeneratorDefine2(l,"constructor",c),c.displayName="GeneratorFunction",_regeneratorDefine2(l,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,i,function(){return this}),_regeneratorDefine2(u,"toString",function(){return"[object Generator]"}),(_regenerator=function(){return{w:s,m:h}})()}function _regeneratorDefine2(e,t,n,i){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}_regeneratorDefine2=function(e,t,n,i){function s(t,n){_regeneratorDefine2(e,t,function(e){return this._invoke(t,n,e)})}t?o?o(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(s("next",0),s("throw",1),s("return",2))},_regeneratorDefine2(e,t,n,i)}function asyncGeneratorStep(e,t,n,i,o,s,a){try{var r=e[s](a),c=r.value}catch(e){return void n(e)}r.done?t(c):Promise.resolve(c).then(i,o)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(i,o){var s=e.apply(t,n);function a(e){asyncGeneratorStep(s,i,o,a,r,"next",e)}function r(e){asyncGeneratorStep(s,i,o,a,r,"throw",e)}a(void 0)})}}function _createForOfIteratorHelper(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var i=0,o=function(){};return{s:o,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,r=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){r=!0,s=e},f:function(){try{a||null==n.return||n.return()}finally{if(r)throw s}}}}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray(e)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray(e,t)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function _iterableToArrayLimit(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,o,s,a,r=[],c=!0,l=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=s.call(n)).done)&&(r.push(i.value),r.length!==t);c=!0);}catch(e){l=!0,o=e}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return r}}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}window.openAIChatManager=function(){var e={generatedImageAltText:"Generated Image",generatedImageMaxWidth:400,generatedChartMaxWidth:900,downloadImageTitle:"Download image",downloadChartTitle:"Download chart as image",downloadChartButtonText:"Download",userLabel:"You",assistantLabel:"Assistant",thumbsUpTitle:"Thumbs up",thumbsDownTitle:"Thumbs down",copyTitle:"Click here to copy response to clipboard.",codeCopiedText:"Copied!",messageTemplate:'\n <div class="ai-chat-messages">\n <div v-for="(message, index) in messages" :key="\'msg-\' + index" class="ai-chat-message-item">\n <div>\n <div v-if="message.role === \'user\'" class="ai-chat-msg-role ai-chat-msg-role-user">{{ userLabel }}</div>\n <div v-else-if="message.role !== \'indicator\'" :class="getAssistantRoleClasses(message)">\n <span :class="getAssistantIconClasses(message, index)"><i :class="getAssistantIcon(message)"></i></span>\n {{ getAssistantLabel(message) }}\n </div>\n <div class="ai-chat-message-body lh-base">\n <h4 v-if="message.title">{{ message.title }}</h4>\n <div v-html="message.htmlContent"></div>\n <span class="message-buttons-container" v-if="!isIndicator(message)">\n <template v-if="metricsEnabled && message.role === \'assistant\'">\n <span class="ai-chat-message-assistant-feedback" :data-message-id="message.id">\n <button class="btn btn-sm btn-link text-success p-0 me-2 button-message-toolbox rate-up-btn" @click="rateMessage(message, true, $event)" :title="thumbsUpTitle">\n <i class="fa-regular fa-thumbs-up"></i>\n </button>\n <button class="btn btn-sm btn-link text-danger p-0 me-2 button-message-toolbox rate-down-btn" @click="rateMessage(message, false, $event)" :title="thumbsDownTitle">\n <i class="fa-regular fa-thumbs-down"></i>\n </button>\n </span>\n </template>\n <button class="btn btn-sm btn-link text-secondary p-0 button-message-toolbox" @click="copyResponse(message.content)" :title="copyTitle">\n <i class="fa-solid fa-copy"></i>\n </button>\n </span>\n </div>\n </div>\n </div>\n <div v-for="notification in notifications" :key="\'notif-\' + notification.type" class="ai-chat-notification" :class="\'ai-chat-notification-\' + (notification.type || \'info\') + \' \' + (notification.cssClass || \'\')">\n <div class="ai-chat-notification-content">\n <i v-if="notification.icon" :class="notification.icon" class="ai-chat-notification-icon"></i>\n <span class="ai-chat-notification-text">{{ notification.content }}</span>\n <button v-if="notification.dismissible" class="btn btn-sm btn-link p-0 ms-2 ai-chat-notification-dismiss" @click="dismissNotification(notification.type)" title="Dismiss">\n <i class="fa-solid fa-xmark"></i>\n </button>\n </div>\n <div v-if="notification.actions && notification.actions.length" class="ai-chat-notification-actions">\n <button v-for="action in notification.actions" :key="action.name" class="btn btn-sm" :class="action.cssClass || \'btn-outline-secondary\'" @click="handleNotificationAction(notification.type, action.name)">\n <i v-if="action.icon" :class="action.icon" class="me-1"></i>\n {{ action.label }}\n </button>\n </div>\n </div>\n </div>\n ',indicatorTemplate:'\n <div class="ai-chat-msg-role ai-chat-msg-role-assistant">\n <span class="ai-streaming-icon"><i class="fa fa-robot" style="display: inline-block;"></i></span>\n Assistant\n </div>\n '};function t(e){if(!e)return"";var t=e.trim();return/^javascript:/i.test(t)||/^vbscript:/i.test(t)||/^data:text\/html/i.test(t)?"":e}function n(e){var t=document.createElement("span");return t.textContent=e,t.innerHTML}function i(e){var t,n,i,o,s,a;if(!e||"object"!==_typeof(e))return null;var r=Object.assign({},e);return r.index=null!==(t=null!==(n=r.index)&&void 0!==n?n:r.Index)&&void 0!==t?t:0,r.text=null!==(i=null!==(o=r.text)&&void 0!==o?o:r.Text)&&void 0!==i?i:null,r.link=null!==(s=null!==(a=r.link)&&void 0!==a?a:r.Link)&&void 0!==s?s:null,r}function o(e){if(!e||"object"!==_typeof(e))return{};for(var t={},n=0,o=Object.entries(e);n<o.length;n++){var s,a=_slicedToArray(o[n],2),r=a[0],c=a[1];t[r]=null!==(s=i(c))&&void 0!==s?s:{}}return t}var s=new marked.Renderer;s.link=function(e){var n=t(e.href);return n?'<a href="'.concat(n,'" target="_blank" rel="noopener noreferrer">').concat(e.text,"</a>"):e.text||""},s.code=function(e){var t=e.text||"",i=(e.lang||"").trim(),o=t;if("undefined"!=typeof hljs)if(i&&hljs.getLanguage(i))try{o=hljs.highlight(t,{language:i}).value}catch(e){}else try{o=hljs.highlightAuto(t).value}catch(e){}else o=n(t);var s=i?n(i):"code";return'<div class="ai-code-block"><div class="ai-code-header"><span class="ai-code-lang"><i class="fa-solid fa-code"></i> '.concat(s,'</span><button type="button" class="ai-code-copy-btn" title="Copy code"><i class="fa-regular fa-copy"></i></button></div><pre><code class="hljs').concat(i?" language-"+i:"",'">').concat(o,"</code></pre></div>")},s.image=function(n){var i=t(n.href);if(!i)return"";var o=n.text||e.generatedImageAltText,s=e.generatedImageMaxWidth;return'<div class="generated-image-container">\n <img src="'.concat(i,'" alt="').concat(o,'" class="img-thumbnail" style="max-width: ').concat(s,'px; height: auto;" />\n <div class="mt-2">\n <a href="').concat(i,'" target="_blank" download="').concat(o,'" title="').concat(e.downloadImageTitle,'" class="btn btn-sm btn-outline-secondary ai-download-image">\n <i class="fa-solid fa-download"></i>\n </a>\n </div>\n </div>')};var a=0,r=[];function c(e){if(e&&e._pendingCharts&&e._pendingCharts.length){var t=_toConsumableArray(e._pendingCharts);e._pendingCharts=[],requestAnimationFrame(function(){var e,n=_createForOfIteratorHelper(t);try{for(n.s();!(e=n.n()).done;){var i=e.value;l(i.chartId,i.config)}}catch(e){n.e(e)}finally{n.f()}})}}function l(e,t){var n=document.getElementById(e);if(n)if("undefined"!=typeof Chart)try{var i;n._chartInstance&&n._chartInstance.destroy();var o="string"==typeof t?JSON.parse(t):t;null!==(i=o.options)&&void 0!==i||(o.options={}),o.options.responsive=!0,o.options.maintainAspectRatio=!1,n._chartInstance=new Chart(n,o),delete window.__chartConfigs[e]}catch(e){console.error("Error creating chart:",e)}else console.warn('Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"><\/script>).')}function d(e,t){r=[];var n=marked.parse(e,{renderer:s});return t._pendingCharts=r.length>0?_toConsumableArray(r):[],DOMPurify.sanitize(n,{ADD_TAGS:["canvas"],ADD_ATTR:["target"]})}window.__chartConfigs=window.__chartConfigs||{},marked.use({extensions:[{name:"chart",level:"block",start:function(e){var t=e.indexOf("[chart:");return t>=0?t:void 0},tokenizer:function(e){var t=function(e){var t="[chart:",n=e.indexOf(t);if(n<0)return null;var i=n+t.length,o=i;for(;o<e.length&&(" "===e[o]||"\n"===e[o]||"\r"===e[o]||"\t"===e[o]);)o++;if(o>=e.length||"{"!==e[o])return null;for(var s=0,a=!1,r=!1;o<e.length;o++){var c=e[o];if(a){if(r){r=!1;continue}if("\\"===c){r=!0;continue}'"'===c&&(a=!1)}else if('"'!==c){if("{"===c)s++;else if("}"===c&&0===--s){var l=o,d=e.indexOf("]",l+1);return d<0?null:{startIndex:n,endIndex:d+1,json:e.substring(i,l+1).trim()}}}else a=!0}return null}(e);if(t&&0===t.startIndex){var n="chat_chart_".concat(++a);return{type:"chart",raw:e.substring(0,t.endIndex),chartId:n,json:t.json}}},renderer:function(t){return r.push({chartId:t.chartId,config:t.json}),window.__chartConfigs[t.chartId]=t.json,n=t.chartId,i=e.generatedChartMaxWidth,'<div class="chart-container" style="position: relative; width: 100%; max-width: '.concat(i,'px;">')+'<canvas id="'.concat(n,'" class="img-thumbnail"></canvas>')+'</div><div class="mt-2">'+'<button type="button" class="btn btn-sm btn-outline-secondary download-chart-btn" data-chart-id="'.concat(n,'" title="').concat(e.downloadChartTitle,'">')+'<i class="fa-solid fa-download"></i> '.concat(e.downloadChartButtonText)+"</button></div>";var n,i}}]}),window.renderPendingCharts=function(){if("undefined"!=typeof Chart){var e=window.__chartConfigs;e&&requestAnimationFrame(function(){for(var t=0,n=Object.keys(e);t<n.length;t++){var i=n[t];l(i,e[i])}})}};return{initialize:function(t){var n=Object.assign({},e,t);if(e=n,n.signalRHubUrl)if(n.appElementSelector)if(n.chatContainerElementSelector)if(n.inputElementSelector){if(n.sendButtonElementSelector)return Vue.createApp({data:function(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isSessionStarted:!1,isPlaceholderVisible:!0,chatWidgetStateName:null,chatWidgetStateSession:null,chatHistorySection:null,widgetIsInitialized:!1,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,messages:[],notifications:[],prompt:"",documents:n.existingDocuments||[],isUploading:!1,uploadErrors:[],isDragOver:!1,documentBar:null,metricsEnabled:!!n.metricsEnabled,userLabel:n.userLabel,assistantLabel:n.assistantLabel,thumbsUpTitle:n.thumbsUpTitle,thumbsDownTitle:n.thumbsDownTitle,copyTitle:n.copyTitle,isRecording:!1,mediaRecorder:null,preRecordingPrompt:"",micButton:null,speechToTextEnabled:"AudioInput"===n.chatMode||"Conversation"===n.chatMode,textToSpeechEnabled:"Conversation"===n.chatMode,ttsVoiceName:n.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,ttsButton:null,conversationModeEnabled:"Conversation"===n.chatMode,conversationButton:null,isConversationMode:!1,notificationDismissTimers:{}}},computed:{lastAssistantIndex:function(){for(var e=this.messages.length-1;e>=0;e--)if("assistant"===this.messages[e].role)return e;return-1}},methods:{handleBeforeUnload:function(){this.isNavigatingAway=!0},handleDragOver:function(e){if(n.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!0;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.add("ai-chat-drag-over")}},handleDragLeave:function(e){if(n.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.remove("ai-chat-drag-over")}},handleDrop:function(e){if(n.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.remove("ai-chat-drag-over"),e.dataTransfer&&e.dataTransfer.files&&e.dataTransfer.files.length>0&&this.uploadFiles(e.dataTransfer.files)}},triggerFileInput:function(){if(n.sessionDocumentsEnabled){var e=document.getElementById("ai-chat-doc-input");e&&e.click()}},handleFileInputChange:function(e){var t=e.target.files;t&&t.length>0&&this.uploadFiles(t),e.target.value=""},uploadFiles:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function i(){var o,s,a,r,c,l,d,u,h,f;return _regenerator().w(function(i){for(;;)switch(i.p=i.n){case 0:if(n.uploadDocumentUrl){i.n=1;break}return i.a(2);case 1:if(o=t.getSessionId(),s=t.getProfileId(),o||s){i.n=2;break}return console.warn("Cannot upload documents without a session or profile."),i.a(2);case 2:for(t.isUploading=!0,t.uploadErrors=[],t.renderDocumentBar(),i.p=3,a=new FormData,o?a.append("sessionId",o):a.append("profileId",s),r=0;r<e.length;r++)a.append("files",e[r]);return i.n=4,fetch(n.uploadDocumentUrl,{method:"POST",body:a});case 4:if((c=i.v).ok){i.n=6;break}return i.n=5,c.text();case 5:return l=i.v,d=t.extractReadableErrorMessage(l,"Upload failed. Please try again."),console.error("Upload failed:",l),t.uploadErrors=[{fileName:"",error:d}],i.a(2);case 6:return i.n=7,c.json();case 7:if((u=i.v).sessionId&&!o&&t.initializeSession(u.sessionId),u.uploaded&&u.uploaded.length>0)for(h=0;h<u.uploaded.length;h++)t.documents.push(u.uploaded[h]);u.failed&&u.failed.length>0&&(t.uploadErrors=u.failed),i.n=9;break;case 8:i.p=8,f=i.v,console.error("Upload error:",f),t.uploadErrors=[{fileName:"",error:"Upload failed. Please try again."}];case 9:return i.p=9,t.isUploading=!1,t.renderDocumentBar(),i.f(9);case 10:return i.a(2)}},i,null,[[3,8,9,10]])}))()},removeDocument:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function i(){var o,s,a,r,c,l;return _regenerator().w(function(i){for(;;)switch(i.p=i.n){case 0:if(n.removeDocumentUrl){i.n=1;break}return i.a(2);case 1:return i.p=1,o=t.getSessionId(),i.n=2,fetch(n.removeDocumentUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({itemId:o,documentId:e.documentId})});case 2:if(!(s=i.v).ok){i.n=3;break}(a=t.documents.indexOf(e))>-1&&t.documents.splice(a,1),i.n=5;break;case 3:return i.n=4,s.text();case 4:r=i.v,c=t.extractReadableErrorMessage(r,"Failed to remove document. Please try again."),console.error("Failed to remove document:",s.status,r),t.uploadErrors=[{fileName:e.fileName||"",error:c}],t.renderDocumentBar();case 5:i.n=7;break;case 6:i.p=6,l=i.v,console.error("Remove document error:",l),t.uploadErrors=[{fileName:e.fileName||"",error:"Failed to remove document. Please try again."}],t.renderDocumentBar();case 7:return i.a(2)}},i,null,[[1,6]])}))()},formatFileSize:function(e){return e<1024?e+" B":e<1048576?(e/1024).toFixed(1)+" KB":(e/1048576).toFixed(1)+" MB"},renderDocumentBar:function(){if(this.documentBar)if(n.sessionDocumentsEnabled){this.documentBar.classList.remove("d-none");var e='<div class="ai-chat-doc-bar p-2">';e+='<div class="d-flex flex-wrap align-items-center gap-1">';for(var t=0;t<this.documents.length;t++){var i=this.documents[t],o=i.fileName||"Document";o.length>20&&(o=o.substring(0,17)+"..."),e+='<span class="badge bg-secondary bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="'+this.escapeHtml(i.fileName||"")+'">',e+='<i class="fa-solid fa-file-lines" style="font-size: 0.7rem;"></i> ',e+=this.escapeHtml(o),e+=' <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-doc-index="'+t+'" aria-label="Remove"></button>',e+="</span>"}for(var s=0;s<this.uploadErrors.length;s++){var a=this.uploadErrors[s],r=a.fileName||"File",c=a.error||"Upload failed";r.length>15&&(r=r.substring(0,12)+"..."),e+='<span class="badge bg-danger bg-opacity-25 text-danger d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="'+this.escapeHtml((a.fileName||"")+": "+c)+'">',e+='<i class="fa-solid fa-circle-exclamation" style="font-size: 0.7rem;"></i> ',e+=this.escapeHtml(r),e+=' <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-error-index="'+s+'" aria-label="Dismiss"></button>',e+="</span>"}this.isUploading&&(e+='<span class="badge bg-info bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;">',e+='<span class="spinner-border spinner-border-sm" style="width: 0.7rem; height: 0.7rem;"></span> Uploading...',e+="</span>"),e+='<button type="button" class="btn btn-sm btn-outline-secondary rounded-pill ai-chat-doc-add-btn d-inline-flex align-items-center gap-1" style="font-size: 0.75rem; padding: 0.15rem 0.5rem;" title="Attach documents">',e+='<i class="fa-solid fa-paperclip"></i>',0!==this.documents.length||this.isUploading||(e+=" <span>Attach files</span>"),e+="</button>",e+="</div>",n.supportedExtensionsText&&(e+='<div class="small text-muted mt-2">Supported formats: '+this.escapeHtml(n.supportedExtensionsText)+"</div>"),e+="</div>",this.documentBar.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}));for(var l=this,d=this.documentBar.querySelectorAll("[data-doc-index]"),u=0;u<d.length;u++)d[u].addEventListener("click",function(e){return function(t){t.preventDefault(),t.stopPropagation();var n=l.documents[e];n&&l.removeDocument(n)}}(parseInt(d[u].getAttribute("data-doc-index"))));for(var h=this.documentBar.querySelectorAll("[data-error-index]"),f=0;f<h.length;f++)h[f].addEventListener("click",function(e){return function(t){t.preventDefault(),t.stopPropagation(),l.uploadErrors.splice(e,1),l.renderDocumentBar()}}(parseInt(h[f].getAttribute("data-error-index"))));var m=this.documentBar.querySelector(".ai-chat-doc-add-btn");m&&m.addEventListener("click",function(e){e.preventDefault(),l.triggerFileInput()})}else this.documentBar.classList.add("d-none")},escapeHtml:function(e){var t=document.createElement("div");return t.textContent=e,t.innerHTML},extractReadableErrorMessage:function(e,t){if(!e||"string"!=typeof e)return t;var n=e.trim();if(!n)return t;if(n.startsWith("{")||n.startsWith("["))try{var i=JSON.parse(n),o=(null==i?void 0:i.error)||(null==i?void 0:i.message)||(null==i?void 0:i.title)||(null==i?void 0:i.detail);return"string"==typeof o&&o.trim()?o.trim():t}catch(e){return t}return/<[^>]+>/.test(n)?t:n},normalizeAssistantAppearance:function(e){if(!e)return null;var t="string"==typeof e.label?e.label.trim():"",n="string"==typeof e.icon?e.icon.trim():"",i="string"==typeof e.cssClass?e.cssClass.trim():"",o=!!e.disableStreamingAnimation;return t||n||i||o?{label:t,icon:n,cssClass:i,disableStreamingAnimation:o}:null},getAssistantLabel:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.label?t.label:this.assistantLabel},getAssistantRoleClasses:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null,n=["ai-chat-msg-role"];return t&&t.cssClass?n.push(t.cssClass):n.push("ai-chat-msg-role-assistant"),n},getAssistantIconClasses:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return[this.shouldAnimateAssistantIcon(e,t)?"ai-streaming-icon":"ai-bot-icon",n&&n.cssClass?n.cssClass:""]},getAssistantIcon:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.icon?t.icon:"fa fa-robot"},shouldAnimateAssistantIcon:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return!!e&&e.isStreaming&&t===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},startConnection:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var i;return _regenerator().w(function(t){for(;;)switch(t.p=t.n){case 0:return e.connection=(new signalR.HubConnectionBuilder).withUrl(n.signalRHubUrl).withAutomaticReconnect().build(),e.connection.serverTimeoutInMilliseconds=6e5,e.connection.keepAliveIntervalInMilliseconds=15e3,e.connection.on("LoadSession",function(t){var i;e.initializeSession(t.sessionId,!0),e.messages=[],e.documents=t.documents||[],(null!==(i=t.messages)&&void 0!==i?i:[]).forEach(function(t){e.addMessage(t),e.$nextTick(function(){c(t)})}),e.$nextTick(function(){e.refreshAllFeedbackIcons()}),0===e.messages.length&&n.initialPrompt&&(e.prompt=n.initialPrompt,e.sendMessage())}),e.connection.on("ReceiveError",function(t){console.error("SignalR Error: ",t),e.isRecording&&e.stopRecording(),!e.widgetIsInitialized||e.isSessionStarted||e._attemptedSessionRecovery||(e._attemptedSessionRecovery=!0,localStorage.removeItem(e.chatWidgetStateSession),e.startNewSession())}),e.connection.on("MessageRated",function(t,n){var i=e.messages.find(function(e){return e.id===t});i&&(i.userRating=n)}),e.connection.on("ReceiveTranscript",function(t,n,i){if(e.isConversationMode){if(!i&&n){e._conversationPartialTranscript=n;var o='<p class="ai-partial-transcript">'+n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")+"</p>";e._conversationPartialMessage?(e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent=o):(e.hidePlaceholder(),e._conversationPartialMessage={role:"user",content:n,htmlContent:o,isPartial:!0},e.messages.push(e._conversationPartialMessage)),e.scrollToBottom()}}else n&&!e._audioInputSent&&(e.prompt=e.preRecordingPrompt+n,e.inputElement&&(e.inputElement.value=e.prompt,e.inputElement.dispatchEvent(new Event("input"))))}),e.connection.on("ReceiveConversationUserMessage",function(t,n){if(n){if(e.stopAudio(),e._conversationAssistantMessage){var i=e.messages[e._conversationAssistantMessage.index];i&&(i.isStreaming=!1),e._conversationAssistantMessage=null}if(e._conversationPartialMessage){var o=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent="<p>"+o+"</p>",e._conversationPartialMessage.isPartial=!1,e._conversationPartialMessage=null}else e.addMessage({role:"user",content:n});e.scrollToBottom()}}),e.connection.on("ReceiveConversationAssistantToken",function(t,n,i,o,s){if(!e._conversationAssistantMessage){e.stopAudio(),e.hideTypingIndicator();for(var a=0;a<e.messages.length;a++)e.messages[a].isStreaming&&(e.messages[a].isStreaming=!1);var r=e.messages.length,l={id:n,role:"assistant",content:"",htmlContent:"",isStreaming:!0,userRating:null,appearance:e.normalizeAssistantAppearance(s)};e.messages.push(l),e._conversationAssistantMessage={index:r,content:""}}e._conversationAssistantMessage.content+=i;var u=e.messages[e._conversationAssistantMessage.index];u&&(u.appearance||(u.appearance=e.normalizeAssistantAppearance(s)),u.content=e._conversationAssistantMessage.content,u.htmlContent=d(u.content,u),e.$nextTick(function(){c(u),e.scrollToBottom()}))}),e.connection.on("ReceiveConversationAssistantComplete",function(t,n){if(e._conversationAssistantMessage){var i=e.messages[e._conversationAssistantMessage.index];i&&(i.isStreaming=!1),e._conversationAssistantMessage=null}}),e.connection.on("ReceiveAudioChunk",function(t,n,i){if(n){for(var o=atob(n),s=new Uint8Array(o.length),a=0;a<o.length;a++)s[a]=o.charCodeAt(a);e.audioChunks.push(s)}}),e.connection.on("ReceiveAudioComplete",function(t){e.playCollectedAudio()}),e.connection.on("ReceiveNotification",function(t){e.receiveNotification(t)}),e.connection.on("UpdateNotification",function(t){e.updateNotification(t)}),e.connection.on("RemoveNotification",function(t){e.removeNotification(t)}),e.connection.onreconnecting(function(){console.warn("SignalR: reconnecting...")}),e.connection.onreconnected(function(){console.info("SignalR: reconnected."),e.isSessionStarted?e.reloadCurrentSession():n.autoCreateSession&&e.startNewSession()}),e.connection.onclose(function(t){e.isNavigatingAway||t&&console.warn("SignalR connection closed with error:",t.message||t)}),t.p=1,t.n=2,e.connection.start();case 2:t.n=4;break;case 3:t.p=3,i=t.v,console.error("SignalR Connection Error: ",i);case 4:return t.a(2)}},t,null,[[1,3]])}))()},addMessageInternal:function(e){var t=this;"assistant"===e.role&&(e.appearance=this.normalizeAssistantAppearance(e.appearance)),e.content&&!e.htmlContent&&(e.htmlContent=d(e.content,e)),this.fireEvent(new CustomEvent("addingOpenAIPromotMessage",{detail:{message:e}})),this.messages.push(e),this.$nextTick(function(){t.fireEvent(new CustomEvent("addedOpenAIPromotMessage",{detail:{message:e}}))})},addMessage:function(e){var t=this;if(void 0===e.userRating&&(e.userRating=null),e.content){var n=e.content.trim();if(e.references=o(e.references),e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length){var i=Object.entries(e.references).filter(function(e){var t=_slicedToArray(e,1)[0];return n.includes(t)});if(i.length){i.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var s,a=1,r=_createForOfIteratorHelper(i);try{for(r.s();!(s=r.n()).done;){var l=_slicedToArray(s.value,2),u=l[0],h=l[1],f="__CITE_".concat(h.index,"__");n=n.replaceAll(u,f),h._displayIndex=a++,h._placeholder=f}}catch(e){r.e(e)}finally{r.f()}var m,p=_createForOfIteratorHelper(i);try{for(p.s();!(m=p.n()).done;){var g=_slicedToArray(m.value,2)[1];n=n.replaceAll(g._placeholder,"<sup><strong>".concat(g._displayIndex,"</strong></sup>"))}}catch(e){p.e(e)}finally{p.f()}n=n.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),n+="<br><br>";var v,y=_createForOfIteratorHelper(i);try{for(y.s();!(v=y.n()).done;){var b=_slicedToArray(v.value,2),S=b[0],A=b[1],_=A.text||S;n+=A.link?"**".concat(A._displayIndex,"**. [").concat(_,"](").concat(A.link,")<br>"):"**".concat(A._displayIndex,"**. ").concat(_,"<br>")}}catch(e){y.e(e)}finally{y.f()}}}e.content=n,e.htmlContent=d(n,e)}this.addMessageInternal(e),this.hidePlaceholder(),this.$nextTick(function(){c(e),t.scrollToBottom()})},addMessages:function(e){for(var t=this,n=0;n<e.length;n++)this.addMessageInternal(e[n]);this.hidePlaceholder(),this.$nextTick(function(){t.scrollToBottom()})},hidePlaceholder:function(){this.placeholder&&this.placeholder.classList.add("d-none"),this.isPlaceholderVisible=!1},showPlaceholder:function(){this.placeholder&&this.placeholder.classList.remove("d-none"),this.isPlaceholderVisible=!0},isOrchestratorAvailable:function(){return!1!==n.isOrchestratorAvailable},applyOrchestratorAvailability:function(){if(this.isOrchestratorAvailable())return!0;var e=n.orchestratorUnavailableMessage||"This orchestrator is not currently available.";return this.inputElement&&(this.inputElement.disabled=!0,this.inputElement.value="",this.inputElement.placeholder=e),this.buttonElement&&(this.buttonElement.disabled=!0),this.micButtonElement&&(this.micButtonElement.disabled=!0,this.micButtonElement.style.display="none"),this.conversationButtonElement&&(this.conversationButtonElement.disabled=!0,this.conversationButtonElement.style.display="none"),!1},fireEvent:function(e){document.dispatchEvent(e)},isIndicator:function(e){return"indicator"===e.role},sendMessage:function(){if(this.applyOrchestratorAvailability()){var e=this.prompt.trim();e&&(this.isRecording&&this.stopRecording(),this._audioInputSent=!0,this.addMessage({role:"user",content:e}),this.streamMessage(this.getProfileId(),e,null),this.inputElement.value="",this.prompt="")}},startRecording:function(){var e=this;!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e.preRecordingPrompt=e.prompt,e._audioInputSent=!1;var i=new signalR.Subject,o=e.getProfileId(),s=e.getSessionId()||"",a=Promise.resolve();e.mediaRecorder.addEventListener("dataavailable",function(e){e.data&&e.data.size>0&&(a=a.then(_asyncToGenerator(_regenerator().m(function t(){var n,o,s,a;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.data.arrayBuffer();case 1:n=t.v,o=new Uint8Array(n),s=o.reduce(function(e,t){return e+String.fromCharCode(t)},""),a=btoa(s),i.next(a);case 2:return t.a(2)}},t)}))))}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),a.then(function(){return i.complete()})});var r=navigator.language||document.documentElement.lang||"en-US";e.connection.send("SendAudioStream",o,s,i,n,r),e.mediaRecorder.start(250),e.isRecording=!0,e.updateMicButton()}).catch(function(e){console.error("Microphone access denied:",e)})},stopRecording:function(){this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1,this.updateMicButton())},toggleRecording:function(){this.isRecording?this.stopRecording():this.startRecording()},updateMicButton:function(){this.micButton&&(this.isRecording?(this.micButton.classList.add("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-stop"></i>'):(this.micButton.classList.remove("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-microphone"></i>'))},streamMessage:function(e,t,n){var o=this;this.stream&&(this.stream.dispose(),this.stream=null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var s="",a={},r=null,l=this.messages.length,u=this.getSessionId();this.stream=this.connection.stream("SendMessage",e,t,u,n).subscribe({next:function(e){var t=o.messages[l];if(!t){e.sessionId&&!u&&o.initializeSession(e.sessionId),o.hideTypingIndicator(),l=o.messages.length;var n={id:e.messageId,role:"assistant",title:e.title,content:"",htmlContent:"",isStreaming:!0,userRating:null};o.messages.push(n),t=n}if(!e.title||t.title&&t.title===e.title||(t.title=e.title),e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length)for(var h=0,f=Object.entries(e.references);h<f.length;h++){var m,p=_slicedToArray(f[h],2),g=p[0],v=p[1];a[g]=null!==(m=i(v))&&void 0!==m?m:{}}if(e.content){e.responseId&&r&&e.responseId!==r&&(s+="\n\n"),e.responseId&&(r=e.responseId);for(var y=e.content,b=0,S=Object.entries(a);b<S.length;b++){var A=_slicedToArray(S[b],2),_=A[0],E=A[1];y=y.replaceAll(_,"<sup><strong>".concat(E.index,"</strong></sup>"))}s+=y.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>")}t.content=s,t.htmlContent=d(s,t),o.messages[l]=t,o.$nextTick(function(){c(t),o.scrollToBottom()})},complete:function(){var e;o.processReferences(a,l),o.streamingFinished();var t=o.messages[l];t&&(t.isStreaming=!1),t&&t.content||o.hideTypingIndicator(),o.isConversationMode&&o.textToSpeechEnabled&&t&&t.content&&o.synthesizeSpeech(t.content),null===(e=o.stream)||void 0===e||e.dispose(),o.stream=null},error:function(e){var t;o.processReferences(a,l),o.streamingFinished();var n=o.messages[l];n&&(n.isStreaming=!1),o.hideTypingIndicator(),o.isNavigatingAway||o.addMessage(o.getServiceDownMessage()),null===(t=o.stream)||void 0===t||t.dispose(),o.stream=null,console.error("Stream error:",e)}})},getServiceDownMessage:function(){return{role:"assistant",content:"Our service is currently unavailable. Please try again later. We apologize for the inconvenience.",htmlContent:""}},processReferences:function(e,t){var n=this;if(e=o(e),Object.keys(e).length){var i=this.messages[t],s=i.content||"",a=Object.entries(e).filter(function(e){var t=_slicedToArray(e,2),n=t[0],i=t[1];return s.includes(n)||s.includes("<sup><strong>".concat(i.index,"</strong></sup>"))});if(!a.length)return;a.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var r,l=s.trim(),u=1,h=_createForOfIteratorHelper(a);try{for(h.s();!(r=h.n()).done;){var f=_slicedToArray(r.value,2),m=f[0],p=f[1],g="__CITE_".concat(p.index,"__");l=(l=l.replaceAll(m,g)).replaceAll("<sup><strong>".concat(p.index,"</strong></sup>"),g),p._displayIndex=u++,p._placeholder=g}}catch(e){h.e(e)}finally{h.f()}var v,y=_createForOfIteratorHelper(a);try{for(y.s();!(v=y.n()).done;){var b=_slicedToArray(v.value,2)[1];l=l.replaceAll(b._placeholder,"<sup><strong>".concat(b._displayIndex,"</strong></sup>"))}}catch(e){y.e(e)}finally{y.f()}l=l.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),l+="<br><br>";var S,A=_createForOfIteratorHelper(a);try{for(A.s();!(S=A.n()).done;){var _=_slicedToArray(S.value,2),E=_[0],w=_[1],C=w.text||E;l+=w.link?"**".concat(w._displayIndex,"**. [").concat(C,"](").concat(w.link,")<br>"):"**".concat(w._displayIndex,"**. ").concat(C,"<br>")}}catch(e){A.e(e)}finally{A.f()}i.content=l,i.htmlContent=d(l,i),this.messages[t]=i,this.$nextTick(function(){c(i),n.scrollToBottom()})}},streamingStarted:function(){var e=this.buttonElement.getAttribute("data-stop-icon");e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&this.inputElement.setAttribute("disabled","disabled")},streamingFinished:function(){var e=this.buttonElement.getAttribute("data-start-icon");if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&(this.inputElement.removeAttribute("disabled"),this.inputElement.focus()),this.chatContainer)for(var t=this.chatContainer.querySelectorAll(".ai-streaming-icon"),n=0;n<t.length;n++)t[n].classList.remove("ai-streaming-icon"),t[n].classList.add("ai-bot-icon");for(n=0;n<this.messages.length;n++)this.messages[n].isStreaming&&(this.messages[n].isStreaming=!1)},synthesizeSpeech:function(e){var t=this;this.textToSpeechEnabled&&e&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this.connection.invoke("SynthesizeSpeech",this.getProfileId(),this.getSessionId(),e,this.ttsVoiceName).catch(function(e){console.error("TTS synthesis error:",e),t.isPlayingAudio=!1}))},playCollectedAudio:function(){if(0!==this.audioChunks.length){var e,t=this.audioChunks.reduce(function(e,t){return e+t.length},0),n=new Uint8Array(t),i=0,o=_createForOfIteratorHelper(this.audioChunks);try{for(o.s();!(e=o.n()).done;){var s=e.value;n.set(s,i),i+=s.length}}catch(e){o.e(e)}finally{o.f()}this.audioChunks=[];var a=new Blob([n],{type:"audio/mp3"});this.currentAudioElement?this.audioPlayQueue.push(a):this.playAudioBlob(a)}else this.currentAudioElement||0!==this.audioPlayQueue.length||(this.isPlayingAudio=!1)},playAudioBlob:function(e){var t=this,n=URL.createObjectURL(e),i=new Audio(n);this.currentAudioElement=i,this.isPlayingAudio=!0,i.addEventListener("ended",function(){URL.revokeObjectURL(n),t.currentAudioElement=null,t.playNextInQueue()}),i.addEventListener("error",function(){URL.revokeObjectURL(n),t.currentAudioElement=null,t.playNextInQueue()}),i.play().catch(function(e){console.error("Audio playback error:",e),URL.revokeObjectURL(n),t.currentAudioElement=null,t.isPlayingAudio=!1})},playNextInQueue:function(){if(this.audioPlayQueue.length>0){var e=this.audioPlayQueue.shift();this.playAudioBlob(e)}else this.isPlayingAudio=!1,this.conversationModeOnAudioEnded()},stopAudio:function(){this.currentAudioElement&&(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,this.currentAudioElement=null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1},toggleConversationMode:function(){this.isConversationMode?this.stopConversationMode():this.startConversationMode()},startConversationMode:function(){var e=this;this.conversationModeEnabled&&!this.isConversationMode&&this.connection&&(this.isConversationMode=!0,this.updateConversationButton(),this._conversationPartialTranscript="",this._conversationAssistantMessage=null,this._conversationPartialMessage=null,this.removeNotification("conversation-ended"),navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e._conversationSubject=new signalR.Subject,e._conversationStream=t;var i=window.AudioContext||window.webkitAudioContext;i&&(e._conversationAudioCtx=new i,e._conversationAnalyser=e._conversationAudioCtx.createAnalyser(),e._conversationAnalyser.fftSize=256,e._conversationAudioCtx.createMediaStreamSource(t).connect(e._conversationAnalyser));var o=Promise.resolve(),s=e._conversationAnalyser;e.mediaRecorder.addEventListener("dataavailable",function(t){if(t.data&&t.data.size>0){if(e.isPlayingAudio&&s){var n=new Uint8Array(s.frequencyBinCount);s.getByteFrequencyData(n);for(var i=0,a=0;a<n.length;a++)i+=n[a];i/n.length>=30&&e.stopAudio()}o=o.then(_asyncToGenerator(_regenerator().m(function n(){var i,o,s,a;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:return n.n=1,t.data.arrayBuffer();case 1:i=n.v,o=new Uint8Array(i),s=o.reduce(function(e,t){return e+String.fromCharCode(t)},""),a=btoa(s);try{e._conversationSubject.next(a)}catch(e){}case 2:return n.a(2)}},n)})))}}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),o.then(function(){try{e._conversationSubject.complete()}catch(e){}})});var a=e.getProfileId(),r=e.getSessionId()||"",c=navigator.language||document.documentElement.lang||"en-US";e.connection.send("StartConversation",a,r,e._conversationSubject,n,c),e.mediaRecorder.start(250),e.isRecording=!0}).catch(function(t){console.error("Microphone access denied:",t),e.isConversationMode=!1,e.updateConversationButton()}))},stopConversationMode:function(){if(this.isConversationMode){if(this.isConversationMode=!1,this.updateConversationButton(),this.connection&&this.connection.invoke("StopConversation").catch(function(){}),this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1),this.stopAudio(),this._conversationPartialTranscript="",this._conversationPartialMessage=null,this._conversationAudioCtx&&(this._conversationAudioCtx.close().catch(function(){}),this._conversationAudioCtx=null,this._conversationAnalyser=null),this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:"conversation-ended",content:"Conversation ended.",icon:"fa-solid fa-circle-check",dismissible:!0,autoDismissMs:5e3})}},updateConversationButton:function(){if(this.conversationButton)if(this.isConversationMode){this.conversationButton.classList.add("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-dark","btn-outline-secondary"),this.conversationButton.title=this.conversationButton.getAttribute("data-end-title")||"End Conversation";var e=this.conversationButton.getAttribute("data-end-html");e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}else{this.conversationButton.classList.remove("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-secondary"),this.conversationButton.classList.add("btn-outline-dark"),this.conversationButton.blur(),this.conversationButton.title=this.conversationButton.getAttribute("data-start-title")||"Start Conversation";var t=this.conversationButton.getAttribute("data-start-html");t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))}},conversationModeSendPrompt:function(){},conversationModeOnAudioEnded:function(){},generatePrompt:function(e){if(e){var t=e.getAttribute("data-profile-id"),n=this.getSessionId(),i=this.getProfileId();t&&n?this.streamMessage(t,null,i):console.error("The given element is missing data-profile-id or the session has not yet started.")}else console.error("The element paramter is required.")},createSessionUrl:function(e,t,n){var i=e.toLowerCase().startsWith("http")?e:window.location.origin+e,o=new URL(i);return o.searchParams.set(t,n),o.toString()},showTypingIndicator:function(){this.addMessage({role:"indicator",htmlContent:n.indicatorTemplate})},hideTypingIndicator:function(){var e=this.messages.length;return this.messages=this.messages.filter(function(e){return"indicator"!==e.role}),e-this.messages.length},receiveNotification:function(e){var t=this;if(e&&e.type){this.clearNotificationDismiss(e.type);var n=this.notifications.findIndex(function(t){return t.type===e.type});n>=0?this.notifications.splice(n,1,e):this.notifications.push(e),this.scheduleNotificationDismiss(e),this.$nextTick(function(){t.scrollToBottom()})}},updateNotification:function(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(function(t){return t.type===e.type});t>=0&&(this.notifications.splice(t,1,e),this.scheduleNotificationDismiss(e))}},scheduleNotificationDismiss:function(e){var t=this;e&&e.type&&e.autoDismissMs&&!(e.autoDismissMs<=0)&&(this.notificationDismissTimers[e.type]=setTimeout(function(){t.removeNotification(e.type)},e.autoDismissMs))},clearNotificationDismiss:function(e){var t=this.notificationDismissTimers[e];t&&(clearTimeout(t),delete this.notificationDismissTimers[e])},removeNotification:function(e){this.clearNotificationDismiss(e),this.notifications=this.notifications.filter(function(t){return t.type!==e})},dismissNotification:function(e){this.removeNotification(e)},handleNotificationAction:function(e,t){if(this.connection){var n=this.getSessionId();this.connection.invoke("HandleNotificationAction",n,e,t).catch(function(e){console.error("Error handling notification action:",e)})}},scrollToBottom:function(){var e=this;this.autoScroll&&setTimeout(function(){e.chatContainer.scrollTop=e.chatContainer.scrollHeight-e.chatContainer.clientHeight},50)},handleUserInput:function(e){this.prompt=e.target.value},getProfileId:function(){return this.inputElement.getAttribute("data-profile-id")},setSessionId:function(e){this.inputElement.setAttribute("data-session-id",e||"")},resetSession:function(){this.stopRecording(),this.setSessionId(""),this.isSessionStarted=!1,this.sessionRating=null,this.widgetIsInitialized&&localStorage.removeItem(this.chatWidgetStateSession),this.messages=[],this.documents=[],n.autoCreateSession||this.showPlaceholder(),n.autoCreateSession&&this.startNewSession()},startNewSession:function(){if(this.applyOrchestratorAvailability()){var e=this.getProfileId();e&&this.connection&&this.connection.invoke("StartSession",e,null).catch(function(e){return console.error(e)})}},initializeApp:function(){var e=this;this.inputElement=document.querySelector(n.inputElementSelector),this.buttonElement=document.querySelector(n.sendButtonElementSelector),this.chatContainer=document.querySelector(n.chatContainerElementSelector),this.placeholder=document.querySelector(n.placeholderElementSelector),this.applyOrchestratorAvailability();var t=this.getSessionId();if(!n.widget&&t?this.loadSession(t):this.isOrchestratorAvailable()&&n.autoCreateSession&&!n.widget&&!t&&this.startNewSession(),n.sessionDocumentsEnabled&&n.documentBarSelector&&(this.documentBar=document.querySelector(n.documentBarSelector),this.documentBar)){this.renderDocumentBar();var i=document.createElement("input");i.type="file",i.id="ai-chat-doc-input",i.className="d-none",i.multiple=!0,n.allowedExtensions&&(i.accept=n.allowedExtensions),i.addEventListener("change",function(t){return e.handleFileInputChange(t)}),this.documentBar.parentElement.appendChild(i);var o=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;o&&(o.addEventListener("dragover",function(t){return e.handleDragOver(t)}),o.addEventListener("dragleave",function(t){return e.handleDragLeave(t)}),o.addEventListener("drop",function(t){return e.handleDrop(t)}))}this.chatContainer.addEventListener("scroll",function(){if(e.stream){var t=e.chatContainer.scrollHeight-e.chatContainer.clientHeight-e.chatContainer.scrollTop<=30;e.autoScroll=t}}),this.inputElement.addEventListener("keydown",function(t){null==e.stream&&("Enter"!==t.key||t.shiftKey||(t.preventDefault(),e.buttonElement.click()))}),this.inputElement.addEventListener("input",function(t){e.handleUserInput(t),t.target.value.trim()?e.buttonElement.removeAttribute("disabled"):e.buttonElement.setAttribute("disabled",!0)}),this.buttonElement.addEventListener("click",function(){if(null==e.stream)e.sendMessage();else if(e.stream.dispose(),e.stream=null,e.streamingFinished(),e.hideTypingIndicator(),e.messages.length>0){var t=e.messages[e.messages.length-1];"assistant"!==t.role||t.content?t.isStreaming&&(t.isStreaming=!1):e.messages.pop()}});for(var s=document.getElementsByClassName("profile-generated-prompt"),a=0;a<s.length;a++)s[a].addEventListener("click",function(t){t.preventDefault(),e.generatePrompt(t.target)});var r=document.getElementsByClassName("chat-session-history-item");for(a=0;a<r.length;a++)r[a].addEventListener("click",function(t){t.preventDefault();var n=t.target.getAttribute("data-session-id");n?(e.loadSession(n),e.showChatScreen()):console.error("an element with the class chat-session-history-item with no data-session-id set.")});for(var c=0;c<n.messages.length;c++)this.addMessage(n.messages[c]);this.$nextTick(function(){e.refreshAllFeedbackIcons()}),this.chatContainer&&this.chatContainer.addEventListener("click",function(e){var t=e.target.closest(".ai-code-copy-btn");if(t){var i=t.closest(".ai-code-block")||t.closest("pre");if(i){var o=i.querySelector("code");if(o){navigator.clipboard.writeText(o.textContent);var s=n.codeCopiedText||"Copied!";t.innerHTML='<i class="fa-solid fa-check"></i> '+s,setTimeout(function(){t.innerHTML='<i class="fa-regular fa-copy"></i>'},2e3)}}}}),this.speechToTextEnabled&&n.micButtonElementSelector&&(this.micButton=document.querySelector(n.micButtonElementSelector),this.micButton&&(this.micButton.style.display="",this.micButton.addEventListener("click",function(){e.toggleRecording()}))),this.conversationModeEnabled&&n.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(n.conversationButtonElementSelector),this.conversationButton&&this.conversationButton.addEventListener("click",function(){e.toggleConversationMode()}))},loadSession:function(e){this.connection.invoke("LoadSession",e).catch(function(e){return console.error(e)})},reloadCurrentSession:function(){var e=this.getSessionId();e&&this.loadSession(e)},initializeSession:function(e,t){this.isSessionStarted&&!t||(this.fireEvent(new CustomEvent("initializingSessionOpenAIChat",{detail:{sessionId:e}})),this.setSessionId(e),this.isSessionStarted=!0,this.widgetIsInitialized&&localStorage.setItem(this.chatWidgetStateSession,e))},initializeWidget:function(){var e=this;if(n.widget.chatWidgetContainer)if(n.widget.chatWidgetStateName){if(document.querySelector(n.widget.chatWidgetContainer)){if(n.widget.chatHistorySection&&(this.chatHistorySection=document.querySelector(n.widget.chatHistorySection)),this.chatWidgetStateName=n.widget.chatWidgetStateName,this.chatWidgetStateSession=n.widget.chatWidgetStateName+"Session",this.widgetIsInitialized=!0,this.reloadCurrentSession(),n.autoCreateSession&&!this.getSessionId()&&this.startNewSession(),n.widget.showHistoryButton&&this.chatHistorySection){var t=document.querySelector(n.widget.showHistoryButton);if(t&&t.addEventListener("click",function(){e.chatHistorySection.classList.toggle("show")}),n.widget.closeHistoryButton){var i=document.querySelector(n.widget.closeHistoryButton);i&&i.addEventListener("click",function(){e.showChatScreen()})}}if(n.widget.newChatButton){var o=document.querySelector(n.widget.newChatButton);o&&o.addEventListener("click",function(){e.resetSession(),e.showChatScreen()})}}}else console.error("The widget chatWidgetStateName is required.");else console.error("The widget chatWidgetContainer is required.")},showChatScreen:function(){this.chatHistorySection&&this.chatHistorySection.classList.remove("show")},getSessionId:function(){var e=this.inputElement.getAttribute("data-session-id");return!e&&this.widgetIsInitialized&&(e=localStorage.getItem(this.chatWidgetStateSession)),e},copyResponse:function(e){navigator.clipboard.writeText(e)},updateFeedbackIcons:function(e,t){if(e){var n=e.querySelector(".rate-up-btn"),i=e.querySelector(".rate-down-btn");if(n){var o=!0===t?"fa-solid fa-thumbs-up":"fa-regular fa-thumbs-up",s=document.createElement("i");s.className=o,s.style.fontSize="0.9rem",n.textContent="",n.appendChild(s)}if(i){var a=!1===t?"fa-solid fa-thumbs-down":"fa-regular fa-thumbs-down",r=document.createElement("i");r.className=a,r.style.fontSize="0.9rem",i.textContent="",i.appendChild(r)}window.FontAwesome&&FontAwesome.dom&&FontAwesome.dom.i2svg&&FontAwesome.dom.i2svg({node:e})}},refreshAllFeedbackIcons:function(){for(var e=this.$el.querySelectorAll(".ai-chat-message-assistant-feedback"),t=0;t<e.length;t++){var n=e[t].getAttribute("data-message-id"),i=this.messages.find(function(e){return e.id===n});i&&this.updateFeedbackIcons(e[t],i.userRating)}},rateMessage:function(e,t,n){var i=this.getSessionId();if(i&&e.id&&this.connection){var o=e.userRating===t?null:t;e.userRating=o;var s=this.$el.querySelector('.ai-chat-message-assistant-feedback[data-message-id="'+e.id+'"]');this.updateFeedbackIcons(s,o),null!==o&&s&&setTimeout(function(){var e=t?".rate-up-btn":".rate-down-btn",n=s.querySelector(e);n&&(n.classList.remove("spark-effect"),n.offsetWidth,n.classList.add("spark-effect"),n.addEventListener("animationend",function e(){n.removeEventListener("animationend",e),n.classList.remove("spark-effect")}))},50),this.connection.invoke("RateMessage",i,e.id,t).catch(function(e){console.error("Failed to rate message:",e)})}}},watch:{documents:{handler:function(){this.renderDocumentBar()},deep:!0},isUploading:function(){this.renderDocumentBar()},isPlayingAudio:function(){},isConversationMode:function(e){this.micButton&&(this.micButton.style.display=e?"none":this.speechToTextEnabled?"":"none"),this.buttonElement&&(this.buttonElement.style.display=e?"none":""),this.inputElement&&(this.inputElement.disabled=e,e&&(this.inputElement.placeholder=""))}},mounted:function(){var e=this;_asyncToGenerator(_regenerator().m(function t(){return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.startConnection();case 1:e.initializeApp(),n.widget&&e.initializeWidget();case 2:return t.a(2)}},t)}))(),window.addEventListener("beforeunload",this.handleBeforeUnload)},beforeUnmount:function(){window.removeEventListener("beforeunload",this.handleBeforeUnload),this.stream&&(this.stream.dispose(),this.stream=null),this.connection&&this.connection.stop()},template:n.messageTemplate}).mount(n.appElementSelector);console.error("The sendButtonElementSelector is required.")}else console.error("The inputElementSelector is required.");else console.error("The chatContainerElementSelector is required.");else console.error("The appElementSelector is required.");else console.error("The signalRHubUrl is required.")}}}(),document.addEventListener("click",function(e){var t=e.target.closest(".download-chart-btn");if(t){var n=t.getAttribute("data-chart-id"),i=n?document.getElementById(n):null;if(i){var o=document.createElement("a");o.download="chart-"+n+".png",o.href=i.toDataURL("image/png"),o.click()}else console.error("Chart canvas not found:",n)}}),document.addEventListener("click",function(e){var t=e.target.closest(".ai-download-image");if(t){var n=t.closest(".generated-image-container"),i=null==n?void 0:n.querySelector("img");if(i){var o=i.src;o&&o.startsWith("data:")&&(e.preventDefault(),fetch(o).then(function(e){return e.blob()}).then(function(e){var n=URL.createObjectURL(e),i=document.createElement("a");i.href=n,i.download=t.getAttribute("download")||"generated-image.png",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(e){console.error("Failed to download image:",e)}))}}});
|
|
1
|
+
function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",o=n.toStringTag||"@@toStringTag";function s(n,i,o,s){var c=i&&i.prototype instanceof r?i:r,l=Object.create(c.prototype);return _regeneratorDefine2(l,"_invoke",function(n,i,o){var s,r,c,l=0,d=o||[],u=!1,h={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return s=t,r=0,c=e,h.n=n,a}};function f(n,i){for(r=n,c=i,t=0;!u&&l&&!o&&t<d.length;t++){var o,s=d[t],f=h.p,m=s[2];n>3?(o=m===i)&&(c=s[(r=s[4])?5:(r=3,3)],s[4]=s[5]=e):s[0]<=f&&((o=n<2&&f<s[1])?(r=0,h.v=i,h.n=s[1]):f<m&&(o=n<3||s[0]>i||i>m)&&(s[4]=n,s[5]=i,h.n=m,r=0))}if(o||n>1)return a;throw u=!0,i}return function(o,d,m){if(l>1)throw TypeError("Generator is already running");for(u&&1===d&&f(d,m),r=d,c=m;(t=r<2?e:c)||!u;){s||(r?r<3?(r>1&&(h.n=-1),f(r,c)):h.n=c:h.v=c);try{if(l=2,s){if(r||(o="next"),t=s[o]){if(!(t=t.call(s,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,r<2&&(r=0)}else 1===r&&(t=s.return)&&t.call(s),r<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),r=1);s=e}else if((t=(u=h.n<0)?c:n.call(i,h))!==a)break}catch(t){s=e,r=1,c=t}finally{l=1}}return{value:t,done:u}}}(n,o,s),!0),l}var a={};function r(){}function c(){}function l(){}t=Object.getPrototypeOf;var d=[][i]?t(t([][i]())):(_regeneratorDefine2(t={},i,function(){return this}),t),u=l.prototype=r.prototype=Object.create(d);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return c.prototype=l,_regeneratorDefine2(u,"constructor",l),_regeneratorDefine2(l,"constructor",c),c.displayName="GeneratorFunction",_regeneratorDefine2(l,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,i,function(){return this}),_regeneratorDefine2(u,"toString",function(){return"[object Generator]"}),(_regenerator=function(){return{w:s,m:h}})()}function _regeneratorDefine2(e,t,n,i){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}_regeneratorDefine2=function(e,t,n,i){function s(t,n){_regeneratorDefine2(e,t,function(e){return this._invoke(t,n,e)})}t?o?o(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(s("next",0),s("throw",1),s("return",2))},_regeneratorDefine2(e,t,n,i)}function asyncGeneratorStep(e,t,n,i,o,s,a){try{var r=e[s](a),c=r.value}catch(e){return void n(e)}r.done?t(c):Promise.resolve(c).then(i,o)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(i,o){var s=e.apply(t,n);function a(e){asyncGeneratorStep(s,i,o,a,r,"next",e)}function r(e){asyncGeneratorStep(s,i,o,a,r,"throw",e)}a(void 0)})}}function _createForOfIteratorHelper(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var i=0,o=function(){};return{s:o,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,r=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){r=!0,s=e},f:function(){try{a||null==n.return||n.return()}finally{if(r)throw s}}}}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray(e)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray(e,t)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function _iterableToArrayLimit(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,o,s,a,r=[],c=!0,l=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=s.call(n)).done)&&(r.push(i.value),r.length!==t);c=!0);}catch(e){l=!0,o=e}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return r}}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}window.openAIChatManager=function(){var e={generatedImageAltText:"Generated Image",generatedImageMaxWidth:400,downloadImageTitle:"Download image",downloadChartTitle:"Download chart as image",downloadChartButtonText:"Download",userLabel:"You",assistantLabel:"Assistant",thumbsUpTitle:"Thumbs up",thumbsDownTitle:"Thumbs down",copyTitle:"Click here to copy response to clipboard.",codeCopiedText:"Copied!",messageTemplate:'\n <div class="ai-chat-messages">\n <div v-for="(message, index) in messages" :key="\'msg-\' + index" class="ai-chat-message-item">\n <div>\n <div v-if="message.role === \'user\'" class="ai-chat-msg-role ai-chat-msg-role-user">{{ userLabel }}</div>\n <div v-else-if="message.role !== \'indicator\'" :class="getAssistantRoleClasses(message)">\n <span :class="getAssistantIconClasses(message, index)"><i :class="getAssistantIcon(message)"></i></span>\n {{ getAssistantLabel(message) }}\n </div>\n <div class="ai-chat-message-body lh-base">\n <h4 v-if="message.title">{{ message.title }}</h4>\n <div v-html="message.htmlContent"></div>\n <span class="message-buttons-container" v-if="!isIndicator(message)">\n <template v-if="metricsEnabled && message.role === \'assistant\'">\n <span class="ai-chat-message-assistant-feedback" :data-message-id="message.id">\n <button class="btn btn-sm btn-link text-success p-0 me-2 button-message-toolbox rate-up-btn" @click="rateMessage(message, true, $event)" :title="thumbsUpTitle">\n <i class="fa-regular fa-thumbs-up"></i>\n </button>\n <button class="btn btn-sm btn-link text-danger p-0 me-2 button-message-toolbox rate-down-btn" @click="rateMessage(message, false, $event)" :title="thumbsDownTitle">\n <i class="fa-regular fa-thumbs-down"></i>\n </button>\n </span>\n </template>\n <button class="btn btn-sm btn-link text-secondary p-0 button-message-toolbox" @click="copyResponse(message.content)" :title="copyTitle">\n <i class="fa-solid fa-copy"></i>\n </button>\n </span>\n </div>\n </div>\n </div>\n <div v-for="notification in notifications" :key="\'notif-\' + notification.type" class="ai-chat-notification" :class="\'ai-chat-notification-\' + (notification.type || \'info\') + \' \' + (notification.cssClass || \'\')">\n <div class="ai-chat-notification-content">\n <i v-if="notification.icon" :class="notification.icon" class="ai-chat-notification-icon"></i>\n <span class="ai-chat-notification-text">{{ notification.content }}</span>\n <button v-if="notification.dismissible" class="btn btn-sm btn-link p-0 ms-2 ai-chat-notification-dismiss" @click="dismissNotification(notification.type)" title="Dismiss">\n <i class="fa-solid fa-xmark"></i>\n </button>\n </div>\n <div v-if="notification.actions && notification.actions.length" class="ai-chat-notification-actions">\n <button v-for="action in notification.actions" :key="action.name" class="btn btn-sm" :class="action.cssClass || \'btn-outline-secondary\'" @click="handleNotificationAction(notification.type, action.name)">\n <i v-if="action.icon" :class="action.icon" class="me-1"></i>\n {{ action.label }}\n </button>\n </div>\n </div>\n </div>\n ',indicatorTemplate:'\n <div class="ai-chat-msg-role ai-chat-msg-role-assistant">\n <span class="ai-streaming-icon"><i class="fa fa-robot" style="display: inline-block;"></i></span>\n Assistant\n </div>\n '};function t(e){if(!e)return"";var t=e.trim();return/^javascript:/i.test(t)||/^vbscript:/i.test(t)||/^data:text\/html/i.test(t)?"":e}function n(e){var t=document.createElement("span");return t.textContent=e,t.innerHTML}function i(e){var t,n,i,o,s,a;if(!e||"object"!==_typeof(e))return null;var r=Object.assign({},e);return r.index=null!==(t=null!==(n=r.index)&&void 0!==n?n:r.Index)&&void 0!==t?t:0,r.text=null!==(i=null!==(o=r.text)&&void 0!==o?o:r.Text)&&void 0!==i?i:null,r.link=null!==(s=null!==(a=r.link)&&void 0!==a?a:r.Link)&&void 0!==s?s:null,r}function o(e){if(!e||"object"!==_typeof(e))return{};for(var t={},n=0,o=Object.entries(e);n<o.length;n++){var s,a=_slicedToArray(o[n],2),r=a[0],c=a[1];t[r]=null!==(s=i(c))&&void 0!==s?s:{}}return t}var s=new marked.Renderer;s.link=function(e){var n=t(e.href);return n?'<a href="'.concat(n,'" target="_blank" rel="noopener noreferrer">').concat(e.text,"</a>"):e.text||""},s.code=function(e){var t=e.text||"",i=(e.lang||"").trim(),o=t;if("undefined"!=typeof hljs)if(i&&hljs.getLanguage(i))try{o=hljs.highlight(t,{language:i}).value}catch(e){}else try{o=hljs.highlightAuto(t).value}catch(e){}else o=n(t);var s=i?n(i):"code";return'<div class="ai-code-block"><div class="ai-code-header"><span class="ai-code-lang"><i class="fa-solid fa-code"></i> '.concat(s,'</span><button type="button" class="ai-code-copy-btn" title="Copy code"><i class="fa-regular fa-copy"></i></button></div><pre><code class="hljs').concat(i?" language-"+i:"",'">').concat(o,"</code></pre></div>")},s.image=function(n){var i=t(n.href);if(!i)return"";var o=n.text||e.generatedImageAltText,s=e.generatedImageMaxWidth;return'<div class="generated-image-container">\n <img src="'.concat(i,'" alt="').concat(o,'" class="img-thumbnail" style="max-width: ').concat(s,'px; height: auto;" />\n <div class="mt-2">\n <a href="').concat(i,'" target="_blank" download="').concat(o,'" title="').concat(e.downloadImageTitle,'" class="btn btn-sm btn-outline-secondary ai-download-image">\n <i class="fa-solid fa-download"></i>\n </a>\n </div>\n </div>')};var a=0,r=[];function c(e){if(e&&e._pendingCharts&&e._pendingCharts.length){var t=_toConsumableArray(e._pendingCharts);e._pendingCharts=[],requestAnimationFrame(function(){var e,n=_createForOfIteratorHelper(t);try{for(n.s();!(e=n.n()).done;){var i=e.value;l(i.chartId,i.config)}}catch(e){n.e(e)}finally{n.f()}})}}function l(e,t){var n=document.getElementById(e);if(!n)return!1;if("undefined"==typeof Chart)return console.warn('Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"><\/script>).'),!1;if(null===n.offsetParent)return window.__chartConfigs[e]=t,!1;try{var i,o,s;n._chartInstance&&n._chartInstance.destroy();var a="string"==typeof t?JSON.parse(t):t;return null!==(i=a.options)&&void 0!==i||(a.options={}),a.options.responsive=!0,a.options.maintainAspectRatio=!0,null!==(s=(o=a.options).aspectRatio)&&void 0!==s||(o.aspectRatio=4/3),n._chartInstance=new Chart(n,a),delete window.__chartConfigs[e],!0}catch(e){return console.error("Error creating chart:",e),!1}}function d(e,t){r=[];var n=marked.parse(e,{renderer:s});return t._pendingCharts=r.length>0?_toConsumableArray(r):[],DOMPurify.sanitize(n,{ADD_TAGS:["canvas"],ADD_ATTR:["target"]})}window.__chartConfigs=window.__chartConfigs||{},marked.use({extensions:[{name:"chart",level:"block",start:function(e){var t=e.indexOf("[chart:");return t>=0?t:void 0},tokenizer:function(e){var t=function(e){var t="[chart:",n=e.indexOf(t);if(n<0)return null;var i=n+t.length,o=i;for(;o<e.length&&(" "===e[o]||"\n"===e[o]||"\r"===e[o]||"\t"===e[o]);)o++;if(o>=e.length||"{"!==e[o])return null;for(var s=0,a=!1,r=!1;o<e.length;o++){var c=e[o];if(a){if(r){r=!1;continue}if("\\"===c){r=!0;continue}'"'===c&&(a=!1)}else if('"'!==c){if("{"===c)s++;else if("}"===c&&0===--s){var l=o,d=e.indexOf("]",l+1);return d<0?null:{startIndex:n,endIndex:d+1,json:e.substring(i,l+1).trim()}}}else a=!0}return null}(e);if(t&&0===t.startIndex){var n="chat_chart_".concat(++a);return{type:"chart",raw:e.substring(0,t.endIndex),chartId:n,json:t.json}}},renderer:function(t){return r.push({chartId:t.chartId,config:t.json}),window.__chartConfigs[t.chartId]=t.json,n=t.chartId,'<div class="chart-container" style="position: relative; width: 100%; max-width: 560px; min-height: 420px;">'+'<canvas id="'.concat(n,'"></canvas>')+'</div><div class="mt-2">'+'<button type="button" class="btn btn-sm btn-outline-secondary download-chart-btn" data-chart-id="'.concat(n,'" title="').concat(e.downloadChartTitle,'">')+'<i class="fa-solid fa-download"></i> '.concat(e.downloadChartButtonText)+"</button></div>";var n}}]}),window.renderPendingCharts=function(){if("undefined"!=typeof Chart){var e=window.__chartConfigs;e&&requestAnimationFrame(function(){for(var t=0,n=Object.keys(e);t<n.length;t++){var i=n[t];l(i,e[i])}})}};return{initialize:function(t){var n=Object.assign({},e,t);if(e=n,n.signalRHubUrl)if(n.appElementSelector)if(n.chatContainerElementSelector)if(n.inputElementSelector){if(n.sendButtonElementSelector)return Vue.createApp({data:function(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isSessionStarted:!1,isPlaceholderVisible:!0,chatWidgetStateName:null,chatWidgetStateSession:null,chatHistorySection:null,widgetIsInitialized:!1,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,messages:[],notifications:[],prompt:"",documents:n.existingDocuments||[],isUploading:!1,uploadErrors:[],isDragOver:!1,documentBar:null,metricsEnabled:!!n.metricsEnabled,userLabel:n.userLabel,assistantLabel:n.assistantLabel,thumbsUpTitle:n.thumbsUpTitle,thumbsDownTitle:n.thumbsDownTitle,copyTitle:n.copyTitle,isRecording:!1,mediaRecorder:null,preRecordingPrompt:"",micButton:null,speechToTextEnabled:"AudioInput"===n.chatMode||"Conversation"===n.chatMode,textToSpeechEnabled:"Conversation"===n.chatMode,ttsVoiceName:n.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,ttsButton:null,conversationModeEnabled:"Conversation"===n.chatMode,conversationButton:null,isConversationMode:!1,notificationDismissTimers:{}}},computed:{lastAssistantIndex:function(){for(var e=this.messages.length-1;e>=0;e--)if("assistant"===this.messages[e].role)return e;return-1}},methods:{handleBeforeUnload:function(){this.isNavigatingAway=!0},handleDragOver:function(e){if(n.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!0;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.add("ai-chat-drag-over")}},handleDragLeave:function(e){if(n.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.remove("ai-chat-drag-over")}},handleDrop:function(e){if(n.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.remove("ai-chat-drag-over"),e.dataTransfer&&e.dataTransfer.files&&e.dataTransfer.files.length>0&&this.uploadFiles(e.dataTransfer.files)}},triggerFileInput:function(){if(n.sessionDocumentsEnabled){var e=document.getElementById("ai-chat-doc-input");e&&e.click()}},handleFileInputChange:function(e){var t=e.target.files;t&&t.length>0&&this.uploadFiles(t),e.target.value=""},uploadFiles:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function i(){var o,s,a,r,c,l,d,u,h,f;return _regenerator().w(function(i){for(;;)switch(i.p=i.n){case 0:if(n.uploadDocumentUrl){i.n=1;break}return i.a(2);case 1:if(o=t.getSessionId(),s=t.getProfileId(),o||s){i.n=2;break}return console.warn("Cannot upload documents without a session or profile."),i.a(2);case 2:for(t.isUploading=!0,t.uploadErrors=[],t.renderDocumentBar(),i.p=3,a=new FormData,o?a.append("sessionId",o):a.append("profileId",s),r=0;r<e.length;r++)a.append("files",e[r]);return i.n=4,fetch(n.uploadDocumentUrl,{method:"POST",body:a});case 4:if((c=i.v).ok){i.n=6;break}return i.n=5,c.text();case 5:return l=i.v,d=t.extractReadableErrorMessage(l,"Upload failed. Please try again."),console.error("Upload failed:",l),t.uploadErrors=[{fileName:"",error:d}],i.a(2);case 6:return i.n=7,c.json();case 7:if((u=i.v).sessionId&&!o&&t.initializeSession(u.sessionId),u.uploaded&&u.uploaded.length>0)for(h=0;h<u.uploaded.length;h++)t.documents.push(u.uploaded[h]);u.failed&&u.failed.length>0&&(t.uploadErrors=u.failed),i.n=9;break;case 8:i.p=8,f=i.v,console.error("Upload error:",f),t.uploadErrors=[{fileName:"",error:"Upload failed. Please try again."}];case 9:return i.p=9,t.isUploading=!1,t.renderDocumentBar(),i.f(9);case 10:return i.a(2)}},i,null,[[3,8,9,10]])}))()},removeDocument:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function i(){var o,s,a,r,c,l;return _regenerator().w(function(i){for(;;)switch(i.p=i.n){case 0:if(n.removeDocumentUrl){i.n=1;break}return i.a(2);case 1:return i.p=1,o=t.getSessionId(),i.n=2,fetch(n.removeDocumentUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({itemId:o,documentId:e.documentId})});case 2:if(!(s=i.v).ok){i.n=3;break}(a=t.documents.indexOf(e))>-1&&t.documents.splice(a,1),i.n=5;break;case 3:return i.n=4,s.text();case 4:r=i.v,c=t.extractReadableErrorMessage(r,"Failed to remove document. Please try again."),console.error("Failed to remove document:",s.status,r),t.uploadErrors=[{fileName:e.fileName||"",error:c}],t.renderDocumentBar();case 5:i.n=7;break;case 6:i.p=6,l=i.v,console.error("Remove document error:",l),t.uploadErrors=[{fileName:e.fileName||"",error:"Failed to remove document. Please try again."}],t.renderDocumentBar();case 7:return i.a(2)}},i,null,[[1,6]])}))()},formatFileSize:function(e){return e<1024?e+" B":e<1048576?(e/1024).toFixed(1)+" KB":(e/1048576).toFixed(1)+" MB"},renderDocumentBar:function(){if(this.documentBar)if(n.sessionDocumentsEnabled){this.documentBar.classList.remove("d-none");var e='<div class="ai-chat-doc-bar p-2">';e+='<div class="d-flex flex-wrap align-items-center gap-1">';for(var t=0;t<this.documents.length;t++){var i=this.documents[t],o=i.fileName||"Document";o.length>20&&(o=o.substring(0,17)+"..."),e+='<span class="badge bg-secondary bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="'+this.escapeHtml(i.fileName||"")+'">',e+='<i class="fa-solid fa-file-lines" style="font-size: 0.7rem;"></i> ',e+=this.escapeHtml(o),e+=' <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-doc-index="'+t+'" aria-label="Remove"></button>',e+="</span>"}for(var s=0;s<this.uploadErrors.length;s++){var a=this.uploadErrors[s],r=a.fileName||"File",c=a.error||"Upload failed";r.length>15&&(r=r.substring(0,12)+"..."),e+='<span class="badge bg-danger bg-opacity-25 text-danger d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="'+this.escapeHtml((a.fileName||"")+": "+c)+'">',e+='<i class="fa-solid fa-circle-exclamation" style="font-size: 0.7rem;"></i> ',e+=this.escapeHtml(r),e+=' <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-error-index="'+s+'" aria-label="Dismiss"></button>',e+="</span>"}this.isUploading&&(e+='<span class="badge bg-info bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;">',e+='<span class="spinner-border spinner-border-sm" style="width: 0.7rem; height: 0.7rem;"></span> Uploading...',e+="</span>"),e+='<button type="button" class="btn btn-sm btn-outline-secondary rounded-pill ai-chat-doc-add-btn d-inline-flex align-items-center gap-1" style="font-size: 0.75rem; padding: 0.15rem 0.5rem;" title="Attach documents">',e+='<i class="fa-solid fa-paperclip"></i>',0!==this.documents.length||this.isUploading||(e+=" <span>Attach files</span>"),e+="</button>",e+="</div>",n.supportedExtensionsText&&(e+='<div class="small text-muted mt-2">Supported formats: '+this.escapeHtml(n.supportedExtensionsText)+"</div>"),e+="</div>",this.documentBar.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}));for(var l=this,d=this.documentBar.querySelectorAll("[data-doc-index]"),u=0;u<d.length;u++)d[u].addEventListener("click",function(e){return function(t){t.preventDefault(),t.stopPropagation();var n=l.documents[e];n&&l.removeDocument(n)}}(parseInt(d[u].getAttribute("data-doc-index"))));for(var h=this.documentBar.querySelectorAll("[data-error-index]"),f=0;f<h.length;f++)h[f].addEventListener("click",function(e){return function(t){t.preventDefault(),t.stopPropagation(),l.uploadErrors.splice(e,1),l.renderDocumentBar()}}(parseInt(h[f].getAttribute("data-error-index"))));var m=this.documentBar.querySelector(".ai-chat-doc-add-btn");m&&m.addEventListener("click",function(e){e.preventDefault(),l.triggerFileInput()})}else this.documentBar.classList.add("d-none")},escapeHtml:function(e){var t=document.createElement("div");return t.textContent=e,t.innerHTML},extractReadableErrorMessage:function(e,t){if(!e||"string"!=typeof e)return t;var n=e.trim();if(!n)return t;if(n.startsWith("{")||n.startsWith("["))try{var i=JSON.parse(n),o=(null==i?void 0:i.error)||(null==i?void 0:i.message)||(null==i?void 0:i.title)||(null==i?void 0:i.detail);return"string"==typeof o&&o.trim()?o.trim():t}catch(e){return t}return/<[^>]+>/.test(n)?t:n},normalizeAssistantAppearance:function(e){if(!e)return null;var t="string"==typeof e.label?e.label.trim():"",n="string"==typeof e.icon?e.icon.trim():"",i="string"==typeof e.cssClass?e.cssClass.trim():"",o=!!e.disableStreamingAnimation;return t||n||i||o?{label:t,icon:n,cssClass:i,disableStreamingAnimation:o}:null},getAssistantLabel:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.label?t.label:this.assistantLabel},getAssistantRoleClasses:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null,n=["ai-chat-msg-role"];return t&&t.cssClass?n.push(t.cssClass):n.push("ai-chat-msg-role-assistant"),n},getAssistantIconClasses:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return[this.shouldAnimateAssistantIcon(e,t)?"ai-streaming-icon":"ai-bot-icon",n&&n.cssClass?n.cssClass:""]},getAssistantIcon:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.icon?t.icon:"fa fa-robot"},shouldAnimateAssistantIcon:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return!!e&&e.isStreaming&&t===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},startConnection:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var i;return _regenerator().w(function(t){for(;;)switch(t.p=t.n){case 0:return e.connection=(new signalR.HubConnectionBuilder).withUrl(n.signalRHubUrl).withAutomaticReconnect().build(),e.connection.serverTimeoutInMilliseconds=6e5,e.connection.keepAliveIntervalInMilliseconds=15e3,e.connection.on("LoadSession",function(t){var i;e.initializeSession(t.sessionId,!0),e.messages=[],e.documents=t.documents||[],(null!==(i=t.messages)&&void 0!==i?i:[]).forEach(function(t){e.addMessage(t),e.$nextTick(function(){c(t)})}),e.$nextTick(function(){e.refreshAllFeedbackIcons()}),0===e.messages.length&&n.initialPrompt&&(e.prompt=n.initialPrompt,e.sendMessage())}),e.connection.on("ReceiveError",function(t){console.error("SignalR Error: ",t),e.isRecording&&e.stopRecording(),!e.widgetIsInitialized||e.isSessionStarted||e._attemptedSessionRecovery||(e._attemptedSessionRecovery=!0,localStorage.removeItem(e.chatWidgetStateSession),e.startNewSession())}),e.connection.on("MessageRated",function(t,n){var i=e.messages.find(function(e){return e.id===t});i&&(i.userRating=n)}),e.connection.on("ReceiveTranscript",function(t,n,i){if(e.isConversationMode){if(!i&&n){e._conversationPartialTranscript=n;var o='<p class="ai-partial-transcript">'+n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")+"</p>";e._conversationPartialMessage?(e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent=o):(e.hidePlaceholder(),e._conversationPartialMessage={role:"user",content:n,htmlContent:o,isPartial:!0},e.messages.push(e._conversationPartialMessage)),e.scrollToBottom()}}else n&&!e._audioInputSent&&(e.prompt=e.preRecordingPrompt+n,e.inputElement&&(e.inputElement.value=e.prompt,e.inputElement.dispatchEvent(new Event("input"))))}),e.connection.on("ReceiveConversationUserMessage",function(t,n){if(n){if(e.stopAudio(),e._conversationAssistantMessage){var i=e.messages[e._conversationAssistantMessage.index];i&&(i.isStreaming=!1),e._conversationAssistantMessage=null}if(e._conversationPartialMessage){var o=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent="<p>"+o+"</p>",e._conversationPartialMessage.isPartial=!1,e._conversationPartialMessage=null}else e.addMessage({role:"user",content:n});e.scrollToBottom()}}),e.connection.on("ReceiveConversationAssistantToken",function(t,n,i,o,s){if(!e._conversationAssistantMessage){e.stopAudio(),e.hideTypingIndicator();for(var a=0;a<e.messages.length;a++)e.messages[a].isStreaming&&(e.messages[a].isStreaming=!1);var r=e.messages.length,l={id:n,role:"assistant",content:"",htmlContent:"",isStreaming:!0,userRating:null,appearance:e.normalizeAssistantAppearance(s)};e.messages.push(l),e._conversationAssistantMessage={index:r,content:""}}e._conversationAssistantMessage.content+=i;var u=e.messages[e._conversationAssistantMessage.index];u&&(u.appearance||(u.appearance=e.normalizeAssistantAppearance(s)),u.content=e._conversationAssistantMessage.content,u.htmlContent=d(u.content,u),e.$nextTick(function(){c(u),e.scrollToBottom()}))}),e.connection.on("ReceiveConversationAssistantComplete",function(t,n){if(e._conversationAssistantMessage){var i=e.messages[e._conversationAssistantMessage.index];i&&(i.isStreaming=!1),e._conversationAssistantMessage=null}}),e.connection.on("ReceiveAudioChunk",function(t,n,i){if(n){for(var o=atob(n),s=new Uint8Array(o.length),a=0;a<o.length;a++)s[a]=o.charCodeAt(a);e.audioChunks.push(s)}}),e.connection.on("ReceiveAudioComplete",function(t){e.playCollectedAudio()}),e.connection.on("ReceiveNotification",function(t){e.receiveNotification(t)}),e.connection.on("UpdateNotification",function(t){e.updateNotification(t)}),e.connection.on("RemoveNotification",function(t){e.removeNotification(t)}),e.connection.onreconnecting(function(){console.warn("SignalR: reconnecting...")}),e.connection.onreconnected(function(){console.info("SignalR: reconnected."),e.isSessionStarted?e.reloadCurrentSession():n.autoCreateSession&&e.startNewSession()}),e.connection.onclose(function(t){e.isNavigatingAway||t&&console.warn("SignalR connection closed with error:",t.message||t)}),t.p=1,t.n=2,e.connection.start();case 2:t.n=4;break;case 3:t.p=3,i=t.v,console.error("SignalR Connection Error: ",i);case 4:return t.a(2)}},t,null,[[1,3]])}))()},addMessageInternal:function(e){var t=this;"assistant"===e.role&&(e.appearance=this.normalizeAssistantAppearance(e.appearance)),e.content&&!e.htmlContent&&(e.htmlContent=d(e.content,e)),this.fireEvent(new CustomEvent("addingOpenAIPromotMessage",{detail:{message:e}})),this.messages.push(e),this.$nextTick(function(){t.fireEvent(new CustomEvent("addedOpenAIPromotMessage",{detail:{message:e}}))})},addMessage:function(e){var t=this;if(void 0===e.userRating&&(e.userRating=null),e.content){var n=e.content.trim();if(e.references=o(e.references),e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length){var i=Object.entries(e.references).filter(function(e){var t=_slicedToArray(e,1)[0];return n.includes(t)});if(i.length){i.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var s,a=1,r=_createForOfIteratorHelper(i);try{for(r.s();!(s=r.n()).done;){var l=_slicedToArray(s.value,2),u=l[0],h=l[1],f="__CITE_".concat(h.index,"__");n=n.replaceAll(u,f),h._displayIndex=a++,h._placeholder=f}}catch(e){r.e(e)}finally{r.f()}var m,p=_createForOfIteratorHelper(i);try{for(p.s();!(m=p.n()).done;){var g=_slicedToArray(m.value,2)[1];n=n.replaceAll(g._placeholder,"<sup><strong>".concat(g._displayIndex,"</strong></sup>"))}}catch(e){p.e(e)}finally{p.f()}n=n.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),n+="<br><br>";var v,y=_createForOfIteratorHelper(i);try{for(y.s();!(v=y.n()).done;){var b=_slicedToArray(v.value,2),S=b[0],A=b[1],_=A.text||S;n+=A.link?"**".concat(A._displayIndex,"**. [").concat(_,"](").concat(A.link,")<br>"):"**".concat(A._displayIndex,"**. ").concat(_,"<br>")}}catch(e){y.e(e)}finally{y.f()}}}e.content=n,e.htmlContent=d(n,e)}this.addMessageInternal(e),this.hidePlaceholder(),this.$nextTick(function(){c(e),t.scrollToBottom()})},addMessages:function(e){for(var t=this,n=0;n<e.length;n++)this.addMessageInternal(e[n]);this.hidePlaceholder(),this.$nextTick(function(){t.scrollToBottom()})},hidePlaceholder:function(){this.placeholder&&this.placeholder.classList.add("d-none"),this.isPlaceholderVisible=!1},showPlaceholder:function(){this.placeholder&&this.placeholder.classList.remove("d-none"),this.isPlaceholderVisible=!0},isOrchestratorAvailable:function(){return!1!==n.isOrchestratorAvailable},applyOrchestratorAvailability:function(){if(this.isOrchestratorAvailable())return!0;var e=n.orchestratorUnavailableMessage||"This orchestrator is not currently available.";return this.inputElement&&(this.inputElement.disabled=!0,this.inputElement.value="",this.inputElement.placeholder=e),this.buttonElement&&(this.buttonElement.disabled=!0),this.micButtonElement&&(this.micButtonElement.disabled=!0,this.micButtonElement.style.display="none"),this.conversationButtonElement&&(this.conversationButtonElement.disabled=!0,this.conversationButtonElement.style.display="none"),!1},fireEvent:function(e){document.dispatchEvent(e)},isIndicator:function(e){return"indicator"===e.role},sendMessage:function(){if(this.applyOrchestratorAvailability()){var e=this.prompt.trim();e&&(this.isRecording&&this.stopRecording(),this._audioInputSent=!0,this.addMessage({role:"user",content:e}),this.streamMessage(this.getProfileId(),e,null),this.inputElement.value="",this.prompt="")}},startRecording:function(){var e=this;!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e.preRecordingPrompt=e.prompt,e._audioInputSent=!1;var i=new signalR.Subject,o=e.getProfileId(),s=e.getSessionId()||"",a=Promise.resolve();e.mediaRecorder.addEventListener("dataavailable",function(e){e.data&&e.data.size>0&&(a=a.then(_asyncToGenerator(_regenerator().m(function t(){var n,o,s,a;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.data.arrayBuffer();case 1:n=t.v,o=new Uint8Array(n),s=o.reduce(function(e,t){return e+String.fromCharCode(t)},""),a=btoa(s),i.next(a);case 2:return t.a(2)}},t)}))))}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),a.then(function(){return i.complete()})});var r=navigator.language||document.documentElement.lang||"en-US";e.connection.send("SendAudioStream",o,s,i,n,r),e.mediaRecorder.start(250),e.isRecording=!0,e.updateMicButton()}).catch(function(e){console.error("Microphone access denied:",e)})},stopRecording:function(){this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1,this.updateMicButton())},toggleRecording:function(){this.isRecording?this.stopRecording():this.startRecording()},updateMicButton:function(){this.micButton&&(this.isRecording?(this.micButton.classList.add("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-stop"></i>'):(this.micButton.classList.remove("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-microphone"></i>'))},streamMessage:function(e,t,n){var o=this;this.stream&&(this.stream.dispose(),this.stream=null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var s="",a={},r=null,l=this.messages.length,u=this.getSessionId();this.stream=this.connection.stream("SendMessage",e,t,u,n).subscribe({next:function(e){var t=o.messages[l];if(!t){e.sessionId&&!u&&o.initializeSession(e.sessionId),o.hideTypingIndicator(),l=o.messages.length;var n={id:e.messageId,role:"assistant",title:e.title,content:"",htmlContent:"",isStreaming:!0,userRating:null};o.messages.push(n),t=n}if(!e.title||t.title&&t.title===e.title||(t.title=e.title),e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length)for(var h=0,f=Object.entries(e.references);h<f.length;h++){var m,p=_slicedToArray(f[h],2),g=p[0],v=p[1];a[g]=null!==(m=i(v))&&void 0!==m?m:{}}if(e.content){e.responseId&&r&&e.responseId!==r&&(s+="\n\n"),e.responseId&&(r=e.responseId);for(var y=e.content,b=0,S=Object.entries(a);b<S.length;b++){var A=_slicedToArray(S[b],2),_=A[0],E=A[1];y=y.replaceAll(_,"<sup><strong>".concat(E.index,"</strong></sup>"))}s+=y.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>")}t.content=s,t.htmlContent=d(s,t),o.messages[l]=t,o.$nextTick(function(){c(t),o.scrollToBottom()})},complete:function(){var e;o.processReferences(a,l),o.streamingFinished();var t=o.messages[l];t&&(t.isStreaming=!1),t&&t.content||o.hideTypingIndicator(),o.isConversationMode&&o.textToSpeechEnabled&&t&&t.content&&o.synthesizeSpeech(t.content),null===(e=o.stream)||void 0===e||e.dispose(),o.stream=null},error:function(e){var t;o.processReferences(a,l),o.streamingFinished();var n=o.messages[l];n&&(n.isStreaming=!1),o.hideTypingIndicator(),o.isNavigatingAway||o.addMessage(o.getServiceDownMessage()),null===(t=o.stream)||void 0===t||t.dispose(),o.stream=null,console.error("Stream error:",e)}})},getServiceDownMessage:function(){return{role:"assistant",content:"Our service is currently unavailable. Please try again later. We apologize for the inconvenience.",htmlContent:""}},processReferences:function(e,t){var n=this;if(e=o(e),Object.keys(e).length){var i=this.messages[t],s=i.content||"",a=Object.entries(e).filter(function(e){var t=_slicedToArray(e,2),n=t[0],i=t[1];return s.includes(n)||s.includes("<sup><strong>".concat(i.index,"</strong></sup>"))});if(!a.length)return;a.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var r,l=s.trim(),u=1,h=_createForOfIteratorHelper(a);try{for(h.s();!(r=h.n()).done;){var f=_slicedToArray(r.value,2),m=f[0],p=f[1],g="__CITE_".concat(p.index,"__");l=(l=l.replaceAll(m,g)).replaceAll("<sup><strong>".concat(p.index,"</strong></sup>"),g),p._displayIndex=u++,p._placeholder=g}}catch(e){h.e(e)}finally{h.f()}var v,y=_createForOfIteratorHelper(a);try{for(y.s();!(v=y.n()).done;){var b=_slicedToArray(v.value,2)[1];l=l.replaceAll(b._placeholder,"<sup><strong>".concat(b._displayIndex,"</strong></sup>"))}}catch(e){y.e(e)}finally{y.f()}l=l.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),l+="<br><br>";var S,A=_createForOfIteratorHelper(a);try{for(A.s();!(S=A.n()).done;){var _=_slicedToArray(S.value,2),E=_[0],w=_[1],C=w.text||E;l+=w.link?"**".concat(w._displayIndex,"**. [").concat(C,"](").concat(w.link,")<br>"):"**".concat(w._displayIndex,"**. ").concat(C,"<br>")}}catch(e){A.e(e)}finally{A.f()}i.content=l,i.htmlContent=d(l,i),this.messages[t]=i,this.$nextTick(function(){c(i),n.scrollToBottom()})}},streamingStarted:function(){var e=this.buttonElement.getAttribute("data-stop-icon");e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&this.inputElement.setAttribute("disabled","disabled")},streamingFinished:function(){var e=this.buttonElement.getAttribute("data-start-icon");if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&(this.inputElement.removeAttribute("disabled"),this.inputElement.focus()),this.chatContainer)for(var t=this.chatContainer.querySelectorAll(".ai-streaming-icon"),n=0;n<t.length;n++)t[n].classList.remove("ai-streaming-icon"),t[n].classList.add("ai-bot-icon");for(n=0;n<this.messages.length;n++)this.messages[n].isStreaming&&(this.messages[n].isStreaming=!1)},synthesizeSpeech:function(e){var t=this;this.textToSpeechEnabled&&e&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this.connection.invoke("SynthesizeSpeech",this.getProfileId(),this.getSessionId(),e,this.ttsVoiceName).catch(function(e){console.error("TTS synthesis error:",e),t.isPlayingAudio=!1}))},playCollectedAudio:function(){if(0!==this.audioChunks.length){var e,t=this.audioChunks.reduce(function(e,t){return e+t.length},0),n=new Uint8Array(t),i=0,o=_createForOfIteratorHelper(this.audioChunks);try{for(o.s();!(e=o.n()).done;){var s=e.value;n.set(s,i),i+=s.length}}catch(e){o.e(e)}finally{o.f()}this.audioChunks=[];var a=new Blob([n],{type:"audio/mp3"});this.currentAudioElement?this.audioPlayQueue.push(a):this.playAudioBlob(a)}else this.currentAudioElement||0!==this.audioPlayQueue.length||(this.isPlayingAudio=!1)},playAudioBlob:function(e){var t=this,n=URL.createObjectURL(e),i=new Audio(n);this.currentAudioElement=i,this.isPlayingAudio=!0,i.addEventListener("ended",function(){URL.revokeObjectURL(n),t.currentAudioElement=null,t.playNextInQueue()}),i.addEventListener("error",function(){URL.revokeObjectURL(n),t.currentAudioElement=null,t.playNextInQueue()}),i.play().catch(function(e){console.error("Audio playback error:",e),URL.revokeObjectURL(n),t.currentAudioElement=null,t.isPlayingAudio=!1})},playNextInQueue:function(){if(this.audioPlayQueue.length>0){var e=this.audioPlayQueue.shift();this.playAudioBlob(e)}else this.isPlayingAudio=!1,this.conversationModeOnAudioEnded()},stopAudio:function(){this.currentAudioElement&&(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,this.currentAudioElement=null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1},toggleConversationMode:function(){this.isConversationMode?this.stopConversationMode():this.startConversationMode()},startConversationMode:function(){var e=this;this.conversationModeEnabled&&!this.isConversationMode&&this.connection&&(this.isConversationMode=!0,this.updateConversationButton(),this._conversationPartialTranscript="",this._conversationAssistantMessage=null,this._conversationPartialMessage=null,this.removeNotification("conversation-ended"),navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e._conversationSubject=new signalR.Subject,e._conversationStream=t;var i=window.AudioContext||window.webkitAudioContext;i&&(e._conversationAudioCtx=new i,e._conversationAnalyser=e._conversationAudioCtx.createAnalyser(),e._conversationAnalyser.fftSize=256,e._conversationAudioCtx.createMediaStreamSource(t).connect(e._conversationAnalyser));var o=Promise.resolve(),s=e._conversationAnalyser;e.mediaRecorder.addEventListener("dataavailable",function(t){if(t.data&&t.data.size>0){if(e.isPlayingAudio&&s){var n=new Uint8Array(s.frequencyBinCount);s.getByteFrequencyData(n);for(var i=0,a=0;a<n.length;a++)i+=n[a];i/n.length>=30&&e.stopAudio()}o=o.then(_asyncToGenerator(_regenerator().m(function n(){var i,o,s,a;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:return n.n=1,t.data.arrayBuffer();case 1:i=n.v,o=new Uint8Array(i),s=o.reduce(function(e,t){return e+String.fromCharCode(t)},""),a=btoa(s);try{e._conversationSubject.next(a)}catch(e){}case 2:return n.a(2)}},n)})))}}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),o.then(function(){try{e._conversationSubject.complete()}catch(e){}})});var a=e.getProfileId(),r=e.getSessionId()||"",c=navigator.language||document.documentElement.lang||"en-US";e.connection.send("StartConversation",a,r,e._conversationSubject,n,c),e.mediaRecorder.start(250),e.isRecording=!0}).catch(function(t){console.error("Microphone access denied:",t),e.isConversationMode=!1,e.updateConversationButton()}))},stopConversationMode:function(){if(this.isConversationMode){if(this.isConversationMode=!1,this.updateConversationButton(),this.connection&&this.connection.invoke("StopConversation").catch(function(){}),this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1),this.stopAudio(),this._conversationPartialTranscript="",this._conversationPartialMessage=null,this._conversationAudioCtx&&(this._conversationAudioCtx.close().catch(function(){}),this._conversationAudioCtx=null,this._conversationAnalyser=null),this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:"conversation-ended",content:"Conversation ended.",icon:"fa-solid fa-circle-check",dismissible:!0,autoDismissMs:5e3})}},updateConversationButton:function(){if(this.conversationButton)if(this.isConversationMode){this.conversationButton.classList.add("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-dark","btn-outline-secondary"),this.conversationButton.title=this.conversationButton.getAttribute("data-end-title")||"End Conversation";var e=this.conversationButton.getAttribute("data-end-html");e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}else{this.conversationButton.classList.remove("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-secondary"),this.conversationButton.classList.add("btn-outline-dark"),this.conversationButton.blur(),this.conversationButton.title=this.conversationButton.getAttribute("data-start-title")||"Start Conversation";var t=this.conversationButton.getAttribute("data-start-html");t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))}},conversationModeSendPrompt:function(){},conversationModeOnAudioEnded:function(){},generatePrompt:function(e){if(e){var t=e.getAttribute("data-profile-id"),n=this.getSessionId(),i=this.getProfileId();t&&n?this.streamMessage(t,null,i):console.error("The given element is missing data-profile-id or the session has not yet started.")}else console.error("The element paramter is required.")},createSessionUrl:function(e,t,n){var i=e.toLowerCase().startsWith("http")?e:window.location.origin+e,o=new URL(i);return o.searchParams.set(t,n),o.toString()},showTypingIndicator:function(){this.addMessage({role:"indicator",htmlContent:n.indicatorTemplate})},hideTypingIndicator:function(){var e=this.messages.length;return this.messages=this.messages.filter(function(e){return"indicator"!==e.role}),e-this.messages.length},receiveNotification:function(e){var t=this;if(e&&e.type){this.clearNotificationDismiss(e.type);var n=this.notifications.findIndex(function(t){return t.type===e.type});n>=0?this.notifications.splice(n,1,e):this.notifications.push(e),this.scheduleNotificationDismiss(e),this.$nextTick(function(){t.scrollToBottom()})}},updateNotification:function(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(function(t){return t.type===e.type});t>=0&&(this.notifications.splice(t,1,e),this.scheduleNotificationDismiss(e))}},scheduleNotificationDismiss:function(e){var t=this;e&&e.type&&e.autoDismissMs&&!(e.autoDismissMs<=0)&&(this.notificationDismissTimers[e.type]=setTimeout(function(){t.removeNotification(e.type)},e.autoDismissMs))},clearNotificationDismiss:function(e){var t=this.notificationDismissTimers[e];t&&(clearTimeout(t),delete this.notificationDismissTimers[e])},removeNotification:function(e){this.clearNotificationDismiss(e),this.notifications=this.notifications.filter(function(t){return t.type!==e})},dismissNotification:function(e){this.removeNotification(e)},handleNotificationAction:function(e,t){if(this.connection){var n=this.getSessionId();this.connection.invoke("HandleNotificationAction",n,e,t).catch(function(e){console.error("Error handling notification action:",e)})}},scrollToBottom:function(){var e=this;this.autoScroll&&setTimeout(function(){e.chatContainer.scrollTop=e.chatContainer.scrollHeight-e.chatContainer.clientHeight},50)},handleUserInput:function(e){this.prompt=e.target.value},getProfileId:function(){return this.inputElement.getAttribute("data-profile-id")},setSessionId:function(e){this.inputElement.setAttribute("data-session-id",e||"")},resetSession:function(){this.stopRecording(),this.setSessionId(""),this.isSessionStarted=!1,this.sessionRating=null,this.widgetIsInitialized&&localStorage.removeItem(this.chatWidgetStateSession),this.messages=[],this.documents=[],n.autoCreateSession||this.showPlaceholder(),n.autoCreateSession&&this.startNewSession()},startNewSession:function(){if(this.applyOrchestratorAvailability()){var e=this.getProfileId();e&&this.connection&&this.connection.invoke("StartSession",e,null).catch(function(e){return console.error(e)})}},initializeApp:function(){var e=this;this.inputElement=document.querySelector(n.inputElementSelector),this.buttonElement=document.querySelector(n.sendButtonElementSelector),this.chatContainer=document.querySelector(n.chatContainerElementSelector),this.placeholder=document.querySelector(n.placeholderElementSelector),this.applyOrchestratorAvailability();var t=this.getSessionId();if(!n.widget&&t?this.loadSession(t):this.isOrchestratorAvailable()&&n.autoCreateSession&&!n.widget&&!t&&this.startNewSession(),n.sessionDocumentsEnabled&&n.documentBarSelector&&(this.documentBar=document.querySelector(n.documentBarSelector),this.documentBar)){this.renderDocumentBar();var i=document.createElement("input");i.type="file",i.id="ai-chat-doc-input",i.className="d-none",i.multiple=!0,n.allowedExtensions&&(i.accept=n.allowedExtensions),i.addEventListener("change",function(t){return e.handleFileInputChange(t)}),this.documentBar.parentElement.appendChild(i);var o=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;o&&(o.addEventListener("dragover",function(t){return e.handleDragOver(t)}),o.addEventListener("dragleave",function(t){return e.handleDragLeave(t)}),o.addEventListener("drop",function(t){return e.handleDrop(t)}))}this.chatContainer.addEventListener("scroll",function(){if(e.stream){var t=e.chatContainer.scrollHeight-e.chatContainer.clientHeight-e.chatContainer.scrollTop<=30;e.autoScroll=t}}),this.inputElement.addEventListener("keydown",function(t){null==e.stream&&("Enter"!==t.key||t.shiftKey||(t.preventDefault(),e.buttonElement.click()))}),this.inputElement.addEventListener("input",function(t){e.handleUserInput(t),t.target.value.trim()?e.buttonElement.removeAttribute("disabled"):e.buttonElement.setAttribute("disabled",!0)}),this.buttonElement.addEventListener("click",function(){if(null==e.stream)e.sendMessage();else if(e.stream.dispose(),e.stream=null,e.streamingFinished(),e.hideTypingIndicator(),e.messages.length>0){var t=e.messages[e.messages.length-1];"assistant"!==t.role||t.content?t.isStreaming&&(t.isStreaming=!1):e.messages.pop()}});for(var s=document.getElementsByClassName("profile-generated-prompt"),a=0;a<s.length;a++)s[a].addEventListener("click",function(t){t.preventDefault(),e.generatePrompt(t.target)});var r=document.getElementsByClassName("chat-session-history-item");for(a=0;a<r.length;a++)r[a].addEventListener("click",function(t){t.preventDefault();var n=t.target.getAttribute("data-session-id");n?(e.loadSession(n),e.showChatScreen()):console.error("an element with the class chat-session-history-item with no data-session-id set.")});for(var c=0;c<n.messages.length;c++)this.addMessage(n.messages[c]);this.$nextTick(function(){e.refreshAllFeedbackIcons()}),this.chatContainer&&this.chatContainer.addEventListener("click",function(e){var t=e.target.closest(".ai-code-copy-btn");if(t){var i=t.closest(".ai-code-block")||t.closest("pre");if(i){var o=i.querySelector("code");if(o){navigator.clipboard.writeText(o.textContent);var s=n.codeCopiedText||"Copied!";t.innerHTML='<i class="fa-solid fa-check"></i> '+s,setTimeout(function(){t.innerHTML='<i class="fa-regular fa-copy"></i>'},2e3)}}}}),this.speechToTextEnabled&&n.micButtonElementSelector&&(this.micButton=document.querySelector(n.micButtonElementSelector),this.micButton&&(this.micButton.style.display="",this.micButton.addEventListener("click",function(){e.toggleRecording()}))),this.conversationModeEnabled&&n.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(n.conversationButtonElementSelector),this.conversationButton&&this.conversationButton.addEventListener("click",function(){e.toggleConversationMode()}))},loadSession:function(e){this.connection.invoke("LoadSession",e).catch(function(e){return console.error(e)})},reloadCurrentSession:function(){var e=this.getSessionId();e&&this.loadSession(e)},initializeSession:function(e,t){this.isSessionStarted&&!t||(this.fireEvent(new CustomEvent("initializingSessionOpenAIChat",{detail:{sessionId:e}})),this.setSessionId(e),this.isSessionStarted=!0,this.widgetIsInitialized&&localStorage.setItem(this.chatWidgetStateSession,e))},initializeWidget:function(){var e=this;if(n.widget.chatWidgetContainer)if(n.widget.chatWidgetStateName){if(document.querySelector(n.widget.chatWidgetContainer)){if(n.widget.chatHistorySection&&(this.chatHistorySection=document.querySelector(n.widget.chatHistorySection)),this.chatWidgetStateName=n.widget.chatWidgetStateName,this.chatWidgetStateSession=n.widget.chatWidgetStateName+"Session",this.widgetIsInitialized=!0,this.reloadCurrentSession(),n.autoCreateSession&&!this.getSessionId()&&this.startNewSession(),n.widget.showHistoryButton&&this.chatHistorySection){var t=document.querySelector(n.widget.showHistoryButton);if(t&&t.addEventListener("click",function(){e.chatHistorySection.classList.toggle("show")}),n.widget.closeHistoryButton){var i=document.querySelector(n.widget.closeHistoryButton);i&&i.addEventListener("click",function(){e.showChatScreen()})}}if(n.widget.newChatButton){var o=document.querySelector(n.widget.newChatButton);o&&o.addEventListener("click",function(){e.resetSession(),e.showChatScreen()})}}}else console.error("The widget chatWidgetStateName is required.");else console.error("The widget chatWidgetContainer is required.")},showChatScreen:function(){this.chatHistorySection&&this.chatHistorySection.classList.remove("show")},getSessionId:function(){var e=this.inputElement.getAttribute("data-session-id");return!e&&this.widgetIsInitialized&&(e=localStorage.getItem(this.chatWidgetStateSession)),e},copyResponse:function(e){navigator.clipboard.writeText(e)},updateFeedbackIcons:function(e,t){if(e){var n=e.querySelector(".rate-up-btn"),i=e.querySelector(".rate-down-btn");if(n){var o=!0===t?"fa-solid fa-thumbs-up":"fa-regular fa-thumbs-up",s=document.createElement("i");s.className=o,s.style.fontSize="0.9rem",n.textContent="",n.appendChild(s)}if(i){var a=!1===t?"fa-solid fa-thumbs-down":"fa-regular fa-thumbs-down",r=document.createElement("i");r.className=a,r.style.fontSize="0.9rem",i.textContent="",i.appendChild(r)}window.FontAwesome&&FontAwesome.dom&&FontAwesome.dom.i2svg&&FontAwesome.dom.i2svg({node:e})}},refreshAllFeedbackIcons:function(){for(var e=this.$el.querySelectorAll(".ai-chat-message-assistant-feedback"),t=0;t<e.length;t++){var n=e[t].getAttribute("data-message-id"),i=this.messages.find(function(e){return e.id===n});i&&this.updateFeedbackIcons(e[t],i.userRating)}},rateMessage:function(e,t,n){var i=this.getSessionId();if(i&&e.id&&this.connection){var o=e.userRating===t?null:t;e.userRating=o;var s=this.$el.querySelector('.ai-chat-message-assistant-feedback[data-message-id="'+e.id+'"]');this.updateFeedbackIcons(s,o),null!==o&&s&&setTimeout(function(){var e=t?".rate-up-btn":".rate-down-btn",n=s.querySelector(e);n&&(n.classList.remove("spark-effect"),n.offsetWidth,n.classList.add("spark-effect"),n.addEventListener("animationend",function e(){n.removeEventListener("animationend",e),n.classList.remove("spark-effect")}))},50),this.connection.invoke("RateMessage",i,e.id,t).catch(function(e){console.error("Failed to rate message:",e)})}}},watch:{documents:{handler:function(){this.renderDocumentBar()},deep:!0},isUploading:function(){this.renderDocumentBar()},isPlayingAudio:function(){},isConversationMode:function(e){this.micButton&&(this.micButton.style.display=e?"none":this.speechToTextEnabled?"":"none"),this.buttonElement&&(this.buttonElement.style.display=e?"none":""),this.inputElement&&(this.inputElement.disabled=e,e&&(this.inputElement.placeholder=""))}},mounted:function(){var e=this;_asyncToGenerator(_regenerator().m(function t(){return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.startConnection();case 1:e.initializeApp(),n.widget&&e.initializeWidget();case 2:return t.a(2)}},t)}))(),window.addEventListener("beforeunload",this.handleBeforeUnload)},beforeUnmount:function(){window.removeEventListener("beforeunload",this.handleBeforeUnload),this.stream&&(this.stream.dispose(),this.stream=null),this.connection&&this.connection.stop()},template:n.messageTemplate}).mount(n.appElementSelector);console.error("The sendButtonElementSelector is required.")}else console.error("The inputElementSelector is required.");else console.error("The chatContainerElementSelector is required.");else console.error("The appElementSelector is required.");else console.error("The signalRHubUrl is required.")}}}(),document.addEventListener("click",function(e){var t=e.target.closest(".download-chart-btn");if(t){var n=t.getAttribute("data-chart-id"),i=n?document.getElementById(n):null;if(i){var o=document.createElement("a");o.download="chart-"+n+".png",o.href=i.toDataURL("image/png"),o.click()}else console.error("Chart canvas not found:",n)}}),document.addEventListener("click",function(e){var t=e.target.closest(".ai-download-image");if(t){var n=t.closest(".generated-image-container"),i=null==n?void 0:n.querySelector("img");if(i){var o=i.src;o&&o.startsWith("data:")&&(e.preventDefault(),fetch(o).then(function(e){return e.blob()}).then(function(e){var n=URL.createObjectURL(e),i=document.createElement("a");i.href=n,i.download=t.getAttribute("download")||"generated-image.png",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(e){console.error("Failed to download image:",e)}))}}});
|
package/dist/chat-interaction.js
CHANGED
|
@@ -25,7 +25,6 @@ window.chatInteractionManager = function () {
|
|
|
25
25
|
// UI defaults for generated media
|
|
26
26
|
generatedImageAltText: 'Generated Image',
|
|
27
27
|
generatedImageMaxWidth: 400,
|
|
28
|
-
generatedChartMaxWidth: 900,
|
|
29
28
|
downloadImageTitle: 'Download image',
|
|
30
29
|
downloadChartTitle: 'Download chart as image',
|
|
31
30
|
downloadChartButtonText: 'Download',
|
|
@@ -109,8 +108,7 @@ window.chatInteractionManager = function () {
|
|
|
109
108
|
// Global chart config map shared with ai-chat.js
|
|
110
109
|
window.__chartConfigs = window.__chartConfigs || {};
|
|
111
110
|
function createChartHtml(chartId) {
|
|
112
|
-
|
|
113
|
-
return "<div class=\"chart-container\" style=\"position: relative; width: 100%; max-width: ".concat(chartMaxWidth, "px;\">") + "<canvas id=\"".concat(chartId, "\" class=\"img-thumbnail\"></canvas>") + "</div>" + "<div class=\"mt-2\">" + "<button type=\"button\" class=\"btn btn-sm btn-outline-secondary download-chart-btn\" data-chart-id=\"".concat(chartId, "\" title=\"").concat(defaultConfig.downloadChartTitle, "\">") + "<i class=\"fa-solid fa-download\"></i> ".concat(defaultConfig.downloadChartButtonText) + "</button>" + "</div>";
|
|
111
|
+
return "<div class=\"chart-container\" style=\"position: relative; width: 100%; max-width: 560px; min-height: 420px;\">" + "<canvas id=\"".concat(chartId, "\"></canvas>") + "</div>" + "<div class=\"mt-2\">" + "<button type=\"button\" class=\"btn btn-sm btn-outline-secondary download-chart-btn\" data-chart-id=\"".concat(chartId, "\" title=\"").concat(defaultConfig.downloadChartTitle, "\">") + "<i class=\"fa-solid fa-download\"></i> ".concat(defaultConfig.downloadChartButtonText) + "</button>" + "</div>";
|
|
114
112
|
}
|
|
115
113
|
|
|
116
114
|
// Register [chart:{...json...}] as a native marked block extension so the
|
|
@@ -234,8 +232,15 @@ window.chatInteractionManager = function () {
|
|
|
234
232
|
console.warn('Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>).');
|
|
235
233
|
continue;
|
|
236
234
|
}
|
|
235
|
+
|
|
236
|
+
// When the canvas is inside a hidden container (e.g., display:none),
|
|
237
|
+
// it has zero dimensions. Keep the config for later rendering.
|
|
238
|
+
if (canvas.offsetParent === null) {
|
|
239
|
+
window.__chartConfigs[c.chartId] = c.config;
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
237
242
|
try {
|
|
238
|
-
var _cfg$options;
|
|
243
|
+
var _cfg$options, _cfg$options2, _cfg$options2$aspectR;
|
|
239
244
|
// Destroy existing chart instance if re-rendering
|
|
240
245
|
if (canvas._chartInstance) {
|
|
241
246
|
canvas._chartInstance.destroy();
|
|
@@ -243,7 +248,8 @@ window.chatInteractionManager = function () {
|
|
|
243
248
|
var cfg = typeof c.config === 'string' ? JSON.parse(c.config) : c.config;
|
|
244
249
|
(_cfg$options = cfg.options) !== null && _cfg$options !== void 0 ? _cfg$options : cfg.options = {};
|
|
245
250
|
cfg.options.responsive = true;
|
|
246
|
-
cfg.options.maintainAspectRatio =
|
|
251
|
+
cfg.options.maintainAspectRatio = true;
|
|
252
|
+
(_cfg$options2$aspectR = (_cfg$options2 = cfg.options).aspectRatio) !== null && _cfg$options2$aspectR !== void 0 ? _cfg$options2$aspectR : _cfg$options2.aspectRatio = 4 / 3;
|
|
247
253
|
canvas._chartInstance = new Chart(canvas, cfg);
|
|
248
254
|
} catch (e) {
|
|
249
255
|
console.error('Error creating chart:', e);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray(e,t)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,o,a,r,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=a.call(n)).done)&&(s.push(i.value),s.length!==t);c=!0);}catch(e){l=!0,o=e}finally{try{if(!c&&null!=n.return&&(r=n.return(),Object(r)!==r))return}finally{if(l)throw o}}return s}}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",o=n.toStringTag||"@@toStringTag";function a(n,i,o,a){var c=i&&i.prototype instanceof s?i:s,l=Object.create(c.prototype);return _regeneratorDefine2(l,"_invoke",function(n,i,o){var a,s,c,l=0,u=o||[],d=!1,h={p:0,n:0,v:e,a:m,f:m.bind(e,4),d:function(t,n){return a=t,s=0,c=e,h.n=n,r}};function m(n,i){for(s=n,c=i,t=0;!d&&l&&!o&&t<u.length;t++){var o,a=u[t],m=h.p,f=a[2];n>3?(o=f===i)&&(c=a[(s=a[4])?5:(s=3,3)],a[4]=a[5]=e):a[0]<=m&&((o=n<2&&m<a[1])?(s=0,h.v=i,h.n=a[1]):m<f&&(o=n<3||a[0]>i||i>f)&&(a[4]=n,a[5]=i,h.n=f,s=0))}if(o||n>1)return r;throw d=!0,i}return function(o,u,f){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&m(u,f),s=u,c=f;(t=s<2?e:c)||!d;){a||(s?s<3?(s>1&&(h.n=-1),m(s,c)):h.n=c:h.v=c);try{if(l=2,a){if(s||(o="next"),t=a[o]){if(!(t=t.call(a,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=a.return)&&t.call(a),s<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),s=1);a=e}else if((t=(d=h.n<0)?c:n.call(i,h))!==r)break}catch(t){a=e,s=1,c=t}finally{l=1}}return{value:t,done:d}}}(n,o,a),!0),l}var r={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][i]?t(t([][i]())):(_regeneratorDefine2(t={},i,function(){return this}),t),d=l.prototype=s.prototype=Object.create(u);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(d),e}return c.prototype=l,_regeneratorDefine2(d,"constructor",l),_regeneratorDefine2(l,"constructor",c),c.displayName="GeneratorFunction",_regeneratorDefine2(l,o,"GeneratorFunction"),_regeneratorDefine2(d),_regeneratorDefine2(d,o,"Generator"),_regeneratorDefine2(d,i,function(){return this}),_regeneratorDefine2(d,"toString",function(){return"[object Generator]"}),(_regenerator=function(){return{w:a,m:h}})()}function _regeneratorDefine2(e,t,n,i){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}_regeneratorDefine2=function(e,t,n,i){function a(t,n){_regeneratorDefine2(e,t,function(e){return this._invoke(t,n,e)})}t?o?o(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(a("next",0),a("throw",1),a("return",2))},_regeneratorDefine2(e,t,n,i)}function asyncGeneratorStep(e,t,n,i,o,a,r){try{var s=e[a](r),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(i,o)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(i,o){var a=e.apply(t,n);function r(e){asyncGeneratorStep(a,i,o,r,s,"next",e)}function s(e){asyncGeneratorStep(a,i,o,r,s,"throw",e)}r(void 0)})}}function _createForOfIteratorHelper(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var i=0,o=function(){};return{s:o,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,r=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return r=e.done,e},e:function(e){s=!0,a=e},f:function(){try{r||null==n.return||n.return()}finally{if(s)throw a}}}}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray(e)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}window.chatInteractionManager=function(){var e={generatedImageAltText:"Generated Image",generatedImageMaxWidth:400,generatedChartMaxWidth:900,downloadImageTitle:"Download image",downloadChartTitle:"Download chart as image",downloadChartButtonText:"Download",codeCopiedText:"Copied!",assistantLabel:"Assistant",messageTemplate:'\n <div class="ai-chat-messages">\n <div v-for="(message, index) in messages" :key="index" class="ai-chat-message-item">\n <div>\n <div v-if="message.role === \'user\'" class="ai-chat-msg-role ai-chat-msg-role-user">You</div>\n <div v-else-if="message.role !== \'indicator\'" :class="getAssistantRoleClasses(message)">\n <span :class="getAssistantIconClasses(message, index)"><i :class="getAssistantIcon(message)"></i></span>\n {{ getAssistantLabel(message) }}\n </div>\n <div class="lh-base">\n <h4 v-if="message.title">{{ message.title }}</h4>\n <div v-html="message.htmlContent"></div>\n <span class="message-buttons-container" v-if="!isIndicator(message)">\n <button class="btn btn-sm btn-link text-secondary p-0 button-message-toolbox" @click="copyResponse(message.content)" title="Click here to copy response to clipboard.">\n <i class="fa-solid fa-copy"></i>\n </button>\n </span>\n </div>\n </div>\n </div>\n <div v-for="notification in notifications" :key="\'notif-\' + notification.type" class="ai-chat-notification" :class="\'ai-chat-notification-\' + (notification.type || \'info\') + \' \' + (notification.cssClass || \'\')">\n <div class="ai-chat-notification-content">\n <i v-if="notification.icon" :class="notification.icon" class="ai-chat-notification-icon"></i>\n <span class="ai-chat-notification-text">{{ notification.content }}</span>\n <button v-if="notification.dismissible" class="btn btn-sm btn-link p-0 ms-2 ai-chat-notification-dismiss" @click="dismissNotification(notification.type)" title="Dismiss">\n <i class="fa-solid fa-xmark"></i>\n </button>\n </div>\n <div v-if="notification.actions && notification.actions.length" class="ai-chat-notification-actions">\n <button v-for="action in notification.actions" :key="action.name" class="btn btn-sm" :class="action.cssClass || \'btn-outline-secondary\'" @click="handleNotificationAction(notification.type, action.name)">\n <i v-if="action.icon" :class="action.icon" class="me-1"></i>\n {{ action.label }}\n </button>\n </div>\n </div>\n </div>\n ',indicatorTemplate:'\n <div class="ai-chat-msg-role ai-chat-msg-role-assistant">\n <span class="ai-streaming-icon"><i class="fa fa-robot" style="display: inline-block;"></i></span>\n Assistant\n </div>\n ',untitledText:"Untitled",clearHistoryTitle:"Clear History",clearHistoryMessage:"Are you sure you want to clear the chat history? This action cannot be undone. Your documents, parameters, and tools will be preserved.",clearHistoryOkText:"Yes",clearHistoryCancelText:"Cancel"};function t(e){if(!e)return"";var t=e.trim();return/^javascript:/i.test(t)||/^vbscript:/i.test(t)||/^data:text\/html/i.test(t)?"":e}function n(e){var t=document.createElement("span");return t.textContent=e,t.innerHTML}var i=new marked.Renderer;i.link=function(e){var n=t(e.href);return n?'<a href="'.concat(n,'" target="_blank" rel="noopener noreferrer">').concat(e.text,"</a>"):e.text||""},i.code=function(e){var t=e.text||"",i=(e.lang||"").trim(),o=t;if("undefined"!=typeof hljs)if(i&&hljs.getLanguage(i))try{o=hljs.highlight(t,{language:i}).value}catch(e){}else try{o=hljs.highlightAuto(t).value}catch(e){}else o=n(t);var a=i?n(i):"code";return'<div class="ai-code-block"><div class="ai-code-header"><span class="ai-code-lang"><i class="fa-solid fa-code"></i> '.concat(a,'</span><button type="button" class="ai-code-copy-btn" title="Copy code"><i class="fa-regular fa-copy"></i></button></div><pre><code class="hljs').concat(i?" language-"+i:"",'">').concat(o,"</code></pre></div>")},i.image=function(n){var i=t(n.href);if(!i)return"";var o=n.text||e.generatedImageAltText,a=e.generatedImageMaxWidth;return'<div class="generated-image-container">\n <img src="'.concat(i,'" alt="').concat(o,'" class="img-thumbnail" style="max-width: ').concat(a,'px; height: auto;" />\n <div class="mt-2">\n <a href="').concat(i,'" target="_blank" download="').concat(o,'" title="').concat(e.downloadImageTitle,'" class="btn btn-sm btn-outline-secondary ai-download-image">\n <i class="fa-solid fa-download"></i>\n </a>\n </div>\n </div>')};var o=0,a=[];function r(e){if(e&&e._pendingCharts&&e._pendingCharts.length){var t=_toConsumableArray(e._pendingCharts);e._pendingCharts=[],requestAnimationFrame(function(){var e,n=_createForOfIteratorHelper(t);try{for(n.s();!(e=n.n()).done;){var i=e.value,o=document.getElementById(i.chartId);if(o)if("undefined"!=typeof Chart)try{var a;o._chartInstance&&o._chartInstance.destroy();var r="string"==typeof i.config?JSON.parse(i.config):i.config;null!==(a=r.options)&&void 0!==a||(r.options={}),r.options.responsive=!0,r.options.maintainAspectRatio=!1,o._chartInstance=new Chart(o,r)}catch(e){console.error("Error creating chart:",e)}else console.warn('Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"><\/script>).')}}catch(e){n.e(e)}finally{n.f()}})}}function s(e,t){a=[];var n=marked.parse(e,{renderer:i});return t._pendingCharts=a.length>0?_toConsumableArray(a):[],DOMPurify.sanitize(n,{ADD_TAGS:["canvas"],ADD_ATTR:["target"]})}window.__chartConfigs=window.__chartConfigs||{},marked.use({extensions:[{name:"chart",level:"block",start:function(e){var t=e.indexOf("[chart:");return t>=0?t:void 0},tokenizer:function(e){var t=function(e){var t="[chart:",n=e.indexOf(t);if(n<0)return null;var i=n+t.length,o=i;for(;o<e.length&&(" "===e[o]||"\n"===e[o]||"\r"===e[o]||"\t"===e[o]);)o++;if(o>=e.length||"{"!==e[o])return null;for(var a=0,r=!1,s=!1;o<e.length;o++){var c=e[o];if(r){if(s){s=!1;continue}if("\\"===c){s=!0;continue}'"'===c&&(r=!1)}else if('"'!==c){if("{"===c)a++;else if("}"===c&&0===--a){var l=o,u=e.indexOf("]",l+1);return u<0?null:{startIndex:n,endIndex:u+1,json:e.substring(i,l+1).trim()}}}else r=!0}return null}(e);if(t&&0===t.startIndex){var n="chat_chart_".concat(++o);return{type:"chart",raw:e.substring(0,t.endIndex),chartId:n,json:t.json}}},renderer:function(t){return a.push({chartId:t.chartId,config:t.json}),window.__chartConfigs[t.chartId]=t.json,n=t.chartId,i=e.generatedChartMaxWidth,'<div class="chart-container" style="position: relative; width: 100%; max-width: '.concat(i,'px;">')+'<canvas id="'.concat(n,'" class="img-thumbnail"></canvas>')+'</div><div class="mt-2">'+'<button type="button" class="btn btn-sm btn-outline-secondary download-chart-btn" data-chart-id="'.concat(n,'" title="').concat(e.downloadChartTitle,'">')+'<i class="fa-solid fa-download"></i> '.concat(e.downloadChartButtonText)+"</button></div>";var n,i}}]});return{initialize:function(t){var n=Object.assign({},e,t);if(e=n,n.signalRHubUrl)if(n.appElementSelector)if(n.chatContainerElementSelector)if(n.inputElementSelector){if(n.sendButtonElementSelector)return Vue.createApp({data:function(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isInteractionStarted:!1,isPlaceholderVisible:!0,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,messages:[],prompt:"",initialFieldValues:new Map,settingsDirty:!1,saveSettingsTimeout:null,saveIndicatorTimeout:null,isRecording:!1,mediaRecorder:null,preRecordingPrompt:"",micButton:null,speechToTextEnabled:"AudioInput"===n.chatMode||"Conversation"===n.chatMode,textToSpeechEnabled:"Conversation"===n.chatMode,ttsVoiceName:n.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,conversationModeEnabled:"Conversation"===n.chatMode,conversationButton:null,isConversationMode:!1,notifications:[],notificationDismissTimers:{}}},computed:{lastAssistantIndex:function(){for(var e=this.messages.length-1;e>=0;e--)if("assistant"===this.messages[e].role)return e;return-1}},methods:{handleBeforeUnload:function(){this.isNavigatingAway=!0},startConnection:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var i;return _regenerator().w(function(t){for(;;)switch(t.p=t.n){case 0:return e.connection=(new signalR.HubConnectionBuilder).withUrl(n.signalRHubUrl).withAutomaticReconnect().build(),e.connection.serverTimeoutInMilliseconds=6e5,e.connection.keepAliveIntervalInMilliseconds=15e3,e.connection.on("LoadInteraction",function(t){var n;e.initializeInteraction(t.itemId,!0),e.messages=[];var i=document.querySelector('[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]');i&&t.title&&(i.value=t.title),(null!==(n=t.messages)&&void 0!==n?n:[]).forEach(function(t){e.addMessage(t),e.$nextTick(function(){r(t)})})}),e.connection.on("SettingsSaved",function(t,i){var o=document.querySelector('.chat-interaction-history-item[data-interaction-id="'.concat(t,'"]'));o&&(o.textContent=i||n.untitledText);var a=document.querySelector('[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]');a&&i&&(a.value=i),e.showSaveIndicator("Saved","text-success")}),e.connection.on("ReceiveError",function(t){console.error("SignalR Error: ",t),e.showSaveIndicator("Save failed","text-danger"),e.isRecording&&e.stopRecording()}),e.connection.on("ReceiveTranscript",function(t,n,i){if(e.isConversationMode){if(!i&&n){e._conversationPartialTranscript=n;var o='<p class="ai-partial-transcript">'+n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")+"</p>";e._conversationPartialMessage?(e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent=o):(e.hidePlaceholder(),e._conversationPartialMessage={role:"user",content:n,htmlContent:o,isPartial:!0},e.messages.push(e._conversationPartialMessage)),e.scrollToBottom()}}else n&&!e._audioInputSent&&(e.prompt=e.preRecordingPrompt+n,e.inputElement&&(e.inputElement.value=e.prompt,e.inputElement.dispatchEvent(new Event("input"))))}),e.connection.on("ReceiveConversationUserMessage",function(t,n){if(n){if(e.stopAudio(),e._conversationAssistantMessage){var i=e.messages[e._conversationAssistantMessage.index];i&&(i.isStreaming=!1),e._conversationAssistantMessage=null}if(e._conversationPartialMessage){var o=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent="<p>"+o+"</p>",e._conversationPartialMessage.isPartial=!1,e._conversationPartialMessage=null}else e.addMessage({role:"user",content:n});e.scrollToBottom()}}),e.connection.on("ReceiveConversationAssistantToken",function(t,n,i,o,a){if(!e._conversationAssistantMessage){e.stopAudio(),e.hideTypingIndicator();for(var c=0;c<e.messages.length;c++)e.messages[c].isStreaming&&(e.messages[c].isStreaming=!1);var l=e.messages.length,u={id:n,role:"assistant",content:"",htmlContent:"",isStreaming:!0,appearance:e.normalizeAssistantAppearance(a)};e.messages.push(u),e._conversationAssistantMessage={index:l,content:""}}e._conversationAssistantMessage.content+=i;var d=e.messages[e._conversationAssistantMessage.index];d&&(d.appearance||(d.appearance=e.normalizeAssistantAppearance(a)),d.content=e._conversationAssistantMessage.content,d.htmlContent=s(d.content,d),e.$nextTick(function(){r(d),e.scrollToBottom()}))}),e.connection.on("ReceiveConversationAssistantComplete",function(t,n){if(e._conversationAssistantMessage){var i=e.messages[e._conversationAssistantMessage.index];i&&(i.isStreaming=!1),e._conversationAssistantMessage=null}}),e.connection.on("ReceiveAudioChunk",function(t,n,i){if(n){for(var o=atob(n),a=new Uint8Array(o.length),r=0;r<o.length;r++)a[r]=o.charCodeAt(r);e.audioChunks.push(a)}}),e.connection.on("ReceiveAudioComplete",function(t){e.playCollectedAudio()}),e.connection.on("HistoryCleared",function(t){e.messages=[],e.showPlaceholder();var n=document.getElementById("clearHistoryBtn");n&&n.classList.add("d-none")}),e.connection.on("ReceiveNotification",function(t){e.receiveNotification(t)}),e.connection.on("UpdateNotification",function(t){e.updateNotification(t)}),e.connection.on("RemoveNotification",function(t){e.removeNotification(t)}),e.connection.onreconnecting(function(){console.warn("SignalR: reconnecting...")}),e.connection.onreconnected(function(){console.info("SignalR: reconnected."),e.reloadCurrentInteraction()}),e.connection.onclose(function(t){e.isNavigatingAway||t&&console.warn("SignalR connection closed with error:",t.message||t)}),t.p=1,t.n=2,e.connection.start();case 2:t.n=4;break;case 3:t.p=3,i=t.v,console.error("SignalR Connection Error: ",i);case 4:return t.a(2)}},t,null,[[1,3]])}))()},addMessageInternal:function(e){var t=this;"assistant"===e.role&&(e.appearance=this.normalizeAssistantAppearance(e.appearance)),e.content&&!e.htmlContent&&(e.htmlContent=s(e.content,e)),this.fireEvent(new CustomEvent("addingChatInteractionMessage",{detail:{message:e}})),this.messages.push(e),this.$nextTick(function(){t.fireEvent(new CustomEvent("addedChatInteractionMessage",{detail:{message:e}}))})},addMessage:function(e){var t=this;if(e.content){var n=e.content.trim();if(e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length){var i=Object.entries(e.references).filter(function(e){var t=_slicedToArray(e,1)[0];return n.includes(t)});if(i.length){i.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var o,a=1,c=_createForOfIteratorHelper(i);try{for(c.s();!(o=c.n()).done;){var l=_slicedToArray(o.value,2),u=l[0],d=l[1],h="__CITE_".concat(d.index,"__");n=n.replaceAll(u,h),d._displayIndex=a++,d._placeholder=h}}catch(e){c.e(e)}finally{c.f()}var m,f=_createForOfIteratorHelper(i);try{for(f.s();!(m=f.n()).done;){var g=_slicedToArray(m.value,2)[1];n=n.replaceAll(g._placeholder,"<sup><strong>".concat(g._displayIndex,"</strong></sup>"))}}catch(e){f.e(e)}finally{f.f()}n=n.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),n+="<br><br>";var p,v=_createForOfIteratorHelper(i);try{for(v.s();!(p=v.n()).done;){var y=_slicedToArray(p.value,2),b=(y[0],y[1]),S=b.text||"[doc:".concat(b.index,"]");n+=b.link?"**".concat(b._displayIndex,"**. [").concat(S,"](").concat(b.link,")<br>"):"**".concat(b._displayIndex,"**. ").concat(S,"<br>")}}catch(e){v.e(e)}finally{v.f()}}}e.content=n,e.htmlContent=s(n,e)}this.addMessageInternal(e),this.hidePlaceholder(),this.$nextTick(function(){r(e),t.scrollToBottom()})},hidePlaceholder:function(){this.placeholder&&this.placeholder.classList.add("d-none"),this.isPlaceholderVisible=!1},showPlaceholder:function(){this.placeholder&&this.placeholder.classList.remove("d-none"),this.isPlaceholderVisible=!0},fireEvent:function(e){document.dispatchEvent(e)},normalizeAssistantAppearance:function(e){if(!e)return null;var t="string"==typeof e.label?e.label.trim():"",n="string"==typeof e.icon?e.icon.trim():"",i="string"==typeof e.cssClass?e.cssClass.trim():"",o=!!e.disableStreamingAnimation;return t||n||i||o?{label:t,icon:n,cssClass:i,disableStreamingAnimation:o}:null},getAssistantLabel:function(t){var n=t?this.normalizeAssistantAppearance(t.appearance):null;return n&&n.label?n.label:e.assistantLabel},getAssistantRoleClasses:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null,n=["ai-chat-msg-role"];return t&&t.cssClass?n.push(t.cssClass):n.push("ai-chat-msg-role-assistant"),n},getAssistantIconClasses:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return[this.shouldAnimateAssistantIcon(e,t)?"ai-streaming-icon":"ai-bot-icon",n&&n.cssClass?n.cssClass:""]},getAssistantIcon:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.icon?t.icon:"fa fa-robot"},shouldAnimateAssistantIcon:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return!!e&&e.isStreaming&&t===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},isIndicator:function(e){return"indicator"===e.role},sendMessage:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var n,i;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:if(n=e.prompt.trim()){t.n=1;break}return t.a(2);case 1:return e.isRecording&&e.stopRecording(),e._audioInputSent=!0,t.n=2,e.flushPendingSave();case 2:e.addMessage({role:"user",content:n}),(i=document.getElementById("clearHistoryBtn"))&&i.classList.remove("d-none"),e.streamMessage(n),e.inputElement.value="",e.prompt="";case 3:return t.a(2)}},t)}))()},streamMessage:function(e){var t=this;this.stream&&(this.stream.dispose(),this.stream=null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var n="",i={},o=null,a=this.messages.length,c=this.getItemId();this.stream=this.connection.stream("SendMessage",c,e).subscribe({next:function(e){var l=t.messages[a];if(!l){e.sessionId&&!c&&t.setItemId(e.sessionId),t.hideTypingIndicator(),a=t.messages.length;var u={role:"assistant",content:"",htmlContent:"",isStreaming:!0};t.messages.push(u),l=u}if(e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length)for(var d=0,h=Object.entries(e.references);d<h.length;d++){var m=_slicedToArray(h[d],2),f=m[0],g=m[1];i[f]=g}if(e.content){e.responseId&&o&&e.responseId!==o&&(n+="\n\n"),e.responseId&&(o=e.responseId);for(var p=e.content,v=0,y=Object.entries(i);v<y.length;v++){var b=_slicedToArray(y[v],2),S=b[0],A=b[1];p=p.replaceAll(S,"<sup><strong>".concat(A.index,"</strong></sup>"))}n+=p.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>")}l.content=n,l.htmlContent=s(n,l),t.messages[a]=l,t.$nextTick(function(){r(l),t.scrollToBottom()})},complete:function(){var e;t.processReferences(i,a),t.streamingFinished();var n=t.messages[a];n&&(n.isStreaming=!1),n&&n.content||t.hideTypingIndicator(),t.isConversationMode&&t.textToSpeechEnabled&&n&&n.content&&t.synthesizeSpeech(n.content),null===(e=t.stream)||void 0===e||e.dispose(),t.stream=null},error:function(e){var n;t.processReferences(i,a),t.streamingFinished();var o=t.messages[a];o&&(o.isStreaming=!1),t.hideTypingIndicator(),t.isNavigatingAway||t.addMessage(t.getServiceDownMessage()),null===(n=t.stream)||void 0===n||n.dispose(),t.stream=null,console.error("Stream error:",e)}})},getServiceDownMessage:function(){return{role:"assistant",content:"Our service is currently unavailable. Please try again later. We apologize for the inconvenience.",htmlContent:""}},processReferences:function(e,t){var n=this;if(Object.keys(e).length){var i=this.messages[t],o=i.content||"",a=Object.entries(e).filter(function(e){var t=_slicedToArray(e,2),n=t[0],i=t[1];return o.includes(n)||o.includes("<sup><strong>".concat(i.index,"</strong></sup>"))});if(!a.length)return;a.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var c,l=o.trim(),u=1,d=_createForOfIteratorHelper(a);try{for(d.s();!(c=d.n()).done;){var h=_slicedToArray(c.value,2),m=h[0],f=h[1],g="__CITE_".concat(f.index,"__");l=(l=l.replaceAll(m,g)).replaceAll("<sup><strong>".concat(f.index,"</strong></sup>"),g),f._displayIndex=u++,f._placeholder=g}}catch(e){d.e(e)}finally{d.f()}var p,v=_createForOfIteratorHelper(a);try{for(v.s();!(p=v.n()).done;){var y=_slicedToArray(p.value,2)[1];l=l.replaceAll(y._placeholder,"<sup><strong>".concat(y._displayIndex,"</strong></sup>"))}}catch(e){v.e(e)}finally{v.f()}l=l.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),l+="<br><br>";var b,S=_createForOfIteratorHelper(a);try{for(S.s();!(b=S.n()).done;){var A=_slicedToArray(b.value,2),I=(A[0],A[1]),C=I.text||"[doc:".concat(I.index,"]");l+=I.link?"**".concat(I._displayIndex,"**. [").concat(C,"](").concat(I.link,")<br>"):"**".concat(I._displayIndex,"**. ").concat(C,"<br>")}}catch(e){S.e(e)}finally{S.f()}i.content=l,i.htmlContent=s(l,i),this.messages[t]=i,this.$nextTick(function(){r(i),n.scrollToBottom()})}},streamingStarted:function(){var e=this.buttonElement.getAttribute("data-stop-icon");e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))},streamingFinished:function(){var e=this.buttonElement.getAttribute("data-start-icon");if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.chatContainer)for(var t=this.chatContainer.querySelectorAll(".ai-streaming-icon"),n=0;n<t.length;n++)t[n].classList.remove("ai-streaming-icon"),t[n].classList.add("ai-bot-icon");for(n=0;n<this.messages.length;n++)this.messages[n].isStreaming&&(this.messages[n].isStreaming=!1);this.settingsDirty&&this.debouncedSaveSettings()},synthesizeSpeech:function(e){var t=this;this.textToSpeechEnabled&&e&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this.connection.invoke("SynthesizeSpeech",this.getItemId(),e,this.ttsVoiceName).catch(function(e){console.error("TTS synthesis error:",e),t.isPlayingAudio=!1}))},playCollectedAudio:function(){if(0!==this.audioChunks.length){var e,t=this.audioChunks.reduce(function(e,t){return e+t.length},0),n=new Uint8Array(t),i=0,o=_createForOfIteratorHelper(this.audioChunks);try{for(o.s();!(e=o.n()).done;){var a=e.value;n.set(a,i),i+=a.length}}catch(e){o.e(e)}finally{o.f()}this.audioChunks=[];var r=new Blob([n],{type:"audio/mp3"});this.isPlayingAudio&&this.currentAudioElement?this.audioPlayQueue.push(r):this.playAudioBlob(r)}else this.isPlayingAudio||0!==this.audioPlayQueue.length||(this.isPlayingAudio=!1)},playAudioBlob:function(e){var t=this,n=URL.createObjectURL(e),i=new Audio(n);this.currentAudioElement=i,this.isPlayingAudio=!0,i.addEventListener("ended",function(){URL.revokeObjectURL(n),t.currentAudioElement=null,t.playNextInQueue()}),i.addEventListener("error",function(){URL.revokeObjectURL(n),t.currentAudioElement=null,t.playNextInQueue()}),i.play().catch(function(e){console.error("Audio playback error:",e),URL.revokeObjectURL(n),t.currentAudioElement=null,t.isPlayingAudio=!1})},playNextInQueue:function(){if(this.audioPlayQueue.length>0){var e=this.audioPlayQueue.shift();this.playAudioBlob(e)}else this.isPlayingAudio=!1,this.conversationModeOnAudioEnded()},stopAudio:function(){this.currentAudioElement&&(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,this.currentAudioElement=null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1},toggleConversationMode:function(){this.isConversationMode?this.stopConversationMode():this.startConversationMode()},startConversationMode:function(){var e=this;this.conversationModeEnabled&&!this.isConversationMode&&this.connection&&(this.isConversationMode=!0,this.updateConversationButton(),this._conversationPartialTranscript="",this._conversationAssistantMessage=null,this._conversationPartialMessage=null,this.removeNotification("conversation-ended"),navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e._conversationSubject=new signalR.Subject,e._conversationStream=t;var i=window.AudioContext||window.webkitAudioContext;i&&(e._conversationAudioCtx=new i,e._conversationAnalyser=e._conversationAudioCtx.createAnalyser(),e._conversationAnalyser.fftSize=256,e._conversationAudioCtx.createMediaStreamSource(t).connect(e._conversationAnalyser));var o=Promise.resolve(),a=e._conversationAnalyser;e.mediaRecorder.addEventListener("dataavailable",function(t){if(t.data&&t.data.size>0){if(e.isPlayingAudio&&a){var n=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(n);for(var i=0,r=0;r<n.length;r++)i+=n[r];i/n.length>=30&&e.stopAudio()}o=o.then(_asyncToGenerator(_regenerator().m(function n(){var i,o,a,r;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:return n.n=1,t.data.arrayBuffer();case 1:i=n.v,o=new Uint8Array(i),a=o.reduce(function(e,t){return e+String.fromCharCode(t)},""),r=btoa(a);try{e._conversationSubject.next(r)}catch(e){}case 2:return n.a(2)}},n)})))}}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),o.then(function(){try{e._conversationSubject.complete()}catch(e){}})});var r=e.getItemId(),s=navigator.language||document.documentElement.lang||"en-US";e.connection.send("StartConversation",r,e._conversationSubject,n,s),e.mediaRecorder.start(250),e.isRecording=!0}).catch(function(t){console.error("Microphone access denied:",t),e.isConversationMode=!1,e.updateConversationButton()}))},stopConversationMode:function(){if(this.isConversationMode){if(this.isConversationMode=!1,this.updateConversationButton(),this.connection&&this.connection.invoke("StopConversation").catch(function(){}),this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1),this.stopAudio(),this._conversationPartialTranscript="",this._conversationPartialMessage=null,this._conversationAudioCtx&&(this._conversationAudioCtx.close().catch(function(){}),this._conversationAudioCtx=null,this._conversationAnalyser=null),this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:"conversation-ended",content:"Conversation ended.",icon:"fa-solid fa-circle-check",dismissible:!0,autoDismissMs:5e3})}},updateConversationButton:function(){if(this.conversationButton)if(this.isConversationMode){this.conversationButton.classList.add("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-dark","btn-outline-secondary"),this.conversationButton.title=this.conversationButton.getAttribute("data-end-title")||"End Conversation";var e=this.conversationButton.getAttribute("data-end-html");e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}else{this.conversationButton.classList.remove("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-secondary"),this.conversationButton.classList.add("btn-outline-dark"),this.conversationButton.blur(),this.conversationButton.title=this.conversationButton.getAttribute("data-start-title")||"Start Conversation";var t=this.conversationButton.getAttribute("data-start-html");t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))}},conversationModeSendPrompt:function(){},conversationModeOnAudioEnded:function(){},showTypingIndicator:function(){this.addMessage({role:"indicator",htmlContent:n.indicatorTemplate})},hideTypingIndicator:function(){var e=this.messages.length;return this.messages=this.messages.filter(function(e){return"indicator"!==e.role}),e-this.messages.length},scrollToBottom:function(){var e=this;this.autoScroll&&setTimeout(function(){e.chatContainer.scrollTop=e.chatContainer.scrollHeight-e.chatContainer.clientHeight},50)},handleUserInput:function(e){this.prompt=e.target.value},getItemId:function(){return this.inputElement.getAttribute("data-interaction-id")||this.inputElement.getAttribute("data-item-id")},getSaveIndicatorElement:function(){return n.saveIndicatorElementSelector?document.querySelector(n.saveIndicatorElementSelector):document.querySelector("[data-chat-interaction-save-indicator]")},showSaveIndicator:function(e,t){var n=this,i=this.getSaveIndicatorElement();i&&(i.textContent=e||"",i.className="settings-save-indicator "+(t||"text-muted"),this.saveIndicatorTimeout&&(clearTimeout(this.saveIndicatorTimeout),this.saveIndicatorTimeout=null),e&&(this.saveIndicatorTimeout=setTimeout(function(){i.textContent="",n.saveIndicatorTimeout=null},3e3)))},clearPendingSettingsSave:function(){this.saveSettingsTimeout&&(clearTimeout(this.saveSettingsTimeout),this.saveSettingsTimeout=null)},getFieldLabel:function(e){var t,n=null===(t=e.closest(".mb-3, .col-6, .col, .form-group, .form-floating"))||void 0===t?void 0:t.querySelector("label");return n?(n.textContent||"").replace(/\s+/g," ").trim()||e.dataset.setting||"This field":e.dataset.setting||"This field"},getValidationFeedbackElement:function(e){var t=e.nextElementSibling;return t&&t.classList.contains("invalid-feedback")||((t=document.createElement("div")).className="invalid-feedback",e.insertAdjacentElement("afterend",t)),t},clearSettingValidationError:function(e){e.classList.remove("is-invalid"),e.removeAttribute("aria-invalid");var t=e.nextElementSibling;t&&t.classList.contains("invalid-feedback")&&(t.textContent="")},setSettingValidationError:function(e,t){var n=this.getValidationFeedbackElement(e);e.classList.add("is-invalid"),e.setAttribute("aria-invalid","true"),n.textContent=t},getSettingValidationMessage:function(e){if(!e||e.disabled||"number"!==e.type)return null;var t=(e.value||"").trim();if(!t)return null;var n=Number(t),i=this.getFieldLabel(e);if(Number.isNaN(n))return"".concat(i," must be a valid number.");var o=e.getAttribute("min");if(null!==o&&n<Number(o))return"".concat(i," must be ").concat(o," or greater.");var a=e.getAttribute("max");return null!==a&&n>Number(a)?"".concat(i," must be ").concat(a," or less."):null},validateSettingInput:function(e){var t=this.getSettingValidationMessage(e);return t?(this.setSettingValidationError(e,t),!1):(this.clearSettingValidationError(e),!0)},validateSettings:function(){var e=this,t=!0;return this.getSettingInputs().forEach(function(n){t=e.validateSettingInput(n)&&t}),t},queueSettingsSave:function(){if(!this.validateSettings())return this.clearPendingSettingsSave(),this.settingsDirty=!1,void this.showSaveIndicator("Fix errors","text-danger");this.settingsDirty=!0,this.showSaveIndicator("Saving...","text-warning"),this.debouncedSaveSettings()},getSettingInputs:function(){var e=document.querySelectorAll(".setting-input[data-setting]");return e.length>0?e:document.querySelectorAll('input[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["]), select[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["]), textarea[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["])')},getSelectedGroupValues:function(e,t){var n=document.querySelectorAll('.capability-checkbox[data-save-group="'.concat(e,'"]:checked'));if(n.length>0){var i=[];return n.forEach(function(e){var t=e.getAttribute("data-item-id")||e.value;t&&i.push(t)}),i}if(!t)return[];var o=[];return document.querySelectorAll(t).forEach(function(e){var t=e.name.replace(".IsSelected",".ItemId"),n=document.querySelector('input[type="hidden"][name="'.concat(t,'"]'));n&&n.value&&o.push(n.value)}),o},getPromptTemplateSelections:function(){var e=[];return document.querySelectorAll(".prompt-template-card").forEach(function(t){var n=t.querySelector(".prompt-template-id-input"),i=t.querySelector(".prompt-template-parameters-input"),o=n?n.value:t.getAttribute("data-template-id");o&&e.push({templateId:o,promptParameters:i?(i.value||"").trim():""})}),e},receiveNotification:function(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(function(t){return t.type===e.type});t>=0?this.notifications.splice(t,1,e):this.notifications.push(e),this.scheduleNotificationDismiss(e),this.scrollToBottom()}},updateNotification:function(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(function(t){return t.type===e.type});t>=0&&(this.notifications.splice(t,1,e),this.scheduleNotificationDismiss(e),this.scrollToBottom())}},scheduleNotificationDismiss:function(e){var t=this;e&&e.type&&e.autoDismissMs&&!(e.autoDismissMs<=0)&&(this.notificationDismissTimers[e.type]=setTimeout(function(){t.removeNotification(e.type)},e.autoDismissMs))},clearNotificationDismiss:function(e){var t=this.notificationDismissTimers[e];t&&(clearTimeout(t),delete this.notificationDismissTimers[e])},removeNotification:function(e){this.clearNotificationDismiss(e),this.notifications=this.notifications.filter(function(t){return t.type!==e})},dismissNotification:function(e){this.removeNotification(e)},handleNotificationAction:function(e,t){if(this.connection){var n=this.getItemId();this.connection.invoke("HandleNotificationAction",n,e,t).catch(function(e){return console.error("Failed to handle notification action:",e)})}},setItemId:function(e){this.inputElement.setAttribute("data-interaction-id",e||""),this.inputElement.setAttribute("data-item-id",e||"")},resetInteraction:function(){this.setItemId(""),this.isInteractionStarted=!1,this.messages=[],this.showPlaceholder()},initializeApp:function(){var e=this;this.inputElement=document.querySelector(n.inputElementSelector),this.buttonElement=document.querySelector(n.sendButtonElementSelector),this.chatContainer=document.querySelector(n.chatContainerElementSelector),this.placeholder=document.querySelector(n.placeholderElementSelector);var t=this.getItemId();t&&this.loadInteraction(t),this.chatContainer.addEventListener("scroll",function(){if(e.stream){var t=e.chatContainer.scrollHeight-e.chatContainer.clientHeight-e.chatContainer.scrollTop<=30;e.autoScroll=t}}),this.inputElement.addEventListener("keyup",function(t){null==e.stream&&("Enter"!==t.key||t.shiftKey||e.buttonElement.click())}),this.inputElement.addEventListener("input",function(t){e.handleUserInput(t),t.target.value.trim()?e.buttonElement.removeAttribute("disabled"):e.buttonElement.setAttribute("disabled",!0)}),this.inputElement.addEventListener("paste",function(t){setTimeout(function(){e.prompt=e.inputElement.value,e.inputElement.value.trim()?e.buttonElement.removeAttribute("disabled"):e.buttonElement.setAttribute("disabled",!0)},0)}),this.buttonElement.addEventListener("click",function(){if(null==e.stream)e.sendMessage();else if(e.stream.dispose(),e.stream=null,e.streamingFinished(),e.hideTypingIndicator(),e.messages.length>0){var t=e.messages[e.messages.length-1];"assistant"!==t.role||t.content?t.isStreaming&&(t.isStreaming=!1):e.messages.pop()}});for(var i=document.getElementsByClassName("chat-interaction-history-item"),o=0;o<i.length;o++)i[o].addEventListener("click",function(t){t.preventDefault();var n=t.target.getAttribute("data-interaction-id");n?e.loadInteraction(n):console.error("An element with the class chat-interaction-history-item with no data-interaction-id set.")});for(var a=0;a<n.messages.length;a++)this.addMessage(n.messages[a]);this.chatContainer&&this.chatContainer.addEventListener("click",function(e){var t=e.target.closest(".ai-code-copy-btn");if(t){var i=t.closest(".ai-code-block")||t.closest("pre");if(i){var o=i.querySelector("code");if(o){navigator.clipboard.writeText(o.textContent);var a=n.codeCopiedText||"Copied!";t.innerHTML='<i class="fa-solid fa-check"></i> '+a,setTimeout(function(){t.innerHTML='<i class="fa-regular fa-copy"></i>'},2e3)}}}}),document.addEventListener("input",function(t){t.target.matches(".setting-input[data-setting]")&&(e.validateSettingInput(t.target),e.queueSettingsSave())}),document.addEventListener("change",function(t){if(t.target.matches(".setting-input[data-setting], .capability-checkbox[data-save-group], .group-toggle, .ci-agent-global-toggle"))return t.target.matches(".setting-input[data-setting]")&&e.validateSettingInput(t.target),void e.queueSettingsSave();t.target.closest(".prompt-template-parameters-input, .prompt-template-id-input")&&e.queueSettingsSave()}),document.addEventListener("click",function(t){t.target.closest(".prompt-template-add-btn, .remove-prompt-template-btn")&&setTimeout(function(){e.queueSettingsSave()},0)});var r=document.getElementById("clearHistoryBtn");r&&r.addEventListener("click",function(){var t=r.getAttribute("data-interaction-id");t&&e.clearHistory(t)}),this.speechToTextEnabled&&n.micButtonElementSelector&&(this.micButton=document.querySelector(n.micButtonElementSelector),this.micButton&&(this.micButton.style.display="",this.micButton.addEventListener("click",function(){e.toggleRecording()}))),this.conversationModeEnabled&&n.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(n.conversationButtonElementSelector),this.conversationButton&&this.conversationButton.addEventListener("click",function(){e.toggleConversationMode()}))},loadInteraction:function(e){this.connection.invoke("LoadInteraction",e).catch(function(e){return console.error(e)})},reloadCurrentInteraction:function(){var e=this.getItemId();e&&this.loadInteraction(e)},clearHistory:function(e){var t=this;confirmDialog({title:n.clearHistoryTitle,message:n.clearHistoryMessage,okText:n.clearHistoryOkText,cancelText:n.clearHistoryCancelText,callback:function(n){n&&(t.stream&&(t.stream.dispose(),t.stream=null,t.hideTypingIndicator(),t.streamingFinished()),t.connection.invoke("ClearHistory",e).catch(function(e){return console.error("Error clearing history:",e)}))}})},debouncedSaveSettings:function(){var e=this;this.clearPendingSettingsSave(),this.stream||(this.saveSettingsTimeout=setTimeout(function(){e.settingsDirty&&(e.saveSettings(),e.settingsDirty=!1),e.saveSettingsTimeout=null},850))},getSelectedToolNames:function(){return this.getSelectedGroupValues("toolNames",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Tools["]:checked')},getSelectedMcpConnectionIds:function(){return this.getSelectedGroupValues("mcpConnectionIds",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Connections["]:checked')},getSelectedA2AConnectionIds:function(){return this.getSelectedGroupValues("a2aConnectionIds")},getSelectedAgentNames:function(){return this.getSelectedGroupValues("agentNames",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Agents["]:checked')},saveSettings:function(){var e=this,t=this.getItemId();if(!t)return Promise.resolve();if(!this.validateSettings())return this.showSaveIndicator("Fix errors","text-danger"),Promise.resolve();var n={};this.getSettingInputs().forEach(function(e){var t=e.dataset.setting||(e.name||"").replace("ChatInteraction.","").replace(/^[A-Z]/,function(e){return e.toLowerCase()});t&&("checkbox"===e.type?n[t]=e.checked:"number"===e.type?n[t]=e.value?parseFloat(e.value):null:n[t]=e.value||null)}),n.toolNames=this.getSelectedToolNames(),n.mcpConnectionIds=this.getSelectedMcpConnectionIds(),n.a2aConnectionIds=this.getSelectedA2AConnectionIds(),n.agentNames=this.getSelectedAgentNames();var i=this.getPromptTemplateSelections();return i.length>0&&(n.promptTemplates=i,n.promptTemplateIds=i.map(function(e){return e.templateId})),this.connection.invoke("SaveSettings",t,n).catch(function(t){console.error("Error saving settings:",t),e.showSaveIndicator("Save failed","text-danger")})},flushPendingSave:function(){return this.saveSettingsTimeout&&(clearTimeout(this.saveSettingsTimeout),this.saveSettingsTimeout=null),this.settingsDirty?(this.settingsDirty=!1,this.saveSettings()):Promise.resolve()},initializeInteraction:function(e,t){this.isInteractionStarted&&!t||(this.fireEvent(new CustomEvent("initializingChatInteraction",{detail:{itemId:e}})),this.setItemId(e),this.isInteractionStarted=!0)},copyResponse:function(e){navigator.clipboard.writeText(e)},startRecording:function(){var e=this;!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e.preRecordingPrompt=e.prompt,e._audioInputSent=!1;var i=new signalR.Subject,o=e.getItemId(),a=Promise.resolve();e.mediaRecorder.addEventListener("dataavailable",function(e){e.data&&e.data.size>0&&(a=a.then(_asyncToGenerator(_regenerator().m(function t(){var n,o,a,r;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.data.arrayBuffer();case 1:n=t.v,o=new Uint8Array(n),a=o.reduce(function(e,t){return e+String.fromCharCode(t)},""),r=btoa(a),i.next(r);case 2:return t.a(2)}},t)}))))}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),a.then(function(){return i.complete()})});var r=navigator.language||document.documentElement.lang||"en-US";e.connection.send("SendAudioStream",o,i,n,r),e.mediaRecorder.start(250),e.isRecording=!0,e.updateMicButton()}).catch(function(e){console.error("Microphone access denied:",e)})},stopRecording:function(){this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1,this.updateMicButton())},toggleRecording:function(){this.isRecording?this.stopRecording():this.startRecording()},updateMicButton:function(){this.micButton&&(this.isRecording?(this.micButton.classList.add("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-stop"></i>'):(this.micButton.classList.remove("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-microphone"></i>'))}},watch:{isPlayingAudio:function(){},isConversationMode:function(e){this.micButton&&(this.micButton.style.display=e?"none":this.speechToTextEnabled?"":"none"),this.buttonElement&&(this.buttonElement.style.display=e?"none":""),this.inputElement&&(this.inputElement.disabled=e,e&&(this.inputElement.placeholder=""))}},mounted:function(){var e=this;_asyncToGenerator(_regenerator().m(function t(){return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.startConnection();case 1:e.initializeApp();case 2:return t.a(2)}},t)}))(),window.addEventListener("beforeunload",this.handleBeforeUnload)},beforeUnmount:function(){window.removeEventListener("beforeunload",this.handleBeforeUnload),this.stream&&(this.stream.dispose(),this.stream=null),this.connection&&this.connection.stop()},template:n.messageTemplate}).mount(n.appElementSelector);console.error("The sendButtonElementSelector is required.")}else console.error("The inputElementSelector is required.");else console.error("The chatContainerElementSelector is required.");else console.error("The appElementSelector is required.");else console.error("The signalRHubUrl is required.")}}}(),document.addEventListener("click",function(e){var t=e.target.closest(".download-chart-btn");if(t){var n=t.getAttribute("data-chart-id"),i=n?document.getElementById(n):null;if(i){var o=document.createElement("a");o.download="chart-"+n+".png",o.href=i.toDataURL("image/png"),o.click()}else console.error("Chart canvas not found:",n)}}),document.addEventListener("click",function(e){var t=e.target.closest(".ai-download-image");if(t){var n=t.closest(".generated-image-container"),i=null==n?void 0:n.querySelector("img");if(i){var o=i.src;o&&o.startsWith("data:")&&(e.preventDefault(),fetch(o).then(function(e){return e.blob()}).then(function(e){var n=URL.createObjectURL(e),i=document.createElement("a");i.href=n,i.download=t.getAttribute("download")||"generated-image.png",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(e){console.error("Failed to download image:",e)}))}}});
|
|
1
|
+
function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray(e,t)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,o,a,r,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=a.call(n)).done)&&(s.push(i.value),s.length!==t);c=!0);}catch(e){l=!0,o=e}finally{try{if(!c&&null!=n.return&&(r=n.return(),Object(r)!==r))return}finally{if(l)throw o}}return s}}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",o=n.toStringTag||"@@toStringTag";function a(n,i,o,a){var c=i&&i.prototype instanceof s?i:s,l=Object.create(c.prototype);return _regeneratorDefine2(l,"_invoke",function(n,i,o){var a,s,c,l=0,u=o||[],d=!1,h={p:0,n:0,v:e,a:m,f:m.bind(e,4),d:function(t,n){return a=t,s=0,c=e,h.n=n,r}};function m(n,i){for(s=n,c=i,t=0;!d&&l&&!o&&t<u.length;t++){var o,a=u[t],m=h.p,f=a[2];n>3?(o=f===i)&&(c=a[(s=a[4])?5:(s=3,3)],a[4]=a[5]=e):a[0]<=m&&((o=n<2&&m<a[1])?(s=0,h.v=i,h.n=a[1]):m<f&&(o=n<3||a[0]>i||i>f)&&(a[4]=n,a[5]=i,h.n=f,s=0))}if(o||n>1)return r;throw d=!0,i}return function(o,u,f){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&m(u,f),s=u,c=f;(t=s<2?e:c)||!d;){a||(s?s<3?(s>1&&(h.n=-1),m(s,c)):h.n=c:h.v=c);try{if(l=2,a){if(s||(o="next"),t=a[o]){if(!(t=t.call(a,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=a.return)&&t.call(a),s<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),s=1);a=e}else if((t=(d=h.n<0)?c:n.call(i,h))!==r)break}catch(t){a=e,s=1,c=t}finally{l=1}}return{value:t,done:d}}}(n,o,a),!0),l}var r={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][i]?t(t([][i]())):(_regeneratorDefine2(t={},i,function(){return this}),t),d=l.prototype=s.prototype=Object.create(u);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(d),e}return c.prototype=l,_regeneratorDefine2(d,"constructor",l),_regeneratorDefine2(l,"constructor",c),c.displayName="GeneratorFunction",_regeneratorDefine2(l,o,"GeneratorFunction"),_regeneratorDefine2(d),_regeneratorDefine2(d,o,"Generator"),_regeneratorDefine2(d,i,function(){return this}),_regeneratorDefine2(d,"toString",function(){return"[object Generator]"}),(_regenerator=function(){return{w:a,m:h}})()}function _regeneratorDefine2(e,t,n,i){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}_regeneratorDefine2=function(e,t,n,i){function a(t,n){_regeneratorDefine2(e,t,function(e){return this._invoke(t,n,e)})}t?o?o(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(a("next",0),a("throw",1),a("return",2))},_regeneratorDefine2(e,t,n,i)}function asyncGeneratorStep(e,t,n,i,o,a,r){try{var s=e[a](r),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(i,o)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(i,o){var a=e.apply(t,n);function r(e){asyncGeneratorStep(a,i,o,r,s,"next",e)}function s(e){asyncGeneratorStep(a,i,o,r,s,"throw",e)}r(void 0)})}}function _createForOfIteratorHelper(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var i=0,o=function(){};return{s:o,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,r=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return r=e.done,e},e:function(e){s=!0,a=e},f:function(){try{r||null==n.return||n.return()}finally{if(s)throw a}}}}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray(e)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}window.chatInteractionManager=function(){var e={generatedImageAltText:"Generated Image",generatedImageMaxWidth:400,downloadImageTitle:"Download image",downloadChartTitle:"Download chart as image",downloadChartButtonText:"Download",codeCopiedText:"Copied!",assistantLabel:"Assistant",messageTemplate:'\n <div class="ai-chat-messages">\n <div v-for="(message, index) in messages" :key="index" class="ai-chat-message-item">\n <div>\n <div v-if="message.role === \'user\'" class="ai-chat-msg-role ai-chat-msg-role-user">You</div>\n <div v-else-if="message.role !== \'indicator\'" :class="getAssistantRoleClasses(message)">\n <span :class="getAssistantIconClasses(message, index)"><i :class="getAssistantIcon(message)"></i></span>\n {{ getAssistantLabel(message) }}\n </div>\n <div class="lh-base">\n <h4 v-if="message.title">{{ message.title }}</h4>\n <div v-html="message.htmlContent"></div>\n <span class="message-buttons-container" v-if="!isIndicator(message)">\n <button class="btn btn-sm btn-link text-secondary p-0 button-message-toolbox" @click="copyResponse(message.content)" title="Click here to copy response to clipboard.">\n <i class="fa-solid fa-copy"></i>\n </button>\n </span>\n </div>\n </div>\n </div>\n <div v-for="notification in notifications" :key="\'notif-\' + notification.type" class="ai-chat-notification" :class="\'ai-chat-notification-\' + (notification.type || \'info\') + \' \' + (notification.cssClass || \'\')">\n <div class="ai-chat-notification-content">\n <i v-if="notification.icon" :class="notification.icon" class="ai-chat-notification-icon"></i>\n <span class="ai-chat-notification-text">{{ notification.content }}</span>\n <button v-if="notification.dismissible" class="btn btn-sm btn-link p-0 ms-2 ai-chat-notification-dismiss" @click="dismissNotification(notification.type)" title="Dismiss">\n <i class="fa-solid fa-xmark"></i>\n </button>\n </div>\n <div v-if="notification.actions && notification.actions.length" class="ai-chat-notification-actions">\n <button v-for="action in notification.actions" :key="action.name" class="btn btn-sm" :class="action.cssClass || \'btn-outline-secondary\'" @click="handleNotificationAction(notification.type, action.name)">\n <i v-if="action.icon" :class="action.icon" class="me-1"></i>\n {{ action.label }}\n </button>\n </div>\n </div>\n </div>\n ',indicatorTemplate:'\n <div class="ai-chat-msg-role ai-chat-msg-role-assistant">\n <span class="ai-streaming-icon"><i class="fa fa-robot" style="display: inline-block;"></i></span>\n Assistant\n </div>\n ',untitledText:"Untitled",clearHistoryTitle:"Clear History",clearHistoryMessage:"Are you sure you want to clear the chat history? This action cannot be undone. Your documents, parameters, and tools will be preserved.",clearHistoryOkText:"Yes",clearHistoryCancelText:"Cancel"};function t(e){if(!e)return"";var t=e.trim();return/^javascript:/i.test(t)||/^vbscript:/i.test(t)||/^data:text\/html/i.test(t)?"":e}function n(e){var t=document.createElement("span");return t.textContent=e,t.innerHTML}var i=new marked.Renderer;i.link=function(e){var n=t(e.href);return n?'<a href="'.concat(n,'" target="_blank" rel="noopener noreferrer">').concat(e.text,"</a>"):e.text||""},i.code=function(e){var t=e.text||"",i=(e.lang||"").trim(),o=t;if("undefined"!=typeof hljs)if(i&&hljs.getLanguage(i))try{o=hljs.highlight(t,{language:i}).value}catch(e){}else try{o=hljs.highlightAuto(t).value}catch(e){}else o=n(t);var a=i?n(i):"code";return'<div class="ai-code-block"><div class="ai-code-header"><span class="ai-code-lang"><i class="fa-solid fa-code"></i> '.concat(a,'</span><button type="button" class="ai-code-copy-btn" title="Copy code"><i class="fa-regular fa-copy"></i></button></div><pre><code class="hljs').concat(i?" language-"+i:"",'">').concat(o,"</code></pre></div>")},i.image=function(n){var i=t(n.href);if(!i)return"";var o=n.text||e.generatedImageAltText,a=e.generatedImageMaxWidth;return'<div class="generated-image-container">\n <img src="'.concat(i,'" alt="').concat(o,'" class="img-thumbnail" style="max-width: ').concat(a,'px; height: auto;" />\n <div class="mt-2">\n <a href="').concat(i,'" target="_blank" download="').concat(o,'" title="').concat(e.downloadImageTitle,'" class="btn btn-sm btn-outline-secondary ai-download-image">\n <i class="fa-solid fa-download"></i>\n </a>\n </div>\n </div>')};var o=0,a=[];function r(e){if(e&&e._pendingCharts&&e._pendingCharts.length){var t=_toConsumableArray(e._pendingCharts);e._pendingCharts=[],requestAnimationFrame(function(){var e,n=_createForOfIteratorHelper(t);try{for(n.s();!(e=n.n()).done;){var i=e.value,o=document.getElementById(i.chartId);if(o)if("undefined"!=typeof Chart)if(null!==o.offsetParent)try{var a,r,s;o._chartInstance&&o._chartInstance.destroy();var c="string"==typeof i.config?JSON.parse(i.config):i.config;null!==(a=c.options)&&void 0!==a||(c.options={}),c.options.responsive=!0,c.options.maintainAspectRatio=!0,null!==(s=(r=c.options).aspectRatio)&&void 0!==s||(r.aspectRatio=4/3),o._chartInstance=new Chart(o,c)}catch(e){console.error("Error creating chart:",e)}else window.__chartConfigs[i.chartId]=i.config;else console.warn('Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"><\/script>).')}}catch(e){n.e(e)}finally{n.f()}})}}function s(e,t){a=[];var n=marked.parse(e,{renderer:i});return t._pendingCharts=a.length>0?_toConsumableArray(a):[],DOMPurify.sanitize(n,{ADD_TAGS:["canvas"],ADD_ATTR:["target"]})}window.__chartConfigs=window.__chartConfigs||{},marked.use({extensions:[{name:"chart",level:"block",start:function(e){var t=e.indexOf("[chart:");return t>=0?t:void 0},tokenizer:function(e){var t=function(e){var t="[chart:",n=e.indexOf(t);if(n<0)return null;var i=n+t.length,o=i;for(;o<e.length&&(" "===e[o]||"\n"===e[o]||"\r"===e[o]||"\t"===e[o]);)o++;if(o>=e.length||"{"!==e[o])return null;for(var a=0,r=!1,s=!1;o<e.length;o++){var c=e[o];if(r){if(s){s=!1;continue}if("\\"===c){s=!0;continue}'"'===c&&(r=!1)}else if('"'!==c){if("{"===c)a++;else if("}"===c&&0===--a){var l=o,u=e.indexOf("]",l+1);return u<0?null:{startIndex:n,endIndex:u+1,json:e.substring(i,l+1).trim()}}}else r=!0}return null}(e);if(t&&0===t.startIndex){var n="chat_chart_".concat(++o);return{type:"chart",raw:e.substring(0,t.endIndex),chartId:n,json:t.json}}},renderer:function(t){return a.push({chartId:t.chartId,config:t.json}),window.__chartConfigs[t.chartId]=t.json,n=t.chartId,'<div class="chart-container" style="position: relative; width: 100%; max-width: 560px; min-height: 420px;">'+'<canvas id="'.concat(n,'"></canvas>')+'</div><div class="mt-2">'+'<button type="button" class="btn btn-sm btn-outline-secondary download-chart-btn" data-chart-id="'.concat(n,'" title="').concat(e.downloadChartTitle,'">')+'<i class="fa-solid fa-download"></i> '.concat(e.downloadChartButtonText)+"</button></div>";var n}}]});return{initialize:function(t){var n=Object.assign({},e,t);if(e=n,n.signalRHubUrl)if(n.appElementSelector)if(n.chatContainerElementSelector)if(n.inputElementSelector){if(n.sendButtonElementSelector)return Vue.createApp({data:function(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isInteractionStarted:!1,isPlaceholderVisible:!0,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,messages:[],prompt:"",initialFieldValues:new Map,settingsDirty:!1,saveSettingsTimeout:null,saveIndicatorTimeout:null,isRecording:!1,mediaRecorder:null,preRecordingPrompt:"",micButton:null,speechToTextEnabled:"AudioInput"===n.chatMode||"Conversation"===n.chatMode,textToSpeechEnabled:"Conversation"===n.chatMode,ttsVoiceName:n.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,conversationModeEnabled:"Conversation"===n.chatMode,conversationButton:null,isConversationMode:!1,notifications:[],notificationDismissTimers:{}}},computed:{lastAssistantIndex:function(){for(var e=this.messages.length-1;e>=0;e--)if("assistant"===this.messages[e].role)return e;return-1}},methods:{handleBeforeUnload:function(){this.isNavigatingAway=!0},startConnection:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var i;return _regenerator().w(function(t){for(;;)switch(t.p=t.n){case 0:return e.connection=(new signalR.HubConnectionBuilder).withUrl(n.signalRHubUrl).withAutomaticReconnect().build(),e.connection.serverTimeoutInMilliseconds=6e5,e.connection.keepAliveIntervalInMilliseconds=15e3,e.connection.on("LoadInteraction",function(t){var n;e.initializeInteraction(t.itemId,!0),e.messages=[];var i=document.querySelector('[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]');i&&t.title&&(i.value=t.title),(null!==(n=t.messages)&&void 0!==n?n:[]).forEach(function(t){e.addMessage(t),e.$nextTick(function(){r(t)})})}),e.connection.on("SettingsSaved",function(t,i){var o=document.querySelector('.chat-interaction-history-item[data-interaction-id="'.concat(t,'"]'));o&&(o.textContent=i||n.untitledText);var a=document.querySelector('[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]');a&&i&&(a.value=i),e.showSaveIndicator("Saved","text-success")}),e.connection.on("ReceiveError",function(t){console.error("SignalR Error: ",t),e.showSaveIndicator("Save failed","text-danger"),e.isRecording&&e.stopRecording()}),e.connection.on("ReceiveTranscript",function(t,n,i){if(e.isConversationMode){if(!i&&n){e._conversationPartialTranscript=n;var o='<p class="ai-partial-transcript">'+n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")+"</p>";e._conversationPartialMessage?(e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent=o):(e.hidePlaceholder(),e._conversationPartialMessage={role:"user",content:n,htmlContent:o,isPartial:!0},e.messages.push(e._conversationPartialMessage)),e.scrollToBottom()}}else n&&!e._audioInputSent&&(e.prompt=e.preRecordingPrompt+n,e.inputElement&&(e.inputElement.value=e.prompt,e.inputElement.dispatchEvent(new Event("input"))))}),e.connection.on("ReceiveConversationUserMessage",function(t,n){if(n){if(e.stopAudio(),e._conversationAssistantMessage){var i=e.messages[e._conversationAssistantMessage.index];i&&(i.isStreaming=!1),e._conversationAssistantMessage=null}if(e._conversationPartialMessage){var o=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent="<p>"+o+"</p>",e._conversationPartialMessage.isPartial=!1,e._conversationPartialMessage=null}else e.addMessage({role:"user",content:n});e.scrollToBottom()}}),e.connection.on("ReceiveConversationAssistantToken",function(t,n,i,o,a){if(!e._conversationAssistantMessage){e.stopAudio(),e.hideTypingIndicator();for(var c=0;c<e.messages.length;c++)e.messages[c].isStreaming&&(e.messages[c].isStreaming=!1);var l=e.messages.length,u={id:n,role:"assistant",content:"",htmlContent:"",isStreaming:!0,appearance:e.normalizeAssistantAppearance(a)};e.messages.push(u),e._conversationAssistantMessage={index:l,content:""}}e._conversationAssistantMessage.content+=i;var d=e.messages[e._conversationAssistantMessage.index];d&&(d.appearance||(d.appearance=e.normalizeAssistantAppearance(a)),d.content=e._conversationAssistantMessage.content,d.htmlContent=s(d.content,d),e.$nextTick(function(){r(d),e.scrollToBottom()}))}),e.connection.on("ReceiveConversationAssistantComplete",function(t,n){if(e._conversationAssistantMessage){var i=e.messages[e._conversationAssistantMessage.index];i&&(i.isStreaming=!1),e._conversationAssistantMessage=null}}),e.connection.on("ReceiveAudioChunk",function(t,n,i){if(n){for(var o=atob(n),a=new Uint8Array(o.length),r=0;r<o.length;r++)a[r]=o.charCodeAt(r);e.audioChunks.push(a)}}),e.connection.on("ReceiveAudioComplete",function(t){e.playCollectedAudio()}),e.connection.on("HistoryCleared",function(t){e.messages=[],e.showPlaceholder();var n=document.getElementById("clearHistoryBtn");n&&n.classList.add("d-none")}),e.connection.on("ReceiveNotification",function(t){e.receiveNotification(t)}),e.connection.on("UpdateNotification",function(t){e.updateNotification(t)}),e.connection.on("RemoveNotification",function(t){e.removeNotification(t)}),e.connection.onreconnecting(function(){console.warn("SignalR: reconnecting...")}),e.connection.onreconnected(function(){console.info("SignalR: reconnected."),e.reloadCurrentInteraction()}),e.connection.onclose(function(t){e.isNavigatingAway||t&&console.warn("SignalR connection closed with error:",t.message||t)}),t.p=1,t.n=2,e.connection.start();case 2:t.n=4;break;case 3:t.p=3,i=t.v,console.error("SignalR Connection Error: ",i);case 4:return t.a(2)}},t,null,[[1,3]])}))()},addMessageInternal:function(e){var t=this;"assistant"===e.role&&(e.appearance=this.normalizeAssistantAppearance(e.appearance)),e.content&&!e.htmlContent&&(e.htmlContent=s(e.content,e)),this.fireEvent(new CustomEvent("addingChatInteractionMessage",{detail:{message:e}})),this.messages.push(e),this.$nextTick(function(){t.fireEvent(new CustomEvent("addedChatInteractionMessage",{detail:{message:e}}))})},addMessage:function(e){var t=this;if(e.content){var n=e.content.trim();if(e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length){var i=Object.entries(e.references).filter(function(e){var t=_slicedToArray(e,1)[0];return n.includes(t)});if(i.length){i.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var o,a=1,c=_createForOfIteratorHelper(i);try{for(c.s();!(o=c.n()).done;){var l=_slicedToArray(o.value,2),u=l[0],d=l[1],h="__CITE_".concat(d.index,"__");n=n.replaceAll(u,h),d._displayIndex=a++,d._placeholder=h}}catch(e){c.e(e)}finally{c.f()}var m,f=_createForOfIteratorHelper(i);try{for(f.s();!(m=f.n()).done;){var g=_slicedToArray(m.value,2)[1];n=n.replaceAll(g._placeholder,"<sup><strong>".concat(g._displayIndex,"</strong></sup>"))}}catch(e){f.e(e)}finally{f.f()}n=n.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),n+="<br><br>";var p,v=_createForOfIteratorHelper(i);try{for(v.s();!(p=v.n()).done;){var y=_slicedToArray(p.value,2),b=(y[0],y[1]),S=b.text||"[doc:".concat(b.index,"]");n+=b.link?"**".concat(b._displayIndex,"**. [").concat(S,"](").concat(b.link,")<br>"):"**".concat(b._displayIndex,"**. ").concat(S,"<br>")}}catch(e){v.e(e)}finally{v.f()}}}e.content=n,e.htmlContent=s(n,e)}this.addMessageInternal(e),this.hidePlaceholder(),this.$nextTick(function(){r(e),t.scrollToBottom()})},hidePlaceholder:function(){this.placeholder&&this.placeholder.classList.add("d-none"),this.isPlaceholderVisible=!1},showPlaceholder:function(){this.placeholder&&this.placeholder.classList.remove("d-none"),this.isPlaceholderVisible=!0},fireEvent:function(e){document.dispatchEvent(e)},normalizeAssistantAppearance:function(e){if(!e)return null;var t="string"==typeof e.label?e.label.trim():"",n="string"==typeof e.icon?e.icon.trim():"",i="string"==typeof e.cssClass?e.cssClass.trim():"",o=!!e.disableStreamingAnimation;return t||n||i||o?{label:t,icon:n,cssClass:i,disableStreamingAnimation:o}:null},getAssistantLabel:function(t){var n=t?this.normalizeAssistantAppearance(t.appearance):null;return n&&n.label?n.label:e.assistantLabel},getAssistantRoleClasses:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null,n=["ai-chat-msg-role"];return t&&t.cssClass?n.push(t.cssClass):n.push("ai-chat-msg-role-assistant"),n},getAssistantIconClasses:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return[this.shouldAnimateAssistantIcon(e,t)?"ai-streaming-icon":"ai-bot-icon",n&&n.cssClass?n.cssClass:""]},getAssistantIcon:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.icon?t.icon:"fa fa-robot"},shouldAnimateAssistantIcon:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return!!e&&e.isStreaming&&t===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},isIndicator:function(e){return"indicator"===e.role},sendMessage:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var n,i;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:if(n=e.prompt.trim()){t.n=1;break}return t.a(2);case 1:return e.isRecording&&e.stopRecording(),e._audioInputSent=!0,t.n=2,e.flushPendingSave();case 2:e.addMessage({role:"user",content:n}),(i=document.getElementById("clearHistoryBtn"))&&i.classList.remove("d-none"),e.streamMessage(n),e.inputElement.value="",e.prompt="";case 3:return t.a(2)}},t)}))()},streamMessage:function(e){var t=this;this.stream&&(this.stream.dispose(),this.stream=null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var n="",i={},o=null,a=this.messages.length,c=this.getItemId();this.stream=this.connection.stream("SendMessage",c,e).subscribe({next:function(e){var l=t.messages[a];if(!l){e.sessionId&&!c&&t.setItemId(e.sessionId),t.hideTypingIndicator(),a=t.messages.length;var u={role:"assistant",content:"",htmlContent:"",isStreaming:!0};t.messages.push(u),l=u}if(e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length)for(var d=0,h=Object.entries(e.references);d<h.length;d++){var m=_slicedToArray(h[d],2),f=m[0],g=m[1];i[f]=g}if(e.content){e.responseId&&o&&e.responseId!==o&&(n+="\n\n"),e.responseId&&(o=e.responseId);for(var p=e.content,v=0,y=Object.entries(i);v<y.length;v++){var b=_slicedToArray(y[v],2),S=b[0],A=b[1];p=p.replaceAll(S,"<sup><strong>".concat(A.index,"</strong></sup>"))}n+=p.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>")}l.content=n,l.htmlContent=s(n,l),t.messages[a]=l,t.$nextTick(function(){r(l),t.scrollToBottom()})},complete:function(){var e;t.processReferences(i,a),t.streamingFinished();var n=t.messages[a];n&&(n.isStreaming=!1),n&&n.content||t.hideTypingIndicator(),t.isConversationMode&&t.textToSpeechEnabled&&n&&n.content&&t.synthesizeSpeech(n.content),null===(e=t.stream)||void 0===e||e.dispose(),t.stream=null},error:function(e){var n;t.processReferences(i,a),t.streamingFinished();var o=t.messages[a];o&&(o.isStreaming=!1),t.hideTypingIndicator(),t.isNavigatingAway||t.addMessage(t.getServiceDownMessage()),null===(n=t.stream)||void 0===n||n.dispose(),t.stream=null,console.error("Stream error:",e)}})},getServiceDownMessage:function(){return{role:"assistant",content:"Our service is currently unavailable. Please try again later. We apologize for the inconvenience.",htmlContent:""}},processReferences:function(e,t){var n=this;if(Object.keys(e).length){var i=this.messages[t],o=i.content||"",a=Object.entries(e).filter(function(e){var t=_slicedToArray(e,2),n=t[0],i=t[1];return o.includes(n)||o.includes("<sup><strong>".concat(i.index,"</strong></sup>"))});if(!a.length)return;a.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var c,l=o.trim(),u=1,d=_createForOfIteratorHelper(a);try{for(d.s();!(c=d.n()).done;){var h=_slicedToArray(c.value,2),m=h[0],f=h[1],g="__CITE_".concat(f.index,"__");l=(l=l.replaceAll(m,g)).replaceAll("<sup><strong>".concat(f.index,"</strong></sup>"),g),f._displayIndex=u++,f._placeholder=g}}catch(e){d.e(e)}finally{d.f()}var p,v=_createForOfIteratorHelper(a);try{for(v.s();!(p=v.n()).done;){var y=_slicedToArray(p.value,2)[1];l=l.replaceAll(y._placeholder,"<sup><strong>".concat(y._displayIndex,"</strong></sup>"))}}catch(e){v.e(e)}finally{v.f()}l=l.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),l+="<br><br>";var b,S=_createForOfIteratorHelper(a);try{for(S.s();!(b=S.n()).done;){var A=_slicedToArray(b.value,2),I=(A[0],A[1]),T=I.text||"[doc:".concat(I.index,"]");l+=I.link?"**".concat(I._displayIndex,"**. [").concat(T,"](").concat(I.link,")<br>"):"**".concat(I._displayIndex,"**. ").concat(T,"<br>")}}catch(e){S.e(e)}finally{S.f()}i.content=l,i.htmlContent=s(l,i),this.messages[t]=i,this.$nextTick(function(){r(i),n.scrollToBottom()})}},streamingStarted:function(){var e=this.buttonElement.getAttribute("data-stop-icon");e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))},streamingFinished:function(){var e=this.buttonElement.getAttribute("data-start-icon");if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.chatContainer)for(var t=this.chatContainer.querySelectorAll(".ai-streaming-icon"),n=0;n<t.length;n++)t[n].classList.remove("ai-streaming-icon"),t[n].classList.add("ai-bot-icon");for(n=0;n<this.messages.length;n++)this.messages[n].isStreaming&&(this.messages[n].isStreaming=!1);this.settingsDirty&&this.debouncedSaveSettings()},synthesizeSpeech:function(e){var t=this;this.textToSpeechEnabled&&e&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this.connection.invoke("SynthesizeSpeech",this.getItemId(),e,this.ttsVoiceName).catch(function(e){console.error("TTS synthesis error:",e),t.isPlayingAudio=!1}))},playCollectedAudio:function(){if(0!==this.audioChunks.length){var e,t=this.audioChunks.reduce(function(e,t){return e+t.length},0),n=new Uint8Array(t),i=0,o=_createForOfIteratorHelper(this.audioChunks);try{for(o.s();!(e=o.n()).done;){var a=e.value;n.set(a,i),i+=a.length}}catch(e){o.e(e)}finally{o.f()}this.audioChunks=[];var r=new Blob([n],{type:"audio/mp3"});this.isPlayingAudio&&this.currentAudioElement?this.audioPlayQueue.push(r):this.playAudioBlob(r)}else this.isPlayingAudio||0!==this.audioPlayQueue.length||(this.isPlayingAudio=!1)},playAudioBlob:function(e){var t=this,n=URL.createObjectURL(e),i=new Audio(n);this.currentAudioElement=i,this.isPlayingAudio=!0,i.addEventListener("ended",function(){URL.revokeObjectURL(n),t.currentAudioElement=null,t.playNextInQueue()}),i.addEventListener("error",function(){URL.revokeObjectURL(n),t.currentAudioElement=null,t.playNextInQueue()}),i.play().catch(function(e){console.error("Audio playback error:",e),URL.revokeObjectURL(n),t.currentAudioElement=null,t.isPlayingAudio=!1})},playNextInQueue:function(){if(this.audioPlayQueue.length>0){var e=this.audioPlayQueue.shift();this.playAudioBlob(e)}else this.isPlayingAudio=!1,this.conversationModeOnAudioEnded()},stopAudio:function(){this.currentAudioElement&&(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,this.currentAudioElement=null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1},toggleConversationMode:function(){this.isConversationMode?this.stopConversationMode():this.startConversationMode()},startConversationMode:function(){var e=this;this.conversationModeEnabled&&!this.isConversationMode&&this.connection&&(this.isConversationMode=!0,this.updateConversationButton(),this._conversationPartialTranscript="",this._conversationAssistantMessage=null,this._conversationPartialMessage=null,this.removeNotification("conversation-ended"),navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e._conversationSubject=new signalR.Subject,e._conversationStream=t;var i=window.AudioContext||window.webkitAudioContext;i&&(e._conversationAudioCtx=new i,e._conversationAnalyser=e._conversationAudioCtx.createAnalyser(),e._conversationAnalyser.fftSize=256,e._conversationAudioCtx.createMediaStreamSource(t).connect(e._conversationAnalyser));var o=Promise.resolve(),a=e._conversationAnalyser;e.mediaRecorder.addEventListener("dataavailable",function(t){if(t.data&&t.data.size>0){if(e.isPlayingAudio&&a){var n=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(n);for(var i=0,r=0;r<n.length;r++)i+=n[r];i/n.length>=30&&e.stopAudio()}o=o.then(_asyncToGenerator(_regenerator().m(function n(){var i,o,a,r;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:return n.n=1,t.data.arrayBuffer();case 1:i=n.v,o=new Uint8Array(i),a=o.reduce(function(e,t){return e+String.fromCharCode(t)},""),r=btoa(a);try{e._conversationSubject.next(r)}catch(e){}case 2:return n.a(2)}},n)})))}}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),o.then(function(){try{e._conversationSubject.complete()}catch(e){}})});var r=e.getItemId(),s=navigator.language||document.documentElement.lang||"en-US";e.connection.send("StartConversation",r,e._conversationSubject,n,s),e.mediaRecorder.start(250),e.isRecording=!0}).catch(function(t){console.error("Microphone access denied:",t),e.isConversationMode=!1,e.updateConversationButton()}))},stopConversationMode:function(){if(this.isConversationMode){if(this.isConversationMode=!1,this.updateConversationButton(),this.connection&&this.connection.invoke("StopConversation").catch(function(){}),this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1),this.stopAudio(),this._conversationPartialTranscript="",this._conversationPartialMessage=null,this._conversationAudioCtx&&(this._conversationAudioCtx.close().catch(function(){}),this._conversationAudioCtx=null,this._conversationAnalyser=null),this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:"conversation-ended",content:"Conversation ended.",icon:"fa-solid fa-circle-check",dismissible:!0,autoDismissMs:5e3})}},updateConversationButton:function(){if(this.conversationButton)if(this.isConversationMode){this.conversationButton.classList.add("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-dark","btn-outline-secondary"),this.conversationButton.title=this.conversationButton.getAttribute("data-end-title")||"End Conversation";var e=this.conversationButton.getAttribute("data-end-html");e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}else{this.conversationButton.classList.remove("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-secondary"),this.conversationButton.classList.add("btn-outline-dark"),this.conversationButton.blur(),this.conversationButton.title=this.conversationButton.getAttribute("data-start-title")||"Start Conversation";var t=this.conversationButton.getAttribute("data-start-html");t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))}},conversationModeSendPrompt:function(){},conversationModeOnAudioEnded:function(){},showTypingIndicator:function(){this.addMessage({role:"indicator",htmlContent:n.indicatorTemplate})},hideTypingIndicator:function(){var e=this.messages.length;return this.messages=this.messages.filter(function(e){return"indicator"!==e.role}),e-this.messages.length},scrollToBottom:function(){var e=this;this.autoScroll&&setTimeout(function(){e.chatContainer.scrollTop=e.chatContainer.scrollHeight-e.chatContainer.clientHeight},50)},handleUserInput:function(e){this.prompt=e.target.value},getItemId:function(){return this.inputElement.getAttribute("data-interaction-id")||this.inputElement.getAttribute("data-item-id")},getSaveIndicatorElement:function(){return n.saveIndicatorElementSelector?document.querySelector(n.saveIndicatorElementSelector):document.querySelector("[data-chat-interaction-save-indicator]")},showSaveIndicator:function(e,t){var n=this,i=this.getSaveIndicatorElement();i&&(i.textContent=e||"",i.className="settings-save-indicator "+(t||"text-muted"),this.saveIndicatorTimeout&&(clearTimeout(this.saveIndicatorTimeout),this.saveIndicatorTimeout=null),e&&(this.saveIndicatorTimeout=setTimeout(function(){i.textContent="",n.saveIndicatorTimeout=null},3e3)))},clearPendingSettingsSave:function(){this.saveSettingsTimeout&&(clearTimeout(this.saveSettingsTimeout),this.saveSettingsTimeout=null)},getFieldLabel:function(e){var t,n=null===(t=e.closest(".mb-3, .col-6, .col, .form-group, .form-floating"))||void 0===t?void 0:t.querySelector("label");return n?(n.textContent||"").replace(/\s+/g," ").trim()||e.dataset.setting||"This field":e.dataset.setting||"This field"},getValidationFeedbackElement:function(e){var t=e.nextElementSibling;return t&&t.classList.contains("invalid-feedback")||((t=document.createElement("div")).className="invalid-feedback",e.insertAdjacentElement("afterend",t)),t},clearSettingValidationError:function(e){e.classList.remove("is-invalid"),e.removeAttribute("aria-invalid");var t=e.nextElementSibling;t&&t.classList.contains("invalid-feedback")&&(t.textContent="")},setSettingValidationError:function(e,t){var n=this.getValidationFeedbackElement(e);e.classList.add("is-invalid"),e.setAttribute("aria-invalid","true"),n.textContent=t},getSettingValidationMessage:function(e){if(!e||e.disabled||"number"!==e.type)return null;var t=(e.value||"").trim();if(!t)return null;var n=Number(t),i=this.getFieldLabel(e);if(Number.isNaN(n))return"".concat(i," must be a valid number.");var o=e.getAttribute("min");if(null!==o&&n<Number(o))return"".concat(i," must be ").concat(o," or greater.");var a=e.getAttribute("max");return null!==a&&n>Number(a)?"".concat(i," must be ").concat(a," or less."):null},validateSettingInput:function(e){var t=this.getSettingValidationMessage(e);return t?(this.setSettingValidationError(e,t),!1):(this.clearSettingValidationError(e),!0)},validateSettings:function(){var e=this,t=!0;return this.getSettingInputs().forEach(function(n){t=e.validateSettingInput(n)&&t}),t},queueSettingsSave:function(){if(!this.validateSettings())return this.clearPendingSettingsSave(),this.settingsDirty=!1,void this.showSaveIndicator("Fix errors","text-danger");this.settingsDirty=!0,this.showSaveIndicator("Saving...","text-warning"),this.debouncedSaveSettings()},getSettingInputs:function(){var e=document.querySelectorAll(".setting-input[data-setting]");return e.length>0?e:document.querySelectorAll('input[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["]), select[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["]), textarea[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["])')},getSelectedGroupValues:function(e,t){var n=document.querySelectorAll('.capability-checkbox[data-save-group="'.concat(e,'"]:checked'));if(n.length>0){var i=[];return n.forEach(function(e){var t=e.getAttribute("data-item-id")||e.value;t&&i.push(t)}),i}if(!t)return[];var o=[];return document.querySelectorAll(t).forEach(function(e){var t=e.name.replace(".IsSelected",".ItemId"),n=document.querySelector('input[type="hidden"][name="'.concat(t,'"]'));n&&n.value&&o.push(n.value)}),o},getPromptTemplateSelections:function(){var e=[];return document.querySelectorAll(".prompt-template-card").forEach(function(t){var n=t.querySelector(".prompt-template-id-input"),i=t.querySelector(".prompt-template-parameters-input"),o=n?n.value:t.getAttribute("data-template-id");o&&e.push({templateId:o,promptParameters:i?(i.value||"").trim():""})}),e},receiveNotification:function(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(function(t){return t.type===e.type});t>=0?this.notifications.splice(t,1,e):this.notifications.push(e),this.scheduleNotificationDismiss(e),this.scrollToBottom()}},updateNotification:function(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(function(t){return t.type===e.type});t>=0&&(this.notifications.splice(t,1,e),this.scheduleNotificationDismiss(e),this.scrollToBottom())}},scheduleNotificationDismiss:function(e){var t=this;e&&e.type&&e.autoDismissMs&&!(e.autoDismissMs<=0)&&(this.notificationDismissTimers[e.type]=setTimeout(function(){t.removeNotification(e.type)},e.autoDismissMs))},clearNotificationDismiss:function(e){var t=this.notificationDismissTimers[e];t&&(clearTimeout(t),delete this.notificationDismissTimers[e])},removeNotification:function(e){this.clearNotificationDismiss(e),this.notifications=this.notifications.filter(function(t){return t.type!==e})},dismissNotification:function(e){this.removeNotification(e)},handleNotificationAction:function(e,t){if(this.connection){var n=this.getItemId();this.connection.invoke("HandleNotificationAction",n,e,t).catch(function(e){return console.error("Failed to handle notification action:",e)})}},setItemId:function(e){this.inputElement.setAttribute("data-interaction-id",e||""),this.inputElement.setAttribute("data-item-id",e||"")},resetInteraction:function(){this.setItemId(""),this.isInteractionStarted=!1,this.messages=[],this.showPlaceholder()},initializeApp:function(){var e=this;this.inputElement=document.querySelector(n.inputElementSelector),this.buttonElement=document.querySelector(n.sendButtonElementSelector),this.chatContainer=document.querySelector(n.chatContainerElementSelector),this.placeholder=document.querySelector(n.placeholderElementSelector);var t=this.getItemId();t&&this.loadInteraction(t),this.chatContainer.addEventListener("scroll",function(){if(e.stream){var t=e.chatContainer.scrollHeight-e.chatContainer.clientHeight-e.chatContainer.scrollTop<=30;e.autoScroll=t}}),this.inputElement.addEventListener("keyup",function(t){null==e.stream&&("Enter"!==t.key||t.shiftKey||e.buttonElement.click())}),this.inputElement.addEventListener("input",function(t){e.handleUserInput(t),t.target.value.trim()?e.buttonElement.removeAttribute("disabled"):e.buttonElement.setAttribute("disabled",!0)}),this.inputElement.addEventListener("paste",function(t){setTimeout(function(){e.prompt=e.inputElement.value,e.inputElement.value.trim()?e.buttonElement.removeAttribute("disabled"):e.buttonElement.setAttribute("disabled",!0)},0)}),this.buttonElement.addEventListener("click",function(){if(null==e.stream)e.sendMessage();else if(e.stream.dispose(),e.stream=null,e.streamingFinished(),e.hideTypingIndicator(),e.messages.length>0){var t=e.messages[e.messages.length-1];"assistant"!==t.role||t.content?t.isStreaming&&(t.isStreaming=!1):e.messages.pop()}});for(var i=document.getElementsByClassName("chat-interaction-history-item"),o=0;o<i.length;o++)i[o].addEventListener("click",function(t){t.preventDefault();var n=t.target.getAttribute("data-interaction-id");n?e.loadInteraction(n):console.error("An element with the class chat-interaction-history-item with no data-interaction-id set.")});for(var a=0;a<n.messages.length;a++)this.addMessage(n.messages[a]);this.chatContainer&&this.chatContainer.addEventListener("click",function(e){var t=e.target.closest(".ai-code-copy-btn");if(t){var i=t.closest(".ai-code-block")||t.closest("pre");if(i){var o=i.querySelector("code");if(o){navigator.clipboard.writeText(o.textContent);var a=n.codeCopiedText||"Copied!";t.innerHTML='<i class="fa-solid fa-check"></i> '+a,setTimeout(function(){t.innerHTML='<i class="fa-regular fa-copy"></i>'},2e3)}}}}),document.addEventListener("input",function(t){t.target.matches(".setting-input[data-setting]")&&(e.validateSettingInput(t.target),e.queueSettingsSave())}),document.addEventListener("change",function(t){if(t.target.matches(".setting-input[data-setting], .capability-checkbox[data-save-group], .group-toggle, .ci-agent-global-toggle"))return t.target.matches(".setting-input[data-setting]")&&e.validateSettingInput(t.target),void e.queueSettingsSave();t.target.closest(".prompt-template-parameters-input, .prompt-template-id-input")&&e.queueSettingsSave()}),document.addEventListener("click",function(t){t.target.closest(".prompt-template-add-btn, .remove-prompt-template-btn")&&setTimeout(function(){e.queueSettingsSave()},0)});var r=document.getElementById("clearHistoryBtn");r&&r.addEventListener("click",function(){var t=r.getAttribute("data-interaction-id");t&&e.clearHistory(t)}),this.speechToTextEnabled&&n.micButtonElementSelector&&(this.micButton=document.querySelector(n.micButtonElementSelector),this.micButton&&(this.micButton.style.display="",this.micButton.addEventListener("click",function(){e.toggleRecording()}))),this.conversationModeEnabled&&n.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(n.conversationButtonElementSelector),this.conversationButton&&this.conversationButton.addEventListener("click",function(){e.toggleConversationMode()}))},loadInteraction:function(e){this.connection.invoke("LoadInteraction",e).catch(function(e){return console.error(e)})},reloadCurrentInteraction:function(){var e=this.getItemId();e&&this.loadInteraction(e)},clearHistory:function(e){var t=this;confirmDialog({title:n.clearHistoryTitle,message:n.clearHistoryMessage,okText:n.clearHistoryOkText,cancelText:n.clearHistoryCancelText,callback:function(n){n&&(t.stream&&(t.stream.dispose(),t.stream=null,t.hideTypingIndicator(),t.streamingFinished()),t.connection.invoke("ClearHistory",e).catch(function(e){return console.error("Error clearing history:",e)}))}})},debouncedSaveSettings:function(){var e=this;this.clearPendingSettingsSave(),this.stream||(this.saveSettingsTimeout=setTimeout(function(){e.settingsDirty&&(e.saveSettings(),e.settingsDirty=!1),e.saveSettingsTimeout=null},850))},getSelectedToolNames:function(){return this.getSelectedGroupValues("toolNames",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Tools["]:checked')},getSelectedMcpConnectionIds:function(){return this.getSelectedGroupValues("mcpConnectionIds",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Connections["]:checked')},getSelectedA2AConnectionIds:function(){return this.getSelectedGroupValues("a2aConnectionIds")},getSelectedAgentNames:function(){return this.getSelectedGroupValues("agentNames",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Agents["]:checked')},saveSettings:function(){var e=this,t=this.getItemId();if(!t)return Promise.resolve();if(!this.validateSettings())return this.showSaveIndicator("Fix errors","text-danger"),Promise.resolve();var n={};this.getSettingInputs().forEach(function(e){var t=e.dataset.setting||(e.name||"").replace("ChatInteraction.","").replace(/^[A-Z]/,function(e){return e.toLowerCase()});t&&("checkbox"===e.type?n[t]=e.checked:"number"===e.type?n[t]=e.value?parseFloat(e.value):null:n[t]=e.value||null)}),n.toolNames=this.getSelectedToolNames(),n.mcpConnectionIds=this.getSelectedMcpConnectionIds(),n.a2aConnectionIds=this.getSelectedA2AConnectionIds(),n.agentNames=this.getSelectedAgentNames();var i=this.getPromptTemplateSelections();return i.length>0&&(n.promptTemplates=i,n.promptTemplateIds=i.map(function(e){return e.templateId})),this.connection.invoke("SaveSettings",t,n).catch(function(t){console.error("Error saving settings:",t),e.showSaveIndicator("Save failed","text-danger")})},flushPendingSave:function(){return this.saveSettingsTimeout&&(clearTimeout(this.saveSettingsTimeout),this.saveSettingsTimeout=null),this.settingsDirty?(this.settingsDirty=!1,this.saveSettings()):Promise.resolve()},initializeInteraction:function(e,t){this.isInteractionStarted&&!t||(this.fireEvent(new CustomEvent("initializingChatInteraction",{detail:{itemId:e}})),this.setItemId(e),this.isInteractionStarted=!0)},copyResponse:function(e){navigator.clipboard.writeText(e)},startRecording:function(){var e=this;!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e.preRecordingPrompt=e.prompt,e._audioInputSent=!1;var i=new signalR.Subject,o=e.getItemId(),a=Promise.resolve();e.mediaRecorder.addEventListener("dataavailable",function(e){e.data&&e.data.size>0&&(a=a.then(_asyncToGenerator(_regenerator().m(function t(){var n,o,a,r;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.data.arrayBuffer();case 1:n=t.v,o=new Uint8Array(n),a=o.reduce(function(e,t){return e+String.fromCharCode(t)},""),r=btoa(a),i.next(r);case 2:return t.a(2)}},t)}))))}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),a.then(function(){return i.complete()})});var r=navigator.language||document.documentElement.lang||"en-US";e.connection.send("SendAudioStream",o,i,n,r),e.mediaRecorder.start(250),e.isRecording=!0,e.updateMicButton()}).catch(function(e){console.error("Microphone access denied:",e)})},stopRecording:function(){this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1,this.updateMicButton())},toggleRecording:function(){this.isRecording?this.stopRecording():this.startRecording()},updateMicButton:function(){this.micButton&&(this.isRecording?(this.micButton.classList.add("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-stop"></i>'):(this.micButton.classList.remove("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-microphone"></i>'))}},watch:{isPlayingAudio:function(){},isConversationMode:function(e){this.micButton&&(this.micButton.style.display=e?"none":this.speechToTextEnabled?"":"none"),this.buttonElement&&(this.buttonElement.style.display=e?"none":""),this.inputElement&&(this.inputElement.disabled=e,e&&(this.inputElement.placeholder=""))}},mounted:function(){var e=this;_asyncToGenerator(_regenerator().m(function t(){return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.startConnection();case 1:e.initializeApp();case 2:return t.a(2)}},t)}))(),window.addEventListener("beforeunload",this.handleBeforeUnload)},beforeUnmount:function(){window.removeEventListener("beforeunload",this.handleBeforeUnload),this.stream&&(this.stream.dispose(),this.stream=null),this.connection&&this.connection.stop()},template:n.messageTemplate}).mount(n.appElementSelector);console.error("The sendButtonElementSelector is required.")}else console.error("The inputElementSelector is required.");else console.error("The chatContainerElementSelector is required.");else console.error("The appElementSelector is required.");else console.error("The signalRHubUrl is required.")}}}(),document.addEventListener("click",function(e){var t=e.target.closest(".download-chart-btn");if(t){var n=t.getAttribute("data-chart-id"),i=n?document.getElementById(n):null;if(i){var o=document.createElement("a");o.download="chart-"+n+".png",o.href=i.toDataURL("image/png"),o.click()}else console.error("Chart canvas not found:",n)}}),document.addEventListener("click",function(e){var t=e.target.closest(".ai-download-image");if(t){var n=t.closest(".generated-image-container"),i=null==n?void 0:n.querySelector("img");if(i){var o=i.src;o&&o.startsWith("data:")&&(e.preventDefault(),fetch(o).then(function(e){return e.blob()}).then(function(e){var n=URL.createObjectURL(e),i=document.createElement("a");i.href=n,i.download=t.getAttribute("download")||"generated-image.png",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(e){console.error("Failed to download image:",e)}))}}});
|
package/dist/chat-widget.css
CHANGED
|
@@ -98,54 +98,135 @@
|
|
|
98
98
|
font-size: 0.9rem;
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
gap: 0.5rem;
|
|
101
|
+
/* ── Widget message items (ai-chat.js Vue template) ── */
|
|
102
|
+
.ai-chat-widget-messages .ai-chat-messages {
|
|
103
|
+
padding: 0.5rem;
|
|
105
104
|
}
|
|
106
105
|
|
|
107
|
-
.ai-chat-widget-messages .
|
|
108
|
-
|
|
106
|
+
.ai-chat-widget-messages .ai-chat-message-item {
|
|
107
|
+
position: relative;
|
|
108
|
+
padding: 0.5rem 0;
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
-
.ai-chat-widget-messages .
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
111
|
+
.ai-chat-widget-messages .ai-chat-message-item + .ai-chat-message-item::before {
|
|
112
|
+
content: '';
|
|
113
|
+
display: block;
|
|
114
|
+
width: 100%;
|
|
115
|
+
margin-bottom: 0.5rem;
|
|
116
|
+
border-top: 1px solid rgba(33, 37, 41, 0.08);
|
|
117
117
|
}
|
|
118
118
|
|
|
119
|
-
.ai-chat-widget-messages .msg
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
119
|
+
.ai-chat-widget-messages .ai-chat-msg-role {
|
|
120
|
+
font-size: 0.7rem;
|
|
121
|
+
font-weight: 600;
|
|
122
|
+
margin-bottom: 2px;
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
-
.ai-chat-widget-messages .msg
|
|
126
|
-
|
|
127
|
-
color: #212529;
|
|
128
|
-
border-bottom-left-radius: 2px;
|
|
125
|
+
.ai-chat-widget-messages .ai-chat-msg-role-user {
|
|
126
|
+
color: #0d6efd;
|
|
129
127
|
}
|
|
130
128
|
|
|
131
|
-
.ai-chat-widget-messages .msg
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
129
|
+
.ai-chat-widget-messages .ai-chat-msg-role-assistant {
|
|
130
|
+
color: #6f42c1;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
.ai-chat-widget-messages .ai-chat-msg-role-assistant i.ai-streaming-icon {
|
|
134
|
+
animation: ai-widget-pulse 1.5s infinite;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
.ai-chat-widget-messages .ai-chat-msg-role-assistant i.ai-bot-icon {
|
|
138
|
+
color: #6f42c1;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
.ai-chat-widget-messages .ai-chat-message-body {
|
|
142
|
+
position: relative;
|
|
143
|
+
padding: 0 0 1.75rem 0;
|
|
144
|
+
overflow-wrap: break-word;
|
|
145
|
+
word-break: break-word;
|
|
146
|
+
min-width: 0;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
.ai-chat-widget-messages .ai-chat-message-body p:last-child {
|
|
150
|
+
margin-bottom: 0;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/* ── Message action buttons (copy, thumbs up/down) ── */
|
|
154
|
+
.ai-chat-widget-messages .message-buttons-container {
|
|
155
|
+
position: absolute;
|
|
156
|
+
right: 0;
|
|
157
|
+
bottom: 0.25rem;
|
|
158
|
+
display: inline-flex;
|
|
159
|
+
gap: 0.35rem;
|
|
160
|
+
opacity: 0;
|
|
161
|
+
pointer-events: none;
|
|
162
|
+
transition: opacity 0.15s ease-in-out;
|
|
163
|
+
background: rgba(255, 255, 255, 0.92);
|
|
164
|
+
padding: 0.15rem 0.35rem;
|
|
165
|
+
border-radius: 4px;
|
|
166
|
+
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
.ai-chat-widget-messages .ai-chat-message-item:hover .message-buttons-container,
|
|
170
|
+
.ai-chat-widget-messages .ai-chat-message-item:focus-within .message-buttons-container {
|
|
171
|
+
opacity: 1;
|
|
172
|
+
pointer-events: auto;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
.ai-chat-widget-messages .message-buttons-container > .button-message-toolbox {
|
|
176
|
+
color: var(--bs-secondary-color, #6c757d) !important;
|
|
177
|
+
text-decoration: none;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
.ai-chat-widget-messages .message-buttons-container > .button-message-toolbox:hover,
|
|
181
|
+
.ai-chat-widget-messages .message-buttons-container > .button-message-toolbox:focus {
|
|
182
|
+
color: var(--bs-body-color, #212529) !important;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/* ── Notifications ── */
|
|
186
|
+
.ai-chat-widget-messages .ai-chat-notification {
|
|
187
|
+
margin: 0.75rem 0.5rem 0;
|
|
188
|
+
padding: 0.625rem 0.75rem;
|
|
189
|
+
border: 1px solid rgba(33, 37, 41, 0.12);
|
|
190
|
+
border-radius: 0.5rem;
|
|
191
|
+
background: rgba(248, 249, 250, 0.98);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
.ai-chat-widget-messages .ai-chat-notification-content {
|
|
195
|
+
display: flex;
|
|
196
|
+
align-items: flex-start;
|
|
197
|
+
gap: 0.5rem;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
.ai-chat-widget-messages .ai-chat-notification-icon {
|
|
201
|
+
margin-top: 0.1rem;
|
|
202
|
+
color: var(--bs-secondary-color, #6c757d);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
.ai-chat-widget-messages .ai-chat-notification-text {
|
|
206
|
+
flex: 1 1 auto;
|
|
207
|
+
min-width: 0;
|
|
137
208
|
}
|
|
138
209
|
|
|
139
|
-
.ai-chat-widget-messages .
|
|
140
|
-
|
|
141
|
-
|
|
210
|
+
.ai-chat-widget-messages .ai-chat-notification-dismiss {
|
|
211
|
+
margin-left: auto !important;
|
|
212
|
+
color: var(--bs-secondary-color, #6c757d) !important;
|
|
142
213
|
}
|
|
143
214
|
|
|
144
|
-
|
|
145
|
-
|
|
215
|
+
.ai-chat-widget-messages .ai-chat-notification-actions {
|
|
216
|
+
display: flex;
|
|
217
|
+
gap: 0.5rem;
|
|
218
|
+
margin-top: 0.5rem;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/* ── Chart containers inside widget ── */
|
|
222
|
+
.ai-chat-widget-messages .chart-container {
|
|
223
|
+
width: 100%;
|
|
224
|
+
max-width: 100% !important;
|
|
225
|
+
min-height: 280px;
|
|
146
226
|
}
|
|
147
227
|
|
|
148
|
-
|
|
228
|
+
/* ── Code blocks & inline code ── */
|
|
229
|
+
.ai-chat-widget-messages .ai-chat-message-body pre {
|
|
149
230
|
background: #2d2d2d;
|
|
150
231
|
color: #f8f8f2;
|
|
151
232
|
padding: 0.5rem;
|
|
@@ -154,12 +235,13 @@
|
|
|
154
235
|
font-size: 0.8rem;
|
|
155
236
|
}
|
|
156
237
|
|
|
157
|
-
.ai-chat-widget-messages .
|
|
238
|
+
.ai-chat-widget-messages .ai-chat-message-body code {
|
|
158
239
|
font-size: 0.85em;
|
|
159
240
|
}
|
|
160
241
|
|
|
161
|
-
|
|
162
|
-
|
|
242
|
+
@keyframes ai-widget-pulse {
|
|
243
|
+
0%, 100% { opacity: 1; }
|
|
244
|
+
50% { opacity: 0.4; }
|
|
163
245
|
}
|
|
164
246
|
|
|
165
247
|
.ai-chat-widget-input {
|
package/dist/chat-widget.min.css
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
:root{--ai-widget-primary:var(--bs-secondary, #6c757d);--ai-widget-width:380px;--ai-widget-height:520px}.ai-chat-widget-toggle{position:fixed;bottom:1.25rem;right:1.25rem;z-index:10000;width:52px;height:52px;border-radius:50%;background:var(--ai-widget-primary);color:#fff;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:1.5rem;box-shadow:0 4px 12px rgba(0,0,0,.2);transition:transform .2s,box-shadow .2s}.ai-chat-widget-toggle:hover{transform:scale(1.1);box-shadow:0 6px 16px rgba(0,0,0,.3)}.ai-chat-widget-container{position:fixed;bottom:5rem;right:1.25rem;z-index:10001;width:var(--ai-widget-width);height:var(--ai-widget-height);background:#fff;border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,.18);display:none;flex-direction:column;overflow:hidden}.ai-chat-widget-container.open{display:flex}.ai-chat-widget-header{display:flex;align-items:center;justify-content:space-between;padding:.75rem 1rem;background:var(--ai-widget-primary);color:#fff}.ai-chat-widget-header .title{font-weight:600;font-size:.95rem}.ai-chat-widget-header button{background:0 0;border:none;color:#fff;cursor:pointer;font-size:1rem;padding:0 .25rem;opacity:.8}.ai-chat-widget-header button:hover{opacity:1}.ai-chat-widget-profile-select{padding:.5rem .75rem;border-bottom:1px solid #e9ecef;background:#f8f9fa}.ai-chat-widget-profile-select select{width:100%;padding:.35rem .5rem;border:1px solid #ced4da;border-radius:6px;font-size:.85rem}.ai-chat-widget-messages{flex:1;overflow-y:auto;padding:.75rem;font-size:.9rem}.ai-chat-widget-messages .
|
|
1
|
+
:root{--ai-widget-primary:var(--bs-secondary, #6c757d);--ai-widget-width:380px;--ai-widget-height:520px}.ai-chat-widget-toggle{position:fixed;bottom:1.25rem;right:1.25rem;z-index:10000;width:52px;height:52px;border-radius:50%;background:var(--ai-widget-primary);color:#fff;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:1.5rem;box-shadow:0 4px 12px rgba(0,0,0,.2);transition:transform .2s,box-shadow .2s}.ai-chat-widget-toggle:hover{transform:scale(1.1);box-shadow:0 6px 16px rgba(0,0,0,.3)}.ai-chat-widget-container{position:fixed;bottom:5rem;right:1.25rem;z-index:10001;width:var(--ai-widget-width);height:var(--ai-widget-height);background:#fff;border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,.18);display:none;flex-direction:column;overflow:hidden}.ai-chat-widget-container.open{display:flex}.ai-chat-widget-header{display:flex;align-items:center;justify-content:space-between;padding:.75rem 1rem;background:var(--ai-widget-primary);color:#fff}.ai-chat-widget-header .title{font-weight:600;font-size:.95rem}.ai-chat-widget-header button{background:0 0;border:none;color:#fff;cursor:pointer;font-size:1rem;padding:0 .25rem;opacity:.8}.ai-chat-widget-header button:hover{opacity:1}.ai-chat-widget-profile-select{padding:.5rem .75rem;border-bottom:1px solid #e9ecef;background:#f8f9fa}.ai-chat-widget-profile-select select{width:100%;padding:.35rem .5rem;border:1px solid #ced4da;border-radius:6px;font-size:.85rem}.ai-chat-widget-messages{flex:1;overflow-y:auto;padding:.75rem;font-size:.9rem}.ai-chat-widget-messages .ai-chat-messages{padding:.5rem}.ai-chat-widget-messages .ai-chat-message-item{position:relative;padding:.5rem 0}.ai-chat-widget-messages .ai-chat-message-item+.ai-chat-message-item::before{content:'';display:block;width:100%;margin-bottom:.5rem;border-top:1px solid rgba(33,37,41,.08)}.ai-chat-widget-messages .ai-chat-msg-role{font-size:.7rem;font-weight:600;margin-bottom:2px}.ai-chat-widget-messages .ai-chat-msg-role-user{color:#0d6efd}.ai-chat-widget-messages .ai-chat-msg-role-assistant{color:#6f42c1}.ai-chat-widget-messages .ai-chat-msg-role-assistant i.ai-streaming-icon{animation:ai-widget-pulse 1.5s infinite}.ai-chat-widget-messages .ai-chat-msg-role-assistant i.ai-bot-icon{color:#6f42c1}.ai-chat-widget-messages .ai-chat-message-body{position:relative;padding:0 0 1.75rem 0;overflow-wrap:break-word;word-break:break-word;min-width:0}.ai-chat-widget-messages .ai-chat-message-body p:last-child{margin-bottom:0}.ai-chat-widget-messages .message-buttons-container{position:absolute;right:0;bottom:.25rem;display:inline-flex;gap:.35rem;opacity:0;pointer-events:none;transition:opacity .15s ease-in-out;background:rgba(255,255,255,.92);padding:.15rem .35rem;border-radius:4px;box-shadow:0 1px 3px rgba(0,0,0,.08)}.ai-chat-widget-messages .ai-chat-message-item:focus-within .message-buttons-container,.ai-chat-widget-messages .ai-chat-message-item:hover .message-buttons-container{opacity:1;pointer-events:auto}.ai-chat-widget-messages .message-buttons-container>.button-message-toolbox{color:var(--bs-secondary-color,#6c757d)!important;text-decoration:none}.ai-chat-widget-messages .message-buttons-container>.button-message-toolbox:focus,.ai-chat-widget-messages .message-buttons-container>.button-message-toolbox:hover{color:var(--bs-body-color,#212529)!important}.ai-chat-widget-messages .ai-chat-notification{margin:.75rem .5rem 0;padding:.625rem .75rem;border:1px solid rgba(33,37,41,.12);border-radius:.5rem;background:rgba(248,249,250,.98)}.ai-chat-widget-messages .ai-chat-notification-content{display:flex;align-items:flex-start;gap:.5rem}.ai-chat-widget-messages .ai-chat-notification-icon{margin-top:.1rem;color:var(--bs-secondary-color,#6c757d)}.ai-chat-widget-messages .ai-chat-notification-text{flex:1 1 auto;min-width:0}.ai-chat-widget-messages .ai-chat-notification-dismiss{margin-left:auto!important;color:var(--bs-secondary-color,#6c757d)!important}.ai-chat-widget-messages .ai-chat-notification-actions{display:flex;gap:.5rem;margin-top:.5rem}.ai-chat-widget-messages .chart-container{width:100%;max-width:100%!important;min-height:280px}.ai-chat-widget-messages .ai-chat-message-body pre{background:#2d2d2d;color:#f8f8f2;padding:.5rem;border-radius:4px;overflow-x:auto;font-size:.8rem}.ai-chat-widget-messages .ai-chat-message-body code{font-size:.85em}@keyframes ai-widget-pulse{0%,100%{opacity:1}50%{opacity:.4}}.ai-chat-widget-input{border-top:1px solid #e9ecef;padding:.5rem .75rem;display:flex;gap:.5rem;align-items:flex-end}.ai-chat-widget-input textarea{flex:1;border:1px solid #ced4da;border-radius:8px;padding:.4rem .6rem;font-size:.9rem;resize:none;max-height:80px;min-height:36px;line-height:1.4;outline:0}.ai-chat-widget-input textarea:focus{border-color:var(--ai-widget-primary);box-shadow:0 0 0 2px rgba(65,182,112,.15)}.ai-chat-widget-input button{background:var(--ai-widget-primary);color:#fff;border:none;border-radius:8px;padding:.4rem .75rem;cursor:pointer;font-size:.9rem;white-space:nowrap}.ai-chat-widget-input button:disabled{opacity:.5;cursor:not-allowed}.ai-chat-widget-status{padding:.25rem .75rem;font-size:.8rem;color:#6c757d;display:none}.ai-chat-widget-status.visible{display:block}.ai-chat-widget-welcome{text-align:center;color:#6c757d;padding:2rem 1rem;font-size:.9rem}@media (max-width:576px){.ai-chat-widget-container{width:calc(100vw - 1rem);height:calc(100vh - 6rem);right:.5rem;bottom:4.5rem}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crestapps/ai-chat-ui",
|
|
3
|
-
"version": "1.0.0-preview-22-preview.
|
|
3
|
+
"version": "1.0.0-preview-22-preview.4",
|
|
4
4
|
"description": "Browser-ready JavaScript widgets and CSS for CrestApps AI chat sessions and chat interactions. Supports streaming responses, image generation, Chart.js interactive charts, document uploads, copy-to-clipboard, and feedback buttons.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "CrestApps",
|