@crestapps/ai-chat-ui 1.0.0-preview.7 → 1.0.0-preview.9
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.css +362 -0
- package/dist/ai-chat.css.map +1 -0
- package/dist/ai-chat.js +244 -131
- package/dist/ai-chat.js.map +1 -1
- package/dist/ai-chat.min.css +1 -0
- package/dist/ai-chat.min.js +1 -1
- package/dist/ai-chat.min.js.map +1 -1
- package/dist/chat-interaction.js +9 -9
- package/dist/chat-interaction.js.map +1 -1
- package/dist/chat-interaction.min.js +1 -1
- package/dist/chat-interaction.min.js.map +1 -1
- package/dist/chat-widget.css +104 -3
- package/dist/chat-widget.css.map +1 -1
- package/dist/chat-widget.min.css +1 -1
- package/package.json +4 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function _slicedToArray(t,e){return _arrayWithHoles(t)||_iterableToArrayLimit(t,e)||_unsupportedIterableToArray(t,e)||_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(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var i,o,a,r,s=[],c=!0,l=!1;try{if(a=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=a.call(n)).done)&&(s.push(i.value),s.length!==e);c=!0);}catch(t){l=!0,o=t}finally{try{if(!c&&null!=n.return&&(r=n.return(),Object(r)!==r))return}finally{if(l)throw o}}return s}}function _arrayWithHoles(t){if(Array.isArray(t))return t}function _typeof(t){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_typeof(t)}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var t,e,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:t,a:m,f:m.bind(t,4),d:function(e,n){return a=e,s=0,c=t,h.n=n,r}};function m(n,i){for(s=n,c=i,e=0;!d&&l&&!o&&e<u.length;e++){var o,a=u[e],m=h.p,g=a[2];n>3?(o=g===i)&&(c=a[(s=a[4])?5:(s=3,3)],a[4]=a[5]=t):a[0]<=m&&((o=n<2&&m<a[1])?(s=0,h.v=i,h.n=a[1]):m<g&&(o=n<3||a[0]>i||i>g)&&(a[4]=n,a[5]=i,h.n=g,s=0))}if(o||n>1)return r;throw d=!0,i}return function(o,u,g){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&m(u,g),s=u,c=g;(e=s<2?t: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"),e=a[o]){if(!(e=e.call(a,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=a.return)&&e.call(a),s<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),s=1);a=t}else if((e=(d=h.n<0)?c:n.call(i,h))!==r)break}catch(e){a=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,o,a),!0),l}var r={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][i]?e(e([][i]())):(_regeneratorDefine2(e={},i,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function h(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,_regeneratorDefine2(t,o,"GeneratorFunction")),t.prototype=Object.create(d),t}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(t,e,n,i){var o=Object.defineProperty;try{o({},"",{})}catch(t){o=0}_regeneratorDefine2=function(t,e,n,i){function a(e,n){_regeneratorDefine2(t,e,function(t){return this._invoke(e,n,t)})}e?o?o(t,e,{value:n,enumerable:!i,configurable:!i,writable:!i}):t[e]=n:(a("next",0),a("throw",1),a("return",2))},_regeneratorDefine2(t,e,n,i)}function asyncGeneratorStep(t,e,n,i,o,a,r){try{var s=t[a](r),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(i,o)}function _asyncToGenerator(t){return function(){var e=this,n=arguments;return new Promise(function(i,o){var a=t.apply(e,n);function r(t){asyncGeneratorStep(a,i,o,r,s,"next",t)}function s(t){asyncGeneratorStep(a,i,o,r,s,"throw",t)}r(void 0)})}}function _createForOfIteratorHelper(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=_unsupportedIterableToArray(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var i=0,o=function(){};return{s:o,n:function(){return i>=t.length?{done:!0}:{done:!1,value:t[i++]}},e:function(t){throw t},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(t)},n:function(){var t=n.next();return r=t.done,t},e:function(t){s=!0,a=t},f:function(){try{r||null==n.return||n.return()}finally{if(s)throw a}}}}function _toConsumableArray(t){return _arrayWithoutHoles(t)||_iterableToArray(t)||_unsupportedIterableToArray(t)||_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(t,e){if(t){if("string"==typeof t)return _arrayLikeToArray(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(t,e):void 0}}function _iterableToArray(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}function _arrayWithoutHoles(t){if(Array.isArray(t))return _arrayLikeToArray(t)}function _arrayLikeToArray(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,i=Array(e);n<e;n++)i[n]=t[n];return i}window.chatInteractionManager=function(){var t={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="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 <button v-if="textToSpeechEnabled && !isConversationMode && message.role === \'assistant\' && !message.isStreaming" class="btn btn-sm btn-link text-secondary p-0 me-1 button-message-toolbox" :class="{ \'tts-playing\': ttsPlayingMessageIndex === index }" @click="toggleMessageTts(message, index)" :title="ttsPlayingMessageIndex === index ? \'Pause audio\' : \'Read aloud\'">\n <i :class="ttsPlayingMessageIndex === index ? \'fa-solid fa-circle-pause\' : \'fa-solid fa-circle-play\'"></i>\n </button>\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 e(t){if(!t)return"";var e=t.trim();return/^javascript:/i.test(e)||/^vbscript:/i.test(e)||/^data:text\/html/i.test(e)?"":t}function n(t){var e=document.createElement("span");return e.textContent=t,e.innerHTML}var i=new marked.Renderer;i.link=function(t){var n=e(t.href);return n?'<a href="'.concat(n,'" target="_blank" rel="noopener noreferrer">').concat(t.text,"</a>"):t.text||""},i.code=function(t){var e=t.text||"",i=(t.lang||"").trim(),o=e;if("undefined"!=typeof hljs)if(i&&hljs.getLanguage(i))try{o=hljs.highlight(e,{language:i}).value}catch(t){}else try{o=hljs.highlightAuto(e).value}catch(t){}else o=n(e);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=e(n.href);if(!i)return"";var o=n.text||t.generatedImageAltText,a=t.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(t.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(t){if(t&&t._pendingCharts&&t._pendingCharts.length){var e=_toConsumableArray(t._pendingCharts);t._pendingCharts=[],requestAnimationFrame(function(){var t,n=_createForOfIteratorHelper(e);try{for(n.s();!(t=n.n()).done;){var i=t.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(t){console.error("Error creating chart:",t)}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(t){n.e(t)}finally{n.f()}})}}function s(t,e){a=[];var n=marked.parse(t,{renderer:i});return e._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(t){var e=t.indexOf("[chart:");return e>=0?e:void 0},tokenizer:function(t){var e=function(t){var e="[chart:",n=t.indexOf(e);if(n<0)return null;var i=n+e.length,o=i;for(;o<t.length&&(" "===t[o]||"\n"===t[o]||"\r"===t[o]||"\t"===t[o]);)o++;if(o>=t.length||"{"!==t[o])return null;for(var a=0,r=!1,s=!1;o<t.length;o++){var c=t[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=t.indexOf("]",l+1);return u<0?null:{startIndex:n,endIndex:u+1,json:t.substring(i,l+1).trim()}}}else r=!0}return null}(t);if(e&&0===e.startIndex){var n="chat_chart_".concat(++o);return{type:"chart",raw:t.substring(0,e.endIndex),chartId:n,json:e.json}}},renderer:function(e){return a.push({chartId:e.chartId,config:e.json}),window.__chartConfigs[e.chartId]=e.json,n=e.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(t.downloadChartTitle,'">')+'<i class="fa-solid fa-download"></i> '.concat(t.downloadChartButtonText)+"</button></div>";var n}}]});return{initialize:function(e){var n=Object.assign({},t,e);if(t=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||!!n.textToSpeechEnabled,ttsVoiceName:n.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,currentAudioUrl:null,ttsPlayingMessageIndex:-1,ttsAudioCache:{},ttsInstanceId:"chat-interaction-"+Math.random().toString(36).slice(2),conversationModeEnabled:"Conversation"===n.chatMode,conversationButton:null,isConversationMode:!1,notifications:[],notificationDismissTimers:{}}},computed:{lastAssistantIndex:function(){for(var t=this.messages.length-1;t>=0;t--)if("assistant"===this.messages[t].role)return t;return-1}},methods:{handleBeforeUnload:function(){this.isNavigatingAway=!0},startConnection:function(){var t=this;return _asyncToGenerator(_regenerator().m(function e(){var i;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:return t.connection=(new signalR.HubConnectionBuilder).withUrl(n.signalRHubUrl).withAutomaticReconnect().build(),t.connection.serverTimeoutInMilliseconds=6e5,t.connection.keepAliveIntervalInMilliseconds=15e3,t.connection.on("LoadInteraction",function(e){var n;t.initializeInteraction(e.itemId,!0),t.messages=[];var i=document.querySelector('[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]');i&&e.title&&(i.value=e.title),(null!==(n=e.messages)&&void 0!==n?n:[]).forEach(function(e){t.addMessage(e),t.$nextTick(function(){r(e)})})}),t.connection.on("SettingsSaved",function(e,i){var o=document.querySelector('.chat-interaction-history-item[data-interaction-id="'.concat(e,'"]'));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),t.showSaveIndicator("Saved","text-success")}),t.connection.on("ReceiveError",function(e){console.error("SignalR Error: ",e),t.showSaveIndicator("Save failed","text-danger"),t.isRecording&&t.stopRecording()}),t.connection.on("ReceiveTranscript",function(e,n,i){if(t.isConversationMode){if(!i&&n){t._conversationPartialTranscript=n;var o='<p class="ai-partial-transcript">'+n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")+"</p>";t._conversationPartialMessage?(t._conversationPartialMessage.content=n,t._conversationPartialMessage.htmlContent=o):(t.hidePlaceholder(),t._conversationPartialMessage={role:"user",content:n,htmlContent:o,isPartial:!0},t.messages.push(t._conversationPartialMessage)),t.scrollToBottom()}}else n&&!t._audioInputSent&&(t.prompt=t.preRecordingPrompt+n,t.inputElement&&(t.inputElement.value=t.prompt,t.inputElement.dispatchEvent(new Event("input"))))}),t.connection.on("ReceiveConversationUserMessage",function(e,n){if(n){if(t.stopAudio(),t._conversationAssistantMessage){var i=t.messages[t._conversationAssistantMessage.index];i&&(i.isStreaming=!1),t._conversationAssistantMessage=null}if(t._conversationPartialMessage){var o=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");t._conversationPartialMessage.content=n,t._conversationPartialMessage.htmlContent="<p>"+o+"</p>",t._conversationPartialMessage.isPartial=!1,t._conversationPartialMessage=null}else t.addMessage({role:"user",content:n});t.scrollToBottom()}}),t.connection.on("ReceiveConversationAssistantToken",function(e,n,i,o,a){if(!t._conversationAssistantMessage){t.stopAudio(),t.hideTypingIndicator();for(var c=0;c<t.messages.length;c++)t.messages[c].isStreaming&&(t.messages[c].isStreaming=!1);var l=t.messages.length,u={id:n,role:"assistant",content:"",htmlContent:"",isStreaming:!0,appearance:t.normalizeAssistantAppearance(a)};t.messages.push(u),t._conversationAssistantMessage={index:l,content:""}}t._conversationAssistantMessage.content+=i;var d=t.messages[t._conversationAssistantMessage.index];d&&(d.appearance||(d.appearance=t.normalizeAssistantAppearance(a)),d.content=t._conversationAssistantMessage.content,d.htmlContent=s(d.content,d),t.$nextTick(function(){r(d),t.scrollToBottom()}))}),t.connection.on("ReceiveConversationAssistantComplete",function(e,n){if(t._conversationAssistantMessage){var i=t.messages[t._conversationAssistantMessage.index];i&&(i.isStreaming=!1),t._conversationAssistantMessage=null}}),t.connection.on("ReceiveAudioChunk",function(e,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);t.audioChunks.push(a)}}),t.connection.on("ReceiveAudioComplete",function(e){t.playCollectedAudio()}),t.connection.on("HistoryCleared",function(e){t.messages=[],t.showPlaceholder();var n=document.getElementById("clearHistoryBtn");n&&n.classList.add("d-none")}),t.connection.on("ReceiveNotification",function(e){t.receiveNotification(e)}),t.connection.on("UpdateNotification",function(e){t.updateNotification(e)}),t.connection.on("RemoveNotification",function(e){t.removeNotification(e)}),t.connection.onreconnecting(function(){console.warn("SignalR: reconnecting...")}),t.connection.onreconnected(function(){console.info("SignalR: reconnected."),t.reloadCurrentInteraction()}),t.connection.onclose(function(e){t.isNavigatingAway||e&&console.warn("SignalR connection closed with error:",e.message||e)}),e.p=1,e.n=2,t.connection.start();case 2:e.n=4;break;case 3:e.p=3,i=e.v,console.error("SignalR Connection Error: ",i);case 4:return e.a(2)}},e,null,[[1,3]])}))()},addMessageInternal:function(t){var e=this;"assistant"===t.role&&(t.appearance=this.normalizeAssistantAppearance(t.appearance)),t.content&&!t.htmlContent&&(t.htmlContent=s(t.content,t)),this.fireEvent(new CustomEvent("addingChatInteractionMessage",{detail:{message:t}})),this.messages.push(t),this.$nextTick(function(){e.fireEvent(new CustomEvent("addedChatInteractionMessage",{detail:{message:t}}))})},addMessage:function(t){var e=this;if(t.content){var n=t.content.trim();if(t.references&&"object"===_typeof(t.references)&&Object.keys(t.references).length){var i=Object.entries(t.references).filter(function(t){var e=_slicedToArray(t,1)[0];return n.includes(e)});if(i.length){i.sort(function(t,e){var n=_slicedToArray(t,2)[1],i=_slicedToArray(e,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(t){c.e(t)}finally{c.f()}var m,g=_createForOfIteratorHelper(i);try{for(g.s();!(m=g.n()).done;){var f=_slicedToArray(m.value,2)[1];n=n.replaceAll(f._placeholder,"<sup><strong>".concat(f._displayIndex,"</strong></sup>"))}}catch(t){g.e(t)}finally{g.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]),A=b.text||"[doc:".concat(b.index,"]");n+=b.link?"**".concat(b._displayIndex,"**. [").concat(A,"](").concat(b.link,")<br>"):"**".concat(b._displayIndex,"**. ").concat(A,"<br>")}}catch(t){v.e(t)}finally{v.f()}}}t.content=n,t.htmlContent=s(n,t)}this.addMessageInternal(t),this.hidePlaceholder(),this.$nextTick(function(){r(t),e.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(t){document.dispatchEvent(t)},normalizeAssistantAppearance:function(t){if(!t)return null;var e="string"==typeof t.label?t.label.trim():"",n="string"==typeof t.icon?t.icon.trim():"",i="string"==typeof t.cssClass?t.cssClass.trim():"",o=!!t.disableStreamingAnimation;return e||n||i||o?{label:e,icon:n,cssClass:i,disableStreamingAnimation:o}:null},getAssistantLabel:function(e){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return n&&n.label?n.label:t.assistantLabel},getAssistantRoleClasses:function(t){var e=t?this.normalizeAssistantAppearance(t.appearance):null,n=["ai-chat-msg-role"];return e&&e.cssClass?n.push(e.cssClass):n.push("ai-chat-msg-role-assistant"),n},getAssistantIconClasses:function(t,e){var n=t?this.normalizeAssistantAppearance(t.appearance):null;return[this.shouldAnimateAssistantIcon(t,e)?"ai-streaming-icon":"ai-bot-icon",n&&n.cssClass?n.cssClass:""]},getAssistantIcon:function(t){var e=t?this.normalizeAssistantAppearance(t.appearance):null;return e&&e.icon?e.icon:"fa fa-robot"},shouldAnimateAssistantIcon:function(t,e){var n=t?this.normalizeAssistantAppearance(t.appearance):null;return!!t&&t.isStreaming&&e===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},isIndicator:function(t){return"indicator"===t.role},sendMessage:function(){var t=this;return _asyncToGenerator(_regenerator().m(function e(){var n,i;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:if(n=t.prompt.trim()){e.n=1;break}return e.a(2);case 1:return t.isRecording&&t.stopRecording(),t._audioInputSent=!0,e.n=2,t.flushPendingSave();case 2:t.addMessage({role:"user",content:n}),(i=document.getElementById("clearHistoryBtn"))&&i.classList.remove("d-none"),t.streamMessage(n),t.inputElement.value="",t.prompt="";case 3:return e.a(2)}},e)}))()},streamMessage:function(t){var e=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,t).subscribe({next:function(t){var l=e.messages[a];if(!l){t.sessionId&&!c&&e.setItemId(t.sessionId),e.hideTypingIndicator(),a=e.messages.length;var u={role:"assistant",content:"",htmlContent:"",isStreaming:!0};e.messages.push(u),l=u}if(t.references&&"object"===_typeof(t.references)&&Object.keys(t.references).length)for(var d=0,h=Object.entries(t.references);d<h.length;d++){var m=_slicedToArray(h[d],2),g=m[0],f=m[1];i[g]=f}if(t.content){t.responseId&&o&&t.responseId!==o&&(n+="\n\n"),t.responseId&&(o=t.responseId);for(var p=t.content,v=0,y=Object.entries(i);v<y.length;v++){var b=_slicedToArray(y[v],2),A=b[0],S=b[1];p=p.replaceAll(A,"<sup><strong>".concat(S.index,"</strong></sup>"))}n+=p.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>")}l.content=n,l.htmlContent=s(n,l),e.messages[a]=l,e.$nextTick(function(){r(l),e.scrollToBottom()})},complete:function(){var t;e.processReferences(i,a),e.streamingFinished();var n=e.messages[a];n&&(n.isStreaming=!1),n&&n.content||e.hideTypingIndicator(),e.isConversationMode&&e.textToSpeechEnabled&&n&&n.content&&e.synthesizeSpeech(n.content),null===(t=e.stream)||void 0===t||t.dispose(),e.stream=null},error:function(t){var n;e.processReferences(i,a),e.streamingFinished();var o=e.messages[a];o&&(o.isStreaming=!1),e.hideTypingIndicator(),e.isNavigatingAway||e.addMessage(e.getServiceDownMessage()),null===(n=e.stream)||void 0===n||n.dispose(),e.stream=null,console.error("Stream error:",t)}})},getServiceDownMessage:function(){return{role:"assistant",content:"Our service is currently unavailable. Please try again later. We apologize for the inconvenience.",htmlContent:""}},processReferences:function(t,e){var n=this;if(Object.keys(t).length){var i=this.messages[e],o=i.content||"",a=Object.entries(t).filter(function(t){var e=_slicedToArray(t,2),n=e[0],i=e[1];return o.includes(n)||o.includes("<sup><strong>".concat(i.index,"</strong></sup>"))});if(!a.length)return;a.sort(function(t,e){var n=_slicedToArray(t,2)[1],i=_slicedToArray(e,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],g=h[1],f="__CITE_".concat(g.index,"__");l=(l=l.replaceAll(m,f)).replaceAll("<sup><strong>".concat(g.index,"</strong></sup>"),f),g._displayIndex=u++,g._placeholder=f}}catch(t){d.e(t)}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(t){v.e(t)}finally{v.f()}l=l.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),l+="<br><br>";var b,A=_createForOfIteratorHelper(a);try{for(A.s();!(b=A.n()).done;){var S=_slicedToArray(b.value,2),I=(S[0],S[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(t){A.e(t)}finally{A.f()}i.content=l,i.htmlContent=s(l,i),this.messages[e]=i,this.$nextTick(function(){r(i),n.scrollToBottom()})}},streamingStarted:function(){var t=this.buttonElement.getAttribute("data-stop-icon");t&&this.buttonElement.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))},streamingFinished:function(){var t=this.buttonElement.getAttribute("data-start-icon");if(t&&this.buttonElement.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0})),this.chatContainer)for(var e=this.chatContainer.querySelectorAll(".ai-streaming-icon"),n=0;n<e.length;n++)e[n].classList.remove("ai-streaming-icon"),e[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()},handleExternalTtsStop:function(t){var e;(null==t||null===(e=t.detail)||void 0===e?void 0:e.sourceId)!==this.ttsInstanceId&&this.stopAudio(!1)},synthesizeSpeech:function(t,e){var n=this;this.textToSpeechEnabled&&t&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this._ttsCacheIndex=void 0!==e?e:-1,this.connection.invoke("SynthesizeSpeech",this.getItemId(),t,this.ttsVoiceName).catch(function(t){console.error("TTS synthesis error:",t),n.isPlayingAudio=!1,n.ttsPlayingMessageIndex=-1,n._ttsCacheIndex=-1}))},toggleMessageTts:function(t,e){this.ttsPlayingMessageIndex!==e?(this.stopAudio(!1),window.dispatchEvent(new CustomEvent("crestapps-ai-chat-stop-tts",{detail:{sourceId:this.ttsInstanceId}})),this.ttsPlayingMessageIndex=e,this.ttsAudioCache[e]?this.playAudioBlob(this.ttsAudioCache[e]):this.synthesizeSpeech(t.content,e)):this.stopAudio()},playCollectedAudio:function(){if(0!==this.audioChunks.length){var t,e=this.audioChunks.reduce(function(t,e){return t+e.length},0),n=new Uint8Array(e),i=0,o=_createForOfIteratorHelper(this.audioChunks);try{for(o.s();!(t=o.n()).done;){var a=t.value;n.set(a,i),i+=a.length}}catch(t){o.e(t)}finally{o.f()}this.audioChunks=[];var r=new Blob([n],{type:"audio/mp3"});this._ttsCacheIndex>=0&&(this.ttsAudioCache[this._ttsCacheIndex]=r,this._ttsCacheIndex=-1),this.isPlayingAudio&&this.currentAudioElement?this.audioPlayQueue.push(r):this.playAudioBlob(r)}else this.isPlayingAudio||0!==this.audioPlayQueue.length||(this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1)},playAudioBlob:function(t){var e=this,n=URL.createObjectURL(t),i=new Audio(n);this.currentAudioUrl=n,this.currentAudioElement=i,this.isPlayingAudio=!0,i.addEventListener("ended",function(){e.currentAudioElement=null,e.currentAudioUrl=null,URL.revokeObjectURL(n),e.playNextInQueue()}),i.addEventListener("error",function(){e.currentAudioElement=null,e.currentAudioUrl=null,URL.revokeObjectURL(n),e.playNextInQueue()}),i.play().catch(function(t){console.error("Audio playback error:",t),e.currentAudioElement=null,e.currentAudioUrl=null,URL.revokeObjectURL(n),e.audioPlayQueue=[],e.isPlayingAudio=!1,e.ttsPlayingMessageIndex=-1})},playNextInQueue:function(){if(this.audioPlayQueue.length>0){var t=this.audioPlayQueue.shift();this.playAudioBlob(t)}else this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.conversationModeOnAudioEnded()},stopAudio:function(){this.currentAudioElement&&(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,this.currentAudioElement=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1},toggleConversationMode:function(){this.isConversationMode?this.stopConversationMode():this.startConversationMode()},startConversationMode:function(){var t=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(e){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";t.mediaRecorder=new MediaRecorder(e,{mimeType:n,audioBitsPerSecond:128e3}),t._conversationSubject=new signalR.Subject,t._conversationStream=e;var i=window.AudioContext||window.webkitAudioContext;i&&(t._conversationAudioCtx=new i,t._conversationAnalyser=t._conversationAudioCtx.createAnalyser(),t._conversationAnalyser.fftSize=256,t._conversationAudioCtx.createMediaStreamSource(e).connect(t._conversationAnalyser));var o=Promise.resolve(),a=t._conversationAnalyser;t.mediaRecorder.addEventListener("dataavailable",function(e){if(e.data&&e.data.size>0){if(t.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&&t.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,e.data.arrayBuffer();case 1:i=n.v,o=new Uint8Array(i),a=o.reduce(function(t,e){return t+String.fromCharCode(e)},""),r=btoa(a);try{t._conversationSubject.next(r)}catch(t){}case 2:return n.a(2)}},n)})))}}),t.mediaRecorder.addEventListener("stop",function(){e.getTracks().forEach(function(t){return t.stop()}),o.then(function(){try{t._conversationSubject.complete()}catch(t){}})});var r=t.getItemId(),s=navigator.language||document.documentElement.lang||"en-US";t.connection.send("StartConversation",r,t._conversationSubject,n,s),t.mediaRecorder.start(250),t.isRecording=!0}).catch(function(e){console.error("Microphone access denied:",e),t.isConversationMode=!1,t.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 t=this.messages[this._conversationAssistantMessage.index];t&&(t.isStreaming=!1),this._conversationAssistantMessage=null}for(var e=0;e<this.messages.length;e++)this.messages[e].isStreaming&&(this.messages[e].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 t=this.conversationButton.getAttribute("data-end-html");t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{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 e=this.conversationButton.getAttribute("data-start-html");e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}},conversationModeSendPrompt:function(){},conversationModeOnAudioEnded:function(){},showTypingIndicator:function(){this.addMessage({role:"indicator",htmlContent:n.indicatorTemplate})},hideTypingIndicator:function(){var t=this.messages.length;return this.messages=this.messages.filter(function(t){return"indicator"!==t.role}),t-this.messages.length},scrollToBottom:function(){var t=this;this.autoScroll&&setTimeout(function(){t.chatContainer.scrollTop=t.chatContainer.scrollHeight-t.chatContainer.clientHeight},50)},handleUserInput:function(t){this.prompt=t.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(t,e){var n=this,i=this.getSaveIndicatorElement();i&&(i.textContent=t||"",i.className="settings-save-indicator "+(e||"text-muted"),this.saveIndicatorTimeout&&(clearTimeout(this.saveIndicatorTimeout),this.saveIndicatorTimeout=null),t&&(this.saveIndicatorTimeout=setTimeout(function(){i.textContent="",n.saveIndicatorTimeout=null},3e3)))},clearPendingSettingsSave:function(){this.saveSettingsTimeout&&(clearTimeout(this.saveSettingsTimeout),this.saveSettingsTimeout=null)},getFieldLabel:function(t){var e,n=null===(e=t.closest(".mb-3, .col-6, .col, .form-group, .form-floating"))||void 0===e?void 0:e.querySelector("label");return n?(n.textContent||"").replace(/\s+/g," ").trim()||t.dataset.setting||"This field":t.dataset.setting||"This field"},getValidationFeedbackElement:function(t){var e=t.nextElementSibling;return e&&e.classList.contains("invalid-feedback")||((e=document.createElement("div")).className="invalid-feedback",t.insertAdjacentElement("afterend",e)),e},clearSettingValidationError:function(t){t.classList.remove("is-invalid"),t.removeAttribute("aria-invalid");var e=t.nextElementSibling;e&&e.classList.contains("invalid-feedback")&&(e.textContent="")},setSettingValidationError:function(t,e){var n=this.getValidationFeedbackElement(t);t.classList.add("is-invalid"),t.setAttribute("aria-invalid","true"),n.textContent=e},getSettingValidationMessage:function(t){if(!t||t.disabled||"number"!==t.type)return null;var e=(t.value||"").trim();if(!e)return null;var n=Number(e),i=this.getFieldLabel(t);if(Number.isNaN(n))return"".concat(i," must be a valid number.");var o=t.getAttribute("min");if(null!==o&&n<Number(o))return"".concat(i," must be ").concat(o," or greater.");var a=t.getAttribute("max");return null!==a&&n>Number(a)?"".concat(i," must be ").concat(a," or less."):null},validateSettingInput:function(t){var e=this.getSettingValidationMessage(t);return e?(this.setSettingValidationError(t,e),!1):(this.clearSettingValidationError(t),!0)},validateSettings:function(){var t=this,e=!0;return this.getSettingInputs().forEach(function(n){e=t.validateSettingInput(n)&&e}),e},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 t=document.querySelectorAll(".setting-input[data-setting]");return t.length>0?t: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(t,e){var n=document.querySelectorAll('.capability-checkbox[data-save-group="'.concat(t,'"]:checked'));if(n.length>0){var i=[];return n.forEach(function(t){var e=t.getAttribute("data-item-id")||t.value;e&&i.push(e)}),i}if(!e)return[];var o=[];return document.querySelectorAll(e).forEach(function(t){var e=t.name.replace(".IsSelected",".ItemId"),n=document.querySelector('input[type="hidden"][name="'.concat(e,'"]'));n&&n.value&&o.push(n.value)}),o},getPromptTemplateSelections:function(){var t=[];return document.querySelectorAll(".prompt-template-card").forEach(function(e){var n=e.querySelector(".prompt-template-id-input"),i=e.querySelector(".prompt-template-parameters-input"),o=n?n.value:e.getAttribute("data-template-id");o&&t.push({templateId:o,promptParameters:i?(i.value||"").trim():""})}),t},receiveNotification:function(t){if(t&&t.type){this.clearNotificationDismiss(t.type);var e=this.notifications.findIndex(function(e){return e.type===t.type});e>=0?this.notifications.splice(e,1,t):this.notifications.push(t),this.scheduleNotificationDismiss(t),this.scrollToBottom()}},updateNotification:function(t){if(t&&t.type){this.clearNotificationDismiss(t.type);var e=this.notifications.findIndex(function(e){return e.type===t.type});e>=0&&(this.notifications.splice(e,1,t),this.scheduleNotificationDismiss(t),this.scrollToBottom())}},scheduleNotificationDismiss:function(t){var e=this;t&&t.type&&t.autoDismissMs&&!(t.autoDismissMs<=0)&&(this.notificationDismissTimers[t.type]=setTimeout(function(){e.removeNotification(t.type)},t.autoDismissMs))},clearNotificationDismiss:function(t){var e=this.notificationDismissTimers[t];e&&(clearTimeout(e),delete this.notificationDismissTimers[t])},removeNotification:function(t){this.clearNotificationDismiss(t),this.notifications=this.notifications.filter(function(e){return e.type!==t})},dismissNotification:function(t){this.removeNotification(t)},handleNotificationAction:function(t,e){if(this.connection){var n=this.getItemId();this.connection.invoke("HandleNotificationAction",n,t,e).catch(function(t){return console.error("Failed to handle notification action:",t)})}},setItemId:function(t){this.inputElement.setAttribute("data-interaction-id",t||""),this.inputElement.setAttribute("data-item-id",t||"")},resetInteraction:function(){this.setItemId(""),this.isInteractionStarted=!1,this.messages=[],this.showPlaceholder()},initializeApp:function(){var t=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 e=this.getItemId();e&&this.loadInteraction(e),this.chatContainer.addEventListener("scroll",function(){if(t.stream){var e=t.chatContainer.scrollHeight-t.chatContainer.clientHeight-t.chatContainer.scrollTop<=30;t.autoScroll=e}}),this.inputElement.addEventListener("keyup",function(e){null==t.stream&&("Enter"!==e.key||e.shiftKey||t.buttonElement.click())}),this.inputElement.addEventListener("input",function(e){t.handleUserInput(e),e.target.value.trim()?t.buttonElement.removeAttribute("disabled"):t.buttonElement.setAttribute("disabled",!0)}),this.inputElement.addEventListener("paste",function(e){setTimeout(function(){t.prompt=t.inputElement.value,t.inputElement.value.trim()?t.buttonElement.removeAttribute("disabled"):t.buttonElement.setAttribute("disabled",!0)},0)}),this.buttonElement.addEventListener("click",function(){if(null==t.stream)t.sendMessage();else if(t.stream.dispose(),t.stream=null,t.streamingFinished(),t.hideTypingIndicator(),t.messages.length>0){var e=t.messages[t.messages.length-1];"assistant"!==e.role||e.content?e.isStreaming&&(e.isStreaming=!1):t.messages.pop()}});for(var i=document.getElementsByClassName("chat-interaction-history-item"),o=0;o<i.length;o++)i[o].addEventListener("click",function(e){e.preventDefault();var n=e.target.getAttribute("data-interaction-id");n?t.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(t){var e=t.target.closest(".ai-code-copy-btn");if(e){var i=e.closest(".ai-code-block")||e.closest("pre");if(i){var o=i.querySelector("code");if(o){navigator.clipboard.writeText(o.textContent);var a=n.codeCopiedText||"Copied!";e.innerHTML='<i class="fa-solid fa-check"></i> '+a,setTimeout(function(){e.innerHTML='<i class="fa-regular fa-copy"></i>'},2e3)}}}}),document.addEventListener("input",function(e){e.target.matches(".setting-input[data-setting]")&&(t.validateSettingInput(e.target),t.queueSettingsSave())}),document.addEventListener("change",function(e){if(e.target.matches(".setting-input[data-setting], .capability-checkbox[data-save-group], .group-toggle, .ci-agent-global-toggle"))return e.target.matches(".setting-input[data-setting]")&&t.validateSettingInput(e.target),void t.queueSettingsSave();e.target.closest(".prompt-template-parameters-input, .prompt-template-id-input")&&t.queueSettingsSave()}),document.addEventListener("click",function(e){e.target.closest(".prompt-template-add-btn, .remove-prompt-template-btn")&&setTimeout(function(){t.queueSettingsSave()},0)});var r=document.getElementById("clearHistoryBtn");r&&r.addEventListener("click",function(){var e=r.getAttribute("data-interaction-id");e&&t.clearHistory(e)}),this.speechToTextEnabled&&n.micButtonElementSelector&&(this.micButton=document.querySelector(n.micButtonElementSelector),this.micButton&&(this.micButton.style.display="",this.micButton.addEventListener("click",function(){t.toggleRecording()}))),this.conversationModeEnabled&&n.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(n.conversationButtonElementSelector),this.conversationButton&&this.conversationButton.addEventListener("click",function(){t.toggleConversationMode()}))},loadInteraction:function(t){this.connection.invoke("LoadInteraction",t).catch(function(t){return console.error(t)})},reloadCurrentInteraction:function(){var t=this.getItemId();t&&this.loadInteraction(t)},clearHistory:function(t){var e=this;confirmDialog({title:n.clearHistoryTitle,message:n.clearHistoryMessage,okText:n.clearHistoryOkText,cancelText:n.clearHistoryCancelText,callback:function(n){n&&(e.stream&&(e.stream.dispose(),e.stream=null,e.hideTypingIndicator(),e.streamingFinished()),e.connection.invoke("ClearHistory",t).catch(function(t){return console.error("Error clearing history:",t)}))}})},debouncedSaveSettings:function(){var t=this;this.clearPendingSettingsSave(),this.stream||(this.saveSettingsTimeout=setTimeout(function(){t.settingsDirty&&(t.saveSettings(),t.settingsDirty=!1),t.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 t=this,e=this.getItemId();if(!e)return Promise.resolve();if(!this.validateSettings())return this.showSaveIndicator("Fix errors","text-danger"),Promise.resolve();var n={};this.getSettingInputs().forEach(function(t){var e=t.dataset.setting||(t.name||"").replace("ChatInteraction.","").replace(/^[A-Z]/,function(t){return t.toLowerCase()});e&&("checkbox"===t.type?n[e]=t.checked:"number"===t.type?n[e]=t.value?parseFloat(t.value):null:n[e]=t.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(t){return t.templateId})),this.connection.invoke("SaveSettings",e,n).catch(function(e){console.error("Error saving settings:",e),t.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(t,e){this.isInteractionStarted&&!e||(this.fireEvent(new CustomEvent("initializingChatInteraction",{detail:{itemId:t}})),this.setItemId(t),this.isInteractionStarted=!0)},copyResponse:function(t){navigator.clipboard.writeText(t)},startRecording:function(){var t=this;!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(e){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";t.mediaRecorder=new MediaRecorder(e,{mimeType:n,audioBitsPerSecond:128e3}),t.preRecordingPrompt=t.prompt,t._audioInputSent=!1;var i=new signalR.Subject,o=t.getItemId(),a=Promise.resolve();t.mediaRecorder.addEventListener("dataavailable",function(t){t.data&&t.data.size>0&&(a=a.then(_asyncToGenerator(_regenerator().m(function e(){var n,o,a,r;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,t.data.arrayBuffer();case 1:n=e.v,o=new Uint8Array(n),a=o.reduce(function(t,e){return t+String.fromCharCode(e)},""),r=btoa(a),i.next(r);case 2:return e.a(2)}},e)}))))}),t.mediaRecorder.addEventListener("stop",function(){e.getTracks().forEach(function(t){return t.stop()}),a.then(function(){return i.complete()})});var r=navigator.language||document.documentElement.lang||"en-US";t.connection.send("SendAudioStream",o,i,n,r),t.mediaRecorder.start(250),t.isRecording=!0,t.updateMicButton()}).catch(function(t){console.error("Microphone access denied:",t)})},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(t){this.micButton&&(this.micButton.style.display=t?"none":this.speechToTextEnabled?"":"none"),this.buttonElement&&(this.buttonElement.style.display=t?"none":""),this.inputElement&&(this.inputElement.disabled=t,t&&(this.inputElement.placeholder=""))}},mounted:function(){var t=this;_asyncToGenerator(_regenerator().m(function e(){return _regenerator().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,t.startConnection();case 1:t.initializeApp();case 2:return e.a(2)}},e)}))(),window.addEventListener("beforeunload",this.handleBeforeUnload),window.addEventListener("crestapps-ai-chat-stop-tts",this.handleExternalTtsStop)},beforeUnmount:function(){window.removeEventListener("beforeunload",this.handleBeforeUnload),window.removeEventListener("crestapps-ai-chat-stop-tts",this.handleExternalTtsStop),this.stopAudio(!1),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(t){var e=t.target.closest(".download-chart-btn");if(e){var n=e.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(t){var e=t.target.closest(".ai-download-image");if(e){var n=e.closest(".generated-image-container"),i=null==n?void 0:n.querySelector("img");if(i){var o=i.src;o&&o.startsWith("data:")&&(t.preventDefault(),fetch(o).then(function(t){return t.blob()}).then(function(t){var n=URL.createObjectURL(t),i=document.createElement("a");i.href=n,i.download=e.getAttribute("download")||"generated-image.png",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(t){console.error("Failed to download image:",t)}))}}});
|
|
1
|
+
function _slicedToArray(t,e){return _arrayWithHoles(t)||_iterableToArrayLimit(t,e)||_unsupportedIterableToArray(t,e)||_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(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var i,a,o,s,r=[],c=!0,l=!1;try{if(o=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(r.push(i.value),r.length!==e);c=!0);}catch(t){l=!0,a=t}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(l)throw a}}return r}}function _arrayWithHoles(t){if(Array.isArray(t))return t}function _typeof(t){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_typeof(t)}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var t,e,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",a=n.toStringTag||"@@toStringTag";function o(n,i,a,o){var c=i&&i.prototype instanceof r?i:r,l=Object.create(c.prototype);return _regeneratorDefine2(l,"_invoke",function(n,i,a){var o,r,c,l=0,u=a||[],d=!1,h={p:0,n:0,v:t,a:m,f:m.bind(t,4),d:function(e,n){return o=e,r=0,c=t,h.n=n,s}};function m(n,i){for(r=n,c=i,e=0;!d&&l&&!a&&e<u.length;e++){var a,o=u[e],m=h.p,g=o[2];n>3?(a=g===i)&&(c=o[(r=o[4])?5:(r=3,3)],o[4]=o[5]=t):o[0]<=m&&((a=n<2&&m<o[1])?(r=0,h.v=i,h.n=o[1]):m<g&&(a=n<3||o[0]>i||i>g)&&(o[4]=n,o[5]=i,h.n=g,r=0))}if(a||n>1)return s;throw d=!0,i}return function(a,u,g){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&m(u,g),r=u,c=g;(e=r<2?t:c)||!d;){o||(r?r<3?(r>1&&(h.n=-1),m(r,c)):h.n=c:h.v=c);try{if(l=2,o){if(r||(a="next"),e=o[a]){if(!(e=e.call(o,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,r<2&&(r=0)}else 1===r&&(e=o.return)&&e.call(o),r<2&&(c=TypeError("The iterator does not provide a '"+a+"' method"),r=1);o=t}else if((e=(d=h.n<0)?c:n.call(i,h))!==s)break}catch(e){o=t,r=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,a,o),!0),l}var s={};function r(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][i]?e(e([][i]())):(_regeneratorDefine2(e={},i,function(){return this}),e),d=l.prototype=r.prototype=Object.create(u);function h(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,_regeneratorDefine2(t,a,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,_regeneratorDefine2(d,"constructor",l),_regeneratorDefine2(l,"constructor",c),c.displayName="GeneratorFunction",_regeneratorDefine2(l,a,"GeneratorFunction"),_regeneratorDefine2(d),_regeneratorDefine2(d,a,"Generator"),_regeneratorDefine2(d,i,function(){return this}),_regeneratorDefine2(d,"toString",function(){return"[object Generator]"}),(_regenerator=function(){return{w:o,m:h}})()}function _regeneratorDefine2(t,e,n,i){var a=Object.defineProperty;try{a({},"",{})}catch(t){a=0}_regeneratorDefine2=function(t,e,n,i){function o(e,n){_regeneratorDefine2(t,e,function(t){return this._invoke(e,n,t)})}e?a?a(t,e,{value:n,enumerable:!i,configurable:!i,writable:!i}):t[e]=n:(o("next",0),o("throw",1),o("return",2))},_regeneratorDefine2(t,e,n,i)}function asyncGeneratorStep(t,e,n,i,a,o,s){try{var r=t[o](s),c=r.value}catch(t){return void n(t)}r.done?e(c):Promise.resolve(c).then(i,a)}function _asyncToGenerator(t){return function(){var e=this,n=arguments;return new Promise(function(i,a){var o=t.apply(e,n);function s(t){asyncGeneratorStep(o,i,a,s,r,"next",t)}function r(t){asyncGeneratorStep(o,i,a,s,r,"throw",t)}s(void 0)})}}function _createForOfIteratorHelper(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=_unsupportedIterableToArray(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var i=0,a=function(){};return{s:a,n:function(){return i>=t.length?{done:!0}:{done:!1,value:t[i++]}},e:function(t){throw t},f:a}}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 o,s=!0,r=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){r=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(r)throw o}}}}function _toConsumableArray(t){return _arrayWithoutHoles(t)||_iterableToArray(t)||_unsupportedIterableToArray(t)||_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(t,e){if(t){if("string"==typeof t)return _arrayLikeToArray(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(t,e):void 0}}function _iterableToArray(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}function _arrayWithoutHoles(t){if(Array.isArray(t))return _arrayLikeToArray(t)}function _arrayLikeToArray(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,i=Array(e);n<e;n++)i[n]=t[n];return i}window.chatInteractionManager=function(){var t={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)"><span :class="getAssistantIcon(message)"></span></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 <button v-if="textToSpeechEnabled && !isConversationMode && message.role === \'assistant\' && !message.isStreaming" class="btn btn-sm btn-link text-secondary p-0 me-1 button-message-toolbox" :class="{ \'tts-playing\': ttsPlayingMessageIndex === index }" @click="toggleMessageTts(message, index)" :title="ttsPlayingMessageIndex === index ? \'Pause audio\' : \'Read aloud\'">\n <span :class="ttsPlayingMessageIndex === index ? \'fa-solid fa-circle-pause\' : \'fa-solid fa-circle-play\'"></span>\n </button>\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 <span class="fa-solid fa-copy"></span>\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 <span v-if="notification.icon" :class="notification.icon" class="ai-chat-notification-icon"></span>\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 <span class="fa-solid fa-xmark"></span>\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 <span v-if="action.icon" :class="action.icon" class="me-1"></span>\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"><span class="fa fa-robot" style="display: inline-block;"></span></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 e(t){if(!t)return"";var e=t.trim();return/^javascript:/i.test(e)||/^vbscript:/i.test(e)||/^data:text\/html/i.test(e)?"":t}function n(t){var e=document.createElement("span");return e.textContent=t,e.innerHTML}var i=new marked.Renderer;i.link=function(t){var n=e(t.href);return n?'<a href="'.concat(n,'" target="_blank" rel="noopener noreferrer">').concat(t.text,"</a>"):t.text||""},i.code=function(t){var e=t.text||"",i=(t.lang||"").trim(),a=e;if("undefined"!=typeof hljs)if(i&&hljs.getLanguage(i))try{a=hljs.highlight(e,{language:i}).value}catch(t){}else try{a=hljs.highlightAuto(e).value}catch(t){}else a=n(e);var o=i?n(i):"code";return'<div class="ai-code-block"><div class="ai-code-header"><span class="ai-code-lang"><span class="fa-solid fa-code"></span> '.concat(o,'</span><button type="button" class="ai-code-copy-btn" title="Copy code"><span class="fa-regular fa-copy"></span></button></div><pre><code class="hljs').concat(i?" language-"+i:"",'">').concat(a,"</code></pre></div>")},i.image=function(n){var i=e(n.href);if(!i)return"";var a=n.text||t.generatedImageAltText,o=t.generatedImageMaxWidth;return'<div class="generated-image-container">\n <img src="'.concat(i,'" alt="').concat(a,'" class="img-thumbnail" style="max-width: ').concat(o,'px; height: auto;" />\n <div class="mt-2">\n <a href="').concat(i,'" target="_blank" download="').concat(a,'" title="').concat(t.downloadImageTitle,'" class="btn btn-sm btn-outline-secondary ai-download-image">\n <span class="fa-solid fa-download"></span>\n </a>\n </div>\n </div>')};var a=0,o=[];function s(t){if(t&&t._pendingCharts&&t._pendingCharts.length){var e=_toConsumableArray(t._pendingCharts);t._pendingCharts=[],requestAnimationFrame(function(){var t,n=_createForOfIteratorHelper(e);try{for(n.s();!(t=n.n()).done;){var i=t.value,a=document.getElementById(i.chartId);if(a)if("undefined"!=typeof Chart)if(null!==a.offsetParent)try{var o,s,r;a._chartInstance&&a._chartInstance.destroy();var c="string"==typeof i.config?JSON.parse(i.config):i.config;null!==(o=c.options)&&void 0!==o||(c.options={}),c.options.responsive=!0,c.options.maintainAspectRatio=!0,null!==(r=(s=c.options).aspectRatio)&&void 0!==r||(s.aspectRatio=4/3),a._chartInstance=new Chart(a,c)}catch(t){console.error("Error creating chart:",t)}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(t){n.e(t)}finally{n.f()}})}}function r(t,e){o=[];var n=marked.parse(t,{renderer:i});return e._pendingCharts=o.length>0?_toConsumableArray(o):[],DOMPurify.sanitize(n,{ADD_TAGS:["canvas"],ADD_ATTR:["target"]})}window.__chartConfigs=window.__chartConfigs||{},marked.use({extensions:[{name:"chart",level:"block",start:function(t){var e=t.indexOf("[chart:");return e>=0?e:void 0},tokenizer:function(t){var e=function(t){var e="[chart:",n=t.indexOf(e);if(n<0)return null;var i=n+e.length,a=i;for(;a<t.length&&(" "===t[a]||"\n"===t[a]||"\r"===t[a]||"\t"===t[a]);)a++;if(a>=t.length||"{"!==t[a])return null;for(var o=0,s=!1,r=!1;a<t.length;a++){var c=t[a];if(s){if(r){r=!1;continue}if("\\"===c){r=!0;continue}'"'===c&&(s=!1)}else if('"'!==c){if("{"===c)o++;else if("}"===c&&0===--o){var l=a,u=t.indexOf("]",l+1);return u<0?null:{startIndex:n,endIndex:u+1,json:t.substring(i,l+1).trim()}}}else s=!0}return null}(t);if(e&&0===e.startIndex){var n="chat_chart_".concat(++a);return{type:"chart",raw:t.substring(0,e.endIndex),chartId:n,json:e.json}}},renderer:function(e){return o.push({chartId:e.chartId,config:e.json}),window.__chartConfigs[e.chartId]=e.json,n=e.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(t.downloadChartTitle,'">')+'<span class="fa-solid fa-download"></span> '.concat(t.downloadChartButtonText)+"</button></div>";var n}}]});return{initialize:function(e){var n=Object.assign({},t,e);if(t=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||!!n.textToSpeechEnabled,ttsVoiceName:n.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,currentAudioUrl:null,ttsPlayingMessageIndex:-1,ttsAudioCache:{},ttsInstanceId:"chat-interaction-"+Math.random().toString(36).slice(2),conversationModeEnabled:"Conversation"===n.chatMode,conversationButton:null,isConversationMode:!1,notifications:[],notificationDismissTimers:{}}},computed:{lastAssistantIndex:function(){for(var t=this.messages.length-1;t>=0;t--)if("assistant"===this.messages[t].role)return t;return-1}},methods:{handleBeforeUnload:function(){this.isNavigatingAway=!0},startConnection:function(){var t=this;return _asyncToGenerator(_regenerator().m(function e(){var i;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:return t.connection=(new signalR.HubConnectionBuilder).withUrl(n.signalRHubUrl).withAutomaticReconnect().build(),t.connection.serverTimeoutInMilliseconds=6e5,t.connection.keepAliveIntervalInMilliseconds=15e3,t.connection.on("LoadInteraction",function(e){var n;t.initializeInteraction(e.itemId,!0),t.messages=[];var i=document.querySelector('[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]');i&&e.title&&(i.value=e.title),(null!==(n=e.messages)&&void 0!==n?n:[]).forEach(function(e){t.addMessage(e),t.$nextTick(function(){s(e)})})}),t.connection.on("SettingsSaved",function(e,i){var a=document.querySelector('.chat-interaction-history-item[data-interaction-id="'.concat(e,'"]'));a&&(a.textContent=i||n.untitledText);var o=document.querySelector('[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]');o&&i&&(o.value=i),t.showSaveIndicator("Saved","text-success")}),t.connection.on("ReceiveError",function(e){console.error("SignalR Error: ",e),t.showSaveIndicator("Save failed","text-danger"),t.isRecording&&t.stopRecording()}),t.connection.on("ReceiveTranscript",function(e,n,i){if(t.isConversationMode){if(!i&&n){t._conversationPartialTranscript=n;var a='<p class="ai-partial-transcript">'+n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")+"</p>";t._conversationPartialMessage?(t._conversationPartialMessage.content=n,t._conversationPartialMessage.htmlContent=a):(t.hidePlaceholder(),t._conversationPartialMessage={role:"user",content:n,htmlContent:a,isPartial:!0},t.messages.push(t._conversationPartialMessage)),t.scrollToBottom()}}else n&&!t._audioInputSent&&(t.prompt=t.preRecordingPrompt+n,t.inputElement&&(t.inputElement.value=t.prompt,t.inputElement.dispatchEvent(new Event("input"))))}),t.connection.on("ReceiveConversationUserMessage",function(e,n){if(n){if(t.stopAudio(),t._conversationAssistantMessage){var i=t.messages[t._conversationAssistantMessage.index];i&&(i.isStreaming=!1),t._conversationAssistantMessage=null}if(t._conversationPartialMessage){var a=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");t._conversationPartialMessage.content=n,t._conversationPartialMessage.htmlContent="<p>"+a+"</p>",t._conversationPartialMessage.isPartial=!1,t._conversationPartialMessage=null}else t.addMessage({role:"user",content:n});t.scrollToBottom()}}),t.connection.on("ReceiveConversationAssistantToken",function(e,n,i,a,o){if(!t._conversationAssistantMessage){t.stopAudio(),t.hideTypingIndicator();for(var c=0;c<t.messages.length;c++)t.messages[c].isStreaming&&(t.messages[c].isStreaming=!1);var l=t.messages.length,u={id:n,role:"assistant",content:"",htmlContent:"",isStreaming:!0,appearance:t.normalizeAssistantAppearance(o)};t.messages.push(u),t._conversationAssistantMessage={index:l,content:""}}t._conversationAssistantMessage.content+=i;var d=t.messages[t._conversationAssistantMessage.index];d&&(d.appearance||(d.appearance=t.normalizeAssistantAppearance(o)),d.content=t._conversationAssistantMessage.content,d.htmlContent=r(d.content,d),t.$nextTick(function(){s(d),t.scrollToBottom()}))}),t.connection.on("ReceiveConversationAssistantComplete",function(e,n){if(t._conversationAssistantMessage){var i=t.messages[t._conversationAssistantMessage.index];i&&(i.isStreaming=!1),t._conversationAssistantMessage=null}}),t.connection.on("ReceiveAudioChunk",function(e,n,i){if(n){for(var a=atob(n),o=new Uint8Array(a.length),s=0;s<a.length;s++)o[s]=a.charCodeAt(s);t.audioChunks.push(o)}}),t.connection.on("ReceiveAudioComplete",function(e){t.playCollectedAudio()}),t.connection.on("HistoryCleared",function(e){t.messages=[],t.showPlaceholder();var n=document.getElementById("clearHistoryBtn");n&&n.classList.add("d-none")}),t.connection.on("ReceiveNotification",function(e){t.receiveNotification(e)}),t.connection.on("UpdateNotification",function(e){t.updateNotification(e)}),t.connection.on("RemoveNotification",function(e){t.removeNotification(e)}),t.connection.onreconnecting(function(){console.warn("SignalR: reconnecting...")}),t.connection.onreconnected(function(){console.info("SignalR: reconnected."),t.reloadCurrentInteraction()}),t.connection.onclose(function(e){t.isNavigatingAway||e&&console.warn("SignalR connection closed with error:",e.message||e)}),e.p=1,e.n=2,t.connection.start();case 2:e.n=4;break;case 3:e.p=3,i=e.v,console.error("SignalR Connection Error: ",i);case 4:return e.a(2)}},e,null,[[1,3]])}))()},addMessageInternal:function(t){var e=this;"assistant"===t.role&&(t.appearance=this.normalizeAssistantAppearance(t.appearance)),t.content&&!t.htmlContent&&(t.htmlContent=r(t.content,t)),this.fireEvent(new CustomEvent("addingChatInteractionMessage",{detail:{message:t}})),this.messages.push(t),this.$nextTick(function(){e.fireEvent(new CustomEvent("addedChatInteractionMessage",{detail:{message:t}}))})},addMessage:function(t){var e=this;if(t.content){var n=t.content.trim();if(t.references&&"object"===_typeof(t.references)&&Object.keys(t.references).length){var i=Object.entries(t.references).filter(function(t){var e=_slicedToArray(t,1)[0];return n.includes(e)});if(i.length){i.sort(function(t,e){var n=_slicedToArray(t,2)[1],i=_slicedToArray(e,2)[1];return n.index-i.index});var a,o=1,c=_createForOfIteratorHelper(i);try{for(c.s();!(a=c.n()).done;){var l=_slicedToArray(a.value,2),u=l[0],d=l[1],h="__CITE_".concat(d.index,"__");n=n.replaceAll(u,h),d._displayIndex=o++,d._placeholder=h}}catch(t){c.e(t)}finally{c.f()}var m,g=_createForOfIteratorHelper(i);try{for(g.s();!(m=g.n()).done;){var p=_slicedToArray(m.value,2)[1];n=n.replaceAll(p._placeholder,"<sup><strong>".concat(p._displayIndex,"</strong></sup>"))}}catch(t){g.e(t)}finally{g.f()}n=n.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),n+="<br><br>";var f,v=_createForOfIteratorHelper(i);try{for(v.s();!(f=v.n()).done;){var y=_slicedToArray(f.value,2),b=(y[0],y[1]),A=b.text||"[doc:".concat(b.index,"]");n+=b.link?"**".concat(b._displayIndex,"**. [").concat(A,"](").concat(b.link,")<br>"):"**".concat(b._displayIndex,"**. ").concat(A,"<br>")}}catch(t){v.e(t)}finally{v.f()}}}t.content=n,t.htmlContent=r(n,t)}this.addMessageInternal(t),this.hidePlaceholder(),this.$nextTick(function(){s(t),e.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(t){document.dispatchEvent(t)},normalizeAssistantAppearance:function(t){if(!t)return null;var e="string"==typeof t.label?t.label.trim():"",n="string"==typeof t.icon?t.icon.trim():"",i="string"==typeof t.cssClass?t.cssClass.trim():"",a=!!t.disableStreamingAnimation;return e||n||i||a?{label:e,icon:n,cssClass:i,disableStreamingAnimation:a}:null},getAssistantLabel:function(e){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return n&&n.label?n.label:t.assistantLabel},getAssistantRoleClasses:function(t){var e=t?this.normalizeAssistantAppearance(t.appearance):null,n=["ai-chat-msg-role"];return e&&e.cssClass?n.push(e.cssClass):n.push("ai-chat-msg-role-assistant"),n},getAssistantIconClasses:function(t,e){var n=t?this.normalizeAssistantAppearance(t.appearance):null;return[this.shouldAnimateAssistantIcon(t,e)?"ai-streaming-icon":"ai-bot-icon",n&&n.cssClass?n.cssClass:""]},getAssistantIcon:function(t){var e=t?this.normalizeAssistantAppearance(t.appearance):null;return e&&e.icon?e.icon:"fa fa-robot"},shouldAnimateAssistantIcon:function(t,e){var n=t?this.normalizeAssistantAppearance(t.appearance):null;return!!t&&t.isStreaming&&e===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},isIndicator:function(t){return"indicator"===t.role},sendMessage:function(){var t=this;return _asyncToGenerator(_regenerator().m(function e(){var n,i;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:if(n=t.prompt.trim()){e.n=1;break}return e.a(2);case 1:return t.isRecording&&t.stopRecording(),t._audioInputSent=!0,e.n=2,t.flushPendingSave();case 2:t.addMessage({role:"user",content:n}),(i=document.getElementById("clearHistoryBtn"))&&i.classList.remove("d-none"),t.streamMessage(n),t.inputElement.value="",t.prompt="";case 3:return e.a(2)}},e)}))()},streamMessage:function(t){var e=this;this.stream&&(this.stream.dispose(),this.stream=null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var n="",i={},a=null,o=this.messages.length,c=this.getItemId();this.stream=this.connection.stream("SendMessage",c,t).subscribe({next:function(t){var l=e.messages[o];if(!l){t.sessionId&&!c&&e.setItemId(t.sessionId),e.hideTypingIndicator(),o=e.messages.length;var u={role:"assistant",content:"",htmlContent:"",isStreaming:!0};e.messages.push(u),l=u}if(t.references&&"object"===_typeof(t.references)&&Object.keys(t.references).length)for(var d=0,h=Object.entries(t.references);d<h.length;d++){var m=_slicedToArray(h[d],2),g=m[0],p=m[1];i[g]=p}if(t.content){t.responseId&&a&&t.responseId!==a&&(n+="\n\n"),t.responseId&&(a=t.responseId);for(var f=t.content,v=0,y=Object.entries(i);v<y.length;v++){var b=_slicedToArray(y[v],2),A=b[0],S=b[1];f=f.replaceAll(A,"<sup><strong>".concat(S.index,"</strong></sup>"))}n+=f.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>")}l.content=n,l.htmlContent=r(n,l),e.messages[o]=l,e.$nextTick(function(){s(l),e.scrollToBottom()})},complete:function(){var t;e.processReferences(i,o),e.streamingFinished();var n=e.messages[o];n&&(n.isStreaming=!1),n&&n.content||e.hideTypingIndicator(),e.isConversationMode&&e.textToSpeechEnabled&&n&&n.content&&e.synthesizeSpeech(n.content),null===(t=e.stream)||void 0===t||t.dispose(),e.stream=null},error:function(t){var n;e.processReferences(i,o),e.streamingFinished();var a=e.messages[o];a&&(a.isStreaming=!1),e.hideTypingIndicator(),e.isNavigatingAway||e.addMessage(e.getServiceDownMessage()),null===(n=e.stream)||void 0===n||n.dispose(),e.stream=null,console.error("Stream error:",t)}})},getServiceDownMessage:function(){return{role:"assistant",content:"Our service is currently unavailable. Please try again later. We apologize for the inconvenience.",htmlContent:""}},processReferences:function(t,e){var n=this;if(Object.keys(t).length){var i=this.messages[e],a=i.content||"",o=Object.entries(t).filter(function(t){var e=_slicedToArray(t,2),n=e[0],i=e[1];return a.includes(n)||a.includes("<sup><strong>".concat(i.index,"</strong></sup>"))});if(!o.length)return;o.sort(function(t,e){var n=_slicedToArray(t,2)[1],i=_slicedToArray(e,2)[1];return n.index-i.index});var c,l=a.trim(),u=1,d=_createForOfIteratorHelper(o);try{for(d.s();!(c=d.n()).done;){var h=_slicedToArray(c.value,2),m=h[0],g=h[1],p="__CITE_".concat(g.index,"__");l=(l=l.replaceAll(m,p)).replaceAll("<sup><strong>".concat(g.index,"</strong></sup>"),p),g._displayIndex=u++,g._placeholder=p}}catch(t){d.e(t)}finally{d.f()}var f,v=_createForOfIteratorHelper(o);try{for(v.s();!(f=v.n()).done;){var y=_slicedToArray(f.value,2)[1];l=l.replaceAll(y._placeholder,"<sup><strong>".concat(y._displayIndex,"</strong></sup>"))}}catch(t){v.e(t)}finally{v.f()}l=l.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),l+="<br><br>";var b,A=_createForOfIteratorHelper(o);try{for(A.s();!(b=A.n()).done;){var S=_slicedToArray(b.value,2),I=(S[0],S[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(t){A.e(t)}finally{A.f()}i.content=l,i.htmlContent=r(l,i),this.messages[e]=i,this.$nextTick(function(){s(i),n.scrollToBottom()})}},streamingStarted:function(){var t=this.buttonElement.getAttribute("data-stop-icon");t&&this.buttonElement.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))},streamingFinished:function(){var t=this.buttonElement.getAttribute("data-start-icon");if(t&&this.buttonElement.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0})),this.chatContainer)for(var e=this.chatContainer.querySelectorAll(".ai-streaming-icon"),n=0;n<e.length;n++)e[n].classList.remove("ai-streaming-icon"),e[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()},handleExternalTtsStop:function(t){var e;(null==t||null===(e=t.detail)||void 0===e?void 0:e.sourceId)!==this.ttsInstanceId&&this.stopAudio(!1)},synthesizeSpeech:function(t,e){var n=this;this.textToSpeechEnabled&&t&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this._ttsCacheIndex=void 0!==e?e:-1,this.connection.invoke("SynthesizeSpeech",this.getItemId(),t,this.ttsVoiceName).catch(function(t){console.error("TTS synthesis error:",t),n.isPlayingAudio=!1,n.ttsPlayingMessageIndex=-1,n._ttsCacheIndex=-1}))},toggleMessageTts:function(t,e){this.ttsPlayingMessageIndex!==e?(this.stopAudio(!1),window.dispatchEvent(new CustomEvent("crestapps-ai-chat-stop-tts",{detail:{sourceId:this.ttsInstanceId}})),this.ttsPlayingMessageIndex=e,this.ttsAudioCache[e]?this.playAudioBlob(this.ttsAudioCache[e]):this.synthesizeSpeech(t.content,e)):this.stopAudio()},playCollectedAudio:function(){if(0!==this.audioChunks.length){var t,e=this.audioChunks.reduce(function(t,e){return t+e.length},0),n=new Uint8Array(e),i=0,a=_createForOfIteratorHelper(this.audioChunks);try{for(a.s();!(t=a.n()).done;){var o=t.value;n.set(o,i),i+=o.length}}catch(t){a.e(t)}finally{a.f()}this.audioChunks=[];var s=new Blob([n],{type:"audio/mp3"});this._ttsCacheIndex>=0&&(this.ttsAudioCache[this._ttsCacheIndex]=s,this._ttsCacheIndex=-1),this.isPlayingAudio&&this.currentAudioElement?this.audioPlayQueue.push(s):this.playAudioBlob(s)}else this.isPlayingAudio||0!==this.audioPlayQueue.length||(this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1)},playAudioBlob:function(t){var e=this,n=URL.createObjectURL(t),i=new Audio(n);this.currentAudioUrl=n,this.currentAudioElement=i,this.isPlayingAudio=!0,i.addEventListener("ended",function(){e.currentAudioElement=null,e.currentAudioUrl=null,URL.revokeObjectURL(n),e.playNextInQueue()}),i.addEventListener("error",function(){e.currentAudioElement=null,e.currentAudioUrl=null,URL.revokeObjectURL(n),e.playNextInQueue()}),i.play().catch(function(t){console.error("Audio playback error:",t),e.currentAudioElement=null,e.currentAudioUrl=null,URL.revokeObjectURL(n),e.audioPlayQueue=[],e.isPlayingAudio=!1,e.ttsPlayingMessageIndex=-1})},playNextInQueue:function(){if(this.audioPlayQueue.length>0){var t=this.audioPlayQueue.shift();this.playAudioBlob(t)}else this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.conversationModeOnAudioEnded()},stopAudio:function(){this.currentAudioElement&&(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,this.currentAudioElement=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1},toggleConversationMode:function(){this.isConversationMode?this.stopConversationMode():this.startConversationMode()},startConversationMode:function(){var t=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(e){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";t.mediaRecorder=new MediaRecorder(e,{mimeType:n,audioBitsPerSecond:128e3}),t._conversationSubject=new signalR.Subject,t._conversationStream=e;var i=window.AudioContext||window.webkitAudioContext;i&&(t._conversationAudioCtx=new i,t._conversationAnalyser=t._conversationAudioCtx.createAnalyser(),t._conversationAnalyser.fftSize=256,t._conversationAudioCtx.createMediaStreamSource(e).connect(t._conversationAnalyser));var a=Promise.resolve(),o=t._conversationAnalyser;t.mediaRecorder.addEventListener("dataavailable",function(e){if(e.data&&e.data.size>0){if(t.isPlayingAudio&&o){var n=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(n);for(var i=0,s=0;s<n.length;s++)i+=n[s];i/n.length>=30&&t.stopAudio()}a=a.then(_asyncToGenerator(_regenerator().m(function n(){var i,a,o,s;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:return n.n=1,e.data.arrayBuffer();case 1:i=n.v,a=new Uint8Array(i),o=a.reduce(function(t,e){return t+String.fromCharCode(e)},""),s=btoa(o);try{t._conversationSubject.next(s)}catch(t){}case 2:return n.a(2)}},n)})))}}),t.mediaRecorder.addEventListener("stop",function(){e.getTracks().forEach(function(t){return t.stop()}),a.then(function(){try{t._conversationSubject.complete()}catch(t){}})});var s=t.getItemId(),r=navigator.language||document.documentElement.lang||"en-US";t.connection.send("StartConversation",s,t._conversationSubject,n,r),t.mediaRecorder.start(250),t.isRecording=!0}).catch(function(e){console.error("Microphone access denied:",e),t.isConversationMode=!1,t.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 t=this.messages[this._conversationAssistantMessage.index];t&&(t.isStreaming=!1),this._conversationAssistantMessage=null}for(var e=0;e<this.messages.length;e++)this.messages[e].isStreaming&&(this.messages[e].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 t=this.conversationButton.getAttribute("data-end-html");t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{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 e=this.conversationButton.getAttribute("data-start-html");e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}},conversationModeSendPrompt:function(){},conversationModeOnAudioEnded:function(){},showTypingIndicator:function(){this.addMessage({role:"indicator",htmlContent:n.indicatorTemplate})},hideTypingIndicator:function(){var t=this.messages.length;return this.messages=this.messages.filter(function(t){return"indicator"!==t.role}),t-this.messages.length},scrollToBottom:function(){var t=this;this.autoScroll&&setTimeout(function(){t.chatContainer.scrollTop=t.chatContainer.scrollHeight-t.chatContainer.clientHeight},50)},handleUserInput:function(t){this.prompt=t.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(t,e){var n=this,i=this.getSaveIndicatorElement();i&&(i.textContent=t||"",i.className="settings-save-indicator "+(e||"text-muted"),this.saveIndicatorTimeout&&(clearTimeout(this.saveIndicatorTimeout),this.saveIndicatorTimeout=null),t&&(this.saveIndicatorTimeout=setTimeout(function(){i.textContent="",n.saveIndicatorTimeout=null},3e3)))},clearPendingSettingsSave:function(){this.saveSettingsTimeout&&(clearTimeout(this.saveSettingsTimeout),this.saveSettingsTimeout=null)},getFieldLabel:function(t){var e,n=null===(e=t.closest(".mb-3, .col-6, .col, .form-group, .form-floating"))||void 0===e?void 0:e.querySelector("label");return n?(n.textContent||"").replace(/\s+/g," ").trim()||t.dataset.setting||"This field":t.dataset.setting||"This field"},getValidationFeedbackElement:function(t){var e=t.nextElementSibling;return e&&e.classList.contains("invalid-feedback")||((e=document.createElement("div")).className="invalid-feedback",t.insertAdjacentElement("afterend",e)),e},clearSettingValidationError:function(t){t.classList.remove("is-invalid"),t.removeAttribute("aria-invalid");var e=t.nextElementSibling;e&&e.classList.contains("invalid-feedback")&&(e.textContent="")},setSettingValidationError:function(t,e){var n=this.getValidationFeedbackElement(t);t.classList.add("is-invalid"),t.setAttribute("aria-invalid","true"),n.textContent=e},getSettingValidationMessage:function(t){if(!t||t.disabled||"number"!==t.type)return null;var e=(t.value||"").trim();if(!e)return null;var n=Number(e),i=this.getFieldLabel(t);if(Number.isNaN(n))return"".concat(i," must be a valid number.");var a=t.getAttribute("min");if(null!==a&&n<Number(a))return"".concat(i," must be ").concat(a," or greater.");var o=t.getAttribute("max");return null!==o&&n>Number(o)?"".concat(i," must be ").concat(o," or less."):null},validateSettingInput:function(t){var e=this.getSettingValidationMessage(t);return e?(this.setSettingValidationError(t,e),!1):(this.clearSettingValidationError(t),!0)},validateSettings:function(){var t=this,e=!0;return this.getSettingInputs().forEach(function(n){e=t.validateSettingInput(n)&&e}),e},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 t=document.querySelectorAll(".setting-input[data-setting]");return t.length>0?t: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(t,e){var n=document.querySelectorAll('.capability-checkbox[data-save-group="'.concat(t,'"]:checked'));if(n.length>0){var i=[];return n.forEach(function(t){var e=t.getAttribute("data-item-id")||t.value;e&&i.push(e)}),i}if(!e)return[];var a=[];return document.querySelectorAll(e).forEach(function(t){var e=t.name.replace(".IsSelected",".ItemId"),n=document.querySelector('input[type="hidden"][name="'.concat(e,'"]'));n&&n.value&&a.push(n.value)}),a},getPromptTemplateSelections:function(){var t=[];return document.querySelectorAll(".prompt-template-card").forEach(function(e){var n=e.querySelector(".prompt-template-id-input"),i=e.querySelector(".prompt-template-parameters-input"),a=n?n.value:e.getAttribute("data-template-id");a&&t.push({templateId:a,promptParameters:i?(i.value||"").trim():""})}),t},receiveNotification:function(t){if(t&&t.type){this.clearNotificationDismiss(t.type);var e=this.notifications.findIndex(function(e){return e.type===t.type});e>=0?this.notifications.splice(e,1,t):this.notifications.push(t),this.scheduleNotificationDismiss(t),this.scrollToBottom()}},updateNotification:function(t){if(t&&t.type){this.clearNotificationDismiss(t.type);var e=this.notifications.findIndex(function(e){return e.type===t.type});e>=0&&(this.notifications.splice(e,1,t),this.scheduleNotificationDismiss(t),this.scrollToBottom())}},scheduleNotificationDismiss:function(t){var e=this;t&&t.type&&t.autoDismissMs&&!(t.autoDismissMs<=0)&&(this.notificationDismissTimers[t.type]=setTimeout(function(){e.removeNotification(t.type)},t.autoDismissMs))},clearNotificationDismiss:function(t){var e=this.notificationDismissTimers[t];e&&(clearTimeout(e),delete this.notificationDismissTimers[t])},removeNotification:function(t){this.clearNotificationDismiss(t),this.notifications=this.notifications.filter(function(e){return e.type!==t})},dismissNotification:function(t){this.removeNotification(t)},handleNotificationAction:function(t,e){if(this.connection){var n=this.getItemId();this.connection.invoke("HandleNotificationAction",n,t,e).catch(function(t){return console.error("Failed to handle notification action:",t)})}},setItemId:function(t){this.inputElement.setAttribute("data-interaction-id",t||""),this.inputElement.setAttribute("data-item-id",t||"")},resetInteraction:function(){this.setItemId(""),this.isInteractionStarted=!1,this.messages=[],this.showPlaceholder()},initializeApp:function(){var t=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 e=this.getItemId();e&&this.loadInteraction(e),this.chatContainer.addEventListener("scroll",function(){if(t.stream){var e=t.chatContainer.scrollHeight-t.chatContainer.clientHeight-t.chatContainer.scrollTop<=30;t.autoScroll=e}}),this.inputElement.addEventListener("keyup",function(e){null==t.stream&&("Enter"!==e.key||e.shiftKey||t.buttonElement.click())}),this.inputElement.addEventListener("input",function(e){t.handleUserInput(e),e.target.value.trim()?t.buttonElement.removeAttribute("disabled"):t.buttonElement.setAttribute("disabled",!0)}),this.inputElement.addEventListener("paste",function(e){setTimeout(function(){t.prompt=t.inputElement.value,t.inputElement.value.trim()?t.buttonElement.removeAttribute("disabled"):t.buttonElement.setAttribute("disabled",!0)},0)}),this.buttonElement.addEventListener("click",function(){if(null==t.stream)t.sendMessage();else if(t.stream.dispose(),t.stream=null,t.streamingFinished(),t.hideTypingIndicator(),t.messages.length>0){var e=t.messages[t.messages.length-1];"assistant"!==e.role||e.content?e.isStreaming&&(e.isStreaming=!1):t.messages.pop()}});for(var i=document.getElementsByClassName("chat-interaction-history-item"),a=0;a<i.length;a++)i[a].addEventListener("click",function(e){e.preventDefault();var n=e.target.getAttribute("data-interaction-id");n?t.loadInteraction(n):console.error("An element with the class chat-interaction-history-item with no data-interaction-id set.")});for(var o=0;o<n.messages.length;o++)this.addMessage(n.messages[o]);this.chatContainer&&this.chatContainer.addEventListener("click",function(t){var e=t.target.closest(".ai-code-copy-btn");if(e){var i=e.closest(".ai-code-block")||e.closest("pre");if(i){var a=i.querySelector("code");if(a){navigator.clipboard.writeText(a.textContent);var o=n.codeCopiedText||"Copied!";e.innerHTML='<span class="fa-solid fa-check"></span> '+o,setTimeout(function(){e.innerHTML='<span class="fa-regular fa-copy"></span>'},2e3)}}}}),document.addEventListener("input",function(e){e.target.matches(".setting-input[data-setting]")&&(t.validateSettingInput(e.target),t.queueSettingsSave())}),document.addEventListener("change",function(e){if(e.target.matches(".setting-input[data-setting], .capability-checkbox[data-save-group], .group-toggle, .ci-agent-global-toggle"))return e.target.matches(".setting-input[data-setting]")&&t.validateSettingInput(e.target),void t.queueSettingsSave();e.target.closest(".prompt-template-parameters-input, .prompt-template-id-input")&&t.queueSettingsSave()}),document.addEventListener("click",function(e){e.target.closest(".prompt-template-add-btn, .remove-prompt-template-btn")&&setTimeout(function(){t.queueSettingsSave()},0)});var s=document.getElementById("clearHistoryBtn");s&&s.addEventListener("click",function(){var e=s.getAttribute("data-interaction-id");e&&t.clearHistory(e)}),this.speechToTextEnabled&&n.micButtonElementSelector&&(this.micButton=document.querySelector(n.micButtonElementSelector),this.micButton&&(this.micButton.style.display="",this.micButton.addEventListener("click",function(){t.toggleRecording()}))),this.conversationModeEnabled&&n.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(n.conversationButtonElementSelector),this.conversationButton&&this.conversationButton.addEventListener("click",function(){t.toggleConversationMode()}))},loadInteraction:function(t){this.connection.invoke("LoadInteraction",t).catch(function(t){return console.error(t)})},reloadCurrentInteraction:function(){var t=this.getItemId();t&&this.loadInteraction(t)},clearHistory:function(t){var e=this;confirmDialog({title:n.clearHistoryTitle,message:n.clearHistoryMessage,okText:n.clearHistoryOkText,cancelText:n.clearHistoryCancelText,callback:function(n){n&&(e.stream&&(e.stream.dispose(),e.stream=null,e.hideTypingIndicator(),e.streamingFinished()),e.connection.invoke("ClearHistory",t).catch(function(t){return console.error("Error clearing history:",t)}))}})},debouncedSaveSettings:function(){var t=this;this.clearPendingSettingsSave(),this.stream||(this.saveSettingsTimeout=setTimeout(function(){t.settingsDirty&&(t.saveSettings(),t.settingsDirty=!1),t.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 t=this,e=this.getItemId();if(!e)return Promise.resolve();if(!this.validateSettings())return this.showSaveIndicator("Fix errors","text-danger"),Promise.resolve();var n={};this.getSettingInputs().forEach(function(t){var e=t.dataset.setting||(t.name||"").replace("ChatInteraction.","").replace(/^[A-Z]/,function(t){return t.toLowerCase()});e&&("checkbox"===t.type?n[e]=t.checked:"number"===t.type?n[e]=t.value?parseFloat(t.value):null:n[e]=t.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(t){return t.templateId})),this.connection.invoke("SaveSettings",e,n).catch(function(e){console.error("Error saving settings:",e),t.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(t,e){this.isInteractionStarted&&!e||(this.fireEvent(new CustomEvent("initializingChatInteraction",{detail:{itemId:t}})),this.setItemId(t),this.isInteractionStarted=!0)},copyResponse:function(t){navigator.clipboard.writeText(t)},startRecording:function(){var t=this;!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(e){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";t.mediaRecorder=new MediaRecorder(e,{mimeType:n,audioBitsPerSecond:128e3}),t.preRecordingPrompt=t.prompt,t._audioInputSent=!1;var i=new signalR.Subject,a=t.getItemId(),o=Promise.resolve();t.mediaRecorder.addEventListener("dataavailable",function(t){t.data&&t.data.size>0&&(o=o.then(_asyncToGenerator(_regenerator().m(function e(){var n,a,o,s;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,t.data.arrayBuffer();case 1:n=e.v,a=new Uint8Array(n),o=a.reduce(function(t,e){return t+String.fromCharCode(e)},""),s=btoa(o),i.next(s);case 2:return e.a(2)}},e)}))))}),t.mediaRecorder.addEventListener("stop",function(){e.getTracks().forEach(function(t){return t.stop()}),o.then(function(){return i.complete()})});var s=navigator.language||document.documentElement.lang||"en-US";t.connection.send("SendAudioStream",a,i,n,s),t.mediaRecorder.start(250),t.isRecording=!0,t.updateMicButton()}).catch(function(t){console.error("Microphone access denied:",t)})},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='<span class="fa-solid fa-stop"></span>'):(this.micButton.classList.remove("stt-recording"),this.micButton.innerHTML='<span class="fa-solid fa-microphone"></span>'))}},watch:{isPlayingAudio:function(){},isConversationMode:function(t){this.micButton&&(this.micButton.style.display=t?"none":this.speechToTextEnabled?"":"none"),this.buttonElement&&(this.buttonElement.style.display=t?"none":""),this.inputElement&&(this.inputElement.disabled=t,t&&(this.inputElement.placeholder=""))}},mounted:function(){var t=this;_asyncToGenerator(_regenerator().m(function e(){return _regenerator().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,t.startConnection();case 1:t.initializeApp();case 2:return e.a(2)}},e)}))(),window.addEventListener("beforeunload",this.handleBeforeUnload),window.addEventListener("crestapps-ai-chat-stop-tts",this.handleExternalTtsStop)},beforeUnmount:function(){window.removeEventListener("beforeunload",this.handleBeforeUnload),window.removeEventListener("crestapps-ai-chat-stop-tts",this.handleExternalTtsStop),this.stopAudio(!1),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(t){var e=t.target.closest(".download-chart-btn");if(e){var n=e.getAttribute("data-chart-id"),i=n?document.getElementById(n):null;if(i){var a=document.createElement("a");a.download="chart-"+n+".png",a.href=i.toDataURL("image/png"),a.click()}else console.error("Chart canvas not found:",n)}}),document.addEventListener("click",function(t){var e=t.target.closest(".ai-download-image");if(e){var n=e.closest(".generated-image-container"),i=null==n?void 0:n.querySelector("img");if(i){var a=i.src;a&&a.startsWith("data:")&&(t.preventDefault(),fetch(a).then(function(t){return t.blob()}).then(function(t){var n=URL.createObjectURL(t),i=document.createElement("a");i.href=n,i.download=e.getAttribute("download")||"generated-image.png",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(t){console.error("Failed to download image:",t)}))}}});
|
|
2
2
|
//# sourceMappingURL=chat-interaction.min.js.map
|