@crestapps/ai-chat-ui 2.0.0-preview.223 → 2.0.0-preview.225

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.
@@ -1 +1 @@
1
- .ai-chat-message-heading{margin-bottom:.35rem;font-size:.75rem}.ai-chat-message-heading .ai-chat-msg-role{letter-spacing:.03em;margin-bottom:0}.ai-chat-message-heading-assistant .ai-chat-msg-role{align-items:center;gap:.35rem;display:inline-flex}.ai-chat-message-role-label{text-transform:inherit;display:inline-block}.ai-chat-msg-role{text-transform:uppercase;margin-bottom:.35rem;font-weight:600}.ai-chat-msg-role-user{color:var(--bs-primary,#0d6efd)}.ai-chat-msg-role-assistant{color:var(--ai-chat-primary,var(--bs-success,#198754))}.ai-chat-messages .ai-chat-message-item{padding:.25rem 0;position:relative}.ai-chat-messages .ai-chat-message-item+.ai-chat-message-item:before{content:"";border-top:1px solid var(--bs-border-color,#dee2e6);width:100%;margin:.5rem auto .75rem;display:block}.ai-chat-messages .ai-chat-message-item p:last-child{margin-bottom:0}.ai-chat-messages .ai-chat-message-body{overflow-wrap:break-word;word-break:break-word;min-width:0;padding:0;position:relative}.ai-chat-messages .ai-chat-message-body sup{font-size:.75em;line-height:0}.ai-chat-messages table{margin:.75rem 0;font-size:.9em}.ai-chat-messages table th,.ai-chat-messages table td{vertical-align:top;white-space:nowrap}.ai-chat-messages table th[align=right],.ai-chat-messages table td[align=right]{text-align:right}.ai-chat-messages table th[align=center],.ai-chat-messages table td[align=center]{text-align:center}.ai-chat-messages .ai-chat-citation-list{margin:.75rem 0 0;padding-left:1.25rem}.ai-chat-messages .ai-chat-citation-item+.ai-chat-citation-item{margin-top:.25rem}.ai-chat-messages .ai-chat-citation-item a{word-break:break-word}.ai-partial-transcript{opacity:.7;font-style:italic}.ai-chat-messages .message-buttons-container{opacity:0;pointer-events:none;background:rgba(var(--bs-body-bg-rgb,255, 255, 255), .96);width:auto;max-width:max-content;box-shadow:0 1px 3px rgba(var(--bs-body-color-rgb,33, 37, 41), .08);z-index:1;border-radius:999px;align-items:center;gap:.35rem;margin-bottom:1rem;padding:.2rem .35rem;transition:opacity .15s ease-in-out;display:inline-flex;position:absolute;bottom:0;right:.1rem;transform:translateY(50%)}.ai-chat-messages .ai-chat-message-item:hover .message-buttons-container,.ai-chat-messages .ai-chat-message-item:focus-within .message-buttons-container{opacity:1;pointer-events:auto}.ai-chat-messages .message-buttons-container:has(.tts-playing){opacity:1;pointer-events:auto}.ai-chat-messages .message-buttons-container>.button-message-toolbox{border-radius:50%;flex:none;justify-content:center;align-items:center;width:1.75rem;height:1.75rem;text-decoration:none;display:inline-flex;color:var(--bs-secondary-color,#6c757d)!important;margin:0!important;padding:0!important}.ai-chat-messages .message-buttons-container .ai-chat-message-assistant-feedback{align-items:center;gap:.35rem;display:inline-flex}.ai-chat-messages .message-buttons-container>.button-message-toolbox:hover,.ai-chat-messages .message-buttons-container>.button-message-toolbox:focus{text-decoration:none;color:var(--bs-body-color,#212529)!important}.ai-chat-messages .message-buttons-container>.button-message-toolbox.text-success,.ai-chat-messages .message-buttons-container>.button-message-toolbox.text-success:hover,.ai-chat-messages .message-buttons-container>.button-message-toolbox.text-success:focus{text-decoration:none;color:var(--bs-success,#198754)!important}.ai-chat-messages .message-buttons-container>.button-message-toolbox.text-success svg{fill:currentColor;color:inherit!important}.ai-chat-messages .message-buttons-container .tts-playing{color:var(--ai-chat-primary,var(--bs-success,#198754))}@keyframes spark-burst{0%{opacity:1;transform:scale(1)}20%{opacity:.7;transform:scale(1.8)}40%{opacity:1;transform:scale(.9)}60%{transform:scale(1.3)}to{transform:scale(1)}}.spark-effect i,.spark-effect svg{animation:.5s ease-out spark-burst;display:inline-block}.ai-chat-messages .ai-bot-icon{color:currentColor;animation:none;display:inline-block}@keyframes ai-chat-streaming-effect{0%{opacity:1;transform:rotate(0)}10%{opacity:.3;transform:rotate(0)}20%{opacity:1;transform:rotate(0)}30%{opacity:.3;transform:rotate(0)}40%{opacity:1;transform:rotate(0)}50%{opacity:.3;transform:rotate(0)}60%{opacity:1;transform:rotate(0)}80%{opacity:1;transform:rotate(360deg)}to{opacity:1;transform:rotate(360deg)}}.ai-chat-messages .ai-streaming-icon{color:currentColor;animation:4s ease-in-out infinite ai-chat-streaming-effect;display:inline-block}.ai-chat-messages pre{margin:0;position:relative}.ai-chat-messages .ai-code-block{border:1px solid var(--bs-border-color,#dee2e6);background:var(--bs-body-bg,#fff);border-radius:.5rem;margin:.75rem 0;overflow:hidden}.ai-chat-messages .ai-code-header{justify-content:space-between;align-items:center;min-height:2rem;padding:.5rem 1rem;font-size:.8rem;display:flex}.ai-chat-messages .ai-code-lang{color:var(--bs-body-color,#212529);text-transform:capitalize;font-weight:600}.ai-chat-messages .ai-code-lang i{color:var(--bs-secondary-color,#6c757d);margin-right:.25rem}.ai-chat-messages .ai-code-copy-btn{cursor:pointer;color:var(--bs-secondary-color,#6c757d);white-space:nowrap;background:0 0;border:none;align-items:center;gap:.3rem;padding:.2rem;font-size:.8rem;transition:color .15s;display:inline-flex}.ai-chat-messages .ai-code-copy-btn:hover{color:var(--bs-body-color,#212529)}.ai-chat-messages .ai-code-block pre{margin:0;background:0 0!important}.ai-chat-messages .ai-code-block pre code.hljs{padding:.75rem 1rem 1rem;background:0 0!important}.ai-chat-messages pre code.hljs{white-space:pre-wrap;word-wrap:break-word;overflow-wrap:break-word;border-radius:.375rem}.ai-chat-doc-bar{border-bottom:1px solid var(--bs-border-color,#dee2e6)}.ai-chat-drag-over{outline-offset:-2px;outline:2px dashed var(--bs-primary,#0d6efd)!important;background-color:rgba(var(--bs-primary-rgb,13, 110, 253), .05)!important}.ai-chat-notification{border:1px solid var(--bs-border-color,#dee2e6);background-color:var(--bs-tertiary-bg,#f8f9fa);border-radius:.5rem;margin:.75rem 0 .25rem;padding:.625rem .875rem;font-size:.875rem;line-height:1.4}.ai-chat-notification-content{align-items:center;gap:.5rem;display:flex}.ai-chat-notification-icon{opacity:.8;flex-shrink:0;font-size:1rem}.ai-chat-notification-text{flex:1}.ai-chat-notification-dismiss{opacity:.5;flex-shrink:0;transition:opacity .15s}.ai-chat-notification-dismiss:hover{opacity:1}.ai-chat-notification-actions{border-top:1px solid var(--bs-border-color,#dee2e6);gap:.375rem;margin-top:.5rem;padding-top:.5rem;display:flex}.ai-chat-notification-actions .btn{padding:.1875rem .625rem;font-size:.8125rem}.ai-chat-notification-typing{border-color:var(--ai-chat-primary,var(--bs-success,#198754));background-color:rgba(var(--ai-chat-primary-rgb,var(--bs-success-rgb,25, 135, 84)), .05)}.ai-chat-notification-typing .ai-chat-notification-icon{color:var(--ai-chat-primary,var(--bs-success,#198754));animation:1.5s ease-in-out infinite ai-chat-typing-pulse}@keyframes ai-chat-typing-pulse{0%,to{opacity:.4}50%{opacity:1}}.ai-chat-notification-transfer{border-color:var(--bs-warning,#ffc107);background-color:rgba(var(--bs-warning-rgb,255, 193, 7), .06)}.ai-chat-notification-transfer .ai-chat-notification-icon{color:var(--bs-warning,#ffc107);animation:2s ease-in-out infinite ai-chat-transfer-pulse}@keyframes ai-chat-transfer-pulse{0%,to{opacity:.7;transform:scale(1)}50%{opacity:1;transform:scale(1.1)}}.ai-chat-notification-ended,.ai-chat-notification-session-ended,.ai-chat-notification-conversation-ended{border-color:var(--bs-secondary,#6c757d);background-color:rgba(var(--bs-secondary-rgb,108, 117, 125), .05)}.ai-chat-notification-ended .ai-chat-notification-icon,.ai-chat-notification-session-ended .ai-chat-notification-icon,.ai-chat-notification-conversation-ended .ai-chat-notification-icon{color:var(--bs-secondary,#6c757d)}.ai-chat-notification-info,.ai-chat-notification-agent-connected{border-color:var(--bs-info,#0dcaf0);background-color:rgba(var(--bs-info-rgb,13, 202, 240), .05)}.ai-chat-notification-info .ai-chat-notification-icon,.ai-chat-notification-agent-connected .ai-chat-notification-icon{color:var(--bs-info,#0dcaf0)}.ai-chat-notification-warning,.ai-chat-notification-agent-reconnecting{border-color:var(--bs-warning,#ffc107);background-color:rgba(var(--bs-warning-rgb,255, 193, 7), .06)}.ai-chat-notification-warning .ai-chat-notification-icon,.ai-chat-notification-agent-reconnecting .ai-chat-notification-icon{color:var(--bs-warning,#ffc107)}.ai-chat-notification-error,.ai-chat-notification-connection-lost{border-color:var(--bs-danger,#dc3545);background-color:rgba(var(--bs-danger-rgb,220, 53, 69), .05)}.ai-chat-notification-error .ai-chat-notification-icon,.ai-chat-notification-connection-lost .ai-chat-notification-icon{color:var(--bs-danger,#dc3545)}.generated-image-container{vertical-align:top;margin-top:.5rem;display:inline-block;position:relative}.generated-image-container img{object-fit:contain;cursor:zoom-in;height:auto;max-height:60vh;max-width:100%!important}img.medium-zoom-image--opened{background:0 0;border:0;padding:0;max-width:none!important;max-height:none!important}.generated-image-container .ai-download-image{z-index:2;opacity:0;color:#1f2933;background-color:#ffffffeb;border-color:#00000026;transition:opacity .15s ease-in-out;position:absolute;bottom:.5rem;right:.5rem}.generated-image-container .ai-download-image:hover,.generated-image-container .ai-download-image:focus,.generated-image-container .ai-download-image:focus-visible,.generated-image-container .ai-download-image:active{color:#1f2933;background-color:#fff;border-color:#00000059}.generated-image-container:hover .ai-download-image,.generated-image-container:focus-within .ai-download-image{opacity:1}@media (hover:none){.generated-image-container .ai-download-image{opacity:1}}.ai-chat-message-item table{border-collapse:collapse;width:max-content;min-width:100%;max-width:100%;margin-bottom:1rem;font-size:.9375rem;display:block;overflow-x:auto}.ai-chat-message-item table th,.ai-chat-message-item table td{border:1px solid var(--bs-border-color,#dee2e6);text-align:left;vertical-align:top;padding:.4rem .75rem}.ai-chat-message-item table thead th{background-color:var(--bs-secondary-bg,#e9ecef);border-bottom:2px solid var(--bs-border-color,#dee2e6);white-space:nowrap;font-weight:600}.ai-chat-message-item table tbody tr:nth-child(2n){background-color:var(--bs-tertiary-bg,#f8f9fa)}
1
+ .ai-chat-message-heading{margin-bottom:.35rem;font-size:.75rem}.ai-chat-message-heading .ai-chat-msg-role{letter-spacing:.03em;margin-bottom:0}.ai-chat-message-heading-assistant .ai-chat-msg-role{align-items:center;gap:.35rem;display:inline-flex}.ai-chat-message-role-label{text-transform:inherit;display:inline-block}.ai-chat-msg-role{text-transform:uppercase;margin-bottom:.35rem;font-weight:600}.ai-chat-msg-role-user{color:var(--bs-primary,#0d6efd)}.ai-chat-msg-role-assistant{color:var(--ai-chat-primary,var(--bs-success,#198754))}.ai-chat-messages .ai-chat-message-item{padding:.25rem 0;position:relative}.ai-chat-messages .ai-chat-message-item+.ai-chat-message-item:before{content:"";border-top:1px solid var(--bs-border-color,#dee2e6);width:100%;margin:.5rem auto .75rem;display:block}.ai-chat-messages .ai-chat-message-item p:last-child{margin-bottom:0}.ai-chat-messages .ai-chat-message-body{overflow-wrap:break-word;word-break:break-word;min-width:0;padding:0;position:relative}.ai-chat-messages .ai-chat-message-body sup{font-size:.75em;line-height:0}.ai-chat-messages table{margin:.75rem 0;font-size:.9em}.ai-chat-messages table th,.ai-chat-messages table td{vertical-align:top;white-space:nowrap}.ai-chat-messages table th[align=right],.ai-chat-messages table td[align=right]{text-align:right}.ai-chat-messages table th[align=center],.ai-chat-messages table td[align=center]{text-align:center}.ai-chat-messages .ai-chat-citation-list{margin:.75rem 0 0;padding-left:1.25rem}.ai-chat-messages .ai-chat-citation-item+.ai-chat-citation-item{margin-top:.25rem}.ai-chat-messages .ai-chat-citation-item a{word-break:break-word}.ai-partial-transcript{opacity:.7;font-style:italic}.ai-chat-messages .message-buttons-container{opacity:0;pointer-events:none;background:rgba(var(--bs-body-bg-rgb,255, 255, 255), .96);width:auto;max-width:max-content;box-shadow:0 1px 3px rgba(var(--bs-body-color-rgb,33, 37, 41), .08);z-index:1;border-radius:999px;align-items:center;gap:.35rem;margin-bottom:1rem;padding:.2rem .35rem;transition:opacity .15s ease-in-out;display:inline-flex;position:absolute;bottom:0;right:.1rem;transform:translateY(50%)}.ai-chat-messages .ai-chat-message-item:hover .message-buttons-container,.ai-chat-messages .ai-chat-message-item:focus-within .message-buttons-container{opacity:1;pointer-events:auto}.ai-chat-messages .message-buttons-container:has(.tts-playing){opacity:1;pointer-events:auto}.ai-chat-messages .message-buttons-container>.button-message-toolbox{border-radius:50%;flex:none;justify-content:center;align-items:center;width:1.75rem;height:1.75rem;text-decoration:none;display:inline-flex;color:var(--bs-secondary-color,#6c757d)!important;margin:0!important;padding:0!important}.ai-chat-messages .message-buttons-container .ai-chat-message-assistant-feedback{align-items:center;gap:.35rem;display:inline-flex}.ai-chat-messages .message-buttons-container>.button-message-toolbox:hover,.ai-chat-messages .message-buttons-container>.button-message-toolbox:focus{text-decoration:none;color:var(--bs-body-color,#212529)!important}.ai-chat-messages .message-buttons-container>.button-message-toolbox.text-success,.ai-chat-messages .message-buttons-container>.button-message-toolbox.text-success:hover,.ai-chat-messages .message-buttons-container>.button-message-toolbox.text-success:focus{text-decoration:none;color:var(--bs-success,#198754)!important}.ai-chat-messages .message-buttons-container>.button-message-toolbox.text-success svg{fill:currentColor;color:inherit!important}.ai-chat-messages .message-buttons-container .tts-playing{color:var(--ai-chat-primary,var(--bs-success,#198754))}@keyframes spark-burst{0%{opacity:1;transform:scale(1)}20%{opacity:.7;transform:scale(1.8)}40%{opacity:1;transform:scale(.9)}60%{transform:scale(1.3)}to{transform:scale(1)}}.spark-effect i,.spark-effect svg{animation:.5s ease-out spark-burst;display:inline-block}.ai-chat-messages .ai-bot-icon{color:currentColor;animation:none;display:inline-block}@keyframes ai-chat-streaming-effect{0%{opacity:1;transform:rotate(0)}10%{opacity:.3;transform:rotate(0)}20%{opacity:1;transform:rotate(0)}30%{opacity:.3;transform:rotate(0)}40%{opacity:1;transform:rotate(0)}50%{opacity:.3;transform:rotate(0)}60%{opacity:1;transform:rotate(0)}80%{opacity:1;transform:rotate(360deg)}to{opacity:1;transform:rotate(360deg)}}.ai-chat-messages .ai-streaming-icon{color:currentColor;animation:4s ease-in-out infinite ai-chat-streaming-effect;display:inline-block}.ai-chat-messages pre{margin:0;position:relative}.ai-chat-messages .ai-code-block{border:1px solid var(--bs-border-color,#dee2e6);background:var(--bs-body-bg,#fff);border-radius:.5rem;margin:.75rem 0;overflow:hidden}.ai-chat-messages .ai-code-header{justify-content:space-between;align-items:center;min-height:2rem;padding:.5rem 1rem;font-size:.8rem;display:flex}.ai-chat-messages .ai-code-lang{color:var(--bs-body-color,#212529);text-transform:capitalize;font-weight:600}.ai-chat-messages .ai-code-lang i{color:var(--bs-secondary-color,#6c757d);margin-right:.25rem}.ai-chat-messages .ai-code-copy-btn{cursor:pointer;color:var(--bs-secondary-color,#6c757d);white-space:nowrap;background:0 0;border:none;align-items:center;gap:.3rem;padding:.2rem;font-size:.8rem;transition:color .15s;display:inline-flex}.ai-chat-messages .ai-code-copy-btn:hover{color:var(--bs-body-color,#212529)}.ai-chat-messages .ai-code-block pre{margin:0;background:0 0!important}.ai-chat-messages .ai-code-block pre code.hljs{padding:.75rem 1rem 1rem;background:0 0!important}.ai-chat-messages pre code.hljs{white-space:pre-wrap;word-wrap:break-word;overflow-wrap:break-word;border-radius:.375rem}.ai-chat-doc-bar{border-bottom:1px solid var(--bs-border-color,#dee2e6)}.ai-chat-drag-over{outline-offset:-2px;outline:2px dashed var(--bs-primary,#0d6efd)!important;background-color:rgba(var(--bs-primary-rgb,13, 110, 253), .05)!important}.ai-chat-notification{border:1px solid var(--bs-border-color,#dee2e6);background-color:var(--bs-tertiary-bg,#f8f9fa);border-radius:.5rem;margin:.75rem 0 .25rem;padding:.625rem .875rem;font-size:.875rem;line-height:1.4}.ai-chat-notification-content{align-items:center;gap:.5rem;display:flex}.ai-chat-notification-icon{opacity:.8;flex-shrink:0;font-size:1rem}.ai-chat-notification-text{flex:1}.ai-chat-notification-dismiss{opacity:.5;flex-shrink:0;transition:opacity .15s}.ai-chat-notification-dismiss:hover{opacity:1}.ai-chat-notification-actions{border-top:1px solid var(--bs-border-color,#dee2e6);gap:.375rem;margin-top:.5rem;padding-top:.5rem;display:flex}.ai-chat-notification-actions .btn{padding:.1875rem .625rem;font-size:.8125rem}.ai-chat-notification-typing{border-color:var(--ai-chat-primary,var(--bs-success,#198754));background-color:rgba(var(--ai-chat-primary-rgb,var(--bs-success-rgb,25, 135, 84)), .05)}.ai-chat-notification-typing .ai-chat-notification-icon{color:var(--ai-chat-primary,var(--bs-success,#198754));animation:1.5s ease-in-out infinite ai-chat-typing-pulse}@keyframes ai-chat-typing-pulse{0%,to{opacity:.4}50%{opacity:1}}.ai-chat-notification-transfer{border-color:var(--bs-warning,#ffc107);background-color:rgba(var(--bs-warning-rgb,255, 193, 7), .06)}.ai-chat-notification-transfer .ai-chat-notification-icon{color:var(--bs-warning,#ffc107);animation:2s ease-in-out infinite ai-chat-transfer-pulse}@keyframes ai-chat-transfer-pulse{0%,to{opacity:.7;transform:scale(1)}50%{opacity:1;transform:scale(1.1)}}.ai-chat-notification-ended,.ai-chat-notification-session-ended,.ai-chat-notification-conversation-ended{border-color:var(--bs-secondary,#6c757d);background-color:rgba(var(--bs-secondary-rgb,108, 117, 125), .05)}.ai-chat-notification-ended .ai-chat-notification-icon,.ai-chat-notification-session-ended .ai-chat-notification-icon,.ai-chat-notification-conversation-ended .ai-chat-notification-icon{color:var(--bs-secondary,#6c757d)}.ai-chat-notification-info,.ai-chat-notification-agent-connected{border-color:var(--bs-info,#0dcaf0);background-color:rgba(var(--bs-info-rgb,13, 202, 240), .05)}.ai-chat-notification-info .ai-chat-notification-icon,.ai-chat-notification-agent-connected .ai-chat-notification-icon{color:var(--bs-info,#0dcaf0)}.ai-chat-notification-warning,.ai-chat-notification-agent-reconnecting{border-color:var(--bs-warning,#ffc107);background-color:rgba(var(--bs-warning-rgb,255, 193, 7), .06)}.ai-chat-notification-warning .ai-chat-notification-icon,.ai-chat-notification-agent-reconnecting .ai-chat-notification-icon{color:var(--bs-warning,#ffc107)}.ai-chat-notification-error,.ai-chat-notification-connection-lost{border-color:var(--bs-danger,#dc3545);background-color:rgba(var(--bs-danger-rgb,220, 53, 69), .05)}.ai-chat-notification-error .ai-chat-notification-icon,.ai-chat-notification-connection-lost .ai-chat-notification-icon{color:var(--bs-danger,#dc3545)}.generated-image-container{vertical-align:top;margin-top:.5rem;display:inline-block;position:relative}.generated-image-container img{object-fit:contain;cursor:zoom-in;height:auto;max-height:60vh;max-width:100%!important}img.medium-zoom-image--opened{background:0 0;border:0;padding:0;max-width:none!important;max-height:none!important}.generated-image-container .ai-download-image{z-index:2;opacity:0;color:#1f2933;background-color:#ffffffeb;border-color:#00000026;transition:opacity .15s ease-in-out;position:absolute;bottom:.5rem;right:.5rem}.generated-image-container .ai-download-image:hover,.generated-image-container .ai-download-image:focus,.generated-image-container .ai-download-image:focus-visible,.generated-image-container .ai-download-image:active{color:#1f2933;background-color:#fff;border-color:#00000059}.generated-image-container:hover .ai-download-image,.generated-image-container:focus-within .ai-download-image{opacity:1}@media (hover:none){.generated-image-container .ai-download-image{opacity:1}}.ai-chat-message-item table{border-collapse:collapse;width:max-content;min-width:100%;max-width:100%;margin-bottom:1rem;font-size:.9375rem;display:block;overflow-x:auto}.ai-chat-message-item table th,.ai-chat-message-item table td{border:1px solid var(--bs-border-color,#dee2e6);text-align:left;vertical-align:top;padding:.4rem .75rem}.ai-chat-message-item table thead th{background-color:var(--bs-secondary-bg,#e9ecef);border-bottom:2px solid var(--bs-border-color,#dee2e6);white-space:nowrap;font-weight:600}.ai-chat-message-item table tbody tr:nth-child(2n){background-color:var(--bs-tertiary-bg,#f8f9fa)}.ai-chat-assistant-avatar{object-fit:cover;border-radius:50%;width:1.5rem;height:1.5rem;display:block}.ai-bot-avatar,.ai-streaming-avatar{vertical-align:middle;flex-shrink:0;display:inline-flex}@keyframes ai-chat-avatar-pulse{0%,to{opacity:1}50%{opacity:.45}}.ai-streaming-avatar{animation:1.5s ease-in-out infinite ai-chat-avatar-pulse}@media (prefers-reduced-motion:reduce){.ai-streaming-avatar{animation:none}}
@@ -1,4 +1,4 @@
1
- (function(){window.coreAIChatManager=function(){var e={generatedImageAltText:`Generated Image`,generatedImageMaxWidth:400,downloadImageTitle:`Download image`,downloadChartTitle:`Download chart as image`,downloadChartButtonText:`Download`,userLabel:`You`,assistantLabel:`Assistant`,thumbsUpTitle:`Thumbs up`,thumbsDownTitle:`Thumbs down`,copyTitle:`Click here to copy response to clipboard.`,copiedTitle:`Response copied to clipboard.`,codeCopiedText:`Copied!`,copyResetDelayMs:2e3,widget:{chatWidgetContainer:null,chatWidgetStateName:null,chatHistorySection:null,showHistoryButton:null,closeHistoryButton:null,newChatButton:null,toggleButtonSelector:null,resetSizeButtonSelector:null,dragHandleSelector:`.ai-chat-widget-header`,enableDragging:!0,enableResizing:!0,persistLayout:!0,defaultWidth:null,defaultHeight:null,minWidth:320,minHeight:420},messageTemplate:`
1
+ (function(){window.coreAIChatManager=function(){var e={generatedImageAltText:`Generated Image`,generatedImageMaxWidth:400,downloadImageTitle:`Download image`,downloadChartTitle:`Download chart as image`,downloadChartButtonText:`Download`,userLabel:`You`,assistantLabel:`Assistant`,assistantAvatarUrl:null,thumbsUpTitle:`Thumbs up`,thumbsDownTitle:`Thumbs down`,copyTitle:`Click here to copy response to clipboard.`,copiedTitle:`Response copied to clipboard.`,codeCopiedText:`Copied!`,copyResetDelayMs:2e3,widget:{chatWidgetContainer:null,chatWidgetStateName:null,chatHistorySection:null,showHistoryButton:null,closeHistoryButton:null,newChatButton:null,toggleButtonSelector:null,resetSizeButtonSelector:null,dragHandleSelector:`.ai-chat-widget-header`,enableDragging:!0,enableResizing:!0,persistLayout:!0,defaultWidth:null,defaultHeight:null,minWidth:320,minHeight:420},messageTemplate:`
2
2
  <div class="ai-chat-messages">
3
3
  <div v-for="(message, index) in messages" :key="'msg-' + index" class="ai-chat-message-item">
4
4
  <div>
@@ -7,7 +7,7 @@
7
7
  </div>
8
8
  <div v-else-if="message.role !== 'indicator'" class="ai-chat-message-heading ai-chat-message-heading-assistant">
9
9
  <div :class="getAssistantRoleClasses(message)">
10
- <span :class="getAssistantIconClasses(message, index)"><i :class="getAssistantIcon(message)"></i></span>
10
+ <span :class="getAssistantIconClasses(message, index)"><img v-if="getAssistantAvatarUrl(message)" class="ai-chat-assistant-avatar" :src="getAssistantAvatarUrl(message)" alt="" /><i v-else :class="getAssistantIcon(message)"></i></span>
11
11
  <span class="ai-chat-message-role-label">{{ getAssistantLabel(message) }}</span>
12
12
  </div>
13
13
  </div>
@@ -60,8 +60,8 @@
60
60
  `,indicatorTemplate:`
61
61
  <div class="ai-chat-message-heading ai-chat-message-heading-assistant">
62
62
  <div class="ai-chat-msg-role ai-chat-msg-role-assistant">
63
- <span class="ai-streaming-icon"><i class="fa fa-robot" style="display: inline-block;"></i></span>
64
- <span class="ai-chat-message-role-label">Assistant</span>
63
+ {{ assistantIcon }}
64
+ <span class="ai-chat-message-role-label">{{ assistantLabel }}</span>
65
65
  </div>
66
66
  </div>
67
67
  `};function t(e){if(!e)return``;var t=e.trim();return/^javascript:/i.test(t)||/^vbscript:/i.test(t)||/^data:text\/html/i.test(t)?``:e}function n(e){var t=document.createElement(`span`);return t.textContent=e,t.innerHTML}function r(e){if(!e||e.nodeType!==1)return!1;var t=`i[class*="fa-"],i.fa,i.fas,i.far,i.fab`;return typeof e.matches==`function`&&e.matches(t)?!0:typeof e.querySelector==`function`&&!!e.querySelector(t)}function i(e){var t=window.FontAwesome;r(e)&&t&&t.dom&&typeof t.dom.i2svg==`function`&&t.dom.i2svg({node:e})}function a(e){if(!e||typeof MutationObserver>`u`)return null;var t=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){i(e)})})});return t.observe(e,{childList:!0,subtree:!0}),t}function o(e){if(!e||typeof e!=`object`)return null;let n=Object.assign({},e);return n.index=n.index??n.Index??0,n.text=n.text??n.Text??null,n.title=n.title??n.Title??null,n.link=t(n.link??n.Link??null),n.referenceType=n.referenceType??n.ReferenceType??null,n.isGenerated=(n.isGenerated??n.IsGenerated)===!0,n.isImage=(n.isImage??n.IsImage)===!0,n}function s(e){return!e||typeof e!=`object`?!1:!!(typeof e.referenceType==`string`&&e.referenceType.toLowerCase()===`document`||typeof e.link==`string`&&/\/ai\/documents\/.+\/download(?:$|\?)/i.test(e.link))}function c(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))t[n]=o(r)??{};return t}async function l(e,t){if((e.headers&&e.headers.get(`content-type`)||``).toLowerCase().indexOf(`json`)<0)return{ok:!1,data:null,message:e.redirected?`You may not be signed in, or you do not have permission for this. Please reload and try again.`:t};try{return{ok:!0,data:await e.json(),message:null}}catch{return{ok:!1,data:null,message:t}}}let u=window.CoreAIChatMarkers.expandImageMarkers;function d(e,t){return e.title||e.text||t}let f=0,p=window.CoreAIChatMarkers?.citationIdentity??(()=>`unmerged-${++f}`),m=window.CoreAIChatMarkers?.splitCombinedCitations??(e=>e),h=window.CoreAIChatMarkers?.collapseRepeatedCitations??(e=>e),g=window.CoreAIChatMarkers?.separateAdjacentCitations??(e=>e),_=window.CoreAIChatMarkers?.citationMarkerHtml??(e=>`<sup>${e}</sup>`);function v(e,t){let n=m((e||``).trim()),r=c(t),i=Object.entries(r);if(!i.length)return{content:n,citations:[]};let a=i.filter(([e])=>n.includes(e)),o=i.filter(([e,t])=>t.isGenerated&&!n.includes(e));if(!a.length&&!o.length)return{content:n,citations:[]};a.sort(([,e],[,t])=>e.index-t.index),o.sort(([,e],[,t])=>e.index-t.index);let l=[],u=new Map,f=[],v=1;for(let[e,t]of a){let r=d(t,e),i=t.link||null,a=p(r,i),o=u.get(a);o||(o={referenceKey:e,referenceKeys:[],displayIndex:v++,label:r,link:i,isDownload:s(t)},u.set(a,o),l.push(o)),o.referenceKeys.push(e);let c=`__CITE_${o.displayIndex}_${t.index||o.displayIndex}__`;n=n.replaceAll(e,c),f.push({placeholder:c,displayIndex:o.displayIndex,label:o.label})}for(let e of f)n=n.replaceAll(e.placeholder,_(e.displayIndex,e.label));n=h(n),n=g(n);for(let[e,t]of o)l.push({referenceKey:e,referenceKeys:[e],displayIndex:v,label:d(t,e),link:t.link||null,isDownload:!0,placeholder:null}),v++;return{content:n,citations:l.map(({placeholder:e,...t})=>t)}}function y(e,t){let n=(e||``).trim();if(!n||!Array.isArray(t)||t.length===0)return n;for(let e of t)for(let t of e.referenceKeys?.length?e.referenceKeys:[e.referenceKey])n=n.replaceAll(t,`[${e.displayIndex}]`);n+=`
@@ -73,7 +73,7 @@ References:
73
73
  <a href="${r}" target="_blank" download="${i}" title="${e.downloadImageTitle}" class="btn btn-sm btn-outline-secondary ai-download-image">
74
74
  <i class="fa-solid fa-download"></i>
75
75
  </a>
76
- </span>`};let S=0,C=[];window.__chartConfigs=window.__chartConfigs||{};function w(t){return`<div class="chart-container" style="position: relative; width: 100%; max-width: 560px; min-height: 420px;"><canvas id="${t}"></canvas></div><div class="mt-2"><button type="button" class="btn btn-sm btn-outline-secondary download-chart-btn" data-chart-id="${t}" title="${e.downloadChartTitle}"><i class="fa-solid fa-download"></i> ${e.downloadChartButtonText}</button></div>`}let T=window.CoreAIChatMarkers.findChartMarker;marked.use({extensions:[{name:`chart`,level:`block`,start(e){let t=e.indexOf(`[chart:`);return t>=0?t:void 0},tokenizer(e){let t=T(e);if(!t||t.startIndex!==0)return;let n=`chat_chart_${++S}`;return{type:`chart`,raw:e.substring(0,t.endIndex),chartId:n,json:t.json}},renderer(e){return C.push({chartId:e.chartId,config:e.json}),window.__chartConfigs[e.chartId]=e.json,w(e.chartId)}}]});function E(){typeof document<`u`&&typeof requestAnimationFrame==`function`&&(requestAnimationFrame(O),requestAnimationFrame(D))}function D(){if(typeof mediumZoom!=`function`)return;let e=document.querySelectorAll(`.generated-image-container img:not([data-zoom-wired])`);if(e.length!==0){for(let t of e)t.setAttribute(`data-zoom-wired`,`true`);mediumZoom(e,{margin:16,background:`rgba(15, 15, 15, 0.92)`})}}function O(){let e=document.querySelectorAll(`.generated-image-container img:not([data-broken-wired])`);for(let t of e)t.setAttribute(`data-broken-wired`,`true`),t.addEventListener(`error`,function(){let e=t.closest(`.generated-image-container`);if(!e||e.dataset.brokenHandled)return;e.dataset.brokenHandled=`true`,e.hidden=!0;let n=document.createElement(`p`);n.className=`text-muted small fst-italic mb-2`,n.textContent=t.alt?`(the picture "${t.alt}" could not be loaded)`:`(that picture could not be loaded)`,e.insertAdjacentElement(`afterend`,n)},{once:!0})}function k(e){if(E(),!e||!e._pendingCharts||!e._pendingCharts.length)return;let t=[...e._pendingCharts];e._pendingCharts=[],requestAnimationFrame(()=>{for(let e of t)A(e.chartId,e.config)})}function A(e,t){let n=document.getElementById(e);if(!n)return!1;if(typeof Chart>`u`)return console.warn(`Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"><\/script>).`),!1;if(n.offsetParent===null)return window.__chartConfigs[e]=t,!1;try{n._chartInstance&&n._chartInstance.destroy();let r=typeof t==`string`?JSON.parse(t):t;return r.options??={},r.options.responsive=!0,r.options.maintainAspectRatio=!0,r.options.aspectRatio??=4/3,n._chartInstance=new Chart(n,r),delete window.__chartConfigs[e],!0}catch(e){return console.error(`Error creating chart:`,e),!1}}window.renderPendingCharts=function(){if(typeof Chart>`u`)return;let e=window.__chartConfigs;e&&requestAnimationFrame(()=>{for(let t of Object.keys(e))A(t,e[t])})};function j(e){return e.replace(/<table>/g,`<div class="table-responsive"><table class="table table-sm table-bordered table-striped align-middle">`).replace(/<\/table>/g,`</table></div>`)}function M(e,t){C=[];let n=j(marked.parse(e,{renderer:x}));t._pendingCharts=C.length>0?[...C]:[];let r=DOMPurify.sanitize(n,{ADD_TAGS:[`canvas`],ADD_ATTR:[`target`]});return window.CoreAIChatImageCarousel?window.CoreAIChatImageCarousel.stackAdjacentImages(r):r}function N(e){return!e||typeof e!=`object`?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function P(e,t){if(!e)return e;let r=n(t||`Assistant`);return e.replace(/\{\{\s*assistantLabel\s*\}\}/g,r)}let F=t=>{let n=N(t),r=N(n.widget),s=Object.assign({},e,n);s.widget=Object.assign({},e.widget||{},r),s.indicatorTemplate=P(s.indicatorTemplate,s.assistantLabel);let u=!!(r.chatWidgetContainer&&r.chatWidgetStateName),d=window.coreAIChatWidgetBehavior||null;if(e=s,!s.signalRHubUrl){console.error(`The signalRHubUrl is required.`);return}if(!s.appElementSelector){console.error(`The appElementSelector is required.`);return}if(!s.chatContainerElementSelector){console.error(`The chatContainerElementSelector is required.`);return}if(!s.inputElementSelector){console.error(`The inputElementSelector is required.`);return}if(!s.sendButtonElementSelector){console.error(`The sendButtonElementSelector is required.`);return}let f={data(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isSessionStarted:!1,isPlaceholderVisible:!0,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,messages:[],notifications:[],prompt:``,documents:s.existingDocuments||[],isUploading:!1,isDocumentOperationPending:!1,documentOperationQueue:null,uploadErrors:[],isDragOver:!1,documentBar:null,metricsEnabled:!!s.metricsEnabled,userLabel:s.userLabel,assistantLabel:s.assistantLabel,thumbsUpTitle:s.thumbsUpTitle,thumbsDownTitle:s.thumbsDownTitle,copyTitle:s.copyTitle,copiedTitle:s.copiedTitle,isRecording:!1,mediaRecorder:null,preRecordingPrompt:``,micButton:null,speechToTextEnabled:!s.realtimeEnabled&&(s.chatMode===`AudioInput`||s.chatMode===`Conversation`),textToSpeechEnabled:!s.realtimeEnabled&&s.chatMode===`Conversation`||!!s.textToSpeechEnabled,ttsVoiceName:s.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,currentAudioUrl:null,ttsButton:null,ttsPlayingMessageIndex:-1,ttsAudioCache:{},ttsInstanceId:`ai-chat-`+Math.random().toString(36).slice(2),singleResponseMode:!!s.singleResponseMode,conversationModeEnabled:s.chatMode===`Conversation`,realtimeEnabled:!!s.realtimeEnabled,realtimeWebRtcEnabled:s.realtimeWebRtcEnabled===!0&&typeof window.RTCPeerConnection==`function`,realtimeWebRtcIceServers:Array.isArray(s.realtimeWebRtcIceServers)&&s.realtimeWebRtcIceServers.length?s.realtimeWebRtcIceServers:null,realtimeVoiceName:s.realtimeVoiceName||null,conversationButton:null,realtimeHintElement:s.realtimeHintElementSelector?document.querySelector(s.realtimeHintElementSelector):null,isConversationMode:!1,notificationDismissTimers:{},pendingSessionPromise:null,pendingSessionResolver:null,pendingSessionRejector:null,pendingSessionTimeoutId:null,copiedMessageIndex:-1,copyResetTimeoutId:null,activeCopyButton:null}},computed:{lastAssistantIndex(){for(var e=this.messages.length-1;e>=0;e--)if(this.messages[e].role===`assistant`)return e;return-1}},methods:{handleBeforeUnload(){this.isNavigatingAway=!0},handleDragOver(e){if(s.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!0;var t=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;t&&t.classList.add(`ai-chat-drag-over`)}},handleDragLeave(e){if(s.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;t&&t.classList.remove(`ai-chat-drag-over`)}},handleDrop(e){if(s.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;t&&t.classList.remove(`ai-chat-drag-over`),e.dataTransfer&&e.dataTransfer.files&&e.dataTransfer.files.length>0&&this.uploadFiles(Array.from(e.dataTransfer.files))}},triggerFileInput(){if(s.sessionDocumentsEnabled&&!this.isDocumentOperationPending){var e=document.getElementById(`ai-chat-doc-input`);e&&e.click()}},handleFileInputChange(e){var t=e.target.files?Array.from(e.target.files):[];t&&t.length>0&&this.uploadFiles(t),e.target.value=``},queueDocumentOperation(e){var t=this,n=(this.documentOperationQueue||Promise.resolve()).catch(function(){}).then(async function(){t.isDocumentOperationPending=!0;try{return await e()}finally{t.isDocumentOperationPending=!1}});return this.documentOperationQueue=n.finally(function(){t.documentOperationQueue===n&&(t.documentOperationQueue=null)}),this.documentOperationQueue},async uploadFiles(e){if(s.uploadDocumentUrl){var t=Array.isArray(e)?e.slice():Array.from(e||[]);if(t.length!==0)return this.queueDocumentOperation(async()=>{var e=this.getSessionId(),n=this.getProfileId();if(!e)try{e=await this.ensureSessionForDocuments(n)}catch(e){console.error(`Failed to create a chat session for document upload:`,e),this.uploadErrors=[{fileName:``,error:`Could not create a chat session for the upload.`}],this.renderDocumentBar();return}if(!e)console.warn(`Cannot upload documents without a session or profile.`),this.uploadErrors=[{fileName:``,error:`Could not create a chat session for the upload.`}],this.renderDocumentBar();else{this.isUploading=!0,this.uploadErrors=[],this.renderDocumentBar();try{var r=new FormData;r.append(`sessionId`,e);for(var i=0;i<t.length;i++)r.append(`files`,t[i]);var a=await fetch(s.uploadDocumentUrl,{method:`POST`,body:r});if(!a.ok){var o=await a.text(),c=this.extractReadableErrorMessage(o,`Upload failed. Please try again.`);console.error(`Upload failed:`,o),this.uploadErrors=[{fileName:``,error:c}];return}var u=await l(a,`Upload failed. Please try again.`);if(!u.ok){console.error(`Upload failed: response was not JSON.`,{status:a.status,redirected:a.redirected}),this.uploadErrors=[{fileName:``,error:u.message}];return}var d=u.data;d.sessionId&&d.sessionId!==this.getSessionId()&&this.initializeSession(d.sessionId),Array.isArray(d.documents)?this.documents=d.documents:d.uploaded&&d.uploaded.length>0&&(this.documents=this.documents.concat(d.uploaded)),d.failed&&d.failed.length>0&&(this.uploadErrors=d.failed)}catch(e){console.error(`Upload error:`,e),this.uploadErrors=[{fileName:``,error:`Upload failed. Please try again.`}],this.getSessionId()&&this.reloadCurrentSession()}finally{this.isUploading=!1,this.renderDocumentBar()}}})}},async removeDocument(e){if(s.removeDocumentUrl)return this.queueDocumentOperation(async()=>{try{var t=this.getSessionId(),n=await fetch(s.removeDocumentUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({itemId:t,documentId:e.documentId})});if(n.ok){var r=await l(n,`The request could not be completed.`);if(!r.ok){console.error(`Response was not JSON.`,{status:n.status,redirected:n.redirected});return}var i=r.data;if(Array.isArray(i.documents))this.documents=i.documents;else{var a=this.documents.indexOf(e);a>-1&&this.documents.splice(a,1)}}else{var o=await n.text(),c=this.extractReadableErrorMessage(o,`Failed to remove document. Please try again.`);console.error(`Failed to remove document:`,n.status,o),this.uploadErrors=[{fileName:e.fileName||``,error:c}],t&&this.reloadCurrentSession(),this.renderDocumentBar()}}catch(t){console.error(`Remove document error:`,t),this.uploadErrors=[{fileName:e.fileName||``,error:`Failed to remove document. Please try again.`}],this.getSessionId()&&this.reloadCurrentSession(),this.renderDocumentBar()}})},formatFileSize(e){return e<1024?e+` B`:e<1048576?(e/1024).toFixed(1)+` KB`:(e/1048576).toFixed(1)+` MB`},renderDocumentBar(){if(this.documentBar){if(!s.sessionDocumentsEnabled)this.documentBar.classList.add(`d-none`);else{this.documentBar.classList.remove(`d-none`);var e=`<div class="ai-chat-doc-bar p-2">`;e+=`<div class="d-flex flex-wrap align-items-center gap-1">`;for(var t=0;t<this.documents.length;t++){var n=this.documents[t],r=n.fileName||`Document`;r.length>20&&(r=r.substring(0,17)+`...`),e+=`<span class="badge bg-secondary bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="`+this.escapeHtml(n.fileName||``)+`">`,e+=`<i class="fa-solid fa-file-lines" style="font-size: 0.7rem;"></i> `,e+=this.escapeHtml(r),e+=` <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-doc-index="`+t+`" aria-label="Remove"`+(this.isDocumentOperationPending?` disabled`:``)+`></button>`,e+=`</span>`}for(var i=0;i<this.uploadErrors.length;i++){var a=this.uploadErrors[i];a.fileName;var o=a.error||`Upload failed`;e+=`<span class="alert alert-danger d-flex align-items-start gap-2 w-100 mb-1 py-1 px-2" role="alert" style="font-size: 0.8rem;">`,e+=`<i class="fa-solid fa-circle-exclamation mt-1" style="font-size: 0.7rem;"></i>`,e+=`<span class="flex-grow-1">`,a.fileName&&(e+=`<strong>`+this.escapeHtml(a.fileName)+`</strong>: `),e+=this.escapeHtml(o),e+=`</span>`,e+=`<button type="button" class="btn-close btn-close-sm" style="font-size: 0.5rem;" data-error-index="`+i+`" aria-label="Dismiss"></button>`,e+=`</span>`}this.isUploading&&(e+=`<span class="badge bg-info bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;">`,e+=`<span class="spinner-border spinner-border-sm" style="width: 0.7rem; height: 0.7rem;"></span> Uploading...`,e+=`</span>`),e+=`<button type="button" class="btn btn-sm btn-outline-secondary rounded-pill ai-chat-doc-add-btn d-inline-flex align-items-center gap-1" style="font-size: 0.75rem; padding: 0.15rem 0.5rem;" title="Attach documents"`+(this.isDocumentOperationPending?` disabled`:``)+`>`,e+=`<i class="fa-solid fa-paperclip"></i>`,this.documents.length===0&&!this.isUploading&&(e+=` <span>Attach files</span>`),e+=`</button>`,e+=`</div>`,s.supportedExtensionsText&&(e+=`<div class="small text-muted mt-2">Supported formats: `+this.escapeHtml(s.supportedExtensionsText)+`</div>`),e+=`</div>`,this.documentBar.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}));for(var c=this,l=this.documentBar.querySelectorAll(`[data-doc-index]`),u=0;u<l.length;u++)l[u].addEventListener(`click`,(function(e){return function(t){if(t.preventDefault(),t.stopPropagation(),!c.isDocumentOperationPending){var n=c.documents[e];n&&c.removeDocument(n)}}})(parseInt(l[u].getAttribute(`data-doc-index`))));for(var d=this.documentBar.querySelectorAll(`[data-error-index]`),f=0;f<d.length;f++)d[f].addEventListener(`click`,(function(e){return function(t){t.preventDefault(),t.stopPropagation(),c.uploadErrors.splice(e,1),c.renderDocumentBar()}})(parseInt(d[f].getAttribute(`data-error-index`))));var p=this.documentBar.querySelector(`.ai-chat-doc-add-btn`);p&&p.addEventListener(`click`,function(e){e.preventDefault(),!c.isDocumentOperationPending&&c.triggerFileInput()})}}},escapeHtml(e){var t=document.createElement(`div`);return t.textContent=e,t.innerHTML},extractReadableErrorMessage(e,t){if(!e||typeof e!=`string`)return t;var n=e.trim();if(!n)return t;if(n.startsWith(`{`)||n.startsWith(`[`))try{var r=JSON.parse(n),i=r?.error||r?.message||r?.title||r?.detail;return typeof i==`string`&&i.trim()?i.trim():t}catch{return t}return/<[^>]+>/.test(n)?t:n},normalizeAssistantAppearance(e){if(!e)return null;var t=typeof e.label==`string`?e.label.trim():``,n=typeof e.icon==`string`?e.icon.trim():``,r=typeof e.cssClass==`string`?e.cssClass.trim():``,i=!!e.disableStreamingAnimation;return!t&&!n&&!r&&!i?null:{label:t,icon:n,cssClass:r,disableStreamingAnimation:i}},getAssistantLabel(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.label?t.label:this.assistantLabel},getAssistantRoleClasses(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null,n=[`ai-chat-msg-role`];return t&&t.cssClass?n.push(t.cssClass):n.push(`ai-chat-msg-role-assistant`),n},getAssistantIconClasses(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return[this.shouldAnimateAssistantIcon(e,t)?`ai-streaming-icon`:`ai-bot-icon`,n&&n.cssClass?n.cssClass:``]},getAssistantIcon(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.icon?t.icon:`fa fa-robot`},shouldAnimateAssistantIcon(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return!!e&&e.isStreaming&&t===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},async startConnection(){this.connection=new signalR.HubConnectionBuilder().withUrl(s.signalRHubUrl).withAutomaticReconnect().build(),this.connection.serverTimeoutInMilliseconds=6e5,this.connection.keepAliveIntervalInMilliseconds=15e3,this.connection.on(`LoadSession`,e=>{this.forceStopActiveVoice(),this.initializeSession(e.sessionId,!0),this.messages=[],this.documents=e.documents||[],this.uploadErrors=[],(e.messages??[]).forEach(e=>{this.addMessage(e),this.$nextTick(()=>{k(e)})}),this.$nextTick(()=>{this.refreshAllFeedbackIcons()}),this.messages.length===0&&s.initialPrompt&&this.addMessage({role:`assistant`,content:s.initialPrompt})}),this.connection.on(`ReceiveError`,e=>{console.error(`SignalR Error: `,e),this.isRecording&&this.stopRecording(),this.rejectPendingSessionRequest(e),this.hideTypingIndicator(),d&&typeof d.handleReceiveError==`function`?d.handleReceiveError(this,e,s):this.isNavigatingAway||this.addMessage(this.getErrorMessage(e))}),this.connection.on(`ReceiveSessionStartRejected`,e=>{this.rejectPendingSessionRequest(e),this.hideTypingIndicator(),this.isNavigatingAway||this.addMessage(this.getErrorMessage(e))}),this.connection.on(`MessageRated`,(e,t)=>{var n=this.messages.find(t=>t.id===e);n&&(n.userRating=t)}),this.connection.on(`ReceiveTranscript`,(e,t,n)=>{if(this.isConversationMode){if(!n&&t){this._conversationPartialTranscript=t;var r=`<p class="ai-partial-transcript">`+t.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)+`</p>`;this._conversationPartialMessage?(this._conversationPartialMessage.content=t,this._conversationPartialMessage.htmlContent=r):(this.hidePlaceholder(),this._conversationPartialMessage={role:`user`,content:t,htmlContent:r,isPartial:!0},this.messages.push(this._conversationPartialMessage)),this.scrollToBottom()}}else t&&!this._audioInputSent&&(this.prompt=this.preRecordingPrompt+t,this.inputElement&&(this.inputElement.value=this.prompt,this.inputElement.dispatchEvent(new Event(`input`))))}),this.connection.on(`ReceiveConversationUserMessage`,(e,t,n)=>{if(e&&this.getSessionId()!==e&&this.initializeSession(e),t&&this._realtimePendingTurns&&this._realtimePendingTurns[t]){var r=this._realtimePendingTurns[t];delete this._realtimePendingTurns[t],this.stopAudio(),this.fillRealtimePendingTurn(r,n)}else if(n){if(this.stopAudio(),this._conversationPartialMessage){var i=n.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`);this._conversationPartialMessage.content=n,this._conversationPartialMessage.htmlContent=`<p>`+i+`</p>`,this._conversationPartialMessage.isPartial=!1,this._conversationPartialMessage=null}else if(this._conversationAssistantMessage){var a=this._conversationAssistantMessage.index,o={role:`user`,content:n,rawContent:n,userRating:null,references:{}};b(o,o.references),this.messages.splice(a,0,o),this._conversationAssistantMessage.index=a+1}else this.addMessage({role:`user`,content:n});this.scrollToBottom()}}),this.connection.on(`ReceiveConversationAssistantToken`,(e,t,n,r,i,a)=>{if(this._conversationAssistantMessage&&this._conversationAssistantResponseId&&r&&this._conversationAssistantResponseId!==r){var o=this.messages[this._conversationAssistantMessage.index];o&&(o.isStreaming=!1),this._conversationAssistantMessage=null}if(!this._conversationAssistantMessage){this.stopAudio(),this.hideTypingIndicator();for(var s=0;s<this.messages.length;s++)this.messages[s].isStreaming&&(this.messages[s].isStreaming=!1);var l=this.messages.length,u={id:t,role:`assistant`,content:``,htmlContent:``,isStreaming:!0,userRating:null,appearance:this.normalizeAssistantAppearance(a),references:{}};this.messages.push(u),this._conversationAssistantMessage={index:l,content:``},this._conversationAssistantResponseId=r}this._conversationAssistantMessage.content+=n;var d=this.messages[this._conversationAssistantMessage.index];d&&(d.appearance||=this.normalizeAssistantAppearance(a),d.rawContent=this._conversationAssistantMessage.content,d.references=c(Object.assign({},d.references||{},i||{})),b(d,d.references),this.$nextTick(()=>{k(d),this.scrollToBottom()}))}),this.connection.on(`ReceiveConversationAssistantComplete`,(e,t,n)=>{if(this._conversationAssistantMessage){var r=this.messages[this._conversationAssistantMessage.index];r&&(r.isStreaming=!1,r.references=c(Object.assign({},r.references||{},n||{})),b(r,r.references)),this._conversationAssistantMessage=null,this._conversationAssistantResponseId=null}}),this.connection.on(`ReceiveAudioChunk`,(e,t,n)=>{if(!t)return;let r=atob(t),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);n===`audio/pcm`?this.realtimeController&&this.realtimeController.receivePcm(i):this.audioChunks.push(i)}),this.connection.on(`ReceiveAudioComplete`,e=>{this.playCollectedAudio()}),this.connection.on(`ReceiveNotification`,e=>{this.receiveNotification(e)}),this.connection.on(`UpdateNotification`,e=>{this.updateNotification(e)}),this.connection.on(`RemoveNotification`,e=>{this.removeNotification(e)}),this.connection.onreconnecting(()=>{console.warn(`SignalR: reconnecting...`),this.realtimeEnabled&&this.isConversationMode&&this.stopRealtimeConversation()}),this.connection.onreconnected(()=>{console.info(`SignalR: reconnected.`),this.isSessionStarted&&this.reloadCurrentSession()}),this.connection.onclose(e=>{this.isNavigatingAway||(this.realtimeEnabled&&this.isConversationMode&&this.stopRealtimeConversation(),e&&console.warn(`SignalR connection closed with error:`,e.message||e))});try{await this.connection.start()}catch(e){console.error(`SignalR Connection Error: `,e)}},async ensureConnectionStarted(){if(!this.connection)return!1;var e=signalR.HubConnectionState;if(this.connection.state===e.Connected)return!0;if(this.connection.state===e.Disconnected){try{await this.connection.start()}catch(e){console.error(`SignalR Connection Error: `,e)}return this.connection.state===e.Connected}return await new Promise(t=>{var n=e=>{clearTimeout(r),clearInterval(i),t(e)},r=setTimeout(()=>n(this.connection.state===e.Connected),1e4),i=setInterval(()=>{this.connection.state===e.Connected?n(!0):this.connection.state===e.Disconnected&&n(!1)},100)})},addMessageInternal(e){e.role===`assistant`&&(e.appearance=this.normalizeAssistantAppearance(e.appearance)),e.content&&!e.htmlContent&&(e.htmlContent=M(e.content,e)),this.fireEvent(new CustomEvent(`addingCoreAIPromotMessage`,{detail:{message:e}})),this.messages.push(e),this.$nextTick(()=>{this.fireEvent(new CustomEvent(`addedCoreAIPromotMessage`,{detail:{message:e}}))})},addMessage(e){e.userRating===void 0&&(e.userRating=null),e.content&&(e.rawContent=e.rawContent??e.content,b(e,e.references)),this.addMessageInternal(e),this.hidePlaceholder(),this.$nextTick(()=>{k(e),this.scrollToBottom()})},addMessages(e){for(let t=0;t<e.length;t++)this.addMessageInternal(e[t]);this.hidePlaceholder(),this.$nextTick(()=>{this.scrollToBottom()})},hidePlaceholder(){this.placeholder&&this.placeholder.classList.add(`d-none`),this.isPlaceholderVisible=!1},showPlaceholder(){this.placeholder&&this.placeholder.classList.remove(`d-none`),this.isPlaceholderVisible=!0},isOrchestratorAvailable(){return s.isOrchestratorAvailable!==!1},applyOrchestratorAvailability(){if(this.isOrchestratorAvailable())return!0;let e=s.orchestratorUnavailableMessage||`This orchestrator is not currently available.`;return this.inputElement&&(this.inputElement.disabled=!0,this.inputElement.value=``,this.inputElement.placeholder=e),this.buttonElement&&(this.buttonElement.disabled=!0),this.micButtonElement&&(this.micButtonElement.disabled=!0,this.micButtonElement.style.display=`none`),this.conversationButtonElement&&(this.conversationButtonElement.disabled=!0,this.conversationButtonElement.style.display=`none`),!1},fireEvent(e){document.dispatchEvent(e)},isIndicator(e){return e.role===`indicator`},sendMessage(){if(!this.applyOrchestratorAvailability())return;let e=this.prompt.trim();e&&(this.forceStopActiveVoice(),this.isRecording&&this.stopRecording(),this._audioInputSent=!0,this.singleResponseMode&&this.messages.splice(0,this.messages.length),this.addMessage({role:`user`,content:e}),this.streamMessage(this.getProfileId(),e,null),this.inputElement.value=``,this.prompt=``)},startRecording(){!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(e=>{this.preRecordingPrompt=this.prompt,this._audioInputSent=!1;var t=new signalR.Subject,n=this.getProfileId(),r=this.getSessionId()||``;this._sttCapture=this._createPcmCapture(e,e=>{try{t.next(e)}catch{}}),this._sttSubject=t;var i=this._sttCapture&&this._sttCapture.sampleRate||16e3,a=navigator.language||document.documentElement.lang||`en-US`;this.connection.send(`SendAudioStream`,n,r,t,`audio/pcm;rate=`+i,a),this.isRecording=!0,this.updateMicButton()}).catch(e=>{console.error(`Microphone access denied:`,e)})},stopRecording(){if(this.isRecording){if(this._stopPcmCapture(this._sttCapture),this._sttCapture=null,this._sttSubject){try{this._sttSubject.complete()}catch{}this._sttSubject=null}this.isRecording=!1,this.updateMicButton()}},_createPcmCapture(e,t){var n=window.AudioContext||window.webkitAudioContext,r;try{r=new n({sampleRate:16e3})}catch{r=new n}var i=r.sampleRate,a=r.createMediaStreamSource(e),o=r.createScriptProcessor(4096,1,1),s=this;return o.onaudioprocess=function(e){var n=e.inputBuffer.getChannelData(0),r=s._downsampleToInt16(n,i,16e3);if(r&&r.length!==0){for(var a=0,o=0;o<r.length;o++){var c=r[o]/32768;a+=c*c}for(var l=Math.sqrt(a/r.length),u=new Uint8Array(r.buffer),d=``,f=0;f<u.length;f++)d+=String.fromCharCode(u[f]);t(btoa(d),l)}},a.connect(o),o.connect(r.destination),{audioContext:r,source:a,processor:o,stream:e,sampleRate:16e3}},_stopPcmCapture(e){if(e){try{e.processor&&(e.processor.onaudioprocess=null,e.processor.disconnect())}catch{}try{e.source&&e.source.disconnect()}catch{}try{e.stream&&e.stream.getTracks().forEach(function(e){e.stop()})}catch{}try{e.audioContext&&e.audioContext.close()}catch{}}},_downsampleToInt16(e,t,n){var r,i;if(!(n<t)){var a=new Int16Array(e.length);for(i=0;i<e.length;i++)r=Math.max(-1,Math.min(1,e[i])),a[i]=r<0?r*32768:r*32767;return a}for(var o=t/n,s=Math.floor(e.length/o),c=new Int16Array(s),l=0;l<s;l++){var u=l*o,d=Math.floor(u),f=d+1<e.length?d+1:e.length-1,p=u-d;r=e[d]*(1-p)+e[f]*p,r=Math.max(-1,Math.min(1,r)),c[l]=r<0?r*32768:r*32767}return c},toggleRecording(){this.isRecording?this.stopRecording():this.startRecording()},updateMicButton(){this.micButton&&(this.isRecording?(this.micButton.classList.add(`stt-recording`),this.micButton.innerHTML=`<i class="fa-solid fa-stop"></i>`):(this.micButton.classList.remove(`stt-recording`),this.micButton.innerHTML=`<i class="fa-solid fa-microphone"></i>`))},streamMessage(e,t,n){this.stream&&=(this.stream.dispose(),null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var r=``,i={},a=null,s=this.messages.length,c=this.getSessionId();this.stream=this.connection.stream(`SendMessage`,e,t,c,n).subscribe({next:e=>{let t=this.messages[s];if(!t){e.sessionId&&!c&&this.initializeSession(e.sessionId),this.hideTypingIndicator(),s=this.messages.length;let n={id:e.messageId,role:`assistant`,title:e.title,content:``,htmlContent:``,isStreaming:!0,userRating:null};this.messages.push(n),t=n}if(e.title&&(!t.title||t.title!==e.title)&&(t.title=e.title),e.references&&typeof e.references==`object`&&Object.keys(e.references).length)for(let[t,n]of Object.entries(e.references))i[t]=o(n)??{};e.content&&(e.responseId&&a&&e.responseId!==a&&(r+=`
76
+ </span>`};let S=0,C=[];window.__chartConfigs=window.__chartConfigs||{};function w(t){return`<div class="chart-container" style="position: relative; width: 100%; max-width: 560px; min-height: 420px;"><canvas id="${t}"></canvas></div><div class="mt-2"><button type="button" class="btn btn-sm btn-outline-secondary download-chart-btn" data-chart-id="${t}" title="${e.downloadChartTitle}"><i class="fa-solid fa-download"></i> ${e.downloadChartButtonText}</button></div>`}let T=window.CoreAIChatMarkers.findChartMarker;marked.use({extensions:[{name:`chart`,level:`block`,start(e){let t=e.indexOf(`[chart:`);return t>=0?t:void 0},tokenizer(e){let t=T(e);if(!t||t.startIndex!==0)return;let n=`chat_chart_${++S}`;return{type:`chart`,raw:e.substring(0,t.endIndex),chartId:n,json:t.json}},renderer(e){return C.push({chartId:e.chartId,config:e.json}),window.__chartConfigs[e.chartId]=e.json,w(e.chartId)}}]});function E(){typeof document<`u`&&typeof requestAnimationFrame==`function`&&(requestAnimationFrame(O),requestAnimationFrame(D))}function D(){if(typeof mediumZoom!=`function`)return;let e=document.querySelectorAll(`.generated-image-container img:not([data-zoom-wired])`);if(e.length!==0){for(let t of e)t.setAttribute(`data-zoom-wired`,`true`);mediumZoom(e,{margin:16,background:`rgba(15, 15, 15, 0.92)`})}}function O(){let e=document.querySelectorAll(`.generated-image-container img:not([data-broken-wired])`);for(let t of e)t.setAttribute(`data-broken-wired`,`true`),t.addEventListener(`error`,function(){let e=t.closest(`.generated-image-container`);if(!e||e.dataset.brokenHandled)return;e.dataset.brokenHandled=`true`,e.hidden=!0;let n=document.createElement(`p`);n.className=`text-muted small fst-italic mb-2`,n.textContent=t.alt?`(the picture "${t.alt}" could not be loaded)`:`(that picture could not be loaded)`,e.insertAdjacentElement(`afterend`,n)},{once:!0})}function k(e){if(E(),!e||!e._pendingCharts||!e._pendingCharts.length)return;let t=[...e._pendingCharts];e._pendingCharts=[],requestAnimationFrame(()=>{for(let e of t)A(e.chartId,e.config)})}function A(e,t){let n=document.getElementById(e);if(!n)return!1;if(typeof Chart>`u`)return console.warn(`Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"><\/script>).`),!1;if(n.offsetParent===null)return window.__chartConfigs[e]=t,!1;try{n._chartInstance&&n._chartInstance.destroy();let r=typeof t==`string`?JSON.parse(t):t;return r.options??={},r.options.responsive=!0,r.options.maintainAspectRatio=!0,r.options.aspectRatio??=4/3,n._chartInstance=new Chart(n,r),delete window.__chartConfigs[e],!0}catch(e){return console.error(`Error creating chart:`,e),!1}}window.renderPendingCharts=function(){if(typeof Chart>`u`)return;let e=window.__chartConfigs;e&&requestAnimationFrame(()=>{for(let t of Object.keys(e))A(t,e[t])})};function j(e){return e.replace(/<table>/g,`<div class="table-responsive"><table class="table table-sm table-bordered table-striped align-middle">`).replace(/<\/table>/g,`</table></div>`)}function M(e,t){C=[];let n=j(marked.parse(e,{renderer:x}));t._pendingCharts=C.length>0?[...C]:[];let r=DOMPurify.sanitize(n,{ADD_TAGS:[`canvas`],ADD_ATTR:[`target`]});return window.CoreAIChatImageCarousel?window.CoreAIChatImageCarousel.stackAdjacentImages(r):r}function N(e){return!e||typeof e!=`object`?{}:Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function P(e,r,i){if(!e)return e;let a=n(r||`Assistant`),o=t(i),s=o?`<span class="ai-streaming-avatar"><img class="ai-chat-assistant-avatar" src="`+F(o)+`" alt="" /></span>`:`<span class="ai-streaming-icon"><i class="fa fa-robot" style="display: inline-block;"></i></span>`;return e.replace(/\{\{\s*assistantLabel\s*\}\}/g,a).replace(/\{\{\s*assistantIcon\s*\}\}/g,s)}function F(e){return n(e).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}let I=n=>{let r=N(n),s=N(r.widget),u=Object.assign({},e,r);u.widget=Object.assign({},e.widget||{},s),u.indicatorTemplate=P(u.indicatorTemplate,u.assistantLabel,u.assistantAvatarUrl);let d=!!(s.chatWidgetContainer&&s.chatWidgetStateName),f=window.coreAIChatWidgetBehavior||null;if(e=u,!u.signalRHubUrl){console.error(`The signalRHubUrl is required.`);return}if(!u.appElementSelector){console.error(`The appElementSelector is required.`);return}if(!u.chatContainerElementSelector){console.error(`The chatContainerElementSelector is required.`);return}if(!u.inputElementSelector){console.error(`The inputElementSelector is required.`);return}if(!u.sendButtonElementSelector){console.error(`The sendButtonElementSelector is required.`);return}let p={data(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isSessionStarted:!1,isPlaceholderVisible:!0,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,messages:[],notifications:[],prompt:``,documents:u.existingDocuments||[],isUploading:!1,isDocumentOperationPending:!1,documentOperationQueue:null,uploadErrors:[],isDragOver:!1,documentBar:null,metricsEnabled:!!u.metricsEnabled,userLabel:u.userLabel,assistantLabel:u.assistantLabel,assistantAvatarUrl:t(u.assistantAvatarUrl)||null,thumbsUpTitle:u.thumbsUpTitle,thumbsDownTitle:u.thumbsDownTitle,copyTitle:u.copyTitle,copiedTitle:u.copiedTitle,isRecording:!1,mediaRecorder:null,preRecordingPrompt:``,micButton:null,speechToTextEnabled:!u.realtimeEnabled&&(u.chatMode===`AudioInput`||u.chatMode===`Conversation`),textToSpeechEnabled:!u.realtimeEnabled&&u.chatMode===`Conversation`||!!u.textToSpeechEnabled,ttsVoiceName:u.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,currentAudioUrl:null,ttsButton:null,ttsPlayingMessageIndex:-1,ttsAudioCache:{},ttsInstanceId:`ai-chat-`+Math.random().toString(36).slice(2),singleResponseMode:!!u.singleResponseMode,conversationModeEnabled:u.chatMode===`Conversation`,realtimeEnabled:!!u.realtimeEnabled,realtimeWebRtcEnabled:u.realtimeWebRtcEnabled===!0&&typeof window.RTCPeerConnection==`function`,realtimeWebRtcIceServers:Array.isArray(u.realtimeWebRtcIceServers)&&u.realtimeWebRtcIceServers.length?u.realtimeWebRtcIceServers:null,realtimeVoiceName:u.realtimeVoiceName||null,conversationButton:null,realtimeHintElement:u.realtimeHintElementSelector?document.querySelector(u.realtimeHintElementSelector):null,isConversationMode:!1,notificationDismissTimers:{},pendingSessionPromise:null,pendingSessionResolver:null,pendingSessionRejector:null,pendingSessionTimeoutId:null,copiedMessageIndex:-1,copyResetTimeoutId:null,activeCopyButton:null}},computed:{lastAssistantIndex(){for(var e=this.messages.length-1;e>=0;e--)if(this.messages[e].role===`assistant`)return e;return-1}},methods:{handleBeforeUnload(){this.isNavigatingAway=!0},handleDragOver(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!0;var t=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;t&&t.classList.add(`ai-chat-drag-over`)}},handleDragLeave(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;t&&t.classList.remove(`ai-chat-drag-over`)}},handleDrop(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;t&&t.classList.remove(`ai-chat-drag-over`),e.dataTransfer&&e.dataTransfer.files&&e.dataTransfer.files.length>0&&this.uploadFiles(Array.from(e.dataTransfer.files))}},triggerFileInput(){if(u.sessionDocumentsEnabled&&!this.isDocumentOperationPending){var e=document.getElementById(`ai-chat-doc-input`);e&&e.click()}},handleFileInputChange(e){var t=e.target.files?Array.from(e.target.files):[];t&&t.length>0&&this.uploadFiles(t),e.target.value=``},queueDocumentOperation(e){var t=this,n=(this.documentOperationQueue||Promise.resolve()).catch(function(){}).then(async function(){t.isDocumentOperationPending=!0;try{return await e()}finally{t.isDocumentOperationPending=!1}});return this.documentOperationQueue=n.finally(function(){t.documentOperationQueue===n&&(t.documentOperationQueue=null)}),this.documentOperationQueue},async uploadFiles(e){if(u.uploadDocumentUrl){var t=Array.isArray(e)?e.slice():Array.from(e||[]);if(t.length!==0)return this.queueDocumentOperation(async()=>{var e=this.getSessionId(),n=this.getProfileId();if(!e)try{e=await this.ensureSessionForDocuments(n)}catch(e){console.error(`Failed to create a chat session for document upload:`,e),this.uploadErrors=[{fileName:``,error:`Could not create a chat session for the upload.`}],this.renderDocumentBar();return}if(!e)console.warn(`Cannot upload documents without a session or profile.`),this.uploadErrors=[{fileName:``,error:`Could not create a chat session for the upload.`}],this.renderDocumentBar();else{this.isUploading=!0,this.uploadErrors=[],this.renderDocumentBar();try{var r=new FormData;r.append(`sessionId`,e);for(var i=0;i<t.length;i++)r.append(`files`,t[i]);var a=await fetch(u.uploadDocumentUrl,{method:`POST`,body:r});if(!a.ok){var o=await a.text(),s=this.extractReadableErrorMessage(o,`Upload failed. Please try again.`);console.error(`Upload failed:`,o),this.uploadErrors=[{fileName:``,error:s}];return}var c=await l(a,`Upload failed. Please try again.`);if(!c.ok){console.error(`Upload failed: response was not JSON.`,{status:a.status,redirected:a.redirected}),this.uploadErrors=[{fileName:``,error:c.message}];return}var d=c.data;d.sessionId&&d.sessionId!==this.getSessionId()&&this.initializeSession(d.sessionId),Array.isArray(d.documents)?this.documents=d.documents:d.uploaded&&d.uploaded.length>0&&(this.documents=this.documents.concat(d.uploaded)),d.failed&&d.failed.length>0&&(this.uploadErrors=d.failed)}catch(e){console.error(`Upload error:`,e),this.uploadErrors=[{fileName:``,error:`Upload failed. Please try again.`}],this.getSessionId()&&this.reloadCurrentSession()}finally{this.isUploading=!1,this.renderDocumentBar()}}})}},async removeDocument(e){if(u.removeDocumentUrl)return this.queueDocumentOperation(async()=>{try{var t=this.getSessionId(),n=await fetch(u.removeDocumentUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({itemId:t,documentId:e.documentId})});if(n.ok){var r=await l(n,`The request could not be completed.`);if(!r.ok){console.error(`Response was not JSON.`,{status:n.status,redirected:n.redirected});return}var i=r.data;if(Array.isArray(i.documents))this.documents=i.documents;else{var a=this.documents.indexOf(e);a>-1&&this.documents.splice(a,1)}}else{var o=await n.text(),s=this.extractReadableErrorMessage(o,`Failed to remove document. Please try again.`);console.error(`Failed to remove document:`,n.status,o),this.uploadErrors=[{fileName:e.fileName||``,error:s}],t&&this.reloadCurrentSession(),this.renderDocumentBar()}}catch(t){console.error(`Remove document error:`,t),this.uploadErrors=[{fileName:e.fileName||``,error:`Failed to remove document. Please try again.`}],this.getSessionId()&&this.reloadCurrentSession(),this.renderDocumentBar()}})},formatFileSize(e){return e<1024?e+` B`:e<1048576?(e/1024).toFixed(1)+` KB`:(e/1048576).toFixed(1)+` MB`},renderDocumentBar(){if(this.documentBar){if(!u.sessionDocumentsEnabled)this.documentBar.classList.add(`d-none`);else{this.documentBar.classList.remove(`d-none`);var e=`<div class="ai-chat-doc-bar p-2">`;e+=`<div class="d-flex flex-wrap align-items-center gap-1">`;for(var t=0;t<this.documents.length;t++){var n=this.documents[t],r=n.fileName||`Document`;r.length>20&&(r=r.substring(0,17)+`...`),e+=`<span class="badge bg-secondary bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="`+this.escapeHtml(n.fileName||``)+`">`,e+=`<i class="fa-solid fa-file-lines" style="font-size: 0.7rem;"></i> `,e+=this.escapeHtml(r),e+=` <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-doc-index="`+t+`" aria-label="Remove"`+(this.isDocumentOperationPending?` disabled`:``)+`></button>`,e+=`</span>`}for(var i=0;i<this.uploadErrors.length;i++){var a=this.uploadErrors[i],o=a.error||`Upload failed`;e+=`<span class="alert alert-danger d-flex align-items-start gap-2 w-100 mb-1 py-1 px-2" role="alert" style="font-size: 0.8rem;">`,e+=`<i class="fa-solid fa-circle-exclamation mt-1" style="font-size: 0.7rem;"></i>`,e+=`<span class="flex-grow-1">`,a.fileName&&(e+=`<strong>`+this.escapeHtml(a.fileName)+`</strong>: `),e+=this.escapeHtml(o),e+=`</span>`,e+=`<button type="button" class="btn-close btn-close-sm" style="font-size: 0.5rem;" data-error-index="`+i+`" aria-label="Dismiss"></button>`,e+=`</span>`}this.isUploading&&(e+=`<span class="badge bg-info bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;">`,e+=`<span class="spinner-border spinner-border-sm" style="width: 0.7rem; height: 0.7rem;"></span> Uploading...`,e+=`</span>`),e+=`<button type="button" class="btn btn-sm btn-outline-secondary rounded-pill ai-chat-doc-add-btn d-inline-flex align-items-center gap-1" style="font-size: 0.75rem; padding: 0.15rem 0.5rem;" title="Attach documents"`+(this.isDocumentOperationPending?` disabled`:``)+`>`,e+=`<i class="fa-solid fa-paperclip"></i>`,this.documents.length===0&&!this.isUploading&&(e+=` <span>Attach files</span>`),e+=`</button>`,e+=`</div>`,u.supportedExtensionsText&&(e+=`<div class="small text-muted mt-2">Supported formats: `+this.escapeHtml(u.supportedExtensionsText)+`</div>`),e+=`</div>`,this.documentBar.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}));for(var s=this,c=this.documentBar.querySelectorAll(`[data-doc-index]`),l=0;l<c.length;l++)c[l].addEventListener(`click`,(function(e){return function(t){if(t.preventDefault(),t.stopPropagation(),!s.isDocumentOperationPending){var n=s.documents[e];n&&s.removeDocument(n)}}})(parseInt(c[l].getAttribute(`data-doc-index`))));for(var d=this.documentBar.querySelectorAll(`[data-error-index]`),f=0;f<d.length;f++)d[f].addEventListener(`click`,(function(e){return function(t){t.preventDefault(),t.stopPropagation(),s.uploadErrors.splice(e,1),s.renderDocumentBar()}})(parseInt(d[f].getAttribute(`data-error-index`))));var p=this.documentBar.querySelector(`.ai-chat-doc-add-btn`);p&&p.addEventListener(`click`,function(e){e.preventDefault(),!s.isDocumentOperationPending&&s.triggerFileInput()})}}},escapeHtml(e){var t=document.createElement(`div`);return t.textContent=e,t.innerHTML},extractReadableErrorMessage(e,t){if(!e||typeof e!=`string`)return t;var n=e.trim();if(!n)return t;if(n.startsWith(`{`)||n.startsWith(`[`))try{var r=JSON.parse(n),i=r?.error||r?.message||r?.title||r?.detail;return typeof i==`string`&&i.trim()?i.trim():t}catch{return t}return/<[^>]+>/.test(n)?t:n},normalizeAssistantAppearance(e){if(!e)return null;var t=typeof e.label==`string`?e.label.trim():``,n=typeof e.icon==`string`?e.icon.trim():``,r=typeof e.cssClass==`string`?e.cssClass.trim():``,i=!!e.disableStreamingAnimation;return!t&&!n&&!r&&!i?null:{label:t,icon:n,cssClass:r,disableStreamingAnimation:i}},getAssistantLabel(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.label?t.label:this.assistantLabel},getAssistantRoleClasses(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null,n=[`ai-chat-msg-role`];return t&&t.cssClass?n.push(t.cssClass):n.push(`ai-chat-msg-role-assistant`),n},getAssistantIconClasses(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return this.getAssistantAvatarUrl(e)?[this.shouldAnimateAssistantIcon(e,t)?`ai-streaming-avatar`:`ai-bot-avatar`]:[this.shouldAnimateAssistantIcon(e,t)?`ai-streaming-icon`:`ai-bot-icon`,n&&n.cssClass?n.cssClass:``]},getAssistantAvatarUrl(e){return!this.assistantAvatarUrl||e&&this.normalizeAssistantAppearance(e.appearance)?null:this.assistantAvatarUrl},getAssistantIcon(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.icon?t.icon:`fa fa-robot`},shouldAnimateAssistantIcon(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return!!e&&e.isStreaming&&t===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},async startConnection(){this.connection=new signalR.HubConnectionBuilder().withUrl(u.signalRHubUrl).withAutomaticReconnect().build(),this.connection.serverTimeoutInMilliseconds=6e5,this.connection.keepAliveIntervalInMilliseconds=15e3,this.connection.on(`LoadSession`,e=>{this.forceStopActiveVoice(),this.initializeSession(e.sessionId,!0),this.messages=[],this.documents=e.documents||[],this.uploadErrors=[],(e.messages??[]).forEach(e=>{this.addMessage(e),this.$nextTick(()=>{k(e)})}),this.$nextTick(()=>{this.refreshAllFeedbackIcons()}),this.messages.length===0&&u.initialPrompt&&this.addMessage({role:`assistant`,content:u.initialPrompt})}),this.connection.on(`ReceiveError`,e=>{console.error(`SignalR Error: `,e),this.isRecording&&this.stopRecording(),this.rejectPendingSessionRequest(e),this.hideTypingIndicator(),f&&typeof f.handleReceiveError==`function`?f.handleReceiveError(this,e,u):this.isNavigatingAway||this.addMessage(this.getErrorMessage(e))}),this.connection.on(`ReceiveSessionStartRejected`,e=>{this.rejectPendingSessionRequest(e),this.hideTypingIndicator(),this.isNavigatingAway||this.addMessage(this.getErrorMessage(e))}),this.connection.on(`MessageRated`,(e,t)=>{var n=this.messages.find(t=>t.id===e);n&&(n.userRating=t)}),this.connection.on(`ReceiveTranscript`,(e,t,n)=>{if(this.isConversationMode){if(!n&&t){this._conversationPartialTranscript=t;var r=`<p class="ai-partial-transcript">`+t.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)+`</p>`;this._conversationPartialMessage?(this._conversationPartialMessage.content=t,this._conversationPartialMessage.htmlContent=r):(this.hidePlaceholder(),this._conversationPartialMessage={role:`user`,content:t,htmlContent:r,isPartial:!0},this.messages.push(this._conversationPartialMessage)),this.scrollToBottom()}}else t&&!this._audioInputSent&&(this.prompt=this.preRecordingPrompt+t,this.inputElement&&(this.inputElement.value=this.prompt,this.inputElement.dispatchEvent(new Event(`input`))))}),this.connection.on(`ReceiveConversationUserMessage`,(e,t,n)=>{if(e&&this.getSessionId()!==e&&this.initializeSession(e),t&&this._realtimePendingTurns&&this._realtimePendingTurns[t]){var r=this._realtimePendingTurns[t];delete this._realtimePendingTurns[t],this.stopAudio(),this.fillRealtimePendingTurn(r,n)}else if(n){if(this.stopAudio(),this._conversationPartialMessage){var i=n.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`);this._conversationPartialMessage.content=n,this._conversationPartialMessage.htmlContent=`<p>`+i+`</p>`,this._conversationPartialMessage.isPartial=!1,this._conversationPartialMessage=null}else if(this._conversationAssistantMessage){var a=this._conversationAssistantMessage.index,o={role:`user`,content:n,rawContent:n,userRating:null,references:{}};b(o,o.references),this.messages.splice(a,0,o),this._conversationAssistantMessage.index=a+1}else this.addMessage({role:`user`,content:n});this.scrollToBottom()}}),this.connection.on(`ReceiveConversationAssistantToken`,(e,t,n,r,i,a)=>{if(this._conversationAssistantMessage&&this._conversationAssistantResponseId&&r&&this._conversationAssistantResponseId!==r){var o=this.messages[this._conversationAssistantMessage.index];o&&(o.isStreaming=!1),this._conversationAssistantMessage=null}if(!this._conversationAssistantMessage){this.stopAudio(),this.hideTypingIndicator();for(var s=0;s<this.messages.length;s++)this.messages[s].isStreaming&&(this.messages[s].isStreaming=!1);var l=this.messages.length,u={id:t,role:`assistant`,content:``,htmlContent:``,isStreaming:!0,userRating:null,appearance:this.normalizeAssistantAppearance(a),references:{}};this.messages.push(u),this._conversationAssistantMessage={index:l,content:``},this._conversationAssistantResponseId=r}this._conversationAssistantMessage.content+=n;var d=this.messages[this._conversationAssistantMessage.index];d&&(d.appearance||=this.normalizeAssistantAppearance(a),d.rawContent=this._conversationAssistantMessage.content,d.references=c(Object.assign({},d.references||{},i||{})),b(d,d.references),this.$nextTick(()=>{k(d),this.scrollToBottom()}))}),this.connection.on(`ReceiveConversationAssistantComplete`,(e,t,n)=>{if(this._conversationAssistantMessage){var r=this.messages[this._conversationAssistantMessage.index];r&&(r.isStreaming=!1,r.references=c(Object.assign({},r.references||{},n||{})),b(r,r.references)),this._conversationAssistantMessage=null,this._conversationAssistantResponseId=null}}),this.connection.on(`ReceiveAudioChunk`,(e,t,n)=>{if(!t)return;let r=atob(t),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);n===`audio/pcm`?this.realtimeController&&this.realtimeController.receivePcm(i):this.audioChunks.push(i)}),this.connection.on(`ReceiveAudioComplete`,()=>{this.playCollectedAudio()}),this.connection.on(`ReceiveNotification`,e=>{this.receiveNotification(e)}),this.connection.on(`UpdateNotification`,e=>{this.updateNotification(e)}),this.connection.on(`RemoveNotification`,e=>{this.removeNotification(e)}),this.connection.onreconnecting(()=>{console.warn(`SignalR: reconnecting...`),this.realtimeEnabled&&this.isConversationMode&&this.stopRealtimeConversation()}),this.connection.onreconnected(()=>{console.info(`SignalR: reconnected.`),this.isSessionStarted&&this.reloadCurrentSession()}),this.connection.onclose(e=>{this.isNavigatingAway||(this.realtimeEnabled&&this.isConversationMode&&this.stopRealtimeConversation(),e&&console.warn(`SignalR connection closed with error:`,e.message||e))});try{await this.connection.start()}catch(e){console.error(`SignalR Connection Error: `,e)}},async ensureConnectionStarted(){if(!this.connection)return!1;var e=signalR.HubConnectionState;if(this.connection.state===e.Connected)return!0;if(this.connection.state===e.Disconnected){try{await this.connection.start()}catch(e){console.error(`SignalR Connection Error: `,e)}return this.connection.state===e.Connected}return await new Promise(t=>{var n=e=>{clearTimeout(r),clearInterval(i),t(e)},r=setTimeout(()=>n(this.connection.state===e.Connected),1e4),i=setInterval(()=>{this.connection.state===e.Connected?n(!0):this.connection.state===e.Disconnected&&n(!1)},100)})},addMessageInternal(e){e.role===`assistant`&&(e.appearance=this.normalizeAssistantAppearance(e.appearance)),e.content&&!e.htmlContent&&(e.htmlContent=M(e.content,e)),this.fireEvent(new CustomEvent(`addingCoreAIPromotMessage`,{detail:{message:e}})),this.messages.push(e),this.$nextTick(()=>{this.fireEvent(new CustomEvent(`addedCoreAIPromotMessage`,{detail:{message:e}}))})},addMessage(e){e.userRating===void 0&&(e.userRating=null),e.content&&(e.rawContent=e.rawContent??e.content,b(e,e.references)),this.addMessageInternal(e),this.hidePlaceholder(),this.$nextTick(()=>{k(e),this.scrollToBottom()})},addMessages(e){for(let t=0;t<e.length;t++)this.addMessageInternal(e[t]);this.hidePlaceholder(),this.$nextTick(()=>{this.scrollToBottom()})},hidePlaceholder(){this.placeholder&&this.placeholder.classList.add(`d-none`),this.isPlaceholderVisible=!1},showPlaceholder(){this.placeholder&&this.placeholder.classList.remove(`d-none`),this.isPlaceholderVisible=!0},isOrchestratorAvailable(){return u.isOrchestratorAvailable!==!1},applyOrchestratorAvailability(){if(this.isOrchestratorAvailable())return!0;let e=u.orchestratorUnavailableMessage||`This orchestrator is not currently available.`;return this.inputElement&&(this.inputElement.disabled=!0,this.inputElement.value=``,this.inputElement.placeholder=e),this.buttonElement&&(this.buttonElement.disabled=!0),this.micButtonElement&&(this.micButtonElement.disabled=!0,this.micButtonElement.style.display=`none`),this.conversationButtonElement&&(this.conversationButtonElement.disabled=!0,this.conversationButtonElement.style.display=`none`),!1},fireEvent(e){document.dispatchEvent(e)},isIndicator(e){return e.role===`indicator`},sendMessage(){if(!this.applyOrchestratorAvailability())return;let e=this.prompt.trim();e&&(this.forceStopActiveVoice(),this.isRecording&&this.stopRecording(),this._audioInputSent=!0,this.singleResponseMode&&this.messages.splice(0,this.messages.length),this.addMessage({role:`user`,content:e}),this.streamMessage(this.getProfileId(),e,null),this.inputElement.value=``,this.prompt=``)},startRecording(){!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(e=>{this.preRecordingPrompt=this.prompt,this._audioInputSent=!1;var t=new signalR.Subject,n=this.getProfileId(),r=this.getSessionId()||``;this._sttCapture=this._createPcmCapture(e,e=>{try{t.next(e)}catch{}}),this._sttSubject=t;var i=this._sttCapture&&this._sttCapture.sampleRate||16e3,a=navigator.language||document.documentElement.lang||`en-US`;this.connection.send(`SendAudioStream`,n,r,t,`audio/pcm;rate=`+i,a),this.isRecording=!0,this.updateMicButton()}).catch(e=>{console.error(`Microphone access denied:`,e)})},stopRecording(){if(this.isRecording){if(this._stopPcmCapture(this._sttCapture),this._sttCapture=null,this._sttSubject){try{this._sttSubject.complete()}catch{}this._sttSubject=null}this.isRecording=!1,this.updateMicButton()}},_createPcmCapture(e,t){var n=window.AudioContext||window.webkitAudioContext,r;try{r=new n({sampleRate:16e3})}catch{r=new n}var i=r.sampleRate,a=r.createMediaStreamSource(e),o=r.createScriptProcessor(4096,1,1),s=this;return o.onaudioprocess=function(e){var n=e.inputBuffer.getChannelData(0),r=s._downsampleToInt16(n,i,16e3);if(r&&r.length!==0){for(var a=0,o=0;o<r.length;o++){var c=r[o]/32768;a+=c*c}for(var l=Math.sqrt(a/r.length),u=new Uint8Array(r.buffer),d=``,f=0;f<u.length;f++)d+=String.fromCharCode(u[f]);t(btoa(d),l)}},a.connect(o),o.connect(r.destination),{audioContext:r,source:a,processor:o,stream:e,sampleRate:16e3}},_stopPcmCapture(e){if(e){try{e.processor&&(e.processor.onaudioprocess=null,e.processor.disconnect())}catch{}try{e.source&&e.source.disconnect()}catch{}try{e.stream&&e.stream.getTracks().forEach(function(e){e.stop()})}catch{}try{e.audioContext&&e.audioContext.close()}catch{}}},_downsampleToInt16(e,t,n){var r,i;if(!(n<t)){var a=new Int16Array(e.length);for(i=0;i<e.length;i++)r=Math.max(-1,Math.min(1,e[i])),a[i]=r<0?r*32768:r*32767;return a}for(var o=t/n,s=Math.floor(e.length/o),c=new Int16Array(s),l=0;l<s;l++){var u=l*o,d=Math.floor(u),f=d+1<e.length?d+1:e.length-1,p=u-d;r=e[d]*(1-p)+e[f]*p,r=Math.max(-1,Math.min(1,r)),c[l]=r<0?r*32768:r*32767}return c},toggleRecording(){this.isRecording?this.stopRecording():this.startRecording()},updateMicButton(){this.micButton&&(this.isRecording?(this.micButton.classList.add(`stt-recording`),this.micButton.innerHTML=`<i class="fa-solid fa-stop"></i>`):(this.micButton.classList.remove(`stt-recording`),this.micButton.innerHTML=`<i class="fa-solid fa-microphone"></i>`))},streamMessage(e,t,n){this.stream&&=(this.stream.dispose(),null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var r=``,i={},a=null,s=this.messages.length,c=this.getSessionId();this.stream=this.connection.stream(`SendMessage`,e,t,c,n).subscribe({next:e=>{let t=this.messages[s];if(!t){e.sessionId&&!c&&this.initializeSession(e.sessionId),this.hideTypingIndicator(),s=this.messages.length;let n={id:e.messageId,role:`assistant`,title:e.title,content:``,htmlContent:``,isStreaming:!0,userRating:null};this.messages.push(n),t=n}if(e.title&&(!t.title||t.title!==e.title)&&(t.title=e.title),e.references&&typeof e.references==`object`&&Object.keys(e.references).length)for(let[t,n]of Object.entries(e.references))i[t]=o(n)??{};e.content&&(e.responseId&&a&&e.responseId!==a&&(r+=`
77
77
 
78
- `),e.responseId&&(a=e.responseId),r+=e.content),t.rawContent=r,b(t,i),this.messages[s]=t,this.$nextTick(()=>{k(t),this.scrollToBottom()})},complete:()=>{this.processReferences(i,s),this.streamingFinished();let e=this.messages[s];e&&(e.isStreaming=!1),(!e||!e.content)&&this.hideTypingIndicator(),this.isConversationMode&&this.textToSpeechEnabled&&e&&e.content&&this.synthesizeSpeech(e.content),this.stream?.dispose(),this.stream=null},error:e=>{this.processReferences(i,s),this.streamingFinished();let t=this.messages[s];t&&(t.isStreaming=!1),this.hideTypingIndicator(),this.isNavigatingAway||this.addMessage(this.getServiceDownMessage()),this.stream?.dispose(),this.stream=null,console.error(`Stream error:`,e)}})},getServiceDownMessage(){return{role:`assistant`,content:`Our service is currently unavailable. Please try again later. We apologize for the inconvenience.`,htmlContent:``}},getErrorMessage(e){return{role:`assistant`,content:typeof e==`string`&&e.trim()?e:`Something went wrong. Please try again.`,htmlContent:``}},processReferences(e,t){if(e=c(e),Object.keys(e).length){let n=this.messages[t];n.rawContent=n.rawContent??n.content??``,b(n,e),this.messages[t]=n,this.$nextTick(()=>{k(n),this.scrollToBottom()})}},streamingStarted(){var e=this.buttonElement.getAttribute(`data-stop-icon`);e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&this.inputElement.setAttribute(`disabled`,`disabled`)},streamingFinished(){var e=this.buttonElement.getAttribute(`data-start-icon`);if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&(this.inputElement.removeAttribute(`disabled`),this.inputElement.focus()),this.chatContainer)for(var t=this.chatContainer.querySelectorAll(`.ai-streaming-icon`),n=0;n<t.length;n++)t[n].classList.remove(`ai-streaming-icon`),t[n].classList.add(`ai-bot-icon`);for(var n=0;n<this.messages.length;n++)this.messages[n].isStreaming&&(this.messages[n].isStreaming=!1)},handleExternalTtsStop(e){e?.detail?.sourceId!==this.ttsInstanceId&&this.stopAudio(!1)},updateTtsPlaybackButtons(){this.chatContainer&&this.chatContainer.querySelectorAll(`[data-tts-message-index]`).forEach(e=>{var t=Number(e.getAttribute(`data-tts-message-index`))===this.ttsPlayingMessageIndex;e.classList.toggle(`tts-playing`,t),e.setAttribute(`title`,t?`Pause audio`:`Read aloud`)})},updateCopyButtons(){this.chatContainer&&this.chatContainer.querySelectorAll(`[data-copy-message-index]`).forEach(e=>{var t=Number(e.getAttribute(`data-copy-message-index`))===this.copiedMessageIndex,n=t?`<i class="fa-solid fa-check"></i>`:`<i class="fa-solid fa-copy"></i>`;e.classList.toggle(`text-success`,t),e.classList.toggle(`text-secondary`,!t),e.setAttribute(`title`,t?this.copiedTitle:this.copyTitle),e.replaceChildren(DOMPurify.sanitize(n,{RETURN_DOM_FRAGMENT:!0}))})},setCopyButtonState(e,t){if(e){var n=t?`<i class="fa-solid fa-check"></i>`:`<i class="fa-solid fa-copy"></i>`;e.classList.toggle(`text-success`,t),e.classList.toggle(`text-secondary`,!t),e.setAttribute(`title`,t?this.copiedTitle:this.copyTitle),e.replaceChildren(DOMPurify.sanitize(n,{RETURN_DOM_FRAGMENT:!0}))}},synthesizeSpeech(e,t){this.textToSpeechEnabled&&e&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this._ttsCacheIndex=t===void 0?-1:t,this.connection.invoke(`SynthesizeSpeech`,this.getProfileId(),this.getSessionId(),e,this.ttsVoiceName).catch(e=>{console.error(`TTS synthesis error:`,e),this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this._ttsCacheIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons())}))},toggleMessageTts(e,t){this.ttsPlayingMessageIndex===t?this.stopAudio():(this.stopAudio(!1),window.dispatchEvent(new CustomEvent(`crestapps-ai-chat-stop-tts`,{detail:{sourceId:this.ttsInstanceId}})),this.ttsPlayingMessageIndex=t,this.$nextTick(()=>this.updateTtsPlaybackButtons()),this.ttsAudioCache[t]?this.playAudioBlob(this.ttsAudioCache[t]):this.synthesizeSpeech(e.content,t))},playCollectedAudio(){if(this.audioChunks.length===0){!this.currentAudioElement&&this.audioPlayQueue.length===0&&(this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons()));return}let e=this.audioChunks.reduce((e,t)=>e+t.length,0),t=new Uint8Array(e),n=0;for(let e of this.audioChunks)t.set(e,n),n+=e.length;this.audioChunks=[];let r=new Blob([t],{type:`audio/mp3`});this._ttsCacheIndex>=0&&(this.ttsAudioCache[this._ttsCacheIndex]=r,this._ttsCacheIndex=-1),this.currentAudioElement?this.audioPlayQueue.push(r):this.playAudioBlob(r)},playAudioBlob(e){let t=URL.createObjectURL(e),n=new Audio(t);this.currentAudioUrl=t,this.currentAudioElement=n,this.isPlayingAudio=!0,n.addEventListener(`ended`,()=>{this.currentAudioElement=null,this.currentAudioUrl=null,URL.revokeObjectURL(t),this.playNextInQueue()}),n.addEventListener(`error`,()=>{this.currentAudioElement=null,this.currentAudioUrl=null,URL.revokeObjectURL(t),this.playNextInQueue()}),n.play().catch(e=>{console.error(`Audio playback error:`,e),this.currentAudioElement=null,this.currentAudioUrl=null,URL.revokeObjectURL(t),this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons())})},playNextInQueue(){if(this.audioPlayQueue.length>0){var e=this.audioPlayQueue.shift();this.playAudioBlob(e)}else this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons()),this.conversationModeOnAudioEnded()},stopAudio(){this.currentAudioElement&&=(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,null),this.currentAudioUrl&&=(URL.revokeObjectURL(this.currentAudioUrl),null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons())},voiceSettingsElement(){var e=this.conversationButton&&this.conversationButton.nextElementSibling;return e&&e.id===`realtime-audio-settings`?e:null},setVoiceSessionLive(e){this.inputElement&&(this.inputElement.hidden=e),this.buttonElement&&(this.buttonElement.hidden=e),this.conversationButton&&this.conversationButton.classList.toggle(`flex-grow-1`,e);var t=this.voiceSettingsElement();t&&(t.hidden=!e);var n=this.realtimeHintElement;n&&n.classList.toggle(`d-none`,!e)},toggleConversationMode(){this.realtimeEnabled?this.realtimeController&&this.realtimeController.toggle():this.isConversationMode?this.stopConversationMode():this.startConversationMode()},forceStopActiveVoice(){this.isConversationMode&&(this.realtimeEnabled?this.stopRealtimeConversation():this.stopConversationMode())},startRealtimeConversation(){this.realtimeController&&this.realtimeController.start()},stopRealtimeConversation(){this.realtimeController&&this.realtimeController.stop()},setupRealtimeController(e){if(!this.realtimeController&&this.conversationButton){if(!window.CoreAIRealtime||typeof window.CoreAIRealtime.attach!=`function`)console.error(`realtime-audio.js is not loaded; realtime voice is unavailable on this page.`);else{var t=this;this.realtimeController=window.CoreAIRealtime.attach({connection:this.connection,ensureConnected:function(){return t.ensureConnectionStarted().then(function(e){if(!e)throw Error(`The chat connection is not available.`);return e})},sendStart:function(e,n,r,i,a,o){t.connection.send(`StartRealtimeConversation`,t.getProfileId(),t.getSessionId()||``,e,n,r,i,a,o)},webRtcEnabled:this.realtimeWebRtcEnabled,sendStartWebRtc:function(e,n,r,i,a,o){t.connection.send(`StartRealtimeWebRtc`,t.getProfileId(),t.getSessionId()||``,e,n,r,i,a,o)},webRtcIceServers:this.realtimeWebRtcIceServers||void 0,voiceName:this.realtimeVoiceName||``,getVoiceName:function(){return t.realtimeVoiceName||``},realtimeEnabled:!0,selectors:{realtimeButton:e.conversationButtonElementSelector,micButton:e.micButtonElementSelector},onSessionStateChanged:function(e){t.setVoiceSessionLive(e)},onActivate:function(){t.isConversationMode=!0,t._conversationAssistantMessage=null,t._conversationPartialMessage=null,t.removeNotification(`conversation-ended`)},onDeactivate:function(){t.isConversationMode=!1,t.finishRealtimeConversationCleanup()},onUserTurnPending:function(e){t.addRealtimePendingTurn(e)},onUserTurnDropped:function(e){t.dropRealtimePendingTurn(e)}})}}},finishRealtimeConversationCleanup(){if(this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:`conversation-ended`,content:`Conversation ended.`,icon:`fa-solid fa-circle-check`,dismissible:!0,autoDismissMs:5e3})},addRealtimePendingTurn(e){if(e){this._realtimePendingTurns=this._realtimePendingTurns||{};var t=this.messages.length;this.addMessage({role:`user`,content:``,isPartial:!0}),this._realtimePendingTurns[e]=this.messages[t]}},fillRealtimePendingTurn(e,t){if(e){if(t){var n=t.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`);e.content=t,e.htmlContent=`<p>`+n+`</p>`,e.isPartial=!1}else{var r=this.messages.indexOf(e);r>=0&&this.messages.splice(r,1)}}},dropRealtimePendingTurn(e){if(e&&this._realtimePendingTurns){var t=this._realtimePendingTurns[e];if(t){delete this._realtimePendingTurns[e];var n=this.messages.indexOf(t);n>=0&&this.messages.splice(n,1)}}},startConversationMode(){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(e=>{this._conversationSubject=new signalR.Subject,this._conversationStream=e;var t=.12;this._conversationCapture=this._createPcmCapture(e,(e,n)=>{this.isPlayingAudio&&n>=t&&this.stopAudio();try{this._conversationSubject.next(e)}catch{}});var n=this.getProfileId(),r=this.getSessionId()||``,i=navigator.language||document.documentElement.lang||`en-US`,a=this._conversationCapture&&this._conversationCapture.sampleRate||16e3;this.connection.send(`StartConversation`,n,r,this._conversationSubject,`audio/pcm;rate=`+a,i),this.isRecording=!0}).catch(e=>{console.error(`Microphone access denied:`,e),this.isConversationMode=!1,this.updateConversationButton()}))},stopConversationMode(){if(this.isConversationMode){if(this.isConversationMode=!1,this.updateConversationButton(),this.connection&&this.connection.invoke(`StopConversation`).catch(function(){}),this.isRecording){if(this._stopPcmCapture(this._conversationCapture),this._conversationCapture=null,this._conversationSubject)try{this._conversationSubject.complete()}catch{}this.isRecording=!1}if(this.stopAudio(),this._conversationPartialTranscript=``,this._conversationPartialMessage=null,this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:`conversation-ended`,content:`Conversation ended.`,icon:`fa-solid fa-circle-check`,dismissible:!0,autoDismissMs:5e3})}},updateConversationButton(){if(this.conversationButton){if(this.isConversationMode){this.conversationButton.classList.add(`active`,`btn-primary`),this.conversationButton.classList.remove(`btn-dark`,`btn-outline-dark`,`btn-outline-secondary`),this.conversationButton.title=this.conversationButton.getAttribute(`data-end-title`)||`End Conversation`;var e=this.conversationButton.getAttribute(`data-end-html`);e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}else{this.conversationButton.classList.remove(`active`,`btn-primary`),this.conversationButton.classList.remove(`btn-dark`,`btn-outline-secondary`),this.conversationButton.classList.add(`btn-outline-dark`),this.conversationButton.blur(),this.conversationButton.title=this.conversationButton.getAttribute(`data-start-title`)||`Start Conversation`;var t=this.conversationButton.getAttribute(`data-start-html`);t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))}}},conversationModeSendPrompt(){},conversationModeOnAudioEnded(){},generatePrompt(e){if(!e){console.error(`The element paramter is required.`);return}let t=e.getAttribute(`data-profile-id`),n=this.getSessionId(),r=this.getProfileId();!t||!n?console.error(`The given element is missing data-profile-id or the session has not yet started.`):this.streamMessage(t,null,r)},createSessionUrl(e,t,n){let r=e.toLowerCase().startsWith(`http`)?e:window.location.origin+e,i=new URL(r);return i.searchParams.set(t,n),i.toString()},showTypingIndicator(){this.addMessage({role:`indicator`,htmlContent:s.indicatorTemplate})},hideTypingIndicator(){let e=this.messages.length;return this.messages=this.messages.filter(e=>e.role!==`indicator`),e-this.messages.length},receiveNotification(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(t=>t.type===e.type);t>=0?this.notifications.splice(t,1,e):this.notifications.push(e),this.scheduleNotificationDismiss(e),this.$nextTick(()=>{this.scrollToBottom()})}},updateNotification(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(t=>t.type===e.type);t>=0&&(this.notifications.splice(t,1,e),this.scheduleNotificationDismiss(e))}},scheduleNotificationDismiss(e){!e||!e.type||!e.autoDismissMs||e.autoDismissMs<=0||(this.notificationDismissTimers[e.type]=setTimeout(()=>{this.removeNotification(e.type)},e.autoDismissMs))},clearNotificationDismiss(e){var t=this.notificationDismissTimers[e];t&&(clearTimeout(t),delete this.notificationDismissTimers[e])},removeNotification(e){this.clearNotificationDismiss(e),this.notifications=this.notifications.filter(t=>t.type!==e)},dismissNotification(e){this.removeNotification(e)},handleNotificationAction(e,t){if(this.connection){var n=this.getSessionId();this.connection.invoke(`HandleNotificationAction`,n,e,t).catch(function(e){console.error(`Error handling notification action:`,e)})}},scrollToBottom(){this.autoScroll&&setTimeout(()=>{this.chatContainer.scrollTop=this.chatContainer.scrollHeight-this.chatContainer.clientHeight},50)},handleUserInput(e){this.prompt=e.target.value},getProfileId(){return this.inputElement?this.inputElement.getAttribute(`data-profile-id`):null},setSessionId(e){this.inputElement&&this.inputElement.setAttribute(`data-session-id`,e||``)},resetSession(){this.forceStopActiveVoice(),this.stopRecording(),this.rejectPendingSessionRequest(`Session was reset.`),this.setSessionId(``),this.isSessionStarted=!1,this.sessionRating=null,this.messages=[],this.documents=[],s.initialPrompt?this.addMessage({role:`assistant`,content:s.initialPrompt}):this.showPlaceholder(),d&&typeof d.onSessionReset==`function`&&d.onSessionReset(this,s)},startNewSession(){if(!this.applyOrchestratorAvailability())return;let e=this.getProfileId();e&&this.connection&&(this.forceStopActiveVoice(),this.requestNewSession(e).catch(e=>console.error(e)))},async ensureSessionForDocuments(e){return this.getSessionId()||(!e||!this.connection?null:await this.requestNewSession(e))},requestNewSession(e){return this.pendingSessionPromise?this.pendingSessionPromise:!e||!this.connection?Promise.resolve(null):(this.pendingSessionPromise=new Promise((e,t)=>{this.pendingSessionResolver=e,this.pendingSessionRejector=t,this.pendingSessionTimeoutId=window.setTimeout(()=>{this.rejectPendingSessionRequest(`Timed out while creating a chat session.`)},15e3)}),this.connection.invoke(`StartSession`,e,null).catch(e=>{this.rejectPendingSessionRequest(e)}),this.pendingSessionPromise)},resolvePendingSessionRequest(e){this.pendingSessionResolver&&this.pendingSessionResolver(e),this.clearPendingSessionRequest()},rejectPendingSessionRequest(e){this.pendingSessionRejector&&this.pendingSessionRejector(e),this.clearPendingSessionRequest()},clearPendingSessionRequest(){this.pendingSessionTimeoutId&&window.clearTimeout(this.pendingSessionTimeoutId),this.pendingSessionPromise=null,this.pendingSessionResolver=null,this.pendingSessionRejector=null,this.pendingSessionTimeoutId=null},initializeApp(){if(this.inputElement=document.querySelector(s.inputElementSelector),this.buttonElement=document.querySelector(s.sendButtonElementSelector),this.chatContainer=document.querySelector(s.chatContainerElementSelector),this.placeholder=document.querySelector(s.placeholderElementSelector),!this.inputElement||!this.buttonElement||!this.chatContainer||!this.placeholder)return console.error(`AI chat app could not initialize because one or more required elements were not found.`,{inputElementSelector:s.inputElementSelector,sendButtonElementSelector:s.sendButtonElementSelector,chatContainerElementSelector:s.chatContainerElementSelector,placeholderElementSelector:s.placeholderElementSelector}),!1;this.applyOrchestratorAvailability();let e=this.getSessionId();if(!u&&e&&this.loadSession(e),s.sessionDocumentsEnabled&&s.documentBarSelector&&(this.documentBar=document.querySelector(s.documentBarSelector),this.documentBar)){this.renderDocumentBar();var t=document.createElement(`input`);t.type=`file`,t.id=`ai-chat-doc-input`,t.className=`d-none`,t.multiple=!0,s.allowedExtensions&&(t.accept=s.allowedExtensions),t.addEventListener(`change`,e=>this.handleFileInputChange(e)),this.documentBar.parentElement.appendChild(t);var n=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;n&&(n.addEventListener(`dragover`,e=>this.handleDragOver(e)),n.addEventListener(`dragleave`,e=>this.handleDragLeave(e)),n.addEventListener(`drop`,e=>this.handleDrop(e)))}this.chatContainer.addEventListener(`scroll`,()=>{if(!this.stream)return;let e=this.chatContainer.scrollHeight-this.chatContainer.clientHeight-this.chatContainer.scrollTop<=30;this.autoScroll=e}),this.inputElement.addEventListener(`keydown`,e=>{this.stream==null&&e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.buttonElement.click())}),this.inputElement.addEventListener(`input`,e=>{this.handleUserInput(e),e.target.value.trim()?this.buttonElement.removeAttribute(`disabled`):this.buttonElement.setAttribute(`disabled`,!0)}),this.buttonElement.addEventListener(`click`,()=>{if(this.stream!=null){if(this.stream.dispose(),this.stream=null,this.streamingFinished(),this.hideTypingIndicator(),this.messages.length>0){let e=this.messages[this.messages.length-1];e.role===`assistant`&&!e.content?this.messages.pop():e.isStreaming&&=!1}}else this.sendMessage()});let r=document.getElementsByClassName(`profile-generated-prompt`);for(var i=0;i<r.length;i++)r[i].addEventListener(`click`,e=>{e.preventDefault(),this.generatePrompt(e.target)});let a=document.getElementsByClassName(`chat-session-history-item`);for(var i=0;i<a.length;i++)a[i].addEventListener(`click`,e=>{e.preventDefault();var t=e.target.getAttribute(`data-session-id`);t?(this.loadSession(t),this.showChatScreen()):console.error(`an element with the class chat-session-history-item with no data-session-id set.`)});let o=Array.isArray(s.messages)?s.messages:[];for(let e=0;e<o.length;e++)this.addMessage(o[e]);return this.messages.length===0&&s.initialPrompt&&this.addMessage({role:`assistant`,content:s.initialPrompt}),this.$nextTick(()=>{this.refreshAllFeedbackIcons()}),this.chatContainer&&this.chatContainer.addEventListener(`click`,e=>{var t=e.target.closest(`.ai-code-copy-btn`);if(t){var n=t.closest(`.ai-code-block`)||t.closest(`pre`);if(n){var r=n.querySelector(`code`);r&&(navigator.clipboard.writeText(r.textContent),t.innerHTML=`<i class="fa-solid fa-check"></i> `+(s.codeCopiedText||`Copied!`),setTimeout(()=>{t.innerHTML=`<i class="fa-regular fa-copy"></i>`},2e3))}}}),this.speechToTextEnabled&&s.micButtonElementSelector&&(this.micButton=document.querySelector(s.micButtonElementSelector),this.micButton&&(this.micButton.style.display=``,this.micButton.addEventListener(`click`,()=>{this.toggleRecording()}))),(this.conversationModeEnabled||this.realtimeEnabled)&&s.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(s.conversationButtonElementSelector),this.conversationButton&&(this.realtimeEnabled?(this.setupRealtimeController(s),this.setVoiceSessionLive(!1)):this.conversationButton.addEventListener(`click`,()=>{this.toggleConversationMode()}))),!0},loadSession(e){this.connection.invoke(`LoadSession`,e).catch(e=>console.error(e))},reloadCurrentSession(){var e=this.getSessionId();e&&this.loadSession(e)},initializeSession(e,t){if(this.isSessionStarted&&!t)e&&this.getSessionId()===e&&this.resolvePendingSessionRequest(e);else if(this.fireEvent(new CustomEvent(`initializingSessionCoreAIChat`,{detail:{sessionId:e}})),this.setSessionId(e),this.isSessionStarted=!0,this.resolvePendingSessionRequest(e),d&&typeof d.onSessionInitialized==`function`&&d.onSessionInitialized(this,e,s),!u&&e&&s.sessionUrlTemplate&&typeof history<`u`&&history.replaceState){var n=s.sessionUrlTemplate.replace(`{sessionId}`,encodeURIComponent(e));history.replaceState(null,``,n)}},getSessionId(){let e=this.inputElement?this.inputElement.getAttribute(`data-session-id`):null;return!e&&d&&typeof d.resolveSessionId==`function`&&(e=d.resolveSessionId(this,s)),e},clearCopiedMessageState(){this.copyResetTimeoutId&&=(window.clearTimeout(this.copyResetTimeoutId),null),this.activeCopyButton&&=(this.setCopyButtonState(this.activeCopyButton,!1),null),this.copiedMessageIndex=-1},copyResponse(e,t,n){let r=e&&typeof e==`object`?e.copyContent??e.content??``:e??``,i=n?.currentTarget||n?.target?.closest?.(`[data-copy-message-index]`)||null;navigator.clipboard.writeText(r).then(()=>{this.clearCopiedMessageState(),this.copiedMessageIndex=typeof t==`number`?t:-1,this.activeCopyButton=i,i?this.setCopyButtonState(i,!0):this.$nextTick(()=>this.updateCopyButtons()),this.copyResetTimeoutId=window.setTimeout(()=>{this.clearCopiedMessageState(),this.$nextTick(()=>this.updateCopyButtons())},Number(s.copyResetDelayMs)||2e3)}).catch(e=>console.error(`Failed to copy response:`,e))},updateFeedbackIcons(e,t){if(e){var n=e.querySelector(`.rate-up-btn`),r=e.querySelector(`.rate-down-btn`);if(n){var i=t===!0?`fa-solid fa-thumbs-up`:`fa-regular fa-thumbs-up`,a=document.createElement(`span`);a.className=i,a.style.fontSize=`0.9rem`,n.textContent=``,n.appendChild(a)}if(r){var o=t===!1?`fa-solid fa-thumbs-down`:`fa-regular fa-thumbs-down`,s=document.createElement(`span`);s.className=o,s.style.fontSize=`0.9rem`,r.textContent=``,r.appendChild(s)}}},refreshAllFeedbackIcons(){for(var e=this.$el.querySelectorAll(`.ai-chat-message-assistant-feedback`),t=0;t<e.length;t++){var n=e[t].getAttribute(`data-message-id`),r=this.messages.find(e=>e.id===n);r&&this.updateFeedbackIcons(e[t],r.userRating)}},rateMessage(e,t,n){var r=this.getSessionId();if(r&&e.id&&this.connection){var i=e.userRating===t?null:t;e.userRating=i;var a=this.$el.querySelector(`.ai-chat-message-assistant-feedback[data-message-id="`+e.id+`"]`);this.updateFeedbackIcons(a,i),i!==null&&a&&setTimeout(()=>{var e=t?`.rate-up-btn`:`.rate-down-btn`,n=a.querySelector(e);n&&(n.classList.remove(`spark-effect`),n.offsetWidth,n.classList.add(`spark-effect`),n.addEventListener(`animationend`,function e(){n.removeEventListener(`animationend`,e),n.classList.remove(`spark-effect`)}))},50),this.connection.invoke(`RateMessage`,r,e.id,t).catch(function(e){console.error(`Failed to rate message:`,e)})}}},watch:{documents:{handler(){this.renderDocumentBar(),d&&typeof d.onDocumentsChanged==`function`&&d.onDocumentsChanged(this,this.documents,s)},deep:!0},isUploading(){this.renderDocumentBar()},isDocumentOperationPending(){this.renderDocumentBar()},isPlayingAudio(){},copiedMessageIndex(){this.$nextTick(()=>this.updateCopyButtons())},isConversationMode(e){this.micButton&&(this.micButton.style.display=e?`none`:this.speechToTextEnabled?``:`none`),this.realtimeEnabled||this.setVoiceSessionLive(e)}},mounted(){(async()=>{await this.startConnection(),this.initializeApp()&&u&&d&&typeof d.onMounted==`function`&&d.onMounted(this,s),this.$nextTick(()=>{this.updateCopyButtons(),i(this.$el),this.fontAwesomeObserver=a(this.$el)})})(),window.addEventListener(`beforeunload`,this.handleBeforeUnload),window.addEventListener(`crestapps-ai-chat-stop-tts`,this.handleExternalTtsStop)},beforeUnmount(){window.removeEventListener(`beforeunload`,this.handleBeforeUnload),window.removeEventListener(`crestapps-ai-chat-stop-tts`,this.handleExternalTtsStop),this.fontAwesomeObserver&&=(this.fontAwesomeObserver.disconnect(),null),this.clearCopiedMessageState(),this.stopAudio(!1),this.stream&&=(this.stream.dispose(),null),this.connection&&this.connection.stop(),d&&typeof d.onBeforeUnmount==`function`&&d.onBeforeUnmount(this,s)},template:s.messageTemplate},p=Vue.createApp(f).mount(s.appElementSelector);return d&&typeof d.attach==`function`&&d.attach(p,s),p},I=`[data-coreai-chat-config],[data-coreai-chat-app-element-selector]`;function L(e,t){let n=e.getAttribute(t);return n===null||n===``?null:n}function R(e){if(e==null)return null;if(typeof e==`boolean`)return e;let t=String(e).trim().toLowerCase();return t===`true`||t!==`false`&&null}function z(e,t,n){let r=L(e,t);if(!r)return null;try{return JSON.parse(r)}catch(e){return console.error(`Failed to parse `+n+` JSON.`,e),null}}function B(e,t){let n=t||{};if(e.hasAttribute(`data-coreai-chat-widget-container-selector`)&&n.allowWidgetHost!==!0)return null;let r=L(e,`data-coreai-chat-app-element-selector`);if(!r)return null;let i={signalRHubUrl:L(e,`data-coreai-chat-signalr-hub-url`),appElementSelector:r,chatContainerElementSelector:L(e,`data-coreai-chat-container-element-selector`),inputElementSelector:L(e,`data-coreai-chat-input-element-selector`),sendButtonElementSelector:L(e,`data-coreai-chat-send-button-element-selector`),placeholderElementSelector:L(e,`data-coreai-chat-placeholder-element-selector`),messages:z(e,`data-coreai-chat-messages`,`CoreAI chat messages`)??void 0,chatMode:L(e,`data-coreai-chat-mode`),micButtonElementSelector:L(e,`data-coreai-chat-mic-button-element-selector`),conversationButtonElementSelector:L(e,`data-coreai-chat-conversation-button-element-selector`),realtimeHintElementSelector:L(e,`data-coreai-chat-realtime-hint-element-selector`),ttsVoiceName:L(e,`data-coreai-chat-tts-voice-name`),realtimeVoiceName:L(e,`data-coreai-chat-realtime-voice-name`),documentBarSelector:L(e,`data-coreai-chat-document-bar-selector`),uploadDocumentUrl:L(e,`data-coreai-chat-upload-document-url`),removeDocumentUrl:L(e,`data-coreai-chat-remove-document-url`),allowedExtensions:L(e,`data-coreai-chat-allowed-extensions`),supportedExtensionsText:L(e,`data-coreai-chat-supported-extensions-text`),existingDocuments:z(e,`data-coreai-chat-existing-documents`,`CoreAI chat existing documents`)??void 0,initialPrompt:L(e,`data-coreai-chat-initial-prompt`),sessionUrlTemplate:L(e,`data-coreai-chat-session-url-template`),userLabel:L(e,`data-coreai-chat-user-label`),assistantLabel:L(e,`data-coreai-chat-assistant-label`),copyTitle:L(e,`data-coreai-chat-copy-title`),copiedTitle:L(e,`data-coreai-chat-copied-title`)},a={metricsEnabled:`data-coreai-chat-metrics-enabled`,textToSpeechEnabled:`data-coreai-chat-text-to-speech-enabled`,sessionDocumentsEnabled:`data-coreai-chat-session-documents-enabled`,singleResponseMode:`data-coreai-chat-single-response-mode`,realtimeEnabled:`data-coreai-chat-realtime-enabled`,realtimeWebRtcEnabled:`data-coreai-chat-realtime-webrtc-enabled`};return Object.keys(a).forEach(t=>{let n=R(L(e,a[t]));n!==null&&(i[t]=n)}),N(i)}function V(e,t){let n=z(e,`data-coreai-chat-config`,`CoreAI chat config`),r=B(e,t);return!n&&!r?null:Object.assign({},n||{},r||{})}function H(e){if(!e||e.dataset.coreAiChatInitialized===`true`)return e&&e.__coreAIChatApp||null;let t=V(e);if(!t)return null;let n=F(t);return n?(e.dataset.coreAiChatInitialized=`true`,e.__coreAIChatApp=n,n):null}function U(e){e&&typeof e.querySelectorAll==`function`&&(typeof e.matches==`function`&&e.matches(I)&&H(e),e.querySelectorAll(I).forEach(H))}function W(){U(document),typeof MutationObserver<`u`&&new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e&&e.nodeType===1&&U(e)})})}).observe(document.body,{childList:!0,subtree:!0})}return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,W,{once:!0}):W(),{initialize:F,initializeFromElement:H,buildConfigFromElement:V}}(),document.addEventListener(`click`,function(e){let t=e.target.closest(`.download-chart-btn`);if(!t)return;let n=t.getAttribute(`data-chart-id`),r=n?document.getElementById(n):null;if(!r){console.error(`Chart canvas not found:`,n);return}let i=document.createElement(`a`);i.download=`chart-`+n+`.png`,i.href=r.toDataURL(`image/png`),i.click()}),document.addEventListener(`click`,function(e){let t=e.target.closest(`.ai-download-image`);if(!t)return;let n=t.closest(`.generated-image-container`)?.querySelector(`img`);if(!n)return;let r=n.src;r&&r.startsWith(`data:`)&&(e.preventDefault(),fetch(r).then(function(e){return e.blob()}).then(function(e){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t.getAttribute(`download`)||`generated-image.png`,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(e){console.error(`Failed to download image:`,e)}))})})();
78
+ `),e.responseId&&(a=e.responseId),r+=e.content),t.rawContent=r,b(t,i),this.messages[s]=t,this.$nextTick(()=>{k(t),this.scrollToBottom()})},complete:()=>{this.processReferences(i,s),this.streamingFinished();let e=this.messages[s];e&&(e.isStreaming=!1),(!e||!e.content)&&this.hideTypingIndicator(),this.isConversationMode&&this.textToSpeechEnabled&&e&&e.content&&this.synthesizeSpeech(e.content),this.stream?.dispose(),this.stream=null},error:e=>{this.processReferences(i,s),this.streamingFinished();let t=this.messages[s];t&&(t.isStreaming=!1),this.hideTypingIndicator(),this.isNavigatingAway||this.addMessage(this.getServiceDownMessage()),this.stream?.dispose(),this.stream=null,console.error(`Stream error:`,e)}})},getServiceDownMessage(){return{role:`assistant`,content:`Our service is currently unavailable. Please try again later. We apologize for the inconvenience.`,htmlContent:``}},getErrorMessage(e){return{role:`assistant`,content:typeof e==`string`&&e.trim()?e:`Something went wrong. Please try again.`,htmlContent:``}},processReferences(e,t){if(e=c(e),Object.keys(e).length){let n=this.messages[t];n.rawContent=n.rawContent??n.content??``,b(n,e),this.messages[t]=n,this.$nextTick(()=>{k(n),this.scrollToBottom()})}},streamingStarted(){var e=this.buttonElement.getAttribute(`data-stop-icon`);e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&this.inputElement.setAttribute(`disabled`,`disabled`)},streamingFinished(){var e=this.buttonElement.getAttribute(`data-start-icon`);if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&(this.inputElement.removeAttribute(`disabled`),this.inputElement.focus()),this.chatContainer)for(var t=this.chatContainer.querySelectorAll(`.ai-streaming-icon`),n=0;n<t.length;n++)t[n].classList.remove(`ai-streaming-icon`),t[n].classList.add(`ai-bot-icon`);for(n=0;n<this.messages.length;n++)this.messages[n].isStreaming&&(this.messages[n].isStreaming=!1)},handleExternalTtsStop(e){e?.detail?.sourceId!==this.ttsInstanceId&&this.stopAudio(!1)},updateTtsPlaybackButtons(){this.chatContainer&&this.chatContainer.querySelectorAll(`[data-tts-message-index]`).forEach(e=>{var t=Number(e.getAttribute(`data-tts-message-index`))===this.ttsPlayingMessageIndex;e.classList.toggle(`tts-playing`,t),e.setAttribute(`title`,t?`Pause audio`:`Read aloud`)})},updateCopyButtons(){this.chatContainer&&this.chatContainer.querySelectorAll(`[data-copy-message-index]`).forEach(e=>{var t=Number(e.getAttribute(`data-copy-message-index`))===this.copiedMessageIndex,n=t?`<i class="fa-solid fa-check"></i>`:`<i class="fa-solid fa-copy"></i>`;e.classList.toggle(`text-success`,t),e.classList.toggle(`text-secondary`,!t),e.setAttribute(`title`,t?this.copiedTitle:this.copyTitle),e.replaceChildren(DOMPurify.sanitize(n,{RETURN_DOM_FRAGMENT:!0}))})},setCopyButtonState(e,t){if(e){var n=t?`<i class="fa-solid fa-check"></i>`:`<i class="fa-solid fa-copy"></i>`;e.classList.toggle(`text-success`,t),e.classList.toggle(`text-secondary`,!t),e.setAttribute(`title`,t?this.copiedTitle:this.copyTitle),e.replaceChildren(DOMPurify.sanitize(n,{RETURN_DOM_FRAGMENT:!0}))}},synthesizeSpeech(e,t){this.textToSpeechEnabled&&e&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this._ttsCacheIndex=t===void 0?-1:t,this.connection.invoke(`SynthesizeSpeech`,this.getProfileId(),this.getSessionId(),e,this.ttsVoiceName).catch(e=>{console.error(`TTS synthesis error:`,e),this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this._ttsCacheIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons())}))},toggleMessageTts(e,t){this.ttsPlayingMessageIndex===t?this.stopAudio():(this.stopAudio(!1),window.dispatchEvent(new CustomEvent(`crestapps-ai-chat-stop-tts`,{detail:{sourceId:this.ttsInstanceId}})),this.ttsPlayingMessageIndex=t,this.$nextTick(()=>this.updateTtsPlaybackButtons()),this.ttsAudioCache[t]?this.playAudioBlob(this.ttsAudioCache[t]):this.synthesizeSpeech(e.content,t))},playCollectedAudio(){if(this.audioChunks.length===0){!this.currentAudioElement&&this.audioPlayQueue.length===0&&(this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons()));return}let e=this.audioChunks.reduce((e,t)=>e+t.length,0),t=new Uint8Array(e),n=0;for(let e of this.audioChunks)t.set(e,n),n+=e.length;this.audioChunks=[];let r=new Blob([t],{type:`audio/mp3`});this._ttsCacheIndex>=0&&(this.ttsAudioCache[this._ttsCacheIndex]=r,this._ttsCacheIndex=-1),this.currentAudioElement?this.audioPlayQueue.push(r):this.playAudioBlob(r)},playAudioBlob(e){let t=URL.createObjectURL(e),n=new Audio(t);this.currentAudioUrl=t,this.currentAudioElement=n,this.isPlayingAudio=!0,n.addEventListener(`ended`,()=>{this.currentAudioElement=null,this.currentAudioUrl=null,URL.revokeObjectURL(t),this.playNextInQueue()}),n.addEventListener(`error`,()=>{this.currentAudioElement=null,this.currentAudioUrl=null,URL.revokeObjectURL(t),this.playNextInQueue()}),n.play().catch(e=>{console.error(`Audio playback error:`,e),this.currentAudioElement=null,this.currentAudioUrl=null,URL.revokeObjectURL(t),this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons())})},playNextInQueue(){if(this.audioPlayQueue.length>0){var e=this.audioPlayQueue.shift();this.playAudioBlob(e)}else this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons()),this.conversationModeOnAudioEnded()},stopAudio(){this.currentAudioElement&&=(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,null),this.currentAudioUrl&&=(URL.revokeObjectURL(this.currentAudioUrl),null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(()=>this.updateTtsPlaybackButtons())},voiceSettingsElement(){var e=this.conversationButton&&this.conversationButton.nextElementSibling;return e&&e.id===`realtime-audio-settings`?e:null},setVoiceSessionLive(e){this.inputElement&&(this.inputElement.hidden=e),this.buttonElement&&(this.buttonElement.hidden=e),this.conversationButton&&this.conversationButton.classList.toggle(`flex-grow-1`,e);var t=this.voiceSettingsElement();t&&(t.hidden=!e);var n=this.realtimeHintElement;n&&n.classList.toggle(`d-none`,!e)},toggleConversationMode(){this.realtimeEnabled?this.realtimeController&&this.realtimeController.toggle():this.isConversationMode?this.stopConversationMode():this.startConversationMode()},forceStopActiveVoice(){this.isConversationMode&&(this.realtimeEnabled?this.stopRealtimeConversation():this.stopConversationMode())},startRealtimeConversation(){this.realtimeController&&this.realtimeController.start()},stopRealtimeConversation(){this.realtimeController&&this.realtimeController.stop()},setupRealtimeController(e){if(!this.realtimeController&&this.conversationButton){if(!window.CoreAIRealtime||typeof window.CoreAIRealtime.attach!=`function`)console.error(`realtime-audio.js is not loaded; realtime voice is unavailable on this page.`);else{var t=this;this.realtimeController=window.CoreAIRealtime.attach({connection:this.connection,ensureConnected:function(){return t.ensureConnectionStarted().then(function(e){if(!e)throw Error(`The chat connection is not available.`);return e})},sendStart:function(e,n,r,i,a,o){t.connection.send(`StartRealtimeConversation`,t.getProfileId(),t.getSessionId()||``,e,n,r,i,a,o)},webRtcEnabled:this.realtimeWebRtcEnabled,sendStartWebRtc:function(e,n,r,i,a,o){t.connection.send(`StartRealtimeWebRtc`,t.getProfileId(),t.getSessionId()||``,e,n,r,i,a,o)},webRtcIceServers:this.realtimeWebRtcIceServers||void 0,voiceName:this.realtimeVoiceName||``,getVoiceName:function(){return t.realtimeVoiceName||``},realtimeEnabled:!0,selectors:{realtimeButton:e.conversationButtonElementSelector,micButton:e.micButtonElementSelector},onSessionStateChanged:function(e){t.setVoiceSessionLive(e)},onActivate:function(){t.isConversationMode=!0,t._conversationAssistantMessage=null,t._conversationPartialMessage=null,t.removeNotification(`conversation-ended`)},onDeactivate:function(){t.isConversationMode=!1,t.finishRealtimeConversationCleanup()},onUserTurnPending:function(e){t.addRealtimePendingTurn(e)},onUserTurnDropped:function(e){t.dropRealtimePendingTurn(e)}})}}},finishRealtimeConversationCleanup(){if(this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:`conversation-ended`,content:`Conversation ended.`,icon:`fa-solid fa-circle-check`,dismissible:!0,autoDismissMs:5e3})},addRealtimePendingTurn(e){if(e){this._realtimePendingTurns=this._realtimePendingTurns||{};var t=this.messages.length;this.addMessage({role:`user`,content:``,isPartial:!0}),this._realtimePendingTurns[e]=this.messages[t]}},fillRealtimePendingTurn(e,t){if(e){if(t){var n=t.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`);e.content=t,e.htmlContent=`<p>`+n+`</p>`,e.isPartial=!1}else{var r=this.messages.indexOf(e);r>=0&&this.messages.splice(r,1)}}},dropRealtimePendingTurn(e){if(e&&this._realtimePendingTurns){var t=this._realtimePendingTurns[e];if(t){delete this._realtimePendingTurns[e];var n=this.messages.indexOf(t);n>=0&&this.messages.splice(n,1)}}},startConversationMode(){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(e=>{this._conversationSubject=new signalR.Subject,this._conversationStream=e;var t=.12;this._conversationCapture=this._createPcmCapture(e,(e,n)=>{this.isPlayingAudio&&n>=t&&this.stopAudio();try{this._conversationSubject.next(e)}catch{}});var n=this.getProfileId(),r=this.getSessionId()||``,i=navigator.language||document.documentElement.lang||`en-US`,a=this._conversationCapture&&this._conversationCapture.sampleRate||16e3;this.connection.send(`StartConversation`,n,r,this._conversationSubject,`audio/pcm;rate=`+a,i),this.isRecording=!0}).catch(e=>{console.error(`Microphone access denied:`,e),this.isConversationMode=!1,this.updateConversationButton()}))},stopConversationMode(){if(this.isConversationMode){if(this.isConversationMode=!1,this.updateConversationButton(),this.connection&&this.connection.invoke(`StopConversation`).catch(function(){}),this.isRecording){if(this._stopPcmCapture(this._conversationCapture),this._conversationCapture=null,this._conversationSubject)try{this._conversationSubject.complete()}catch{}this.isRecording=!1}if(this.stopAudio(),this._conversationPartialTranscript=``,this._conversationPartialMessage=null,this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:`conversation-ended`,content:`Conversation ended.`,icon:`fa-solid fa-circle-check`,dismissible:!0,autoDismissMs:5e3})}},updateConversationButton(){if(this.conversationButton){if(this.isConversationMode){this.conversationButton.classList.add(`active`,`btn-primary`),this.conversationButton.classList.remove(`btn-dark`,`btn-outline-dark`,`btn-outline-secondary`),this.conversationButton.title=this.conversationButton.getAttribute(`data-end-title`)||`End Conversation`;var e=this.conversationButton.getAttribute(`data-end-html`);e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}else{this.conversationButton.classList.remove(`active`,`btn-primary`),this.conversationButton.classList.remove(`btn-dark`,`btn-outline-secondary`),this.conversationButton.classList.add(`btn-outline-dark`),this.conversationButton.blur(),this.conversationButton.title=this.conversationButton.getAttribute(`data-start-title`)||`Start Conversation`;var t=this.conversationButton.getAttribute(`data-start-html`);t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))}}},conversationModeSendPrompt(){},conversationModeOnAudioEnded(){},generatePrompt(e){if(!e){console.error(`The element paramter is required.`);return}let t=e.getAttribute(`data-profile-id`),n=this.getSessionId(),r=this.getProfileId();!t||!n?console.error(`The given element is missing data-profile-id or the session has not yet started.`):this.streamMessage(t,null,r)},createSessionUrl(e,t,n){let r=e.toLowerCase().startsWith(`http`)?e:window.location.origin+e,i=new URL(r);return i.searchParams.set(t,n),i.toString()},showTypingIndicator(){this.addMessage({role:`indicator`,htmlContent:u.indicatorTemplate})},hideTypingIndicator(){let e=this.messages.length;return this.messages=this.messages.filter(e=>e.role!==`indicator`),e-this.messages.length},receiveNotification(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(t=>t.type===e.type);t>=0?this.notifications.splice(t,1,e):this.notifications.push(e),this.scheduleNotificationDismiss(e),this.$nextTick(()=>{this.scrollToBottom()})}},updateNotification(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(t=>t.type===e.type);t>=0&&(this.notifications.splice(t,1,e),this.scheduleNotificationDismiss(e))}},scheduleNotificationDismiss(e){!e||!e.type||!e.autoDismissMs||e.autoDismissMs<=0||(this.notificationDismissTimers[e.type]=setTimeout(()=>{this.removeNotification(e.type)},e.autoDismissMs))},clearNotificationDismiss(e){var t=this.notificationDismissTimers[e];t&&(clearTimeout(t),delete this.notificationDismissTimers[e])},removeNotification(e){this.clearNotificationDismiss(e),this.notifications=this.notifications.filter(t=>t.type!==e)},dismissNotification(e){this.removeNotification(e)},handleNotificationAction(e,t){if(this.connection){var n=this.getSessionId();this.connection.invoke(`HandleNotificationAction`,n,e,t).catch(function(e){console.error(`Error handling notification action:`,e)})}},scrollToBottom(){this.autoScroll&&setTimeout(()=>{this.chatContainer.scrollTop=this.chatContainer.scrollHeight-this.chatContainer.clientHeight},50)},handleUserInput(e){this.prompt=e.target.value},getProfileId(){return this.inputElement?this.inputElement.getAttribute(`data-profile-id`):null},setSessionId(e){this.inputElement&&this.inputElement.setAttribute(`data-session-id`,e||``)},resetSession(){this.forceStopActiveVoice(),this.stopRecording(),this.rejectPendingSessionRequest(`Session was reset.`),this.setSessionId(``),this.isSessionStarted=!1,this.sessionRating=null,this.messages=[],this.documents=[],u.initialPrompt?this.addMessage({role:`assistant`,content:u.initialPrompt}):this.showPlaceholder(),f&&typeof f.onSessionReset==`function`&&f.onSessionReset(this,u)},startNewSession(){if(!this.applyOrchestratorAvailability())return;let e=this.getProfileId();e&&this.connection&&(this.forceStopActiveVoice(),this.requestNewSession(e).catch(e=>console.error(e)))},async ensureSessionForDocuments(e){return this.getSessionId()||(!e||!this.connection?null:await this.requestNewSession(e))},requestNewSession(e){return this.pendingSessionPromise?this.pendingSessionPromise:!e||!this.connection?Promise.resolve(null):(this.pendingSessionPromise=new Promise((e,t)=>{this.pendingSessionResolver=e,this.pendingSessionRejector=t,this.pendingSessionTimeoutId=window.setTimeout(()=>{this.rejectPendingSessionRequest(`Timed out while creating a chat session.`)},15e3)}),this.connection.invoke(`StartSession`,e,null).catch(e=>{this.rejectPendingSessionRequest(e)}),this.pendingSessionPromise)},resolvePendingSessionRequest(e){this.pendingSessionResolver&&this.pendingSessionResolver(e),this.clearPendingSessionRequest()},rejectPendingSessionRequest(e){this.pendingSessionRejector&&this.pendingSessionRejector(e),this.clearPendingSessionRequest()},clearPendingSessionRequest(){this.pendingSessionTimeoutId&&window.clearTimeout(this.pendingSessionTimeoutId),this.pendingSessionPromise=null,this.pendingSessionResolver=null,this.pendingSessionRejector=null,this.pendingSessionTimeoutId=null},initializeApp(){if(this.inputElement=document.querySelector(u.inputElementSelector),this.buttonElement=document.querySelector(u.sendButtonElementSelector),this.chatContainer=document.querySelector(u.chatContainerElementSelector),this.placeholder=document.querySelector(u.placeholderElementSelector),!this.inputElement||!this.buttonElement||!this.chatContainer||!this.placeholder)return console.error(`AI chat app could not initialize because one or more required elements were not found.`,{inputElementSelector:u.inputElementSelector,sendButtonElementSelector:u.sendButtonElementSelector,chatContainerElementSelector:u.chatContainerElementSelector,placeholderElementSelector:u.placeholderElementSelector}),!1;this.applyOrchestratorAvailability();let e=this.getSessionId();if(!d&&e&&this.loadSession(e),u.sessionDocumentsEnabled&&u.documentBarSelector&&(this.documentBar=document.querySelector(u.documentBarSelector),this.documentBar)){this.renderDocumentBar();var t=document.createElement(`input`);t.type=`file`,t.id=`ai-chat-doc-input`,t.className=`d-none`,t.multiple=!0,u.allowedExtensions&&(t.accept=u.allowedExtensions),t.addEventListener(`change`,e=>this.handleFileInputChange(e)),this.documentBar.parentElement.appendChild(t);var n=this.inputElement?this.inputElement.closest(`.ai-admin-widget-input, .text-bg-light`):null;n&&(n.addEventListener(`dragover`,e=>this.handleDragOver(e)),n.addEventListener(`dragleave`,e=>this.handleDragLeave(e)),n.addEventListener(`drop`,e=>this.handleDrop(e)))}this.chatContainer.addEventListener(`scroll`,()=>{if(!this.stream)return;let e=this.chatContainer.scrollHeight-this.chatContainer.clientHeight-this.chatContainer.scrollTop<=30;this.autoScroll=e}),this.inputElement.addEventListener(`keydown`,e=>{this.stream==null&&e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.buttonElement.click())}),this.inputElement.addEventListener(`input`,e=>{this.handleUserInput(e),e.target.value.trim()?this.buttonElement.removeAttribute(`disabled`):this.buttonElement.setAttribute(`disabled`,!0)}),this.buttonElement.addEventListener(`click`,()=>{if(this.stream!=null){if(this.stream.dispose(),this.stream=null,this.streamingFinished(),this.hideTypingIndicator(),this.messages.length>0){let e=this.messages[this.messages.length-1];e.role===`assistant`&&!e.content?this.messages.pop():e.isStreaming&&=!1}}else this.sendMessage()});let r=document.getElementsByClassName(`profile-generated-prompt`);for(var i=0;i<r.length;i++)r[i].addEventListener(`click`,e=>{e.preventDefault(),this.generatePrompt(e.target)});let a=document.getElementsByClassName(`chat-session-history-item`);for(i=0;i<a.length;i++)a[i].addEventListener(`click`,e=>{e.preventDefault();var t=e.target.getAttribute(`data-session-id`);t?(this.loadSession(t),this.showChatScreen()):console.error(`an element with the class chat-session-history-item with no data-session-id set.`)});let o=Array.isArray(u.messages)?u.messages:[];for(let e=0;e<o.length;e++)this.addMessage(o[e]);return this.messages.length===0&&u.initialPrompt&&this.addMessage({role:`assistant`,content:u.initialPrompt}),this.$nextTick(()=>{this.refreshAllFeedbackIcons()}),this.chatContainer&&this.chatContainer.addEventListener(`click`,e=>{var t=e.target.closest(`.ai-code-copy-btn`);if(t){var n=t.closest(`.ai-code-block`)||t.closest(`pre`);if(n){var r=n.querySelector(`code`);r&&(navigator.clipboard.writeText(r.textContent),t.innerHTML=`<i class="fa-solid fa-check"></i> `+(u.codeCopiedText||`Copied!`),setTimeout(()=>{t.innerHTML=`<i class="fa-regular fa-copy"></i>`},2e3))}}}),this.speechToTextEnabled&&u.micButtonElementSelector&&(this.micButton=document.querySelector(u.micButtonElementSelector),this.micButton&&(this.micButton.style.display=``,this.micButton.addEventListener(`click`,()=>{this.toggleRecording()}))),(this.conversationModeEnabled||this.realtimeEnabled)&&u.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(u.conversationButtonElementSelector),this.conversationButton&&(this.realtimeEnabled?(this.setupRealtimeController(u),this.setVoiceSessionLive(!1)):this.conversationButton.addEventListener(`click`,()=>{this.toggleConversationMode()}))),!0},loadSession(e){this.connection.invoke(`LoadSession`,e).catch(e=>console.error(e))},reloadCurrentSession(){var e=this.getSessionId();e&&this.loadSession(e)},initializeSession(e,t){if(this.isSessionStarted&&!t)e&&this.getSessionId()===e&&this.resolvePendingSessionRequest(e);else if(this.fireEvent(new CustomEvent(`initializingSessionCoreAIChat`,{detail:{sessionId:e}})),this.setSessionId(e),this.isSessionStarted=!0,this.resolvePendingSessionRequest(e),f&&typeof f.onSessionInitialized==`function`&&f.onSessionInitialized(this,e,u),!d&&e&&u.sessionUrlTemplate&&typeof history<`u`&&history.replaceState){var n=u.sessionUrlTemplate.replace(`{sessionId}`,encodeURIComponent(e));history.replaceState(null,``,n)}},getSessionId(){let e=this.inputElement?this.inputElement.getAttribute(`data-session-id`):null;return!e&&f&&typeof f.resolveSessionId==`function`&&(e=f.resolveSessionId(this,u)),e},clearCopiedMessageState(){this.copyResetTimeoutId&&=(window.clearTimeout(this.copyResetTimeoutId),null),this.activeCopyButton&&=(this.setCopyButtonState(this.activeCopyButton,!1),null),this.copiedMessageIndex=-1},copyResponse(e,t,n){let r=e&&typeof e==`object`?e.copyContent??e.content??``:e??``,i=n?.currentTarget||n?.target?.closest?.(`[data-copy-message-index]`)||null;navigator.clipboard.writeText(r).then(()=>{this.clearCopiedMessageState(),this.copiedMessageIndex=typeof t==`number`?t:-1,this.activeCopyButton=i,i?this.setCopyButtonState(i,!0):this.$nextTick(()=>this.updateCopyButtons()),this.copyResetTimeoutId=window.setTimeout(()=>{this.clearCopiedMessageState(),this.$nextTick(()=>this.updateCopyButtons())},Number(u.copyResetDelayMs)||2e3)}).catch(e=>console.error(`Failed to copy response:`,e))},updateFeedbackIcons(e,t){if(e){var n=e.querySelector(`.rate-up-btn`),r=e.querySelector(`.rate-down-btn`);if(n){var i=t===!0?`fa-solid fa-thumbs-up`:`fa-regular fa-thumbs-up`,a=document.createElement(`span`);a.className=i,a.style.fontSize=`0.9rem`,n.textContent=``,n.appendChild(a)}if(r){var o=t===!1?`fa-solid fa-thumbs-down`:`fa-regular fa-thumbs-down`,s=document.createElement(`span`);s.className=o,s.style.fontSize=`0.9rem`,r.textContent=``,r.appendChild(s)}}},refreshAllFeedbackIcons(){for(var e=this.$el.querySelectorAll(`.ai-chat-message-assistant-feedback`),t=0;t<e.length;t++){var n=e[t].getAttribute(`data-message-id`),r=this.messages.find(e=>e.id===n);r&&this.updateFeedbackIcons(e[t],r.userRating)}},rateMessage(e,t){var n=this.getSessionId();if(n&&e.id&&this.connection){var r=e.userRating===t?null:t;e.userRating=r;var i=this.$el.querySelector(`.ai-chat-message-assistant-feedback[data-message-id="`+e.id+`"]`);this.updateFeedbackIcons(i,r),r!==null&&i&&setTimeout(()=>{var e=t?`.rate-up-btn`:`.rate-down-btn`,n=i.querySelector(e);n&&(n.classList.remove(`spark-effect`),n.offsetWidth,n.classList.add(`spark-effect`),n.addEventListener(`animationend`,function e(){n.removeEventListener(`animationend`,e),n.classList.remove(`spark-effect`)}))},50),this.connection.invoke(`RateMessage`,n,e.id,t).catch(function(e){console.error(`Failed to rate message:`,e)})}}},watch:{documents:{handler(){this.renderDocumentBar(),f&&typeof f.onDocumentsChanged==`function`&&f.onDocumentsChanged(this,this.documents,u)},deep:!0},isUploading(){this.renderDocumentBar()},isDocumentOperationPending(){this.renderDocumentBar()},isPlayingAudio(){},copiedMessageIndex(){this.$nextTick(()=>this.updateCopyButtons())},isConversationMode(e){this.micButton&&(this.micButton.style.display=e?`none`:this.speechToTextEnabled?``:`none`),this.realtimeEnabled||this.setVoiceSessionLive(e)}},mounted(){(async()=>{await this.startConnection(),this.initializeApp()&&d&&f&&typeof f.onMounted==`function`&&f.onMounted(this,u),this.$nextTick(()=>{this.updateCopyButtons(),i(this.$el),this.fontAwesomeObserver=a(this.$el)})})(),window.addEventListener(`beforeunload`,this.handleBeforeUnload),window.addEventListener(`crestapps-ai-chat-stop-tts`,this.handleExternalTtsStop)},beforeUnmount(){window.removeEventListener(`beforeunload`,this.handleBeforeUnload),window.removeEventListener(`crestapps-ai-chat-stop-tts`,this.handleExternalTtsStop),this.fontAwesomeObserver&&=(this.fontAwesomeObserver.disconnect(),null),this.clearCopiedMessageState(),this.stopAudio(!1),this.stream&&=(this.stream.dispose(),null),this.connection&&this.connection.stop(),f&&typeof f.onBeforeUnmount==`function`&&f.onBeforeUnmount(this,u)},template:u.messageTemplate},m=Vue.createApp(p).mount(u.appElementSelector);return f&&typeof f.attach==`function`&&f.attach(m,u),m},L=`[data-coreai-chat-config],[data-coreai-chat-app-element-selector]`;function R(e,t){let n=e.getAttribute(t);return n===null||n===``?null:n}function z(e){if(e==null)return null;if(typeof e==`boolean`)return e;let t=String(e).trim().toLowerCase();return t===`true`||t!==`false`&&null}function B(e,t,n){let r=R(e,t);if(!r)return null;try{return JSON.parse(r)}catch(e){return console.error(`Failed to parse `+n+` JSON.`,e),null}}function V(e,t){let n=t||{};if(e.hasAttribute(`data-coreai-chat-widget-container-selector`)&&n.allowWidgetHost!==!0)return null;let r=R(e,`data-coreai-chat-app-element-selector`);if(!r)return null;let i={signalRHubUrl:R(e,`data-coreai-chat-signalr-hub-url`),appElementSelector:r,chatContainerElementSelector:R(e,`data-coreai-chat-container-element-selector`),inputElementSelector:R(e,`data-coreai-chat-input-element-selector`),sendButtonElementSelector:R(e,`data-coreai-chat-send-button-element-selector`),placeholderElementSelector:R(e,`data-coreai-chat-placeholder-element-selector`),messages:B(e,`data-coreai-chat-messages`,`CoreAI chat messages`)??void 0,chatMode:R(e,`data-coreai-chat-mode`),micButtonElementSelector:R(e,`data-coreai-chat-mic-button-element-selector`),conversationButtonElementSelector:R(e,`data-coreai-chat-conversation-button-element-selector`),realtimeHintElementSelector:R(e,`data-coreai-chat-realtime-hint-element-selector`),ttsVoiceName:R(e,`data-coreai-chat-tts-voice-name`),realtimeVoiceName:R(e,`data-coreai-chat-realtime-voice-name`),documentBarSelector:R(e,`data-coreai-chat-document-bar-selector`),uploadDocumentUrl:R(e,`data-coreai-chat-upload-document-url`),removeDocumentUrl:R(e,`data-coreai-chat-remove-document-url`),allowedExtensions:R(e,`data-coreai-chat-allowed-extensions`),supportedExtensionsText:R(e,`data-coreai-chat-supported-extensions-text`),existingDocuments:B(e,`data-coreai-chat-existing-documents`,`CoreAI chat existing documents`)??void 0,initialPrompt:R(e,`data-coreai-chat-initial-prompt`),sessionUrlTemplate:R(e,`data-coreai-chat-session-url-template`),userLabel:R(e,`data-coreai-chat-user-label`),assistantLabel:R(e,`data-coreai-chat-assistant-label`),assistantAvatarUrl:R(e,`data-coreai-chat-assistant-avatar-url`),copyTitle:R(e,`data-coreai-chat-copy-title`),copiedTitle:R(e,`data-coreai-chat-copied-title`)},a={metricsEnabled:`data-coreai-chat-metrics-enabled`,textToSpeechEnabled:`data-coreai-chat-text-to-speech-enabled`,sessionDocumentsEnabled:`data-coreai-chat-session-documents-enabled`,singleResponseMode:`data-coreai-chat-single-response-mode`,realtimeEnabled:`data-coreai-chat-realtime-enabled`,realtimeWebRtcEnabled:`data-coreai-chat-realtime-webrtc-enabled`};return Object.keys(a).forEach(t=>{let n=z(R(e,a[t]));n!==null&&(i[t]=n)}),N(i)}function H(e,t){let n=B(e,`data-coreai-chat-config`,`CoreAI chat config`),r=V(e,t);return!n&&!r?null:Object.assign({},n||{},r||{})}function U(e){if(!e||e.dataset.coreAiChatInitialized===`true`)return e&&e.__coreAIChatApp||null;let t=H(e);if(!t)return null;let n=I(t);return n?(e.dataset.coreAiChatInitialized=`true`,e.__coreAIChatApp=n,n):null}function W(e){e&&typeof e.querySelectorAll==`function`&&(typeof e.matches==`function`&&e.matches(L)&&U(e),e.querySelectorAll(L).forEach(U))}function G(){W(document),typeof MutationObserver<`u`&&new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e&&e.nodeType===1&&W(e)})})}).observe(document.body,{childList:!0,subtree:!0})}return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,G,{once:!0}):G(),{initialize:I,initializeFromElement:U,buildConfigFromElement:H}}(),document.addEventListener(`click`,function(e){let t=e.target.closest(`.download-chart-btn`);if(!t)return;let n=t.getAttribute(`data-chart-id`),r=n?document.getElementById(n):null;if(!r){console.error(`Chart canvas not found:`,n);return}let i=document.createElement(`a`);i.download=`chart-`+n+`.png`,i.href=r.toDataURL(`image/png`),i.click()}),document.addEventListener(`click`,function(e){let t=e.target.closest(`.ai-download-image`);if(!t)return;let n=t.closest(`.generated-image-container`)?.querySelector(`img`);if(!n)return;let r=n.src;r&&r.startsWith(`data:`)&&(e.preventDefault(),fetch(r).then(function(e){return e.blob()}).then(function(e){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t.getAttribute(`download`)||`generated-image.png`,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(e){console.error(`Failed to download image:`,e)}))})})();
79
79
  //# sourceMappingURL=ai-chat.min.js.map