deep-chat-dev 9.0.242 → 9.0.244

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
- class t{static render(t,e){const i=document.createElement("div");i.id="error-view",i.innerText=e,t.replaceChildren(i)}}class e{static onLoad(t){t.innerHTML='<div id="loading-validate-key-property"></div>'}static createElements(){const t=document.createElement("div");return t.id="validate-property-key-view",t}static render(i,s,n){const o=e.createElements(),r={onSuccess:s,onFail:t.render.bind(this,i,"Your 'key' has failed authentication"),onLoad:e.onLoad.bind(this,o)};n.key&&n.verifyKey(n.key,r),i.replaceChildren(o)}}class i{static unsetStyle(t,e){const i=Object.keys(e).reduce(((t,e)=>(t[e]="",t)),{});Object.assign(t.style,i)}static unsetActivityCSSMouseStates(t,e){e.click&&i.unsetStyle(t,e.click),e.hover&&i.unsetStyle(t,e.hover)}static unsetAllCSSMouseStates(t,e){i.unsetActivityCSSMouseStates(t,e),e.default&&i.unsetStyle(t,e.default)}static processStateful(t){const e=t.default||{},i=Object.assign(JSON.parse(JSON.stringify(e)),null==t?void 0:t.hover);return{default:e,hover:i,click:Object.assign(JSON.parse(JSON.stringify(i)),null==t?void 0:t.click)}}static mergeStatefulStyles(t){const e={default:{},hover:{},click:{}};return t.forEach((t=>{e.default=Object.assign(e.default,t.default),e.hover=Object.assign(e.hover,t.hover),e.click=Object.assign(e.click,t.click)})),e}static overwriteDefaultWithAlreadyApplied(t,e){Object.keys(t.default||[]).forEach((i=>{var s;const n=i;e.style[n]&&null!=(s=t.default)&&s[n]&&(t.default[i]=e.style[n])}))}static applyToStyleIfNotDefined(t,e){for(const i in e){const s=e[i];""===t[i]&&s&&(t[i]=s)}}}const s=class t{static attemptAppendStyleSheetToHead(e){if(e.fontFamily&&e.fontFamily!==t.DEFAULT_FONT_FAMILY)return;const i=document.getElementsByTagName("head")[0];if(!Array.from(i.getElementsByTagName("link")).some((e=>e.getAttribute("href")===t.FONT_URL))){const e=document.createElement("link");e.rel="stylesheet",e.href=t.FONT_URL,i.appendChild(e)}}};s.FONT_URL="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap",s.DEFAULT_FONT_FAMILY="'Inter', sans-serif, Avenir, Helvetica, Arial";let n=s;const o=class t{static apply(e,i){if(i)try{t.applyStyleSheet(e,i)}catch{t.addStyleElement(e,i)}}static applyStyleSheet(t,e){const i=new CSSStyleSheet;i.replaceSync(t),e.adoptedStyleSheets.push(i)}static addStyleElement(t,e){const i=document.createElement("style");i.innerHTML=t,e.appendChild(i)}static applyDefaultStyleToComponent(e,s){s&&i.applyToStyleIfNotDefined(e,s),i.applyToStyleIfNotDefined(e,t.DEFAULT_COMPONENT_STYLE)}};o.DEFAULT_COMPONENT_STYLE={height:"350px",width:"320px",borderTop:"1px solid #cacaca",borderRight:"1px solid #cacaca",borderLeft:"1px solid #cacaca",borderBottom:"1px solid #cacaca",fontFamily:n.DEFAULT_FONT_FAMILY,fontSize:"0.9rem",backgroundColor:"white",position:"relative",overflow:"hidden"};let r=o;const a=class{};a.IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),a.IS_CHROMIUM=window.chrome;let l=a;var c=(t=>(t.ESCAPE="Escape",t.ENTER="Enter",t.TAB="Tab",t.ARROW_UP="ArrowUp",t.ARROW_DOWN="ArrowDown",t.ARROW_RIGHT="ArrowRight",t.ARROW_LEFT="ArrowLeft",t.BACKSPACE="Backspace",t.DELETE="Delete",t.META="Meta",t.CONTROL="Control",t))(c||{});const h=class t{static add(e,i,s,n){void 0!==s&&e.addEventListener("keydown",t.onKeyDown.bind(this,s)),e.oninput=t.onInput.bind(this,s,n),e.addEventListener("paste",(t=>{var e;t.preventDefault(),null!=(e=t.clipboardData)&&e.files.length&&i.addFilesToAnyType(Array.from(t.clipboardData.files))}))}static onKeyDown(e,i){const s=i.target.textContent;s&&s.length>=e&&!t.PERMITTED_KEYS.has(i.key)&&!t.isKeyCombinationPermitted(i)&&i.preventDefault()}static isKeyCombinationPermitted(t){return"a"===t.key&&(t.ctrlKey||t.metaKey)}static onInput(t,e,i){const s=i.target,n=s.textContent||"";void 0!==t&&n.length>t&&(s.textContent=n.substring(0,t),v.focusEndOfInput(s)),null==e||e()}};h.PERMITTED_KEYS=new Set([c.BACKSPACE,c.DELETE,c.ARROW_RIGHT,c.ARROW_LEFT,c.ARROW_DOWN,c.ARROW_UP,c.META,c.CONTROL,c.ENTER]);let u=h;class d{static sanitizePastedTextContent(t){var e,i;t.preventDefault();const s=null==(e=t.clipboardData)?void 0:e.getData("text/plain");s&&(null==(i=document.execCommand)||i.call(document,"insertText",!1,s))}}const p=class t{constructor(e,i,s){var n,o;const r=t.processConfig(i,e.textInput);this.elementRef=t.createContainerElement(null==(n=null==r?void 0:r.styles)?void 0:n.container),this._config=r,this.inputElementRef=this.createInputElement(),this.elementRef.appendChild(this.inputElementRef),e.setPlaceholderText=this.setPlaceholderText.bind(this),e.setPlaceholderText((null==(o=this._config.placeholder)?void 0:o.text)||"Ask me anything!"),setTimeout((()=>{u.add(this.inputElementRef,s,this._config.characterLimit,e._validationHandler)}))}static processConfig(t,e){var i;return e??(e={}),e.disabled??(e.disabled=t.isTextInputDisabled),e.placeholder??(e.placeholder={}),(i=e.placeholder).text??(i.text=t.textInputPlaceholderText),e}static createContainerElement(t){const e=document.createElement("div");return e.id="text-input-container",Object.assign(e.style,t),e}static preventAutomaticScrollUpOnNewLine(t){let e;t.addEventListener("keydown",(()=>{e=window.scrollY})),t.addEventListener("input",(()=>{e!==window.scrollY&&window.scrollTo({top:e})}))}clear(){var t;const e=window.scrollY;this.inputElementRef.classList.contains("text-input-disabled")||(Object.assign(this.inputElementRef.style,null==(t=this._config.placeholder)?void 0:t.style),this.inputElementRef.textContent="",v.focusEndOfInput(this.inputElementRef)),l.IS_CHROMIUM&&window.scrollTo({top:e})}createInputElement(){var e,i,s,n;const o=document.createElement("div");return o.id=t.TEXT_INPUT_ID,o.classList.add("text-input-styling"),o.role="textbox",l.IS_CHROMIUM&&t.preventAutomaticScrollUpOnNewLine(o),"boolean"==typeof this._config.disabled&&!0===this._config.disabled?(o.contentEditable="false",o.classList.add("text-input-disabled"),o.setAttribute("aria-disabled","true")):(o.contentEditable="true",o.removeAttribute("aria-disabled"),this.addEventListeners(o)),Object.assign(o.style,null==(e=this._config.styles)?void 0:e.text),Object.assign(o.style,null==(i=this._config.placeholder)?void 0:i.style),null!=(n=null==(s=this._config.placeholder)?void 0:s.style)&&n.color||o.setAttribute("textcolor",""),o}removePlaceholderStyle(){var t,e,s,n;!this.inputElementRef.classList.contains("text-input-disabled")&&null!=(t=this._config.placeholder)&&t.style&&(i.unsetStyle(this.inputElementRef,null==(e=this._config.placeholder)?void 0:e.style),Object.assign(this.inputElementRef.style,null==(n=null==(s=this._config)?void 0:s.styles)?void 0:n.text))}addEventListeners(t){var e,i;null!=(e=this._config.styles)&&e.focus&&(t.onfocus=()=>{var t;return Object.assign(this.elementRef.style,null==(t=this._config.styles)?void 0:t.focus)},t.onblur=this.onBlur.bind(this,this._config.styles.focus,null==(i=this._config.styles)?void 0:i.container)),t.addEventListener("keydown",this.onKeydown.bind(this)),t.addEventListener("input",this.onInput.bind(this)),t.addEventListener("paste",d.sanitizePastedTextContent)}onBlur(t,e){i.unsetStyle(this.elementRef,t),e&&Object.assign(this.elementRef.style,e)}onKeydown(t){var e;t.key===c.ENTER&&!t.ctrlKey&&!t.shiftKey&&(t.preventDefault(),null==(e=this.submit)||e.call(this))}onInput(){var t;this.isTextInputEmpty()?Object.assign(this.inputElementRef.style,null==(t=this._config.placeholder)?void 0:t.style):this.removePlaceholderStyle()}setPlaceholderText(t){this.inputElementRef.setAttribute("deep-chat-placeholder-text",t),this.inputElementRef.setAttribute("aria-label",t)}isTextInputEmpty(){return""===this.inputElementRef.textContent}};p.TEXT_INPUT_ID="text-input";let m=p;class v{static focusEndOfInput(t){const e=document.createRange();e.selectNodeContents(t),e.collapse(!1);const i=window.getSelection();null==i||i.removeAllRanges(),null==i||i.addRange(e)}static focusFromParentElement(t){const e=t.querySelector(`#${m.TEXT_INPUT_ID}`);e&&(l.IS_SAFARI&&e.focus(),v.focusEndOfInput(e))}}function f(t){return t.charAt(0).toUpperCase()+t.slice(1)}function g(t,e,i,s){const n=`\n${f(e)} message: ${JSON.stringify(t)} \n`,o=i?`${f(e)} message after interceptor: ${function(t){return t&&JSON.stringify(t)}(s)} \n`:"";return n+o}const b="Make sure the events are using {text: string} or {html: string} format.\nYou can also augment them using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor",y={INVALID_KEY:"Invalid API Key",CONNECTION_FAILED:"Failed to connect",INVALID_RESPONSE:function(t,e,i,s){return`${g(t,e,i,s)}Make sure the ${e} message is using the Response format: https://deepchat.dev/docs/connect/#Response \nYou can also augment it using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor`},INVALID_MODEL_REQUEST:function(t,e){const i="request";return`${g(t,i,e)}Make sure the ${i} message is using the {body: {text: string}} format, e.g: {body: {text: "Model Response"}}`},INVALID_MODEL_RESPONSE:function(t,e,i){const s="response";return`${g(t,s,e,i)}Make sure the ${s} message is using the {text: string} format, e.g: {text: "Model Response"}`},INVALID_STREAM_ARRAY_RESPONSE:"Multi-response arrays are not supported for streaming",INVALID_STREAM_EVENT:b,INVALID_STREAM_EVENT_MIX:"Cannot mix {text: string} and {html: string} responses.",NO_VALID_STREAM_EVENTS_SENT:`No valid stream events were sent.\n${b}`},w=class t{static addElements(t,...e){e.forEach((e=>t.appendChild(e)))}static isScrollbarAtBottomOfElement(e){const i=e.scrollHeight,s=e.clientHeight;return e.scrollTop>=i-s-t.CODE_SNIPPET_GENERATION_JUMP}static cloneElement(t){const e=t.cloneNode(!0);return t.parentNode.replaceChild(e,t),e}static scrollToBottom(t,e=!1){e?t.scrollTo({left:0,top:t.scrollHeight,behavior:"smooth"}):t.scrollTop=t.scrollHeight}static scrollToTop(t){t.scrollTop=0}};w.CODE_SNIPPET_GENERATION_JUMP=.5;let x=w;const k=class t{static speak(t,e){if(window.SpeechSynthesisUtterance){const i=new SpeechSynthesisUtterance(t);Object.assign(i,e),speechSynthesis.speak(i)}}static processConfig(e,i){const s={};setTimeout((()=>{if("object"==typeof e&&(e.lang&&(s.lang=e.lang),e.pitch&&(s.pitch=e.pitch),e.rate&&(s.rate=e.rate),e.volume&&(s.volume=e.volume),e.voiceName)){const t=window.speechSynthesis.getVoices().find((t=>{var i;return t.name.toLocaleLowerCase()===(null==(i=e.voiceName)?void 0:i.toLocaleLowerCase())}));t&&(s.voice=t)}i(s)}),t.LOAD_VOICES_MS)}};k.LOAD_VOICES_MS=200;let _=k;const S=class t{static colorToHex(t){const e=document.createElement("div");return e.style.color=t,document.body.appendChild(e),`#${window.getComputedStyle(e).color.match(/\d+/g).map((t=>parseInt(t).toString(16).padStart(2,"0"))).join("")}`}static setDots(e,i){var s,n,o,r;if(null!=(r=null==(o=null==(n=null==(s=null==i?void 0:i.loading)?void 0:s.message)?void 0:n.styles)?void 0:o.bubble)&&r.color){const s=t.colorToHex(i.loading.message.styles.bubble.color);e.style.setProperty("--loading-message-color",s),e.style.setProperty("--loading-message-color-fade",`${s}33`)}else e.style.setProperty("--loading-message-color","#848484"),e.style.setProperty("--loading-message-color-fade","#55555533")}static setRing(e,i){const{color:s,width:n,height:o,margin:r,border:a}=i||{};if(s){const i=t.colorToHex(s);e.style.setProperty("--loading-history-color",i)}else e.style.setProperty("--loading-history-color","#dbdbdb");e.style.setProperty("--loading-history-height",o||"57px"),e.style.setProperty("--loading-history-width",n||"57px"),e.style.setProperty("--loading-history-margin",r||"7px"),e.style.setProperty("--loading-history-border",a||"6px solid")}};S.BUBBLE_CLASS="deep-chat-loading-message-bubble",S.DOTS_CONTAINER_CLASS="deep-chat-loading-message-dots-container";let A=S;const T=class t{static setElementProps(e,i,s,n){var o;"loading"!==s&&(e.applyCustomStyles(i,n,!0,null==(o=e.messageStyles)?void 0:o[s]),i.bubbleElement.classList.add(t.FILE_BUBBLE_CLASS))}static addMessage(e,i,s,n,o){t.setElementProps(e,i,s,n),o||(e.appendOuterContainerElemet(i.outerContainer),e.focusMode||(e.elementRef.scrollTop=e.elementRef.scrollHeight))}static wrapInLink(e,i,s){const n=document.createElement("a");return n.href=i,n.download=s||t.DEFAULT_FILE_NAME,n.target="_blank",n.appendChild(e),n}static isNonLinkableDataUrl(t,e){return!(!e.startsWith("data")||"image"===t)&&("any"===t&&e.startsWith("data:text/javascript")||!e.startsWith("data:image")&&!e.startsWith("data:application"))}static processContent(e,i,s,n){return!s||t.isNonLinkableDataUrl(e,s)?i:t.wrapInLink(i,s,n)}static waitToLoadThenScroll(t){setTimeout((()=>{t.scrollTop=t.scrollHeight}),60)}static scrollDownOnImageLoad(e,i){if(e.startsWith("data"))t.waitToLoadThenScroll(i);else try{fetch(e,{mode:"no-cors"}).catch((()=>{})).finally((()=>{t.waitToLoadThenScroll(i)}))}catch{i.scrollTop=i.scrollHeight}}static reAddFileRefToObject(t,e){var i;null==(i=t.files)||i.forEach(((t,i)=>{var s;t.ref&&null!=(s=e.message.files)&&s[i]&&(e.message.files[i].ref=t.ref)}))}static removeFileRef(t){const e={...t};return delete e.ref,e}static isAudioFile(t){const{type:e,src:i}=t;return"audio"===e||(null==i?void 0:i.startsWith("data:audio"))||i&&/\.(mp3|ogg|wav|aac|webm|4a)$/i.test(i)}static isImageFile(e){const{type:i,src:s}=e;return"image"===i||(null==s?void 0:s.startsWith("data:image"))||s&&t.isImageFileExtension(s)}static isImageFileExtension(t){return/\.(jpg|jpeg|png|gif|bmp)$/i.test(t)}};T.DEFAULT_FILE_NAME="file",T.FILE_BUBBLE_CLASS="file-message";let M=T;class O{static checkForContainerStyles(t,e){const i=t.containerStyle;i&&(Object.assign(e.style,i),console.error("The containerStyle property is deprecated since version 1.3.14."),console.error("Please change to using the style property instead: https://deepchat.dev/docs/styles#style"))}static handleResponseProperty(t){return console.error("The {result: ....} response object type is deprecated since version 1.3.0."),console.error("Please change to using the new response object: https://deepchat.dev/docs/connect#Response"),t.result}static processHistory(t){const e=t.initialMessages;if(e)return console.error("The initialMessages property is deprecated since version 2.0.0."),console.error("Please change to using the history property instead: https://deepchat.dev/docs/messages/#history"),e}static processHistoryFile(t){const e=t.file;e&&(console.error("The file property in MessageContent is deprecated since version 1.3.17."),console.error("Please change to using the files array property: https://deepchat.dev/docs/messages/#MessageContent"),t.files=[e])}static processValidateInput(t){const e=t.validateMessageBeforeSending;if(e)return console.error("The validateMessageBeforeSending property is deprecated since version 1.3.24."),console.error("Please change to using validateInput: https://deepchat.dev/docs/interceptors#validateInput"),e}static processSubmitUserMessage(t){return console.error("The submitUserMessage(text: string) argument string type is deprecated since version 1.4.4."),console.error("Please change to using the new argument type: https://deepchat.dev/docs/methods#submitUserMessage"),{text:t}}static flagHTMLUpdateClass(t){var e;null!=(e=t.children[0])&&e.classList.contains("deep-chat-update-message")&&(console.error('The "deep-chat-update-message" html class is deprecated since version 1.4.4.'),console.error("Please change to using {..., overwrite: true} object: https://deepchat.dev/docs/connect#Response"))}static processConnect(t){const e=t;e.request&&(e.connect?Object.assign(e.connect,e.request):e.connect=e.request,console.error("The request property is deprecated since version 2.0.0."),console.error("Please see the connect object: https://deepchat.dev/docs/connect#connect-1"))}static checkForStream(t){const e=t.stream;if(e)return console.error("The stream property has been moved to the connect object in version 2.0.0."),console.error("Please see the connect object: https://deepchat.dev/docs/connect#connect-1"),e}static fireOnNewMessage(t,e){var i;const s=t;s.onNewMessage&&(console.error("The onNewMessage event has been deprecated since version 2.0.0."),console.error("Please see the onMessage event: https://deepchat.dev/docs/events#onMessage"),null==(i=s.onNewMessage)||i.call(s,e)),t.dispatchEvent(new CustomEvent("new-message",{detail:e}))}static processFileConfigConnect(t){const e=t;e.request&&(console.error("The request property in file configuration is deprecated since version 2.0.0."),console.error("Please use the connect property instead: https://deepchat.dev/docs/files"),e.connect||(e.connect=e.request))}static processMessageStyles(t){if(!t)return;const e=JSON.parse(JSON.stringify(t)),i=e.loading;return i&&(i.outerContainer||i.innerContainer||i.bubble||i.media)&&(console.error("The loading message styles are defined using LoadingMessageStyles interface since version 2.1.0."),console.error("Check it out here: https://deepchat.dev/docs/messages/styles#LoadingMessageStyles"),e.loading={message:{styles:i}}),e}static processDemo(t){return"boolean"==typeof t||t.displayLoadingBubble&&(console.error("The demo displayLoadingBubble property is deprecated since version 2.1.0."),console.error("Please use displayLoading instead: https://deepchat.dev/docs/demo#demo"),t.displayLoading={message:!0}),t}}class j{static mouseUp(t,e){i.unsetAllCSSMouseStates(t,e),Object.assign(t.style,e.default),Object.assign(t.style,e.hover)}static mouseDown(t,e){Object.assign(t.style,e.click)}static mouseLeave(t,e){i.unsetAllCSSMouseStates(t,e),Object.assign(t.style,e.default)}static mouseEnter(t,e){Object.assign(t.style,e.hover)}static add(t,e){t.addEventListener("mouseenter",j.mouseEnter.bind(this,t,e)),t.addEventListener("mouseleave",j.mouseLeave.bind(this,t,e)),t.addEventListener("mousedown",j.mouseDown.bind(this,t,e)),t.addEventListener("mouseup",j.mouseUp.bind(this,t,e))}}const C={"deep-chat-button":{styles:{default:{backgroundColor:"white",padding:"5px",paddingLeft:"7px",paddingRight:"7px",border:"1px solid #c2c2c2",borderRadius:"6px",cursor:"pointer"},hover:{backgroundColor:"#fafafa"},click:{backgroundColor:"#f1f1f1"}}}},E=Object.keys(C);class I{static applySuggestionEvent(t,e){setTimeout((()=>{e.addEventListener("click",(()=>{var i,s;null==(s=t.submitUserMessage)||s.call(t,{text:(null==(i=e.textContent)?void 0:i.trim())||""})}))}))}static isElementTemporary(t){var e;return!!t&&(null==(e=t.bubbleElement.children[0])?void 0:e.classList.contains("deep-chat-temporary-message"))}static doesElementContainDeepChatClass(t){return E.find((e=>t.classList.contains(e)))}static applyEvents(t,e){const i=C[e].events;Object.keys(i||[]).forEach((e=>{t.addEventListener(e,null==i?void 0:i[e])}))}static getProcessedStyles(t,e,s){const n=Array.from(e.classList).reduce(((e,i)=>{var s;const n=null==(s=t[i])?void 0:s.styles;return n&&t[i].styles&&e.push(n),e}),[]),o=C[s].styles;if(o){const t=JSON.parse(JSON.stringify(o));t.default&&i.overwriteDefaultWithAlreadyApplied(t,e),n.unshift(t)}const r=i.mergeStatefulStyles(n);return i.processStateful(r)}static applyDeepChatUtilities(t,e,i){E.forEach((t=>{const s=i.getElementsByClassName(t);Array.from(s||[]).forEach((i=>{const s=I.getProcessedStyles(e,i,t);P.applyStylesToElement(i,s),I.applyEvents(i,t)}))}));const s=i.getElementsByClassName("deep-chat-suggestion-button");Array.from(s).forEach((e=>I.applySuggestionEvent(t,e)))}}class P{static applyStylesToElement(t,e){const s=i.processStateful(e);j.add(t,s),Object.assign(t.style,s.default)}static applyEventsToElement(t,e){Object.keys(e).forEach((i=>{const s=e[i];s&&t.addEventListener(i,s)}))}static applyClassUtilitiesToElement(t,e){const{events:i,styles:s}=e;i&&P.applyEventsToElement(t,i),s&&!I.doesElementContainDeepChatClass(t)&&P.applyStylesToElement(t,s)}static applyCustomClassUtilities(t,e){Object.keys(t).forEach((i=>{const s=e.getElementsByClassName(i);Array.from(s).forEach((e=>{t[i]&&P.applyClassUtilitiesToElement(e,t[i])}))}))}static apply(t,e){I.applyDeepChatUtilities(t,t.htmlClassUtilities,e),P.applyCustomClassUtilities(t.htmlClassUtilities,e)}static traverseNodes(t,e){t.nodeType===Node.ELEMENT_NODE&&e.push(t.outerHTML),t.childNodes.forEach((t=>{P.traverseNodes(t,e)}))}static splitHTML(t){const e=(new DOMParser).parseFromString(t,"text/html"),i=[];return e.body.childNodes.forEach((t=>{P.traverseNodes(t,i)})),i}static replaceElementWithNewClone(t,e){var i;const s=(e||t).cloneNode(!0);return null==(i=t.parentNode)||i.replaceChild(s,t),s}}const N=class t{static addElement(t,e){t.appendOuterContainerElemet(e),t.focusMode||(t.elementRef.scrollTop=t.elementRef.scrollHeight)}static createElements(e,i,s,n){const o=e.createMessageElementsOnOrientation("",s,n);return o.bubbleElement.classList.add(t.HTML_BUBBLE_CLASS),o.bubbleElement.innerHTML=i,o}static overwriteElements(t,e,i){i.bubbleElement.innerHTML=e,P.apply(t,i.outerContainer),O.flagHTMLUpdateClass(i.bubbleElement)}static overwrite(e,i,s,n){const{messageToElements:o}=e,r=Se.overwriteMessage(o,n,i,s,"html",t.HTML_BUBBLE_CLASS);return r&&t.overwriteElements(e,i,r),r}static create(e,i,s,n=!1){var o;const r=t.createElements(e,i,s,n);return Se.fillEmptyMessageElement(r.bubbleElement,i),P.apply(e,r.outerContainer),O.flagHTMLUpdateClass(r.bubbleElement),e.applyCustomStyles(r,s,!1,null==(o=e.messageStyles)?void 0:o.html),r}static add(e,i,s,n,o,r=!1){if(null!=o&&o.status){const t=this.overwrite(e,i,s,n);if(t)return t;o.status=!1}const a=t.create(e,i,s,r);return r||t.addElement(e,a.outerContainer),a}};N.HTML_BUBBLE_CLASS="html-message";let R=N;var q;function B(t){return(q=q||document.createElement("textarea")).innerHTML="&"+t+";",q.value}var L=Object.prototype.hasOwnProperty;function F(t){return[].slice.call(arguments,1).forEach((function(e){if(e){if("object"!=typeof e)throw new TypeError(e+"must be object");Object.keys(e).forEach((function(i){t[i]=e[i]}))}})),t}var z=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function D(t){return t.indexOf("\\")<0?t:t.replace(z,"$1")}function $(t){return!(t>=55296&&t<=57343||t>=64976&&t<=65007||!(65535&~t)||65534==(65535&t)||t>=0&&t<=8||11===t||t>=14&&t<=31||t>=127&&t<=159||t>1114111)}function J(t){if(t>65535){var e=55296+((t-=65536)>>10),i=56320+(1023&t);return String.fromCharCode(e,i)}return String.fromCharCode(t)}var U=/&([a-z#][a-z0-9]{1,31});/gi,V=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;function H(t,e){var i=0,s=B(e);return e!==s?s:35===e.charCodeAt(0)&&V.test(e)&&$(i="x"===e[1].toLowerCase()?parseInt(e.slice(2),16):parseInt(e.slice(1),10))?J(i):t}function K(t){return t.indexOf("&")<0?t:t.replace(U,H)}var G=/[&<>"]/,Z=/[&<>"]/g,W={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function X(t){return W[t]}function Y(t){return G.test(t)?t.replace(Z,X):t}var Q={};function tt(t,e){return++e>=t.length-2?e:"paragraph_open"===t[e].type&&t[e].tight&&"inline"===t[e+1].type&&0===t[e+1].content.length&&"paragraph_close"===t[e+2].type&&t[e+2].tight?tt(t,e+2):e}Q.blockquote_open=function(){return"<blockquote>\n"},Q.blockquote_close=function(t,e){return"</blockquote>"+et(t,e)},Q.code=function(t,e){return t[e].block?"<pre><code>"+Y(t[e].content)+"</code></pre>"+et(t,e):"<code>"+Y(t[e].content)+"</code>"},Q.fence=function(t,e,i,s,n){var o,r,a=t[e],l="",c=i.langPrefix;if(a.params){if(r=(o=a.params.split(/\s+/g)).join(" "),function(t,e){return!!t&&L.call(t,e)}(n.rules.fence_custom,o[0]))return n.rules.fence_custom[o[0]](t,e,i,s,n);l=' class="'+c+Y(K(D(r)))+'"'}return"<pre><code"+l+">"+(i.highlight&&i.highlight.apply(i.highlight,[a.content].concat(o))||Y(a.content))+"</code></pre>"+et(t,e)},Q.fence_custom={},Q.heading_open=function(t,e){return"<h"+t[e].hLevel+">"},Q.heading_close=function(t,e){return"</h"+t[e].hLevel+">\n"},Q.hr=function(t,e,i){return(i.xhtmlOut?"<hr />":"<hr>")+et(t,e)},Q.bullet_list_open=function(){return"<ul>\n"},Q.bullet_list_close=function(t,e){return"</ul>"+et(t,e)},Q.list_item_open=function(){return"<li>"},Q.list_item_close=function(){return"</li>\n"},Q.ordered_list_open=function(t,e){var i=t[e];return"<ol"+(i.order>1?' start="'+i.order+'"':"")+">\n"},Q.ordered_list_close=function(t,e){return"</ol>"+et(t,e)},Q.paragraph_open=function(t,e){return t[e].tight?"":"<p>"},Q.paragraph_close=function(t,e){var i=!(t[e].tight&&e&&"inline"===t[e-1].type&&!t[e-1].content);return(t[e].tight?"":"</p>")+(i?et(t,e):"")},Q.link_open=function(t,e,i){var s=t[e].title?' title="'+Y(K(t[e].title))+'"':"",n=i.linkTarget?' target="'+i.linkTarget+'"':"";return'<a href="'+Y(t[e].href)+'"'+s+n+">"},Q.link_close=function(){return"</a>"},Q.image=function(t,e,i){var s=' src="'+Y(t[e].src)+'"',n=t[e].title?' title="'+Y(K(t[e].title))+'"':"";return"<img"+s+(' alt="'+(t[e].alt?Y(K(D(t[e].alt))):"")+'"')+n+(i.xhtmlOut?" /":"")+">"},Q.table_open=function(){return"<table>\n"},Q.table_close=function(){return"</table>\n"},Q.thead_open=function(){return"<thead>\n"},Q.thead_close=function(){return"</thead>\n"},Q.tbody_open=function(){return"<tbody>\n"},Q.tbody_close=function(){return"</tbody>\n"},Q.tr_open=function(){return"<tr>"},Q.tr_close=function(){return"</tr>\n"},Q.th_open=function(t,e){var i=t[e];return"<th"+(i.align?' style="text-align:'+i.align+'"':"")+">"},Q.th_close=function(){return"</th>"},Q.td_open=function(t,e){var i=t[e];return"<td"+(i.align?' style="text-align:'+i.align+'"':"")+">"},Q.td_close=function(){return"</td>"},Q.strong_open=function(){return"<strong>"},Q.strong_close=function(){return"</strong>"},Q.em_open=function(){return"<em>"},Q.em_close=function(){return"</em>"},Q.del_open=function(){return"<del>"},Q.del_close=function(){return"</del>"},Q.ins_open=function(){return"<ins>"},Q.ins_close=function(){return"</ins>"},Q.mark_open=function(){return"<mark>"},Q.mark_close=function(){return"</mark>"},Q.sub=function(t,e){return"<sub>"+Y(t[e].content)+"</sub>"},Q.sup=function(t,e){return"<sup>"+Y(t[e].content)+"</sup>"},Q.hardbreak=function(t,e,i){return i.xhtmlOut?"<br />\n":"<br>\n"},Q.softbreak=function(t,e,i){return i.breaks?i.xhtmlOut?"<br />\n":"<br>\n":"\n"},Q.text=function(t,e){return Y(t[e].content)},Q.htmlblock=function(t,e){return t[e].content},Q.htmltag=function(t,e){return t[e].content},Q.abbr_open=function(t,e){return'<abbr title="'+Y(K(t[e].title))+'">'},Q.abbr_close=function(){return"</abbr>"},Q.footnote_ref=function(t,e){var i=Number(t[e].id+1).toString(),s="fnref"+i;return t[e].subId>0&&(s+=":"+t[e].subId),'<sup class="footnote-ref"><a href="#fn'+i+'" id="'+s+'">['+i+"]</a></sup>"},Q.footnote_block_open=function(t,e,i){return(i.xhtmlOut?'<hr class="footnotes-sep" />\n':'<hr class="footnotes-sep">\n')+'<section class="footnotes">\n<ol class="footnotes-list">\n'},Q.footnote_block_close=function(){return"</ol>\n</section>\n"},Q.footnote_open=function(t,e){return'<li id="fn'+Number(t[e].id+1).toString()+'" class="footnote-item">'},Q.footnote_close=function(){return"</li>\n"},Q.footnote_anchor=function(t,e){var i="fnref"+Number(t[e].id+1).toString();return t[e].subId>0&&(i+=":"+t[e].subId),' <a href="#'+i+'" class="footnote-backref">↩</a>'},Q.dl_open=function(){return"<dl>\n"},Q.dt_open=function(){return"<dt>"},Q.dd_open=function(){return"<dd>"},Q.dl_close=function(){return"</dl>\n"},Q.dt_close=function(){return"</dt>\n"},Q.dd_close=function(){return"</dd>\n"};var et=Q.getBreak=function(t,e){return(e=tt(t,e))<t.length&&"list_item_close"===t[e].type?"":"\n"};function it(){this.rules=F({},Q),this.getBreak=Q.getBreak}function st(){this.t=[],this.i=null}function nt(t,e,i,s,n){this.src=t,this.env=s,this.options=i,this.parser=e,this.tokens=n,this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache=[],this.isInLabel=!1,this.linkLevel=0,this.linkContent="",this.labelUnmatchedScopes=0}function ot(t,e){var i,s,n,o=-1,r=t.posMax,a=t.pos,l=t.isInLabel;if(t.isInLabel)return-1;if(t.labelUnmatchedScopes)return t.labelUnmatchedScopes--,-1;for(t.pos=e+1,t.isInLabel=!0,i=1;t.pos<r;){if(91===(n=t.src.charCodeAt(t.pos)))i++;else if(93===n&&0===--i){s=!0;break}t.parser.skipToken(t)}return s?(o=t.pos,t.labelUnmatchedScopes=0):t.labelUnmatchedScopes=i-1,t.pos=a,t.isInLabel=l,o}function rt(t,e,i,s){var n,o,r,a,l,c;if(42!==t.charCodeAt(0)||91!==t.charCodeAt(1)||-1===t.indexOf("]:")||((o=ot(n=new nt(t,e,i,s,[]),1))<0||58!==t.charCodeAt(o+1)))return-1;for(a=n.posMax,r=o+2;r<a&&10!==n.src.charCodeAt(r);r++);return l=t.slice(2,o),0===(c=t.slice(o+2,r).trim()).length?-1:(s.abbreviations||(s.abbreviations={}),typeof s.abbreviations[":"+l]>"u"&&(s.abbreviations[":"+l]=c),r)}function at(t){var e=K(t);try{e=decodeURI(e)}catch{}return encodeURI(e)}function lt(t,e){var i,s,n,o=e,r=t.posMax;if(60===t.src.charCodeAt(e)){for(e++;e<r;){if(10===(i=t.src.charCodeAt(e)))return!1;if(62===i)return n=at(D(t.src.slice(o+1,e))),!!t.parser.validateLink(n)&&(t.pos=e+1,t.linkContent=n,!0);92===i&&e+1<r?e+=2:e++}return!1}for(s=0;e<r&&!(32===(i=t.src.charCodeAt(e))||i<32||127===i);)if(92===i&&e+1<r)e+=2;else{if(40===i&&++s>1||41===i&&--s<0)break;e++}return!(o===e||(n=D(t.src.slice(o,e)),!t.parser.validateLink(n)))&&(t.linkContent=n,t.pos=e,!0)}function ct(t,e){var i,s=e,n=t.posMax,o=t.src.charCodeAt(e);if(34!==o&&39!==o&&40!==o)return!1;for(e++,40===o&&(o=41);e<n;){if((i=t.src.charCodeAt(e))===o)return t.pos=e+1,t.linkContent=D(t.src.slice(s+1,e)),!0;92===i&&e+1<n?e+=2:e++}return!1}function ht(t){return t.trim().replace(/\s+/g," ").toUpperCase()}function ut(t,e,i,s){var n,o,r,a,l,c,h,u,d;if(91!==t.charCodeAt(0)||-1===t.indexOf("]:")||((o=ot(n=new nt(t,e,i,s,[]),0))<0||58!==t.charCodeAt(o+1)))return-1;for(a=n.posMax,r=o+2;r<a&&(32===(l=n.src.charCodeAt(r))||10===l);r++);if(!lt(n,r))return-1;for(h=n.linkContent,c=r=n.pos,r+=1;r<a&&(32===(l=n.src.charCodeAt(r))||10===l);r++);for(r<a&&c!==r&&ct(n,r)?(u=n.linkContent,r=n.pos):(u="",r=c);r<a&&32===n.src.charCodeAt(r);)r++;return r<a&&10!==n.src.charCodeAt(r)?-1:(d=ht(t.slice(1,o)),typeof s.references[d]>"u"&&(s.references[d]={title:u,href:h}),r)}it.prototype.renderInline=function(t,e,i){for(var s=this.rules,n=t.length,o=0,r="";n--;)r+=s[t[o].type](t,o++,e,i,this);return r},it.prototype.render=function(t,e,i){for(var s=this.rules,n=t.length,o=-1,r="";++o<n;)"inline"===t[o].type?r+=this.renderInline(t[o].children,e,i):r+=s[t[o].type](t,o,e,i,this);return r},st.prototype.o=function(t){for(var e=this.t.length,i=-1;e--;)if(this.t[++i].name===t)return i;return-1},st.prototype.l=function(){var t=this,e=[""];t.t.forEach((function(t){t.enabled&&t.alt.forEach((function(t){e.indexOf(t)<0&&e.push(t)}))})),t.i={},e.forEach((function(e){t.i[e]=[],t.t.forEach((function(i){i.enabled&&(e&&i.alt.indexOf(e)<0||t.i[e].push(i.fn))}))}))},st.prototype.at=function(t,e,i){var s=this.o(t),n=i||{};if(-1===s)throw new Error("Parser rule not found: "+t);this.t[s].fn=e,this.t[s].alt=n.alt||[],this.i=null},st.prototype.before=function(t,e,i,s){var n=this.o(t),o=s||{};if(-1===n)throw new Error("Parser rule not found: "+t);this.t.splice(n,0,{name:e,enabled:!0,fn:i,alt:o.alt||[]}),this.i=null},st.prototype.after=function(t,e,i,s){var n=this.o(t),o=s||{};if(-1===n)throw new Error("Parser rule not found: "+t);this.t.splice(n+1,0,{name:e,enabled:!0,fn:i,alt:o.alt||[]}),this.i=null},st.prototype.push=function(t,e,i){var s=i||{};this.t.push({name:t,enabled:!0,fn:e,alt:s.alt||[]}),this.i=null},st.prototype.enable=function(t,e){t=Array.isArray(t)?t:[t],e&&this.t.forEach((function(t){t.enabled=!1})),t.forEach((function(t){var e=this.o(t);if(e<0)throw new Error("Rules manager: invalid rule name "+t);this.t[e].enabled=!0}),this),this.i=null},st.prototype.disable=function(t){(t=Array.isArray(t)?t:[t]).forEach((function(t){var e=this.o(t);if(e<0)throw new Error("Rules manager: invalid rule name "+t);this.t[e].enabled=!1}),this),this.i=null},st.prototype.getRules=function(t){return null===this.i&&this.l(),this.i[t]||[]},nt.prototype.pushPending=function(){this.tokens.push({type:"text",content:this.pending,level:this.pendingLevel}),this.pending=""},nt.prototype.push=function(t){this.pending&&this.pushPending(),this.tokens.push(t),this.pendingLevel=this.level},nt.prototype.cacheSet=function(t,e){for(var i=this.cache.length;i<=t;i++)this.cache.push(0);this.cache[t]=e},nt.prototype.cacheGet=function(t){return t<this.cache.length?this.cache[t]:0};var dt=" \n()[]'\".,!?-";function pt(t){return t.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1")}var mt=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,vt=/\((c|tm|r|p)\)/gi,ft={c:"©",r:"®",p:"§",tm:"™"};function gt(t){return t.indexOf("(")<0?t:t.replace(vt,(function(t,e){return ft[e.toLowerCase()]}))}var bt=/['"]/,yt=/['"]/g,wt=/[-\s()\[\]]/;function xt(t,e){return!(e<0||e>=t.length)&&!wt.test(t[e])}function kt(t,e,i){return t.substr(0,e)+i+t.substr(e+1)}var _t=[["block",function(t){t.inlineMode?t.tokens.push({type:"inline",content:t.src.replace(/\n/g," ").trim(),level:0,lines:[0,1],children:[]}):t.block.parse(t.src,t.options,t.env,t.tokens)}],["abbr",function(t){var e,i,s,n,o=t.tokens;if(!t.inlineMode)for(e=1,i=o.length-1;e<i;e++)if("paragraph_open"===o[e-1].type&&"inline"===o[e].type&&"paragraph_close"===o[e+1].type){for(s=o[e].content;s.length&&!((n=rt(s,t.inline,t.options,t.env))<0);)s=s.slice(n).trim();o[e].content=s,s.length||(o[e-1].tight=!0,o[e+1].tight=!0)}}],["references",function(t){var e,i,s,n,o=t.tokens;if(t.env.references=t.env.references||{},!t.inlineMode)for(e=1,i=o.length-1;e<i;e++)if("inline"===o[e].type&&"paragraph_open"===o[e-1].type&&"paragraph_close"===o[e+1].type){for(s=o[e].content;s.length&&!((n=ut(s,t.inline,t.options,t.env))<0);)s=s.slice(n).trim();o[e].content=s,s.length||(o[e-1].tight=!0,o[e+1].tight=!0)}}],["inline",function(t){var e,i,s,n=t.tokens;for(i=0,s=n.length;i<s;i++)"inline"===(e=n[i]).type&&t.inline.parse(e.content,t.options,t.env,e.children)}],["footnote_tail",function(t){var e,i,s,n,o,r,a,l,c,h=0,u=!1,d={};if(t.env.footnotes&&(t.tokens=t.tokens.filter((function(t){return"footnote_reference_open"===t.type?(u=!0,l=[],c=t.label,!1):"footnote_reference_close"===t.type?(u=!1,d[":"+c]=l,!1):(u&&l.push(t),!u)})),t.env.footnotes.list)){for(r=t.env.footnotes.list,t.tokens.push({type:"footnote_block_open",level:h++}),e=0,i=r.length;e<i;e++){for(t.tokens.push({type:"footnote_open",id:e,level:h++}),r[e].tokens?((a=[]).push({type:"paragraph_open",tight:!1,level:h++}),a.push({type:"inline",content:"",level:h,children:r[e].tokens}),a.push({type:"paragraph_close",tight:!1,level:--h})):r[e].label&&(a=d[":"+r[e].label]),t.tokens=t.tokens.concat(a),o="paragraph_close"===t.tokens[t.tokens.length-1].type?t.tokens.pop():null,n=r[e].count>0?r[e].count:1,s=0;s<n;s++)t.tokens.push({type:"footnote_anchor",id:e,subId:s,level:h});o&&t.tokens.push(o),t.tokens.push({type:"footnote_close",level:--h})}t.tokens.push({type:"footnote_block_close",level:--h})}}],["abbr2",function(t){var e,i,s,n,o,r,a,l,c,h,u,d,p=t.tokens;if(t.env.abbreviations)for(t.env.abbrRegExp||(d="(^|["+dt.split("").map(pt).join("")+"])("+Object.keys(t.env.abbreviations).map((function(t){return t.substr(1)})).sort((function(t,e){return e.length-t.length})).map(pt).join("|")+")($|["+dt.split("").map(pt).join("")+"])",t.env.abbrRegExp=new RegExp(d,"g")),h=t.env.abbrRegExp,i=0,s=p.length;i<s;i++)if("inline"===p[i].type)for(e=(n=p[i].children).length-1;e>=0;e--)if("text"===(o=n[e]).type){for(l=0,r=o.content,h.lastIndex=0,c=o.level,a=[];u=h.exec(r);)h.lastIndex>l&&a.push({type:"text",content:r.slice(l,u.index+u[1].length),level:c}),a.push({type:"abbr_open",title:t.env.abbreviations[":"+u[2]],level:c++}),a.push({type:"text",content:u[2],level:c}),a.push({type:"abbr_close",level:--c}),l=h.lastIndex-u[3].length;a.length&&(l<r.length&&a.push({type:"text",content:r.slice(l),level:c}),p[i].children=n=[].concat(n.slice(0,e),a,n.slice(e+1)))}}],["replacements",function(t){var e,i,s,n,o;if(t.options.typographer)for(o=t.tokens.length-1;o>=0;o--)if("inline"===t.tokens[o].type)for(e=(n=t.tokens[o].children).length-1;e>=0;e--)"text"===(i=n[e]).type&&(s=gt(s=i.content),mt.test(s)&&(s=s.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---([^-]|$)/gm,"$1—$2").replace(/(^|\s)--(\s|$)/gm,"$1–$2").replace(/(^|[^-\s])--([^-\s]|$)/gm,"$1–$2")),i.content=s)}],["smartquotes",function(t){var e,i,s,n,o,r,a,l,c,h,u,d,p,m,v,f,g;if(t.options.typographer)for(g=[],v=t.tokens.length-1;v>=0;v--)if("inline"===t.tokens[v].type)for(f=t.tokens[v].children,g.length=0,e=0;e<f.length;e++)if("text"===(i=f[e]).type&&!bt.test(i.text)){for(a=f[e].level,p=g.length-1;p>=0&&!(g[p].level<=a);p--);g.length=p+1,o=0,r=(s=i.content).length;t:for(;o<r&&(yt.lastIndex=o,n=yt.exec(s),n);)if(l=!xt(s,n.index-1),o=n.index+1,m="'"===n[0],(c=!xt(s,o))||l){if(u=!c,d=!l)for(p=g.length-1;p>=0&&(h=g[p],!(g[p].level<a));p--)if(h.single===m&&g[p].level===a){h=g[p],m?(f[h.token].content=kt(f[h.token].content,h.pos,t.options.quotes[2]),i.content=kt(i.content,n.index,t.options.quotes[3])):(f[h.token].content=kt(f[h.token].content,h.pos,t.options.quotes[0]),i.content=kt(i.content,n.index,t.options.quotes[1])),g.length=p;continue t}u?g.push({token:e,pos:n.index,single:m,level:a}):d&&m&&(i.content=kt(i.content,n.index,"’"))}else m&&(i.content=kt(i.content,n.index,"’"))}}]];function St(){this.options={},this.ruler=new st;for(var t=0;t<_t.length;t++)this.ruler.push(_t[t][0],_t[t][1])}function At(t,e,i,s,n){var o,r,a,l,c,h,u;for(this.src=t,this.parser=e,this.options=i,this.env=s,this.tokens=n,this.bMarks=[],this.eMarks=[],this.tShift=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.parentType="root",this.ddIndent=-1,this.level=0,this.result="",h=0,u=!1,a=l=h=0,c=(r=this.src).length;l<c;l++){if(o=r.charCodeAt(l),!u){if(32===o){h++;continue}u=!0}(10===o||l===c-1)&&(10!==o&&l++,this.bMarks.push(a),this.eMarks.push(l),this.tShift.push(h),u=!1,h=0,a=l+1)}this.bMarks.push(r.length),this.eMarks.push(r.length),this.tShift.push(0),this.lineMax=this.bMarks.length-1}function Tt(t,e){var i,s,n;return(s=t.bMarks[e]+t.tShift[e])>=(n=t.eMarks[e])||42!==(i=t.src.charCodeAt(s++))&&45!==i&&43!==i||s<n&&32!==t.src.charCodeAt(s)?-1:s}function Mt(t,e){var i,s=t.bMarks[e]+t.tShift[e],n=t.eMarks[e];if(s+1>=n||((i=t.src.charCodeAt(s++))<48||i>57))return-1;for(;;){if(s>=n)return-1;if(!((i=t.src.charCodeAt(s++))>=48&&i<=57)){if(41===i||46===i)break;return-1}}return s<n&&32!==t.src.charCodeAt(s)?-1:s}St.prototype.process=function(t){var e,i,s;for(e=0,i=(s=this.ruler.getRules("")).length;e<i;e++)s[e](t)},At.prototype.isEmpty=function(t){return this.bMarks[t]+this.tShift[t]>=this.eMarks[t]},At.prototype.skipEmptyLines=function(t){for(var e=this.lineMax;t<e&&!(this.bMarks[t]+this.tShift[t]<this.eMarks[t]);t++);return t},At.prototype.skipSpaces=function(t){for(var e=this.src.length;t<e&&32===this.src.charCodeAt(t);t++);return t},At.prototype.skipChars=function(t,e){for(var i=this.src.length;t<i&&this.src.charCodeAt(t)===e;t++);return t},At.prototype.skipCharsBack=function(t,e,i){if(t<=i)return t;for(;t>i;)if(e!==this.src.charCodeAt(--t))return t+1;return t},At.prototype.getLines=function(t,e,i,s){var n,o,r,a,l,c=t;if(t>=e)return"";if(c+1===e)return o=this.bMarks[c]+Math.min(this.tShift[c],i),r=s?this.eMarks[c]+1:this.eMarks[c],this.src.slice(o,r);for(a=new Array(e-t),n=0;c<e;c++,n++)(l=this.tShift[c])>i&&(l=i),l<0&&(l=0),o=this.bMarks[c]+l,r=c+1<e||s?this.eMarks[c]+1:this.eMarks[c],a[n]=this.src.slice(o,r);return a.join("")};var Ot={};["article","aside","button","blockquote","body","canvas","caption","col","colgroup","dd","div","dl","dt","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","hr","iframe","li","map","object","ol","output","p","pre","progress","script","section","style","table","tbody","td","textarea","tfoot","th","tr","thead","ul","video"].forEach((function(t){Ot[t]=!0}));var jt=/^<([a-zA-Z]{1,15})[\s\/>]/,Ct=/^<\/([a-zA-Z]{1,15})[\s>]/;function Et(t,e){var i=t.bMarks[e]+t.blkIndent,s=t.eMarks[e];return t.src.substr(i,s-i)}function It(t,e){var i,s,n=t.bMarks[e]+t.tShift[e],o=t.eMarks[e];return n>=o||126!==(s=t.src.charCodeAt(n++))&&58!==s||n===(i=t.skipSpaces(n))||i>=o?-1:i}var Pt=[["code",function(t,e,i){var s,n;if(t.tShift[e]-t.blkIndent<4)return!1;for(n=s=e+1;s<i;)if(t.isEmpty(s))s++;else{if(!(t.tShift[s]-t.blkIndent>=4))break;n=++s}return t.line=s,t.tokens.push({type:"code",content:t.getLines(e,n,4+t.blkIndent,!0),block:!0,lines:[e,t.line],level:t.level}),!0}],["fences",function(t,e,i,s){var n,o,r,a,l,c=!1,h=t.bMarks[e]+t.tShift[e],u=t.eMarks[e];if(h+3>u||126!==(n=t.src.charCodeAt(h))&&96!==n||(l=h,(o=(h=t.skipChars(h,n))-l)<3)||(r=t.src.slice(h,u).trim()).indexOf("`")>=0)return!1;if(s)return!0;for(a=e;!(++a>=i||(h=l=t.bMarks[a]+t.tShift[a],u=t.eMarks[a],h<u&&t.tShift[a]<t.blkIndent));)if(!(t.src.charCodeAt(h)!==n||t.tShift[a]-t.blkIndent>=4||(h=t.skipChars(h,n),h-l<o||(h=t.skipSpaces(h),h<u)))){c=!0;break}return o=t.tShift[e],t.line=a+(c?1:0),t.tokens.push({type:"fence",params:r,content:t.getLines(e+1,a,o,!0),lines:[e,t.line],level:t.level}),!0},["paragraph","blockquote","list"]],["blockquote",function(t,e,i,s){var n,o,r,a,l,c,h,u,d,p,m,v=t.bMarks[e]+t.tShift[e],f=t.eMarks[e];if(v>f||62!==t.src.charCodeAt(v++)||t.level>=t.options.maxNesting)return!1;if(s)return!0;for(32===t.src.charCodeAt(v)&&v++,l=t.blkIndent,t.blkIndent=0,a=[t.bMarks[e]],t.bMarks[e]=v,o=(v=v<f?t.skipSpaces(v):v)>=f,r=[t.tShift[e]],t.tShift[e]=v-t.bMarks[e],u=t.parser.ruler.getRules("blockquote"),n=e+1;n<i&&!((v=t.bMarks[n]+t.tShift[n])>=(f=t.eMarks[n]));n++)if(62!==t.src.charCodeAt(v++)){if(o)break;for(m=!1,d=0,p=u.length;d<p;d++)if(u[d](t,n,i,!0)){m=!0;break}if(m)break;a.push(t.bMarks[n]),r.push(t.tShift[n]),t.tShift[n]=-1337}else 32===t.src.charCodeAt(v)&&v++,a.push(t.bMarks[n]),t.bMarks[n]=v,o=(v=v<f?t.skipSpaces(v):v)>=f,r.push(t.tShift[n]),t.tShift[n]=v-t.bMarks[n];for(c=t.parentType,t.parentType="blockquote",t.tokens.push({type:"blockquote_open",lines:h=[e,0],level:t.level++}),t.parser.tokenize(t,e,n),t.tokens.push({type:"blockquote_close",level:--t.level}),t.parentType=c,h[1]=t.line,d=0;d<r.length;d++)t.bMarks[d+e]=a[d],t.tShift[d+e]=r[d];return t.blkIndent=l,!0},["paragraph","blockquote","list"]],["hr",function(t,e,i,s){var n,o,r,a=t.bMarks[e],l=t.eMarks[e];if((a+=t.tShift[e])>l||42!==(n=t.src.charCodeAt(a++))&&45!==n&&95!==n)return!1;for(o=1;a<l;){if((r=t.src.charCodeAt(a++))!==n&&32!==r)return!1;r===n&&o++}return!(o<3)&&(s||(t.line=e+1,t.tokens.push({type:"hr",lines:[e,t.line],level:t.level})),!0)},["paragraph","blockquote","list"]],["list",function(t,e,i,s){var n,o,r,a,l,c,h,u,d,p,m,v,f,g,b,y,w,x,k,_,S,A=!0;if((u=Mt(t,e))>=0)v=!0;else{if(!((u=Tt(t,e))>=0))return!1;v=!1}if(t.level>=t.options.maxNesting)return!1;if(m=t.src.charCodeAt(u-1),s)return!0;for(g=t.tokens.length,v?(h=t.bMarks[e]+t.tShift[e],p=Number(t.src.substr(h,u-h-1)),t.tokens.push({type:"ordered_list_open",order:p,lines:y=[e,0],level:t.level++})):t.tokens.push({type:"bullet_list_open",lines:y=[e,0],level:t.level++}),n=e,b=!1,x=t.parser.ruler.getRules("list");n<i&&((d=(f=t.skipSpaces(u))>=t.eMarks[n]?1:f-u)>4&&(d=1),d<1&&(d=1),o=u-t.bMarks[n]+d,t.tokens.push({type:"list_item_open",lines:w=[e,0],level:t.level++}),a=t.blkIndent,l=t.tight,r=t.tShift[e],c=t.parentType,t.tShift[e]=f-t.bMarks[e],t.blkIndent=o,t.tight=!0,t.parentType="list",t.parser.tokenize(t,e,i,!0),(!t.tight||b)&&(A=!1),b=t.line-e>1&&t.isEmpty(t.line-1),t.blkIndent=a,t.tShift[e]=r,t.tight=l,t.parentType=c,t.tokens.push({type:"list_item_close",level:--t.level}),n=e=t.line,w[1]=n,f=t.bMarks[e],!(n>=i||t.isEmpty(n)||t.tShift[n]<t.blkIndent));){for(S=!1,k=0,_=x.length;k<_;k++)if(x[k](t,n,i,!0)){S=!0;break}if(S)break;if(v){if((u=Mt(t,n))<0)break}else if((u=Tt(t,n))<0)break;if(m!==t.src.charCodeAt(u-1))break}return t.tokens.push({type:v?"ordered_list_close":"bullet_list_close",level:--t.level}),y[1]=n,t.line=n,A&&function(t,e){var i,s,n=t.level+2;for(i=e+2,s=t.tokens.length-2;i<s;i++)t.tokens[i].level===n&&"paragraph_open"===t.tokens[i].type&&(t.tokens[i+2].tight=!0,t.tokens[i].tight=!0,i+=2)}(t,g),!0},["paragraph","blockquote"]],["footnote",function(t,e,i,s){var n,o,r,a,l,c=t.bMarks[e]+t.tShift[e],h=t.eMarks[e];if(c+4>h||91!==t.src.charCodeAt(c)||94!==t.src.charCodeAt(c+1)||t.level>=t.options.maxNesting)return!1;for(a=c+2;a<h;a++){if(32===t.src.charCodeAt(a))return!1;if(93===t.src.charCodeAt(a))break}return!(a===c+2||a+1>=h||58!==t.src.charCodeAt(++a))&&(s||(a++,t.env.footnotes||(t.env.footnotes={}),t.env.footnotes.refs||(t.env.footnotes.refs={}),l=t.src.slice(c+2,a-2),t.env.footnotes.refs[":"+l]=-1,t.tokens.push({type:"footnote_reference_open",label:l,level:t.level++}),n=t.bMarks[e],o=t.tShift[e],r=t.parentType,t.tShift[e]=t.skipSpaces(a)-a,t.bMarks[e]=a,t.blkIndent+=4,t.parentType="footnote",t.tShift[e]<t.blkIndent&&(t.tShift[e]+=t.blkIndent,t.bMarks[e]-=t.blkIndent),t.parser.tokenize(t,e,i,!0),t.parentType=r,t.blkIndent-=4,t.tShift[e]=o,t.bMarks[e]=n,t.tokens.push({type:"footnote_reference_close",level:--t.level})),!0)},["paragraph"]],["heading",function(t,e,i,s){var n,o,r,a=t.bMarks[e]+t.tShift[e],l=t.eMarks[e];if(a>=l||(35!==(n=t.src.charCodeAt(a))||a>=l))return!1;for(o=1,n=t.src.charCodeAt(++a);35===n&&a<l&&o<=6;)o++,n=t.src.charCodeAt(++a);return!(o>6||a<l&&32!==n)&&(s||(l=t.skipCharsBack(l,32,a),(r=t.skipCharsBack(l,35,a))>a&&32===t.src.charCodeAt(r-1)&&(l=r),t.line=e+1,t.tokens.push({type:"heading_open",hLevel:o,lines:[e,t.line],level:t.level}),a<l&&t.tokens.push({type:"inline",content:t.src.slice(a,l).trim(),level:t.level+1,lines:[e,t.line],children:[]}),t.tokens.push({type:"heading_close",hLevel:o,level:t.level})),!0)},["paragraph","blockquote"]],["lheading",function(t,e,i){var s,n,o,r=e+1;return!(r>=i||t.tShift[r]<t.blkIndent||t.tShift[r]-t.blkIndent>3||(n=t.bMarks[r]+t.tShift[r],o=t.eMarks[r],n>=o)||(s=t.src.charCodeAt(n),45!==s&&61!==s)||(n=t.skipChars(n,s),n=t.skipSpaces(n),n<o))&&(n=t.bMarks[e]+t.tShift[e],t.line=r+1,t.tokens.push({type:"heading_open",hLevel:61===s?1:2,lines:[e,t.line],level:t.level}),t.tokens.push({type:"inline",content:t.src.slice(n,t.eMarks[e]).trim(),level:t.level+1,lines:[e,t.line-1],children:[]}),t.tokens.push({type:"heading_close",hLevel:61===s?1:2,level:t.level}),!0)}],["htmlblock",function(t,e,i,s){var n,o,r,a=t.bMarks[e],l=t.eMarks[e],c=t.tShift[e];if(a+=c,!t.options.html||c>3||a+2>=l||60!==t.src.charCodeAt(a))return!1;if(33===(n=t.src.charCodeAt(a+1))||63===n){if(s)return!0}else{if(47!==n&&!function(t){var e=32|t;return e>=97&&e<=122}(n))return!1;if(47===n){if(!(o=t.src.slice(a,l).match(Ct)))return!1}else if(!(o=t.src.slice(a,l).match(jt)))return!1;if(!0!==Ot[o[1].toLowerCase()])return!1;if(s)return!0}for(r=e+1;r<t.lineMax&&!t.isEmpty(r);)r++;return t.line=r,t.tokens.push({type:"htmlblock",level:t.level,lines:[e,t.line],content:t.getLines(e,r,0,!0)}),!0},["paragraph","blockquote"]],["table",function(t,e,i,s){var n,o,r,a,l,c,h,u,d,p,m;if(e+2>i||(l=e+1,t.tShift[l]<t.blkIndent)||(r=t.bMarks[l]+t.tShift[l])>=t.eMarks[l]||124!==(n=t.src.charCodeAt(r))&&45!==n&&58!==n||(o=Et(t,e+1),!/^[-:| ]+$/.test(o))||(c=o.split("|"))<=2)return!1;for(u=[],a=0;a<c.length;a++){if(!(d=c[a].trim())){if(0===a||a===c.length-1)continue;return!1}if(!/^:?-+:?$/.test(d))return!1;58===d.charCodeAt(d.length-1)?u.push(58===d.charCodeAt(0)?"center":"right"):58===d.charCodeAt(0)?u.push("left"):u.push("")}if(-1===(o=Et(t,e).trim()).indexOf("|")||(c=o.replace(/^\||\|$/g,"").split("|"),u.length!==c.length))return!1;if(s)return!0;for(t.tokens.push({type:"table_open",lines:p=[e,0],level:t.level++}),t.tokens.push({type:"thead_open",lines:[e,e+1],level:t.level++}),t.tokens.push({type:"tr_open",lines:[e,e+1],level:t.level++}),a=0;a<c.length;a++)t.tokens.push({type:"th_open",align:u[a],lines:[e,e+1],level:t.level++}),t.tokens.push({type:"inline",content:c[a].trim(),lines:[e,e+1],level:t.level,children:[]}),t.tokens.push({type:"th_close",level:--t.level});for(t.tokens.push({type:"tr_close",level:--t.level}),t.tokens.push({type:"thead_close",level:--t.level}),t.tokens.push({type:"tbody_open",lines:m=[e+2,0],level:t.level++}),l=e+2;l<i&&!(t.tShift[l]<t.blkIndent||(o=Et(t,l).trim(),-1===o.indexOf("|")));l++){for(c=o.replace(/^\||\|$/g,"").split("|"),t.tokens.push({type:"tr_open",level:t.level++}),a=0;a<c.length;a++)t.tokens.push({type:"td_open",align:u[a],level:t.level++}),h=c[a].substring(124===c[a].charCodeAt(0)?1:0,124===c[a].charCodeAt(c[a].length-1)?c[a].length-1:c[a].length).trim(),t.tokens.push({type:"inline",content:h,level:t.level,children:[]}),t.tokens.push({type:"td_close",level:--t.level});t.tokens.push({type:"tr_close",level:--t.level})}return t.tokens.push({type:"tbody_close",level:--t.level}),t.tokens.push({type:"table_close",level:--t.level}),p[1]=m[1]=l,t.line=l,!0},["paragraph"]],["deflist",function(t,e,i,s){var n,o,r,a,l,c,h,u,d,p,m,v,f,g;if(s)return!(t.ddIndent<0)&&It(t,e)>=0;if(h=e+1,t.isEmpty(h)&&++h>i||t.tShift[h]<t.blkIndent||(n=It(t,h))<0||t.level>=t.options.maxNesting)return!1;c=t.tokens.length,t.tokens.push({type:"dl_open",lines:l=[e,0],level:t.level++}),r=e,o=h;t:for(;;){for(g=!0,f=!1,t.tokens.push({type:"dt_open",lines:[r,r],level:t.level++}),t.tokens.push({type:"inline",content:t.getLines(r,r+1,t.blkIndent,!1).trim(),level:t.level+1,lines:[r,r],children:[]}),t.tokens.push({type:"dt_close",level:--t.level});;){if(t.tokens.push({type:"dd_open",lines:a=[h,0],level:t.level++}),v=t.tight,d=t.ddIndent,u=t.blkIndent,m=t.tShift[o],p=t.parentType,t.blkIndent=t.ddIndent=t.tShift[o]+2,t.tShift[o]=n-t.bMarks[o],t.tight=!0,t.parentType="deflist",t.parser.tokenize(t,o,i,!0),(!t.tight||f)&&(g=!1),f=t.line-o>1&&t.isEmpty(t.line-1),t.tShift[o]=m,t.tight=v,t.parentType=p,t.blkIndent=u,t.ddIndent=d,t.tokens.push({type:"dd_close",level:--t.level}),a[1]=h=t.line,h>=i||t.tShift[h]<t.blkIndent)break t;if((n=It(t,h))<0)break;o=h}if(h>=i||(r=h,t.isEmpty(r))||t.tShift[r]<t.blkIndent||(o=r+1)>=i||(t.isEmpty(o)&&o++,o>=i)||t.tShift[o]<t.blkIndent||(n=It(t,o))<0)break}return t.tokens.push({type:"dl_close",level:--t.level}),l[1]=h,t.line=h,g&&function(t,e){var i,s,n=t.level+2;for(i=e+2,s=t.tokens.length-2;i<s;i++)t.tokens[i].level===n&&"paragraph_open"===t.tokens[i].type&&(t.tokens[i+2].tight=!0,t.tokens[i].tight=!0,i+=2)}(t,c),!0},["paragraph"]],["paragraph",function(t,e){var i,s,n,o,r,a,l=e+1;if(l<(i=t.lineMax)&&!t.isEmpty(l))for(a=t.parser.ruler.getRules("paragraph");l<i&&!t.isEmpty(l);l++)if(!(t.tShift[l]-t.blkIndent>3)){for(n=!1,o=0,r=a.length;o<r;o++)if(a[o](t,l,i,!0)){n=!0;break}if(n)break}return s=t.getLines(e,l,t.blkIndent,!1).trim(),t.line=l,s.length&&(t.tokens.push({type:"paragraph_open",tight:!1,lines:[e,t.line],level:t.level}),t.tokens.push({type:"inline",content:s,level:t.level+1,lines:[e,t.line],children:[]}),t.tokens.push({type:"paragraph_close",tight:!1,level:t.level})),!0}]];function Nt(){this.ruler=new st;for(var t=0;t<Pt.length;t++)this.ruler.push(Pt[t][0],Pt[t][1],{alt:(Pt[t][2]||[]).slice()})}Nt.prototype.tokenize=function(t,e,i){for(var s,n=this.ruler.getRules(""),o=n.length,r=e,a=!1;r<i&&(t.line=r=t.skipEmptyLines(r),!(r>=i||t.tShift[r]<t.blkIndent));){for(s=0;s<o&&!n[s](t,r,i,!1);s++);if(t.tight=!a,t.isEmpty(t.line-1)&&(a=!0),(r=t.line)<i&&t.isEmpty(r)){if(a=!0,++r<i&&"list"===t.parentType&&t.isEmpty(r))break;t.line=r}}};var Rt=/[\n\t]/g,qt=/\r[\n\u0085]|[\u2424\u2028\u0085]/g,Bt=/\u00a0/g;function Lt(t){switch(t){case 10:case 92:case 96:case 42:case 95:case 94:case 91:case 93:case 33:case 38:case 60:case 62:case 123:case 125:case 36:case 37:case 64:case 126:case 43:case 61:case 58:return!0;default:return!1}}Nt.prototype.parse=function(t,e,i,s){var n,o=0,r=0;if(!t)return[];(t=(t=t.replace(Bt," ")).replace(qt,"\n")).indexOf("\t")>=0&&(t=t.replace(Rt,(function(e,i){var s;return 10===t.charCodeAt(i)?(o=i+1,r=0,e):(s=" ".slice((i-o-r)%4),r=i-o+1,s)}))),n=new At(t,this,e,i,s),this.tokenize(n,n.line,n.lineMax)};for(var Ft=[],zt=0;zt<256;zt++)Ft.push(0);function Dt(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}function $t(t,e){var i,s,n,o=e,r=!0,a=!0,l=t.posMax,c=t.src.charCodeAt(e);for(i=e>0?t.src.charCodeAt(e-1):-1;o<l&&t.src.charCodeAt(o)===c;)o++;return o>=l&&(r=!1),(n=o-e)>=4?r=a=!1:((32===(s=o<l?t.src.charCodeAt(o):-1)||10===s)&&(r=!1),(32===i||10===i)&&(a=!1),95===c&&(Dt(i)&&(r=!1),Dt(s)&&(a=!1))),{can_open:r,can_close:a,delims:n}}"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach((function(t){Ft[t.charCodeAt(0)]=1}));var Jt=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Ut=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Vt=["coap","doi","javascript","aaa","aaas","about","acap","cap","cid","crid","data","dav","dict","dns","file","ftp","geo","go","gopher","h323","http","https","iax","icap","im","imap","info","ipp","iris","iris.beep","iris.xpc","iris.xpcs","iris.lwz","ldap","mailto","mid","msrp","msrps","mtqp","mupdate","news","nfs","ni","nih","nntp","opaquelocktoken","pop","pres","rtsp","service","session","shttp","sieve","sip","sips","sms","snmp","soap.beep","soap.beeps","tag","tel","telnet","tftp","thismessage","tn3270","tip","tv","urn","vemmi","ws","wss","xcon","xcon-userid","xmlrpc.beep","xmlrpc.beeps","xmpp","z39.50r","z39.50s","adiumxtra","afp","afs","aim","apt","attachment","aw","beshare","bitcoin","bolo","callto","chrome","chrome-extension","com-eventbrite-attendee","content","cvs","dlna-playsingle","dlna-playcontainer","dtn","dvb","ed2k","facetime","feed","finger","fish","gg","git","gizmoproject","gtalk","hcp","icon","ipn","irc","irc6","ircs","itms","jar","jms","keyparc","lastfm","ldaps","magnet","maps","market","message","mms","ms-help","msnim","mumble","mvn","notes","oid","palm","paparazzi","platform","proxy","psyc","query","res","resource","rmi","rsync","rtmp","secondlife","sftp","sgn","skype","smb","soldat","spotify","ssh","steam","svn","teamspeak","things","udp","unreal","ut2004","ventrilo","view-source","webcal","wtai","wyciwyg","xfire","xri","ymsgr"],Ht=/^<([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/,Kt=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;function Gt(t,e){return t=t.source,e=e||"",function i(s,n){return s?(n=n.source||n,t=t.replace(s,n),i):new RegExp(t,e)}}var Zt=Gt(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",/[^"'=<>`\x00-\x20]+/)("single_quoted",/'[^']*'/)("double_quoted",/"[^"]*"/)(),Wt=Gt(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",/[a-zA-Z_:][a-zA-Z0-9:._-]*/)("attr_value",Zt)(),Xt=Gt(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",Wt)(),Yt=Gt(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",Xt)("close_tag",/<\/[A-Za-z][A-Za-z0-9]*\s*>/)("comment",/<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->/)("processing",/<[?].*?[?]>/)("declaration",/<![A-Z]+\s+[^>]*>/)("cdata",/<!\[CDATA\[[\s\S]*?\]\]>/)();var Qt=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,te=/^&([a-z][a-z0-9]{1,31});/i;var ee=[["text",function(t,e){for(var i=t.pos;i<t.posMax&&!Lt(t.src.charCodeAt(i));)i++;return i!==t.pos&&(e||(t.pending+=t.src.slice(t.pos,i)),t.pos=i,!0)}],["newline",function(t,e){var i,s,n=t.pos;if(10!==t.src.charCodeAt(n))return!1;if(i=t.pending.length-1,s=t.posMax,!e)if(i>=0&&32===t.pending.charCodeAt(i))if(i>=1&&32===t.pending.charCodeAt(i-1)){for(var o=i-2;o>=0;o--)if(32!==t.pending.charCodeAt(o)){t.pending=t.pending.substring(0,o+1);break}t.push({type:"hardbreak",level:t.level})}else t.pending=t.pending.slice(0,-1),t.push({type:"softbreak",level:t.level});else t.push({type:"softbreak",level:t.level});for(n++;n<s&&32===t.src.charCodeAt(n);)n++;return t.pos=n,!0}],["escape",function(t,e){var i,s=t.pos,n=t.posMax;if(92!==t.src.charCodeAt(s))return!1;if(++s<n){if((i=t.src.charCodeAt(s))<256&&0!==Ft[i])return e||(t.pending+=t.src[s]),t.pos+=2,!0;if(10===i){for(e||t.push({type:"hardbreak",level:t.level}),s++;s<n&&32===t.src.charCodeAt(s);)s++;return t.pos=s,!0}}return e||(t.pending+="\\"),t.pos++,!0}],["backticks",function(t,e){var i,s,n,o,r,a=t.pos;if(96!==t.src.charCodeAt(a))return!1;for(i=a,a++,s=t.posMax;a<s&&96===t.src.charCodeAt(a);)a++;for(n=t.src.slice(i,a),o=r=a;-1!==(o=t.src.indexOf("`",r));){for(r=o+1;r<s&&96===t.src.charCodeAt(r);)r++;if(r-o===n.length)return e||t.push({type:"code",content:t.src.slice(a,o).replace(/[ \n]+/g," ").trim(),block:!1,level:t.level}),t.pos=r,!0}return e||(t.pending+=n),t.pos+=n.length,!0}],["del",function(t,e){var i,s,n,o,r,a=t.posMax,l=t.pos;if(126!==t.src.charCodeAt(l)||e||l+4>=a||126!==t.src.charCodeAt(l+1)||t.level>=t.options.maxNesting||(o=l>0?t.src.charCodeAt(l-1):-1,r=t.src.charCodeAt(l+2),126===o)||126===r||32===r||10===r)return!1;for(s=l+2;s<a&&126===t.src.charCodeAt(s);)s++;if(s>l+3)return t.pos+=s-l,e||(t.pending+=t.src.slice(l,s)),!0;for(t.pos=l+2,n=1;t.pos+1<a;){if(126===t.src.charCodeAt(t.pos)&&126===t.src.charCodeAt(t.pos+1)&&(o=t.src.charCodeAt(t.pos-1),126!==(r=t.pos+2<a?t.src.charCodeAt(t.pos+2):-1)&&126!==o&&(32!==o&&10!==o?n--:32!==r&&10!==r&&n++,n<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=l+2,e||(t.push({type:"del_open",level:t.level++}),t.parser.tokenize(t),t.push({type:"del_close",level:--t.level})),t.pos=t.posMax+2,t.posMax=a,!0):(t.pos=l,!1)}],["ins",function(t,e){var i,s,n,o,r,a=t.posMax,l=t.pos;if(43!==t.src.charCodeAt(l)||e||l+4>=a||43!==t.src.charCodeAt(l+1)||t.level>=t.options.maxNesting||(o=l>0?t.src.charCodeAt(l-1):-1,r=t.src.charCodeAt(l+2),43===o)||43===r||32===r||10===r)return!1;for(s=l+2;s<a&&43===t.src.charCodeAt(s);)s++;if(s!==l+2)return t.pos+=s-l,e||(t.pending+=t.src.slice(l,s)),!0;for(t.pos=l+2,n=1;t.pos+1<a;){if(43===t.src.charCodeAt(t.pos)&&43===t.src.charCodeAt(t.pos+1)&&(o=t.src.charCodeAt(t.pos-1),43!==(r=t.pos+2<a?t.src.charCodeAt(t.pos+2):-1)&&43!==o&&(32!==o&&10!==o?n--:32!==r&&10!==r&&n++,n<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=l+2,e||(t.push({type:"ins_open",level:t.level++}),t.parser.tokenize(t),t.push({type:"ins_close",level:--t.level})),t.pos=t.posMax+2,t.posMax=a,!0):(t.pos=l,!1)}],["mark",function(t,e){var i,s,n,o,r,a=t.posMax,l=t.pos;if(61!==t.src.charCodeAt(l)||e||l+4>=a||61!==t.src.charCodeAt(l+1)||t.level>=t.options.maxNesting||(o=l>0?t.src.charCodeAt(l-1):-1,r=t.src.charCodeAt(l+2),61===o)||61===r||32===r||10===r)return!1;for(s=l+2;s<a&&61===t.src.charCodeAt(s);)s++;if(s!==l+2)return t.pos+=s-l,e||(t.pending+=t.src.slice(l,s)),!0;for(t.pos=l+2,n=1;t.pos+1<a;){if(61===t.src.charCodeAt(t.pos)&&61===t.src.charCodeAt(t.pos+1)&&(o=t.src.charCodeAt(t.pos-1),61!==(r=t.pos+2<a?t.src.charCodeAt(t.pos+2):-1)&&61!==o&&(32!==o&&10!==o?n--:32!==r&&10!==r&&n++,n<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=l+2,e||(t.push({type:"mark_open",level:t.level++}),t.parser.tokenize(t),t.push({type:"mark_close",level:--t.level})),t.pos=t.posMax+2,t.posMax=a,!0):(t.pos=l,!1)}],["emphasis",function(t,e){var i,s,n,o,r,a,l,c=t.posMax,h=t.pos,u=t.src.charCodeAt(h);if(95!==u&&42!==u||e)return!1;if(i=(l=$t(t,h)).delims,!l.can_open)return t.pos+=i,e||(t.pending+=t.src.slice(h,t.pos)),!0;if(t.level>=t.options.maxNesting)return!1;for(t.pos=h+i,a=[i];t.pos<c;)if(t.src.charCodeAt(t.pos)!==u)t.parser.skipToken(t);else{if(s=(l=$t(t,t.pos)).delims,l.can_close){for(o=a.pop(),r=s;o!==r;){if(r<o){a.push(o-r);break}if(r-=o,0===a.length)break;t.pos+=o,o=a.pop()}if(0===a.length){i=o,n=!0;break}t.pos+=s;continue}l.can_open&&a.push(s),t.pos+=s}return n?(t.posMax=t.pos,t.pos=h+i,e||((2===i||3===i)&&t.push({type:"strong_open",level:t.level++}),(1===i||3===i)&&t.push({type:"em_open",level:t.level++}),t.parser.tokenize(t),(1===i||3===i)&&t.push({type:"em_close",level:--t.level}),(2===i||3===i)&&t.push({type:"strong_close",level:--t.level})),t.pos=t.posMax+i,t.posMax=c,!0):(t.pos=h,!1)}],["sub",function(t,e){var i,s,n=t.posMax,o=t.pos;if(126!==t.src.charCodeAt(o)||e||o+2>=n||t.level>=t.options.maxNesting)return!1;for(t.pos=o+1;t.pos<n;){if(126===t.src.charCodeAt(t.pos)){i=!0;break}t.parser.skipToken(t)}return!i||o+1===t.pos||(s=t.src.slice(o+1,t.pos)).match(/(^|[^\\])(\\\\)*\s/)?(t.pos=o,!1):(t.posMax=t.pos,t.pos=o+1,e||t.push({type:"sub",level:t.level,content:s.replace(Jt,"$1")}),t.pos=t.posMax+1,t.posMax=n,!0)}],["sup",function(t,e){var i,s,n=t.posMax,o=t.pos;if(94!==t.src.charCodeAt(o)||e||o+2>=n||t.level>=t.options.maxNesting)return!1;for(t.pos=o+1;t.pos<n;){if(94===t.src.charCodeAt(t.pos)){i=!0;break}t.parser.skipToken(t)}return!i||o+1===t.pos||(s=t.src.slice(o+1,t.pos)).match(/(^|[^\\])(\\\\)*\s/)?(t.pos=o,!1):(t.posMax=t.pos,t.pos=o+1,e||t.push({type:"sup",level:t.level,content:s.replace(Ut,"$1")}),t.pos=t.posMax+1,t.posMax=n,!0)}],["links",function(t,e){var i,s,n,o,r,a,l,c,h=!1,u=t.pos,d=t.posMax,p=t.pos,m=t.src.charCodeAt(p);if(33===m&&(h=!0,m=t.src.charCodeAt(++p)),91!==m||t.level>=t.options.maxNesting||(i=p+1,(s=ot(t,p))<0))return!1;if((a=s+1)<d&&40===t.src.charCodeAt(a)){for(a++;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);if(a>=d)return!1;for(p=a,lt(t,a)?(o=t.linkContent,a=t.pos):o="",p=a;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);if(a<d&&p!==a&&ct(t,a))for(r=t.linkContent,a=t.pos;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);else r="";if(a>=d||41!==t.src.charCodeAt(a))return t.pos=u,!1;a++}else{if(t.linkLevel>0)return!1;for(;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);if(a<d&&91===t.src.charCodeAt(a)&&(p=a+1,(a=ot(t,a))>=0?n=t.src.slice(p,a++):a=p-1),n||(typeof n>"u"&&(a=s+1),n=t.src.slice(i,s)),!(l=t.env.references[ht(n)]))return t.pos=u,!1;o=l.href,r=l.title}return e||(t.pos=i,t.posMax=s,h?t.push({type:"image",src:o,title:r,alt:t.src.substr(i,s-i),level:t.level}):(t.push({type:"link_open",href:o,title:r,level:t.level++}),t.linkLevel++,t.parser.tokenize(t),t.linkLevel--,t.push({type:"link_close",level:--t.level}))),t.pos=a,t.posMax=d,!0}],["footnote_inline",function(t,e){var i,s,n,o,r=t.posMax,a=t.pos;return!(a+2>=r||94!==t.src.charCodeAt(a)||91!==t.src.charCodeAt(a+1)||t.level>=t.options.maxNesting||(i=a+2,s=ot(t,a+1),s<0))&&(e||(t.env.footnotes||(t.env.footnotes={}),t.env.footnotes.list||(t.env.footnotes.list=[]),n=t.env.footnotes.list.length,t.pos=i,t.posMax=s,t.push({type:"footnote_ref",id:n,level:t.level}),t.linkLevel++,o=t.tokens.length,t.parser.tokenize(t),t.env.footnotes.list[n]={tokens:t.tokens.splice(o)},t.linkLevel--),t.pos=s+1,t.posMax=r,!0)}],["footnote_ref",function(t,e){var i,s,n,o,r=t.posMax,a=t.pos;if(a+3>r||!t.env.footnotes||!t.env.footnotes.refs||91!==t.src.charCodeAt(a)||94!==t.src.charCodeAt(a+1)||t.level>=t.options.maxNesting)return!1;for(s=a+2;s<r;s++){if(32===t.src.charCodeAt(s)||10===t.src.charCodeAt(s))return!1;if(93===t.src.charCodeAt(s))break}return!(s===a+2||s>=r||(s++,i=t.src.slice(a+2,s-1),typeof t.env.footnotes.refs[":"+i]>"u"))&&(e||(t.env.footnotes.list||(t.env.footnotes.list=[]),t.env.footnotes.refs[":"+i]<0?(n=t.env.footnotes.list.length,t.env.footnotes.list[n]={label:i,count:0},t.env.footnotes.refs[":"+i]=n):n=t.env.footnotes.refs[":"+i],o=t.env.footnotes.list[n].count,t.env.footnotes.list[n].count++,t.push({type:"footnote_ref",id:n,subId:o,level:t.level})),t.pos=s,t.posMax=r,!0)}],["autolink",function(t,e){var i,s,n,o,r,a=t.pos;return!(60!==t.src.charCodeAt(a)||(i=t.src.slice(a),i.indexOf(">")<0))&&((s=i.match(Kt))?!(Vt.indexOf(s[1].toLowerCase())<0||(o=s[0].slice(1,-1),r=at(o),!t.parser.validateLink(o)))&&(e||(t.push({type:"link_open",href:r,level:t.level}),t.push({type:"text",content:o,level:t.level+1}),t.push({type:"link_close",level:t.level})),t.pos+=s[0].length,!0):!!(n=i.match(Ht))&&(r=at("mailto:"+(o=n[0].slice(1,-1))),!!t.parser.validateLink(r)&&(e||(t.push({type:"link_open",href:r,level:t.level}),t.push({type:"text",content:o,level:t.level+1}),t.push({type:"link_close",level:t.level})),t.pos+=n[0].length,!0)))}],["htmltag",function(t,e){var i,s,n,o=t.pos;return!(!t.options.html||(n=t.posMax,60!==t.src.charCodeAt(o)||o+2>=n)||(i=t.src.charCodeAt(o+1),33!==i&&63!==i&&47!==i&&!function(t){var e=32|t;return e>=97&&e<=122}(i))||(s=t.src.slice(o).match(Yt),!s))&&(e||t.push({type:"htmltag",content:t.src.slice(o,o+s[0].length),level:t.level}),t.pos+=s[0].length,!0)}],["entity",function(t,e){var i,s,n=t.pos,o=t.posMax;if(38!==t.src.charCodeAt(n))return!1;if(n+1<o)if(35===t.src.charCodeAt(n+1)){if(s=t.src.slice(n).match(Qt))return e||(i="x"===s[1][0].toLowerCase()?parseInt(s[1].slice(1),16):parseInt(s[1],10),t.pending+=$(i)?J(i):J(65533)),t.pos+=s[0].length,!0}else if(s=t.src.slice(n).match(te)){var r=B(s[1]);if(s[1]!==r)return e||(t.pending+=r),t.pos+=s[0].length,!0}return e||(t.pending+="&"),t.pos++,!0}]];function ie(){this.ruler=new st;for(var t=0;t<ee.length;t++)this.ruler.push(ee[t][0],ee[t][1]);this.validateLink=se}function se(t){var e=t.trim().toLowerCase();return!(-1!==(e=K(e)).indexOf(":")&&-1!==["vbscript","javascript","file","data"].indexOf(e.split(":")[0]))}ie.prototype.skipToken=function(t){var e,i,s=this.ruler.getRules(""),n=s.length,o=t.pos;if((i=t.cacheGet(o))>0)t.pos=i;else{for(e=0;e<n;e++)if(s[e](t,!0))return void t.cacheSet(o,t.pos);t.pos++,t.cacheSet(o,t.pos)}},ie.prototype.tokenize=function(t){for(var e,i,s=this.ruler.getRules(""),n=s.length,o=t.posMax;t.pos<o;){for(i=0;i<n&&!(e=s[i](t,!1));i++);if(e){if(t.pos>=o)break}else t.pending+=t.src[t.pos++]}t.pending&&t.pushPending()},ie.prototype.parse=function(t,e,i,s){var n=new nt(t,this,e,i,s);this.tokenize(n)};var ne={default:{options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["block","inline","references","replacements","smartquotes","references","abbr2","footnote_tail"]},block:{rules:["blockquote","code","fences","footnote","heading","hr","htmlblock","lheading","list","paragraph","table"]},inline:{rules:["autolink","backticks","del","emphasis","entity","escape","footnote_ref","htmltag","links","newline","text"]}}},full:{options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{},block:{},inline:{}}},commonmark:{options:{html:!0,xhtmlOut:!0,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["block","inline","references","abbr2"]},block:{rules:["blockquote","code","fences","heading","hr","htmlblock","lheading","list","paragraph"]},inline:{rules:["autolink","backticks","emphasis","entity","escape","htmltag","links","newline","text"]}}}};function oe(t,e,i){this.src=e,this.env=i,this.options=t.options,this.tokens=[],this.inlineMode=!1,this.inline=t.inline,this.block=t.block,this.renderer=t.renderer,this.typographer=t.typographer}function re(t,e){"string"!=typeof t&&(e=t,t="default"),e&&null!=e.linkify&&console.warn("linkify option is removed. Use linkify plugin instead:\n\nimport Remarkable from 'remarkable';\nimport linkify from 'remarkable/linkify';\nnew Remarkable().use(linkify)\n"),this.inline=new ie,this.block=new Nt,this.core=new St,this.renderer=new it,this.ruler=new st,this.options={},this.configure(ne[t]),this.set(e||{})}re.prototype.set=function(t){F(this.options,t)},re.prototype.configure=function(t){var e=this;if(!t)throw new Error("Wrong `remarkable` preset, check name/content");t.options&&e.set(t.options),t.components&&Object.keys(t.components).forEach((function(i){t.components[i].rules&&e[i].ruler.enable(t.components[i].rules,!0)}))},re.prototype.use=function(t,e){return t(this,e),this},re.prototype.parse=function(t,e){var i=new oe(this,t,e);return this.core.process(i),i.tokens},re.prototype.render=function(t,e){return e=e||{},this.renderer.render(this.parse(t,e),this.options,e)},re.prototype.parseInline=function(t,e){var i=new oe(this,t,e);return i.inlineMode=!0,this.core.process(i),i.tokens},re.prototype.renderInline=function(t,e){return e=e||{},this.renderer.render(this.parseInline(t,e),this.options,e)};const ae=class t{static instantiate(e){if(e)return new re({...t.DEFAULT_PROPERTIES,...e});if(window.hljs){const t=window.hljs;return new re({highlight:function(e,i){if(i&&t.getLanguage(i))try{return t.highlight(e,{language:i}).value}catch{console.error("failed to setup the highlight dependency")}try{return t.highlightAuto(e).value}catch{console.error("failed to automatically highlight messages")}return""},html:!1,xhtmlOut:!1,breaks:!0,langPrefix:"language-",linkTarget:"_blank",typographer:!0})}return new re(t.DEFAULT_PROPERTIES)}static createNew(e){const i=t.instantiate(e);return i.inline.validateLink=()=>!0,i}};ae.DEFAULT_PROPERTIES={breaks:!0,linkTarget:"_blank"};let le=ae;class ce{static applyCustomStylesToElements(t,e,i){if(i&&(Object.assign(t.outerContainer.style,i.outerContainer),Object.assign(t.innerContainer.style,i.innerContainer),Object.assign(t.bubbleElement.style,i.bubble),e)){const e=t.bubbleElement.children[0],s="a"!==e.tagName.toLocaleLowerCase()?e:e.children[0];Object.assign(s.style,i.media)}}static applySideStyles(t,e,i,s){s&&(ce.applyCustomStylesToElements(t,i,s.shared),e===Se.USER_ROLE?ce.applyCustomStylesToElements(t,i,s.user):(ce.applyCustomStylesToElements(t,i,s.ai),ce.applyCustomStylesToElements(t,i,s[e])))}static isElementsStyles(t){return!!(t.outerContainer||t.innerContainer||t.bubble||t.media)}static applyCustomStyles(t,e,i,s,n){var o;n&&t.default!==n?ce.isElementsStyles(n)?(ce.applyCustomStylesToElements(e,s,null==(o=t.default)?void 0:o.shared),ce.applyCustomStylesToElements(e,s,n)):(ce.applySideStyles(e,i,s,t.default),ce.applySideStyles(e,i,s,n)):ce.applySideStyles(e,i,s,t.default)}static extractParticularSharedStyles(t,e){if(null==e||!e.shared)return;const i=e.shared,s={outerContainer:{},innerContainer:{},bubble:{},media:{}};return t.forEach((t=>{var e,n,o,r;s.outerContainer[t]=(null==(e=i.outerContainer)?void 0:e[t])||"",s.innerContainer[t]=(null==(n=i.innerContainer)?void 0:n[t])||"",s.bubble[t]=(null==(o=i.bubble)?void 0:o[t])||"",s.media[t]=(null==(r=i.media)?void 0:r[t])||""})),s}}class he{static onMessage(t,e,i){var s;const n=JSON.parse(JSON.stringify({message:e,isHistory:i,isInitial:i}));M.reAddFileRefToObject(e,n),null==(s=t.onMessage)||s.call(t,n),t.dispatchEvent(new CustomEvent("message",{detail:n})),O.fireOnNewMessage(t,n)}static onClearMessages(t){var e;null==(e=t.onClearMessages)||e.call(t),t.dispatchEvent(new CustomEvent("clear-messages"))}static onRender(t){var e;null==(e=t.onComponentRender)||e.call(t,t),t.dispatchEvent(new CustomEvent("render",{detail:t}))}static onError(t,e){var i;null==(i=t.onError)||i.call(t,e),t.dispatchEvent(new CustomEvent("error",{detail:e}))}}const ue=class t{static generateLoadingRingElement(){const t=document.createElement("div");return t.classList.add("loading-history"),t.appendChild(document.createElement("div")),t.appendChild(document.createElement("div")),t.appendChild(document.createElement("div")),t.appendChild(document.createElement("div")),t}static apply(t,e,i){A.setRing(e.bubbleElement,null==i?void 0:i.bubble),null!=i&&i.bubble&&delete(i=JSON.parse(JSON.stringify(i))).bubble,t.applyCustomStyles(e,"history",!1,i)}static addLoadHistoryMessage(e,i,s=!0){var n,o,r,a,l,c,h,u;e.bubbleElement.classList.add(t.CLASS);const d=s?t.FULL_VIEW_CLASS:t.SMALL_CLASS;e.outerContainer.classList.add(d);const p=s?null==(a=null==(r=null==(o=null==(n=i.messageStyles)?void 0:n.loading)?void 0:o.history)?void 0:r.full)?void 0:a.styles:null==(u=null==(h=null==(c=null==(l=i.messageStyles)?void 0:l.loading)?void 0:c.history)?void 0:h.small)?void 0:u.styles;t.apply(i,e,p),i.elementRef.prepend(e.outerContainer)}static createDefaultElements(e){const i=e.createMessageElements("",Se.AI_ROLE),{bubbleElement:s}=i,n=t.generateLoadingRingElement();return s.appendChild(n),i}static addMessage(e,i=!0){var s,n,o,r;const a=null==(r=null==(o=null==(n=null==(s=e.messageStyles)?void 0:s.loading)?void 0:n.history)?void 0:o.full)?void 0:r.html,l=a?R.createElements(e,a,Se.AI_ROLE,!0):t.createDefaultElements(e);return t.addLoadHistoryMessage(l,e,i),l}static tryChangeViewToSmall(e,i){var s,n,o,r,a,l,c,h;if(null!=i&&i.outerContainer.classList.contains(t.FULL_VIEW_CLASS)){i.outerContainer.classList.replace(t.FULL_VIEW_CLASS,t.SMALL_CLASS);const u=null==(r=null==(o=null==(n=null==(s=e.messageStyles)?void 0:s.loading)?void 0:n.history)?void 0:o.small)?void 0:r.styles;u&&t.apply(e,i,u);const d=null==(h=null==(c=null==(l=null==(a=e.messageStyles)?void 0:a.loading)?void 0:l.history)?void 0:c.small)?void 0:h.html;return d&&(i.bubbleElement.innerHTML=d),!0}return!1}static changeFullViewToSmall(e){const i=e.messageElementRefs[e.messageElementRefs.length-1];t.tryChangeViewToSmall(e,i)||t.tryChangeViewToSmall(e,e.messageElementRefs[0])}};ue.CLASS="loading-history-message",ue.FULL_VIEW_CLASS="loading-history-message-full-view",ue.SMALL_CLASS="loading-history-message-small";let de=ue;const pe=class t{static setFade(e,i){e.style.transitionDuration="number"==typeof i?`${i}ms`:`${t.DEFAULT_FADE_MS}ms`}static async fadeAnimation(e,i){e.style.opacity="0";const s="number"==typeof i?i:t.DEFAULT_FADE_MS;await new Promise((t=>{setTimeout((()=>t()),s)})),e.style.opacity="1"}};pe.DEFAULT_FADE_MS=500;let me=pe;const ve=class t{constructor(e){var i;this.messageElementRefs=[],this.htmlClassUtilities={},this.messageToElements=[],this.elementRef=t.createContainerElement(),this.messageStyles=O.processMessageStyles(e.messageStyles),this._remarkable=le.createNew(e.remarkable),this.avatars=e.avatars,this.names=e.names,this._onMessage=he.onMessage.bind(this,e),e.htmlClassUtilities&&(this.htmlClassUtilities=e.htmlClassUtilities),this.focusMode=e.focusMode,this.focusMode||(this._lastGroupMessagesElement=document.createElement("div")),"boolean"!=typeof this.focusMode&&null!=(i=this.focusMode)&&i.fade&&me.setFade(this.elementRef,this.focusMode.fade),setTimeout((()=>{this.submitUserMessage=e.submitUserMessage}))}static createContainerElement(){const t=document.createElement("div");return t.id="messages",t}addNewTextMessage(e,i,s,n=!1){if(null!=s&&s.status){const t=this.overwriteText(i,e,this.messageElementRefs);if(t)return t;s.status=!1}const o=n?this.createAndPrependNewMessageElement(e,i,n):this.createAndAppendNewMessageElement(e,i);return o.bubbleElement.classList.add(t.TEXT_BUBBLE_CLASS),this.applyCustomStyles(o,i,!1),Se.fillEmptyMessageElement(o.bubbleElement,e),o}overwriteText(e,i,s){const n=Se.overwriteMessage(this.messageToElements,s,i,e,"text",t.TEXT_BUBBLE_CLASS);return n&&this.renderText(n.bubbleElement,i),n}createAndAppendNewMessageElement(t,e){return this.focusMode?this.appendNewMessageElementFocusMode(t,e):this.createAndAppendNewMessageElementDefault(t,e)}appendNewMessageElementFocusMode(t,e){var i,s;const n=this.createNewMessageElement(t,e);if(this.appendOuterContainerElemet(n.outerContainer,e),"user"===e){const t="boolean"!=typeof this.focusMode&&(null==(i=this.focusMode)?void 0:i.isScroll);setTimeout((()=>x.scrollToBottom(this.elementRef,t)))}else null==(s=this.messageElementRefs[this.messageElementRefs.length-2])||s.outerContainer.scrollIntoView();return n}createNewGroupElementFocusMode(){var e;null==(e=this._lastGroupMessagesElement)||e.classList.remove(t.LAST_GROUP_MESSAGES_ACTIVE);const i=document.createElement("div");this._lastGroupMessagesElement&&i.classList.add(t.LAST_GROUP_MESSAGES_ACTIVE),this._lastGroupMessagesElement=i}createAndAppendNewMessageElementDefault(t,e){const i=this.createNewMessageElement(t,e);return this.appendOuterContainerElemet(i.outerContainer),setTimeout((()=>x.scrollToBottom(this.elementRef))),i}appendOuterContainerElemet(t,e){var i;this.focusMode&&("user"===e||!this._lastGroupMessagesElement)&&this.createNewGroupElementFocusMode(),null==(i=this._lastGroupMessagesElement)||i.appendChild(t),this.elementRef.appendChild(this._lastGroupMessagesElement)}createAndPrependNewMessageElement(e,i,s){var n;const o=this.createNewMessageElement(e,i,s);if(s&&null!=(n=this.elementRef.firstChild)&&n.classList.contains(t.INTRO_CLASS)){this.elementRef.firstChild.insertAdjacentElement("afterend",o.outerContainer);const t=this.messageElementRefs[0];this.messageElementRefs[0]=this.messageElementRefs[1],this.messageElementRefs[1]=t}else this.elementRef.insertBefore(o.outerContainer,this.elementRef.firstChild);return o}createMessageElementsOnOrientation(t,e,i){return i?this.createAndPrependNewMessageElement(t,e,!0):this.createNewMessageElement(t,e)}createNewMessageElement(e,i,s=!1){var n;null==(n=this._introPanel)||n.hide();const o=this.messageElementRefs[this.messageElementRefs.length-1];return de.changeFullViewToSmall(this),t.isTemporaryElement(o)&&(this.revealRoleElementsIfTempRemoved(o,i),this.removeLastMessage()),this.createMessageElements(e,i,s)}revealRoleElementsIfTempRemoved(t,e){if((this.avatars||this.names)&&I.isElementTemporary(t)){const i=this.messageElementRefs[this.messageElementRefs.length-2];i&&this.messageToElements.length>0&&!t.bubbleElement.classList.contains(Se.getRoleClass(e))&&Se.revealRoleElements(i.innerContainer,!!this.avatars,!!this.names)}}static isTemporaryElement(e){return t.isLoadingMessage(e)||I.isElementTemporary(e)}createElements(e,i){const s=t.createBaseElements(i),{outerContainer:n,innerContainer:o,bubbleElement:r}=s;return n.appendChild(o),this.addInnerContainerElements(r,e,i),s}createMessageElements(t,e,i=!1){const s=this.createElements(t,e);return Se.updateRefArr(this.messageElementRefs,s,i),Se.classifyRoleMessages(this.messageElementRefs,e),s}static createBaseElements(t){const e=document.createElement("div"),i=document.createElement("div");i.classList.add("inner-message-container"),e.appendChild(i),e.classList.add("outer-message-container"),e.classList.add(Se.buildRoleOuterContainerClass(t));const s=document.createElement("div");return s.classList.add("message-bubble"),i.appendChild(s),{outerContainer:e,innerContainer:i,bubbleElement:s}}addInnerContainerElements(t,e,i){const s=this.messageElementRefs[this.messageElementRefs.length-1];return Se.areOuterContainerClassRolesSame(i,s)&&!this.isLastMessageError()&&Se.hideRoleElements(s.innerContainer,!!this.avatars,!!this.names),t.classList.add("message-bubble",Se.getRoleClass(i),i===Se.USER_ROLE?"user-message-text":"ai-message-text"),this.renderText(t,e),Se.addRoleElements(t,i,this.avatars,this.names),{bubbleElement:t}}applyCustomStyles(t,e,i,s){t&&this.messageStyles&&ce.applyCustomStyles(this.messageStyles,t,e,i,s)}static createMessageContent(t){const{text:e,files:i,html:s,custom:n,_sessionId:o,role:r}=t,a={role:r||Se.AI_ROLE};return e&&(a.text=e),i&&(a.files=i),s&&(a.html=s),!e&&!i&&!s&&(a.text=""),n&&(a.custom=n),o&&(a._sessionId=o),a}removeMessage(t){t.outerContainer.remove();const e=this.messageElementRefs.findIndex((e=>e===t));this.messageElementRefs.splice(e,1)}removeLastMessage(){this.messageElementRefs[this.messageElementRefs.length-1].outerContainer.remove(),this.messageElementRefs.pop()}isLastMessageError(){var t;return null==(t=Se.getLastMessageBubbleElement(this.elementRef))?void 0:t.classList.contains(Se.ERROR_MESSAGE_TEXT_CLASS)}static isLoadingMessage(t){return null==t?void 0:t.bubbleElement.classList.contains(A.BUBBLE_CLASS)}sendClientUpdate(t,e=!1){var i;null==(i=this._onMessage)||i.call(this,t,e)}renderText(t,e){t.innerHTML=this._remarkable.render(e),0===t.innerText.trim().length&&(t.innerText=e)}refreshTextMessages(t){this._remarkable=le.createNew(t),this.messageToElements.forEach((t=>{t[1].text&&t[0].text&&this.renderText(t[1].text.bubbleElement,t[0].text)}))}};ve.TEXT_BUBBLE_CLASS="text-message",ve.INTRO_CLASS="deep-chat-intro",ve.LAST_GROUP_MESSAGES_ACTIVE="deep-chat-last-group-messages-active";let fe=ve;const ge="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='iso-8859-1'?%3e%3csvg%20fill='%23000000'%20version='1.1'%20id='Layer_1'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20viewBox='0%200%2032%2032'%20xml:space='preserve'%3e%3cpath%20d='M23,30.36H9c-2.404,0-4.36-1.956-4.36-4.36V15c0-2.404,1.956-4.36,4.36-4.36h3.659%20c0.167-1.566,1.415-2.813,2.981-2.981V5.333c-1.131-0.174-2-1.154-2-2.333c0-1.301,1.059-2.36,2.36-2.36%20c1.302,0,2.36,1.059,2.36,2.36c0,1.179-0.869,2.159-2,2.333V7.66c1.566,0.167,2.814,1.415,2.981,2.981H23%20c2.404,0,4.36,1.956,4.36,4.36v11C27.36,28.404,25.404,30.36,23,30.36z%20M9,11.36c-2.007,0-3.64,1.633-3.64,3.64v11%20c0,2.007,1.633,3.64,3.64,3.64h14c2.007,0,3.64-1.633,3.64-3.64V15c0-2.007-1.633-3.64-3.64-3.64H9z%20M13.384,10.64h5.231%20C18.439,9.354,17.334,8.36,16,8.36C14.667,8.36,13.561,9.354,13.384,10.64z%20M16,1.36c-0.904,0-1.64,0.736-1.64,1.64%20S15.096,4.64,16,4.64c0.904,0,1.64-0.736,1.64-1.64S16.904,1.36,16,1.36z%20M20,27.36h-8c-1.301,0-2.36-1.059-2.36-2.36%20s1.059-2.36,2.36-2.36h8c1.302,0,2.36,1.059,2.36,2.36S21.302,27.36,20,27.36z%20M12,23.36c-0.904,0-1.64,0.735-1.64,1.64%20s0.736,1.64,1.64,1.64h8c0.904,0,1.64-0.735,1.64-1.64s-0.735-1.64-1.64-1.64H12z%20M31,23.86h-2c-0.199,0-0.36-0.161-0.36-0.36V15%20c0-0.199,0.161-0.36,0.36-0.36h2c0.199,0,0.36,0.161,0.36,0.36v8.5C31.36,23.699,31.199,23.86,31,23.86z%20M29.36,23.14h1.279v-7.78%20H29.36V23.14z%20M3,23.86H1c-0.199,0-0.36-0.161-0.36-0.36V15c0-0.199,0.161-0.36,0.36-0.36h2c0.199,0,0.36,0.161,0.36,0.36v8.5%20C3.36,23.699,3.199,23.86,3,23.86z%20M1.36,23.14h1.28v-7.78H1.36V23.14z%20M20,20.36c-1.302,0-2.36-1.059-2.36-2.36%20s1.059-2.36,2.36-2.36s2.36,1.059,2.36,2.36C22.36,19.302,21.302,20.36,20,20.36z%20M20,16.36c-0.904,0-1.64,0.736-1.64,1.64%20s0.735,1.64,1.64,1.64s1.64-0.735,1.64-1.64S20.904,16.36,20,16.36z%20M12,20.36c-1.301,0-2.36-1.059-2.36-2.36s1.059-2.36,2.36-2.36%20s2.36,1.059,2.36,2.36C14.36,19.302,13.301,20.36,12,20.36z%20M12,16.36c-0.904,0-1.64,0.736-1.64,1.64s0.736,1.64,1.64,1.64%20s1.64-0.735,1.64-1.64S12.904,16.36,12,16.36z'/%3e%3crect%20style='fill:none;'%20width='32'%20height='32'/%3e%3c/svg%3e",be="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAMAAAC/MqoPAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAADNQTFRF////9vX18vLy/Pz86enp4+Li2tnZ1tbWzczM+fn57Ozs4N/f09LS0M/P5uXl7+/v3dzcwtncCAAAAAFiS0dEAIgFHUgAAAAJcEhZcwAAAEgAAABIAEbJaz4AAAZNSURBVHja7d3bdtsqEABQYABZSLH9/3+ZpnUsIcF5iOM6PfElNoMHMfPQdq3GmL0GkLhEUqLaUExnOtOZznSmM53pTGc605nOdKYznelMZzrTmV4LXSqllKyJDkob26xWq8Zae/iH0QoWTm9d1xur4WuypQJtTd+5dqn0VjcxzNO5/57mEBvdLo8Oron6aseWOjYOFkVvjQs3DmgyONMuht52EfztP+4hdu0i6LCO808/M8c1lE/fuPGej41uUzgdtoO/75N+2ELJ9I3b3//hPXbiMenm3pR/Jt4USgcLBIp4Bh10gqKVhvLo0klCxeSky96nKcj3siw6pJIL4XsoiQ7apyvMY/V3HHrSRioLopvEhSpTCn2TPEuwKYMOIX0tAxRBf/Hpa+lfSqBv9gi1FPsNfTrMAiVmIE/vJhz61FGnQxRIEYE4vfNYdN8Rp6MlHaHotHTn8ejekaZPAjEmyvQWdZFTtYTpXqCGJ0zvcek9Yfoel76nS0ffv1NMp1ca+pkgyfRCGind4L7OWWc605l+cxjsyhqy9AGbPpClc1/nvl5VX0c/3Alk6RU3+Am7shNZ+h6bvidLr7jBB+zKBrL0irOOudmIUDzTmf5gIP+iEuXtRuTVaEmY/oZLfyNMrzjryPc0gerMTdpVg0tvjJUU6bLPcGOoUv46SLL6Wi8yhLf06C7TUyekI0efRaaYqdFltkeNpPumRPSMDxgBYvSM035FrKAmH72hRW99PrpvSdEHkTEGUvSsK3yKVDkuJ92RohcZaehzzirPpOg+J92Tolfc4Cumx5xVXpGiZ34+ICX6W84qv5GiR5NPbiIpOv6BCoSvSkTX+eiaGP092zINvBOj4x8mSf9FqejvNo/cvpOji19ZbmviL0GPLsYMFzgzCor0+Bv/ePDvSJKOb9dJ5UlnbnEHiHgzv6cdTpJOWuc/u3FEucLDOL75xGtBiefrcwgoC9NDSH/jkH6pAuXmBqPQ9HSUPVdZBH1GGOrMXAQdYxcKZfxAoK+KKBKFLosoEoX+u4giUehz8jlcnAuhp78I46yDYNAd+QLR6K+pr+yvxdBTHyVDubQh0UfSxaHSd0lbvNkVRE87JGOtc+PQd2QLQ6fHhJkKsSh6yg13tO08JPprsgrrXWH0dJd2vH1MLPprot4eXoujpzrdhngiD40ek2y92lggPcnWa8qN1Yz0BFuvZhRl0uOfR0v4Ewuli/Bg4Qr3lArqGdndQ3UPO1EunXYwnelMZzrTmc50pjOd6UxnOtOZznSmM53pTGf6kuj6oedFKV0s3fX6sX1S3bsi6a4PD7+/YAqYeBw6pIB/4qEgOqxdSPbGiim4NRRCbzs3Jj0L4UfXtQXQVRfn5IdA/Bw7RZzurEV6EtdsLeGXkIPuA+K1UoVeA0l62zmN/LqfSSft9KkepmoRuvi3nd5uKNFB9zbbXEANqdr941XO0NJx2v2jdJenpf+/3bvn0ts16ph+sd6hX7dPo2+2cZzE02Ia43bzDHqr+2Evnhz74ZHU30ffbKOeng1/NPV30Ns1gYQnSP2P6e65Pfxc6h02XZqXQCjhJ6kPL6bFo4NrGvAU4UII4SE2P1vQuZkuOxckVfehisF1MjUddN/MZBN+kvq5uf0O/xa66gyNS9ktMWlz44rO1Z8C19i5FPdHzPamXn+F3hryPfxMr78+4F+kq22kO6Rf6fUQt+puuustyWv4rbG3l/duztFB96GYoe1cTBdXMr+nw9qVM6ZfxOvzezff0nXi/ZOndvrR6Zvpm0c3h6nhdb+5iS7tsIim/qXZD9+97/Jf+rpZ5BET1ayv0GUzLhEuhBBjIy/RdVPgndutIRt9nt7p5cKFEEJ3Z+jQFDZL+XnMDXxHB73gxn5s9Kc3d3/pFciFkN/QTSXHJpX5l66gDrkQoP6hL3xsPw39la4qOiV8tH78XeSbue6N9mvWa6J/ybpc1CT1Wnh5Qq9meP8IOKH3ddH7E/ri1iYux/SXDrXR4UiPdck/wUpU+FtPf6/orja6O9KL3l56LOvVxe5Ib2qjN0d6Vbex4ghWlU3bPqI90If66MNng680FNpbJijH6kCvaF3uMzQ3+IrpFerV4Y9dffQdN3im10ivbuImhD3Qq5u4HdZkua8znelMZ/pS4z9CPVKkxowNxgAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxNy0wMy0yN1QxNTo0NToxNSswMDowMN1xSg4AAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTctMDMtMjdUMTU6NDU6MTUrMDA6MDCsLPKyAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAABJRU5ErkJggg==",ye=class t{static errorFallback(t,e){const i=e.target;i.onerror=null,i.src=t}static hide(e){var i;(i=e.getElementsByClassName(t.CONTAINER_CLASS)[0].style).visibility||(i.visibility="hidden")}static reveal(e){e.getElementsByClassName(t.CONTAINER_CLASS)[0].style.visibility=""}static applyCustomStylesToElements(t,e,i){Object.assign(t.style,i.container),Object.assign(e.style,i.avatar)}static applyCustomStyles(e,i,s,n){var o,r,a,l;if(null!=(o=s.default)&&o.styles&&t.applyCustomStylesToElements(e,i,s.default.styles),n===Se.USER_ROLE)null!=(r=s.user)&&r.styles&&t.applyCustomStylesToElements(e,i,s.user.styles);else{null!=(a=s.ai)&&a.styles&&t.applyCustomStylesToElements(e,i,s.ai.styles);const o=null==(l=s[n])?void 0:l.styles;o&&t.applyCustomStylesToElements(e,i,o)}}static createAvatar(e,i){var s,n,o,r,a;const l=document.createElement("img");e===Se.USER_ROLE?(l.src=(null==(s=null==i?void 0:i.user)?void 0:s.src)||(null==(n=null==i?void 0:i.default)?void 0:n.src)||be,l.onerror=t.errorFallback.bind(this,be)):(l.src=(null==(o=null==i?void 0:i[e])?void 0:o.src)||(null==(r=null==i?void 0:i.ai)?void 0:r.src)||(null==(a=null==i?void 0:i.default)?void 0:a.src)||ge,l.onerror=t.errorFallback.bind(this,ge)),l.classList.add("avatar"),l.alt=`${e} avatar`;const c=document.createElement("div");return c.classList.add(t.CONTAINER_CLASS),c.appendChild(l),i&&t.applyCustomStyles(c,l,i,e),c}static getPosition(t,e){var i,s,n,o,r,a;let l=null==(s=null==(i=null==e?void 0:e[t])?void 0:i.styles)?void 0:s.position;return t!==Se.USER_ROLE&&(l??(l=null==(o=null==(n=null==e?void 0:e.ai)?void 0:n.styles)?void 0:o.position)),l??(l=null==(a=null==(r=null==e?void 0:e.default)?void 0:r.styles)?void 0:a.position),l??(l=t===Se.USER_ROLE?"right":"left"),l}static add(e,i,s){const n="boolean"==typeof s?void 0:s,o=t.createAvatar(i,n),r=t.getPosition(i,n);o.classList.add("left"===r?"left-item-position":"right-item-position"),e.insertAdjacentElement("left"===r?"beforebegin":"afterend",o)}};ye.CONTAINER_CLASS="avatar-container";let we=ye;const xe=class t{static hide(e){var i;(i=e.getElementsByClassName(t.NAME_CLASS)[0].style).visibility||(i.visibility="hidden")}static reveal(e){e.getElementsByClassName(t.NAME_CLASS)[0].style.visibility=""}static getPosition(t,e){var i,s,n;let o=null==(i=null==e?void 0:e[t])?void 0:i.position;return t!==Se.USER_ROLE&&(o??(o=null==(s=null==e?void 0:e.ai)?void 0:s.position)),o??(o=null==(n=null==e?void 0:e.default)?void 0:n.position),o??(o=t===Se.USER_ROLE?"right":"left"),o}static applyStyle(t,e,i){var s,n,o,r;Object.assign(t.style,null==(s=i.default)?void 0:s.style),e===Se.USER_ROLE?Object.assign(t.style,null==(n=i.user)?void 0:n.style):(Object.assign(t.style,null==(o=i.ai)?void 0:o.style),Object.assign(t.style,null==(r=i[e])?void 0:r.style))}static getNameText(t,e){var i,s,n,o,r,a;return t===Se.USER_ROLE?(null==(i=e.user)?void 0:i.text)||(null==(s=e.default)?void 0:s.text)||"User":t===Se.AI_ROLE?(null==(n=e.ai)?void 0:n.text)||(null==(o=e.default)?void 0:o.text)||"AI":(null==(r=e[t])?void 0:r.text)||(null==(a=e.default)?void 0:a.text)||t}static createName(e,i){const s=document.createElement("div");return s.classList.add(t.NAME_CLASS),s.textContent=t.getNameText(e,i),t.applyStyle(s,e,i),s}static add(e,i,s){const n="boolean"==typeof s?{}:s,o=t.createName(i,n),r=t.getPosition(i,n);o.classList.add("left"===r?"left-item-position":"right-item-position"),e.insertAdjacentElement("left"===r?"beforebegin":"afterend",o)}};xe.NAME_CLASS="name";let ke=xe;const _e=class t{static getLastElementsByClass(t,e,i){for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n.bubbleElement.classList.contains(e[0])&&!e.slice(1).find((t=>!n.bubbleElement.classList.contains(t)))){if(!i)return n;if(!i.find((t=>n.bubbleElement.classList.contains(t))))return n}}}static getLastMessage(t,e,i){for(let s=t.length-1;s>=0;s-=1)if(t[s][0].role===e){if(!i)return t[s][0];if(t[s][0][i])return t[s][0]}}static getLastTextToElement(t,e){for(let i=t.length-1;i>=0;i-=1)if(t[i][0]===e)return t[i]}static overwriteMessage(e,i,s,n,o,r){const a=t.getLastElementsByClass(i,[t.getRoleClass(n),r],[A.BUBBLE_CLASS]),l=t.getLastMessage(e,n,o);return l&&(l[o]=s),a}static getRoleClass(t){return`${t}-message`}static fillEmptyMessageElement(e,i){0===i.trim().length&&(e.classList.add(t.EMPTY_MESSAGE_CLASS),e.innerHTML='<div style="color:#00000000">.</div>')}static unfillEmptyMessageElement(e,i){e.classList.contains(t.EMPTY_MESSAGE_CLASS)&&i.trim().length>0&&e.replaceChildren()}static getLastMessageBubbleElement(e){var i,s,n;return Array.from((null==(n=null==(s=null==(i=t.getLastMessageElement(e))?void 0:i.children)?void 0:s[0])?void 0:n.children)||[]).find((t=>t.classList.contains("message-bubble")))}static getLastMessageElement(t){return t.children[t.children.length-1]}static addRoleElements(t,e,i,s){i&&we.add(t,e,i),s&&ke.add(t,e,s)}static hideRoleElements(t,e,i){e&&we.hide(t),i&&ke.hide(t)}static revealRoleElements(t,e,i){e&&we.reveal(t),i&&ke.reveal(t)}static updateRefArr(t,e,i){i?t.unshift(e):t.push(e)}static buildRoleOuterContainerClass(e){return`${t.OUTER_CONTAINER_CLASS_ROLE_PREFIX}${e}`}static addNewPositionClasses(e,i){e.outerContainer.classList.remove(t.POSITION_TOP_MESSAGE_CLASS,t.POSITION_MIDDLE_MESSAGE_CLASS,t.POSITION_BOTTOM_MESSAGE_CLASS),e.outerContainer.classList.add(...i)}static getNumberOfElements(t){let e=0;return void 0!==t.text&&(e+=1),void 0!==t.html&&(e+=1),t.files&&(e+=t.files.length),e}static filterdMessageElements(t,e){return t.filter((t=>t.bubbleElement.classList.contains(e)))}static findMessageElements(t,e){return t.find((t=>t.bubbleElement.classList.contains(e)))}static generateMessageBodyElements(e,i){const s={};return e.text&&(s.text=t.findMessageElements(i,fe.TEXT_BUBBLE_CLASS)),e.html&&(s.html=t.findMessageElements(i,R.HTML_BUBBLE_CLASS)),e.files&&(s.files=t.filterdMessageElements(i,M.FILE_BUBBLE_CLASS)),s}static generateMessageBody(e,i,s=!1){const n=t.getNumberOfElements(e),o=s?i.slice(0,n):i.slice(i.length-n);return t.generateMessageBodyElements(e,o)}static classifyRoleMessages(e,i){let s=i?t.buildRoleOuterContainerClass(i):void 0;for(let n=e.length-1;n>=0;n-=1){if(i||(s=Array.from(e[n].outerContainer.classList).find((e=>e.startsWith(t.OUTER_CONTAINER_CLASS_ROLE_PREFIX)))),!s)continue;const o=e[n],r=o.outerContainer.classList.contains(s),a=e[n-1],l=e[n+1],c=null==a?void 0:a.outerContainer.classList.contains(s),h=null==l?void 0:l.outerContainer.classList.contains(s);if(r)!c&&h?t.addNewPositionClasses(o,[t.POSITION_TOP_MESSAGE_CLASS]):c&&h?t.addNewPositionClasses(o,[t.POSITION_MIDDLE_MESSAGE_CLASS]):c&&!h?t.addNewPositionClasses(o,[t.POSITION_BOTTOM_MESSAGE_CLASS]):!c&&!h&&t.addNewPositionClasses(o,[t.POSITION_TOP_MESSAGE_CLASS,t.POSITION_BOTTOM_MESSAGE_CLASS]);else if(i)break}}static areOuterContainerClassRolesSame(e,i){return!!i&&Array.from(i.outerContainer.classList).find((e=>e.startsWith(t.OUTER_CONTAINER_CLASS_ROLE_PREFIX)))===t.buildRoleOuterContainerClass(e)}static resetAllRoleElements(e,i,s){if(!i&&!s)return;let n="";e.forEach(((o,r)=>{o.bubbleElement.classList.contains(t.ERROR_MESSAGE_TEXT_CLASS)||t.revealRoleElements(o.innerContainer,i,s);const a=Array.from(o.outerContainer.classList).find((e=>e.startsWith(t.OUTER_CONTAINER_CLASS_ROLE_PREFIX)));n===a&&t.hideRoleElements(e[r-1].innerContainer,i,s),n=a}))}};_e.AI_ROLE="ai",_e.USER_ROLE="user",_e.ERROR_MESSAGE_TEXT_CLASS="error-message-text",_e.OUTER_CONTAINER_CLASS_ROLE_PREFIX="deep-chat-outer-container-role-",_e.EMPTY_MESSAGE_CLASS="empty-message",_e.POSITION_TOP_MESSAGE_CLASS="deep-chat-top-message",_e.POSITION_MIDDLE_MESSAGE_CLASS="deep-chat-middle-message",_e.POSITION_BOTTOM_MESSAGE_CLASS="deep-chat-bottom-message";let Se=_e;const Ae=class t{constructor(t){this._fileAdded=!1,this._streamType="",this._hasStreamEnded=!1,this._messages=t}upsertStreamedMessage(t){var e;if(this._hasStreamEnded)return;if(void 0===(null==t?void 0:t.text)&&void 0===(null==t?void 0:t.html))return console.error(y.INVALID_STREAM_EVENT);const i=(null==t?void 0:t.text)||(null==t?void 0:t.html)||"",s=x.isScrollbarAtBottomOfElement(this._messages.elementRef),n=void 0!==(null==t?void 0:t.text)?"text":"html";if(this._elements||this._message){if(this._streamType!==n)return console.error(y.INVALID_STREAM_EVENT_MIX);this.updateBasedOnType(i,n,null==(e=this._elements)?void 0:e.bubbleElement,null==t?void 0:t.overwrite)}else this.setInitialState(n,i,null==t?void 0:t.role);!this._messages.focusMode&&s&&x.scrollToBottom(this._messages.elementRef)}setInitialState(e,i,s){this._streamType=e,s??(s=Se.AI_ROLE),this._elements="text"===e?this._messages.addNewTextMessage(i,s):R.add(this._messages,i,s,this._messages.messageElementRefs),this._elements.bubbleElement.classList.add(t.MESSAGE_CLASS),this._activeMessageRole=s,this._message={role:this._activeMessageRole,[e]:i},this._messages.messageToElements.push([this._message,{[e]:this._elements}])}updateBasedOnType(t,e,i,s=!1){Se.unfillEmptyMessageElement(i,t),("text"===e?this.updateText:this.updateHTML).bind(this)(t,i,s)}updateText(t,e,i){this._message&&(this._message.text=i?t:this._message.text+t,this._messages.renderText(e,this._message.text))}updateHTML(t,e,i){if(this._message)if(i)this._message.html=t,e.innerHTML=t;else{const i=document.createElement("span");i.innerHTML=t,e.appendChild(i),this._message.html=(null==e?void 0:e.innerHTML)||""}}finaliseStreamedMessage(){var e;if(!this._endStreamAfterOperation&&this._message&&(!this._fileAdded||this._elements)){if(!this._elements)throw Error(y.NO_VALID_STREAM_EVENTS_SENT);null!=(e=this._elements.bubbleElement)&&e.classList.contains(t.MESSAGE_CLASS)&&("text"===this._streamType?this._messages.textToSpeech&&_.speak(this._message.text||"",this._messages.textToSpeech):"html"===this._streamType&&this._elements&&P.apply(this._messages,this._elements.outerContainer),this._elements.bubbleElement.classList.remove(t.MESSAGE_CLASS),this._message&&this._messages.sendClientUpdate(fe.createMessageContent(this._message),!1),this._hasStreamEnded=!0)}}markFileAdded(){this._fileAdded=!0}newMessage(){this.finaliseStreamedMessage(),this._elements=void 0,delete this._message,this._fileAdded=!1,this._hasStreamEnded=!1,this._activeMessageRole=void 0}async endStreamAfterFileDownloaded(t,e){var i;this._endStreamAfterOperation=!0;const{text:s,files:n}=await e();s&&this.updateBasedOnType(s,"text",null==(i=this._elements)?void 0:i.bubbleElement,!0),this._endStreamAfterOperation=!1,this.finaliseStreamedMessage(),n&&t.addNewMessage({files:n})}};Ae.MESSAGE_CLASS="streamed-message";let Te=Ae;const Me=class t{static async tempRemoveContentHeader(e,i,s){if(null==e||!e.headers)throw new Error("Request settings have not been set up");const n=e.headers[t.CONTENT_TYPE];let o;delete e.headers[t.CONTENT_TYPE];try{o=await i(s)}catch(i){throw e.headers[t.CONTENT_TYPE]=n,i}return e.headers[t.CONTENT_TYPE]=n,o}static displayError(t,e,i="Service error, please try again."){if(console.error(e),"object"==typeof e)return e instanceof Error?t.addNewErrorMessage("service",e.message):Array.isArray(e)||"string"==typeof e.error?t.addNewErrorMessage("service",e):0===Object.keys(e).length?t.addNewErrorMessage("service",i):t.addNewErrorMessage("service",JSON.stringify(e));t.addNewErrorMessage("service",e)}static fetch(t,e,i,s){var n,o;const r={method:(null==(n=t.connectSettings)?void 0:n.method)||"POST",headers:e};return"GET"!==r.method&&(r.body=i?JSON.stringify(s):s),t.connectSettings.credentials&&(r.credentials=t.connectSettings.credentials),fetch((null==(o=t.connectSettings)?void 0:o.url)||t.url||"",r)}static processResponseByType(t){const e=t.headers.get("content-type");return null!=e&&e.includes("application/json")?t.json():null!=e&&e.includes("text/plain")||!e?t:t.blob()}static async processRequestInterceptor(t,e){var i;const s=await(null==(i=t.requestInterceptor)?void 0:i.call(t,e))||e,n=s,o=s;return{body:n.body,headers:n.headers,error:o.error}}static validateResponseFormat(t,e){if(!t)return!1;const i=Array.isArray(t)?t:[t];return e&&i.length>1?(console.error(y.INVALID_STREAM_ARRAY_RESPONSE),!1):!i.find((t=>"object"!=typeof t||!("string"==typeof t.error||"string"==typeof t.text||"string"==typeof t.html||Array.isArray(t.files))))}static onInterceptorError(t,e,i){t.addNewErrorMessage("service",e),null==i||i()}static async basicResponseProcessing(e,i,s={}){const{io:n,displayError:o=!0,useRI:r=!0}=s;if(null==n||!n.extractResultData)return i;const a=r?n.deepChat.responseInterceptor:void 0,l=await(null==a?void 0:a(i))||i,c=await n.extractResultData(l);if(c&&("object"==typeof c||Array.isArray(c)))return c;if(o){const s=y.INVALID_RESPONSE(i,"response",!!a,l);t.displayError(e,s)}}};Me.CONTENT_TYPE="Content-Type";let Oe=Me;function je(t){let e,i,s,n=!1;return function(o){void 0===e?(e=o,i=0,s=-1):e=function(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}(e,o);const r=e.length;let a=0;for(;i<r;){n&&(10===e[i]&&(a=++i),n=!1);let o=-1;for(;i<r&&-1===o;++i)switch(e[i]){case 58:-1===s&&(s=i-a);break;case 13:n=!0;case 10:o=i}if(-1===o)break;t(e.subarray(a,o),s),a=i,s=-1}a===r?e=void 0:0!==a&&(e=e.subarray(a),i-=a)}}const Ce="text/event-stream",Ee="last-event-id";function Ie(t,e){var{signal:i,headers:s,onopen:n,onmessage:o,onclose:r,onerror:a,openWhenHidden:l,fetch:c}=e,h=function(t,e){var i={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(i[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(i[s[n]]=t[s[n]])}return i}(e,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise(((e,u)=>{const d=Object.assign({},s);let p;function m(){p.abort(),document.hidden||w()}d.accept||(d.accept=Ce),l||document.addEventListener("visibilitychange",m);let v=1e3,f=0;function g(){document.removeEventListener("visibilitychange",m),window.clearTimeout(f),p.abort()}null==i||i.addEventListener("abort",(()=>{g(),e()}));const b=c??window.fetch,y=n??Pe;async function w(){var i;p=new AbortController;try{const i=await b(t,Object.assign(Object.assign({},h),{headers:d,signal:p.signal}));await y(i),await async function(t,e){const i=t.getReader();let s;for(;!(s=await i.read()).done;)e(s.value)}(i.body,je(function(t,e,i){let s={data:"",event:"",id:"",retry:void 0};const n=new TextDecoder;return function(o,r){if(0===o.length)null==i||i(s),s={data:"",event:"",id:"",retry:void 0};else if(r>0){const i=n.decode(o.subarray(0,r)),a=r+(32===o[r+1]?2:1),l=n.decode(o.subarray(a));switch(i){case"data":s.data=s.data?s.data+"\n"+l:l;break;case"event":s.event=l;break;case"id":t(s.id=l);break;case"retry":const i=parseInt(l,10);isNaN(i)||e(s.retry=i)}}}}((t=>{t?d[Ee]=t:delete d[Ee]}),(t=>{v=t}),o))),null==r||r(),g(),e()}catch(t){if(!p.signal.aborted)try{const e=null!==(i=null==a?void 0:a(t))&&void 0!==i?i:v;window.clearTimeout(f),f=window.setTimeout(w,e)}catch(t){g(),u(t)}}}w()}))}function Pe(t){const e=t.headers.get("content-type");if(null==e||!e.startsWith(Ce))throw new Error(`Expected content-type to be ${Ce}, Actual: ${e}`)}class Ne{static async request(t,e,i,s=!0,n=!1){var o,r,a,l,c,h;const u={body:e,headers:null==(o=t.connectSettings)?void 0:o.headers},{body:d,headers:p,error:m}=await Oe.processRequestInterceptor(t.deepChat,u),{onOpen:v,onClose:f,abortStream:g}=t.streamHandlers;if(m)return Oe.onInterceptorError(i,m,f);if(null!=(r=t.connectSettings)&&r.handler)return Le.stream(t,d,i);if((null==(a=t.connectSettings)?void 0:a.url)===qe.URL)return qe.requestStream(i,t);const b=new Te(i),y=Oe.fetch.bind(this,t,p,s);return Ie((null==(l=t.connectSettings)?void 0:l.url)||t.url||"",{method:(null==(c=t.connectSettings)?void 0:c.method)||"POST",headers:p,credentials:null==(h=t.connectSettings)?void 0:h.credentials,body:s?JSON.stringify(d):d,openWhenHidden:!0,async onopen(t){if(t.ok)return v();throw await Oe.processResponseByType(t)},async onmessage(e){var s,n,o;if(JSON.stringify(e.data)!==JSON.stringify("[DONE]")){let r;try{r=JSON.parse(e.data)}catch{r={}}const a=await(null==(n=(s=t.deepChat).responseInterceptor)?void 0:n.call(s,r))||r;null==(o=t.extractResultData)||o.call(t,a,y,d).then((e=>{t.asyncCallInProgress&&e&&""!==e.text?(Ne.simulate(i,t.streamHandlers,e),f(),t.asyncCallInProgress=!1):Ne.upsertWFiles(i,b.upsertStreamedMessage.bind(b),b,e)})).catch((t=>Oe.displayError(i,t)))}},onerror(t){throw f(),t},onclose(){if(!t.asyncCallInProgress)try{b.finaliseStreamedMessage(),f()}catch(t){if(!n)throw t}},signal:g.signal}).catch((e=>{var s;i.isLastMessageError()||null==(s=t.extractResultData)||s.call(t,e).then((()=>{Oe.displayError(i,e)})).catch((t=>{Oe.displayError(i,t)}))})),b}static async simulate(t,e,i,s){const n=e;if(!await Oe.basicResponseProcessing(t,i,{io:s,useRI:!1}))return e.onClose();if(Array.isArray(i)&&(i=i[0]),i.files){const e=await Oe.basicResponseProcessing(t,{files:i.files},{io:s});t.addNewMessage({sendUpdate:!1,ignoreText:!0,...e},!1)}if(i.text){e.onOpen();const o=i.text.split("");Ne.populateMessages(t,o,new Te(t),n,"text",0,s)}if(i.html){e.onOpen();let o=P.splitHTML(i.html);0===o.length&&(o=i.html.split("")),Ne.populateMessages(t,o,new Te(t),n,"html",0,s)}}static async populateMessages(t,e,i,s,n,o,r){const a=e[o];if(a){const l=await Oe.basicResponseProcessing(t,{[n]:a},{io:r});Ne.upsertWFiles(t,i.upsertStreamedMessage.bind(i),i,l);const c=setTimeout((()=>{Ne.populateMessages(t,e,i,s,n,o+1,r)}),s.simulationInterim||6);s.abortStream.abort=()=>{Ne.abort(c,i,s.onClose)}}else i.finaliseStreamedMessage(),s.onClose()}static isSimulation(t){return"object"==typeof t&&!!t.simulation}static isSimulatable(t,e){return Ne.isSimulation(t)&&e&&(e.text||e.html)}static abort(t,e,i){clearTimeout(t),e.finaliseStreamedMessage(),i()}static upsertWFiles(t,e,i,s){if(s&&Array.isArray(s)&&(s=s[0]),null!=s&&s.text||null!=s&&s.html){const t=e(s);i??(i=t||void 0)}null!=s&&s.files&&(t.addNewMessage({files:s.files}),null==i||i.markFileAdded())}}const Re=class t{static generateResponse(t){const e=t[t.length-1][0];if(e.files&&e.files.length>0){if(e.files.length>1)return"These are interesting files!";const t=e.files[0];return t.src&&t.src.startsWith("data:image/gif")?"That is a nice gif!":"image"===t.type?"That is a nice image!":"audio"===t.type?"I like the sound of that!":"That is an interesting file!"}if(e.text){if("?"===e.text.charAt(e.text.length-1))return"I'm sorry but I can't answer that question...";if(e.text.includes("updog"))return"What's updog?"}return"Hi there! This is a demo response!"}static getCustomResponse(t,e){return"function"==typeof t?t(e):t}static getResponse({customDemoResponse:e,messageToElements:i}){return e?t.getCustomResponse(e,i[i.length-1][0]):{text:t.generateResponse(i)}}static request(e,i){const s=t.getResponse(i);setTimeout((async()=>{const t=await Oe.basicResponseProcessing(i,s,{io:e});if(!t)return e.completionsHandlers.onFinish();const n=Array.isArray(t)?t:[t],o=n.find((t=>"string"==typeof t.error));o?(i.addNewErrorMessage("service",o.error),e.completionsHandlers.onFinish()):Ne.isSimulatable(e.stream,t)?Ne.simulate(i,e.streamHandlers,t):(n.forEach((t=>i.addNewMessage(t))),e.completionsHandlers.onFinish())}),400)}static requestStream(e,i){setTimeout((()=>{const s=t.getResponse(e);Ne.simulate(e,i.streamHandlers,s,i)}),400)}};Re.URL="deep-chat-demo";let qe=Re;class Be{static setup(t){t.permittedErrorPrefixes=["Connection error","Error in server message"],t.websocket="pending"}static isElementPresentInDOM(t){return t.getRootNode({composed:!0})instanceof Document}static createConnection(t,e){if(!Be.isElementPresentInDOM(t.deepChat))return;const i=t.connectSettings.websocket;if(i){if(t.connectSettings.handler)return Le.websocket(t,e);try{const s="boolean"!=typeof i?i:void 0,n=new WebSocket(t.connectSettings.url||"",s);t.websocket=n,t.websocket.onopen=()=>{var i,s;e.removeError(),t.websocket&&"object"==typeof t.websocket&&Be.assignListeners(t,n,e),null==(s=(i=t.deepChat)._validationHandler)||s.call(i)},t.websocket.onerror=i=>{console.error(i),Be.retryConnection(t,e)}}catch(i){console.error(i),Be.retryConnection(t,e)}}}static retryConnection(t,e){var i,s;null==(s=(i=t.deepChat)._validationHandler)||s.call(i),Be.isElementPresentInDOM(t.deepChat)&&(t.websocket="pending",e.isLastMessageError()||e.addNewErrorMessage("service","Connection error"),setTimeout((()=>{Be.createConnection(t,e)}),5e3))}static assignListeners(t,e,i){const s={};e.onmessage=async e=>{if(t.extractResultData)try{const n=JSON.parse(e.data),o=await Oe.basicResponseProcessing(i,n,{io:t,displayError:!1});if(!o)throw Error(y.INVALID_RESPONSE(n,"server",!!t.deepChat.responseInterceptor,o));if(Ne.isSimulation(t.stream)){const e=Be.stream.bind(this,t,i,s),r=s[n.role||Se.AI_ROLE];Ne.upsertWFiles(i,e,r,o)}else(Array.isArray(o)?o:[o]).forEach((t=>i.addNewMessage(t)))}catch(t){Oe.displayError(i,t,"Error in server message")}},e.onclose=()=>{console.error("Connection closed"),i.isLastMessageError()||i.addNewErrorMessage("service","Connection error"),t.stream&&t.streamHandlers.abortStream.abort(),Be.createConnection(t,i)}}static async sendWebsocket(t,e,i,s=!0){var n,o;if((null==(n=t.connectSettings)?void 0:n.url)===qe.URL)return qe.request(t,i);const r=t.websocket;if(!r||"pending"===r)return;const a={body:e,headers:null==(o=t.connectSettings)?void 0:o.headers},{body:l,error:c}=await Oe.processRequestInterceptor(t.deepChat,a);if(c)return i.addNewErrorMessage("service",c);if(!Be.isWebSocket(r))return r.newUserMessage.listener(l);const h=s?JSON.stringify(l):l;void 0===r.readyState||r.readyState!==r.OPEN?(console.error("Connection is not open"),i.isLastMessageError()||i.addNewErrorMessage("service","Connection error")):(r.send(JSON.stringify(h)),t.completionsHandlers.onFinish())}static canSendMessage(t){return!t||"pending"!==t&&(Be.isWebSocket(t)?void 0!==t.readyState&&t.readyState===t.OPEN:t.isOpen)}static isWebSocket(t){return void 0!==t.send}static stream(t,e,i,s){if(!s)return;const n=t.stream.simulation;if("string"==typeof n){const t=s.role||Se.AI_ROLE,o=i[t];s.text===n||s.html===n?(null==o||o.finaliseStreamedMessage(),delete i[t]):(i[t]??(i[t]=new Te(e)),i[t].upsertStreamedMessage(s))}else Ne.simulate(e,t.streamHandlers,s)}}class Le{static async request(t,e,i){var s,n;let o=!0;const r=Le.generateOptionalSignals();null==(n=(s=t.connectSettings).handler)||n.call(s,e,{...r,onResponse:async e=>{if(!o)return;o=!1;const s=await Oe.basicResponseProcessing(i,e,{io:t,displayError:!1});if(s){const e=Array.isArray(s)?s:[s],n=e.find((t=>"string"==typeof t.error));n?(console.error(n.error),i.addNewErrorMessage("service",n.error),t.completionsHandlers.onFinish()):Ne.isSimulatable(t.stream,s)?Ne.simulate(i,t.streamHandlers,s):(e.forEach((t=>i.addNewMessage(t))),t.completionsHandlers.onFinish())}else console.error(y.INVALID_RESPONSE(e,"server",!!t.deepChat.responseInterceptor,s)),i.addNewErrorMessage("service","Error in server message"),t.completionsHandlers.onFinish()}})}static attemptToFinaliseStream(t,e){try{const i=e.messageElementRefs[e.messageElementRefs.length-1];fe.isLoadingMessage(i)?e.removeLastMessage():t.finaliseStreamedMessage()}catch(t){console.error(t),e.addNewErrorMessage("service",t)}}static stream(t,e,i){var s,n;let o=!0,r=!1;const a=new Te(i);t.streamHandlers.abortStream.abort=()=>{Le.attemptToFinaliseStream(a,i),t.streamHandlers.onClose(),o=!1};const l=Le.generateOptionalSignals();null==(n=(s=t.connectSettings).handler)||n.call(s,e,{...l,onOpen:()=>{r||!o||(t.streamHandlers.onOpen(),r=!0)},onResponse:async e=>{if(!o)return;const s=await Oe.basicResponseProcessing(i,e,{io:t,displayError:!1});if(s)s.error?(Le.streamError(s.error,a,t,i),o=!1):Ne.upsertWFiles(i,a.upsertStreamedMessage.bind(a),a,s);else{const n=y.INVALID_RESPONSE(e,"server",!!t.deepChat.responseInterceptor,s);Le.streamError(n,a,t,i),o=!1}},onClose:()=>{o&&(Le.attemptToFinaliseStream(a,i),t.streamHandlers.onClose(),o=!1)},stopClicked:t.streamHandlers.stopClicked})}static streamError(t,e,i,s){console.error(t),e.finaliseStreamedMessage(),s.addNewErrorMessage("service",t),i.streamHandlers.onClose()}static websocket(t,e){var i,s;const n={isOpen:!1,newUserMessage:{listener:()=>{}},roleToStream:{}};t.websocket=n;const o=Le.generateOptionalSignals();null==(s=(i=t.connectSettings).handler)||s.call(i,void 0,{...o,onOpen:()=>{e.removeError(),n.isOpen=!0},onResponse:async i=>{if(!n.isOpen)return;const s=await Oe.basicResponseProcessing(e,i,{io:t,displayError:!1});if(s){const i=Array.isArray(s)?s:[s],o=i.find((t=>"string"==typeof t.error));if(o)console.error(o.error),e.isLastMessageError()||e.addNewErrorMessage("service",o.error);else if(Ne.isSimulation(t.stream)){const i=s,o=Be.stream.bind(this,t,e,n.roleToStream),r=n.roleToStream[i.role||Se.AI_ROLE];Ne.upsertWFiles(e,o,r,i)}else i.forEach((t=>e.addNewMessage(t)))}else console.error(y.INVALID_RESPONSE(i,"server",!!t.deepChat.responseInterceptor,s)),e.addNewErrorMessage("service","Error in server message")},onClose:()=>{n.isOpen=!1},newUserMessage:n.newUserMessage})}static generateOptionalSignals(){return{onClose:()=>{},onOpen:()=>{},stopClicked:{listener:()=>{}},newUserMessage:{listener:()=>{}}}}}class Fe{static async request(t,e,i,s=!0){var n,o,r;const a={body:e,headers:null==(n=t.connectSettings)?void 0:n.headers},{body:l,headers:c,error:h}=await Oe.processRequestInterceptor(t.deepChat,a),{onFinish:u}=t.completionsHandlers;if(h)return Oe.onInterceptorError(i,h,u);if(null!=(o=t.connectSettings)&&o.handler)return Le.request(t,l,i);if((null==(r=t.connectSettings)?void 0:r.url)===qe.URL)return qe.request(t,i);let d=!0;const p=Oe.fetch.bind(this,t,c,s);p(l).then((t=>(d=!!t.ok,t))).then((t=>Oe.processResponseByType(t))).then((async e=>{var s,n;if(!t.extractResultData)return;const o=await(null==(n=(s=t.deepChat).responseInterceptor)?void 0:n.call(s,e))||e,r=await t.extractResultData(o,p,l);if(!d)throw e;if(!r||"object"!=typeof r&&!Array.isArray(r))throw Error(y.INVALID_RESPONSE(e,"response",!!t.deepChat.responseInterceptor,o));r.makingAnotherRequest||(Ne.isSimulatable(t.stream,r)?Ne.simulate(i,t.streamHandlers,r):((Array.isArray(r)?r:[r]).forEach((t=>i.addNewMessage(t))),u()))})).catch((t=>{Oe.displayError(i,t),u()}))}static executePollRequest(t,e,i,s){const{onFinish:n}=t.completionsHandlers;fetch(e,i).then((t=>t.json())).then((async o=>{var r,a;if(!t.extractPollResultData)return;const l=await t.extractPollResultData(await(null==(a=(r=t.deepChat).responseInterceptor)?void 0:a.call(r,o))||o);l.timeoutMS?setTimeout((()=>{Fe.executePollRequest(t,e,i,s)}),l.timeoutMS):Ne.isSimulatable(t.stream,l)?Ne.simulate(s,t.streamHandlers,l):(s.addNewMessage(l),n())})).catch((t=>{Oe.displayError(s,t),n()}))}static async poll(t,e,i,s=!0){var n,o,r;const a={body:e,headers:null==(n=t.connectSettings)?void 0:n.headers},{body:l,headers:c,error:h}=await Oe.processRequestInterceptor(t.deepChat,a);if(h)return Oe.onInterceptorError(i,h);const u=(null==(o=t.connectSettings)?void 0:o.url)||t.url||"",d={method:(null==(r=t.connectSettings)?void 0:r.method)||"POST",body:s?JSON.stringify(l):l,headers:c};t.connectSettings.credentials&&(d.credentials=t.connectSettings.credentials),Fe.executePollRequest(t,u,d,i)}static verifyKey(t,e,i,s,n,o,r,a,l){if(""===t)return o(y.INVALID_KEY);r(),fetch(e,{method:s,headers:i,body:l||null}).then((t=>Oe.processResponseByType(t))).then((e=>{a(e,t,n,o)})).catch((t=>{o(y.CONNECTION_FAILED),console.error(t)}))}}const ze=class t{constructor(t,e,i){this._isLoading=!1,this._isPaginationComplete=!1,this._index=0,this._messages=e,i.fetchHistory&&this.fetchHistory(i.fetchHistory),t.loadHistory&&this.setupLoadHistoryOnScroll(t.loadHistory),this.setupInitialHistory(t)}async fetchHistory(e){const i=de.addMessage(this._messages),s=await e();this._messages.removeMessage(i),t.displayIntroMessages(this._messages.messageElementRefs),s.forEach((t=>this._messages.addAnyMessage(t,!0))),setTimeout((()=>x.scrollToBottom(this._messages.elementRef)),0)}processLoadedHistory(t){var e;const{messageElementRefs:i,messageToElements:s,elementRef:n}=this._messages,o=null==(e=i.find((t=>!t.outerContainer.classList.contains(fe.INTRO_CLASS))))?void 0:e.outerContainer,r=n.scrollTop;null==t||t.reverse().map((t=>{const e=this._messages.addAnyMessage({...t,sendUpdate:!0},!0,!0);if(e){const t=Se.generateMessageBody(e,i,!0);s.unshift([e,t])}return e})).filter((t=>!!t)).reverse().forEach((t=>this._messages.sendClientUpdate(t,!0))),o&&(n.scrollTop=r+o.offsetTop-40)}populateMessages(t,e){this._messages.removeMessage(t),this._isPaginationComplete=e.findIndex((t=>!t))<0;const i=e.filter((t=>!!t));this.processLoadedHistory(i);const{messageElementRefs:s,avatars:n,names:o}=this._messages;Se.resetAllRoleElements(s,!!n,!!o)}async setupLoadHistoryOnScroll(e){this._messages.elementRef.onscroll=async()=>{if(!this._isLoading&&!this._isPaginationComplete&&0===this._messages.elementRef.scrollTop){this._isLoading=!0;const i=de.addMessage(this._messages,!1);try{const t=await e(this._index++);this.populateMessages(i,t),this._isLoading=!1}catch(e){this._messages.removeMessage(i),this._isPaginationComplete=!0,this._messages.addNewErrorMessage("service",t.FAILED_ERROR_MESSAGE,!0),console.error(e)}}}}populateInitialHistory(t){t.forEach((t=>{O.processHistoryFile(t),this._messages.addAnyMessage(t,!0)}))}async loadInitialHistory(e){this._isLoading=!0;const i=de.addMessage(this._messages);try{const t=await e(this._index++),s=this._messages.elementRef.scrollTop;this.populateMessages(i,t),0===s&&setTimeout((()=>x.scrollToBottom(this._messages.elementRef)),0)}catch(e){this._messages.removeMessage(i),this._isPaginationComplete=!0,this._messages.addNewErrorMessage("service",t.FAILED_ERROR_MESSAGE,!0),console.error(e)}t.displayIntroMessages(this._messages.messageElementRefs),this._isLoading=!1}async setupInitialHistory(t){t.loadHistory&&this.loadInitialHistory(t.loadHistory);const e=t.history||O.processHistory(t);e&&(this.populateInitialHistory(e),this._index+=1)}static addErrorPrefix(e){e.permittedErrorPrefixes??(e.permittedErrorPrefixes=[]),e.permittedErrorPrefixes.push(t.FAILED_ERROR_MESSAGE)}static displayIntroMessages(t){for(let e=0;e<t.length;e+=1){const e=t[0];if(!e.outerContainer.classList.contains(fe.INTRO_CLASS))break;e.outerContainer.style.display=""}}};ze.FAILED_ERROR_MESSAGE="Failed to load history";let De=ze;class $e{static getCharacterLimitMessages(t,e){var i;if(-1===e)return t;let s=0,n=t.length-1;for(;n>=0;n-=1){const o=null==(i=t[n])?void 0:i.text;if(void 0!==o&&(s+=o.length,s>e)){t[n].text=o.substring(0,o.length-(s-e));break}}return t.slice(Math.max(n,0))}static getMaxMessages(t,e){return t.slice(Math.max(t.length-e,0))}static processMessages(t,e,i){return void 0!==e?e>0&&(t=$e.getMaxMessages(t,e)):t=[t[t.length-1]],t=JSON.parse(JSON.stringify(t)),void 0===i?t:$e.getCharacterLimitMessages(t,i)}}class Je{static parseConfig(t,e,i,s){var n;const o={files:e};if("object"==typeof s){O.processFileConfigConnect(s);const{files:e,connect:r,button:a}=s;e&&(e.infoModal&&(o.files.infoModal=e.infoModal,null!=(n=e.infoModal)&&n.textMarkDown&&(o.infoModalTextMarkUp=i.render(e.infoModal.textMarkDown))),e.acceptedFormats&&(o.files.acceptedFormats=e.acceptedFormats),e.maxNumberOfFiles&&(o.files.maxNumberOfFiles=e.maxNumberOfFiles)),o.button=a,r&&(r.headers||r.method||r.url||r.credentials||t.headers||t.method||t.url||t.credentials)&&(o.connect={url:(null==r?void 0:r.url)||t.url,method:(null==r?void 0:r.method)||t.method,headers:(null==r?void 0:r.headers)||t.headers,credentials:(null==r?void 0:r.credentials)||t.credentials})}return o}static processMixedFiles(t,e,i){if(i){const s={acceptedFormats:""};t.fileTypes.mixedFiles=Je.parseConfig(t.connectSettings,s,e,i)}}static processMicrophone(t,e,i,s){var n,o,r,a,l,c;const h={acceptedFormats:"audio/*",...(null==(n=t.fileTypes.audio)?void 0:n.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.recordAudio=Je.parseConfig(t.connectSettings,h,e,i),"object"==typeof i&&i.files&&((o=t.recordAudio).files??(o.files={}),t.recordAudio.files.format=null==(r=i.files)?void 0:r.format,t.recordAudio.files.maxDurationSeconds=null==(a=i.files)?void 0:a.maxDurationSeconds,null!=(l=t.fileTypes.audio)&&l.files&&((c=t.fileTypes.audio.files).maxNumberOfFiles??(c.maxNumberOfFiles=i.files.maxNumberOfFiles)))):s||(t.fileTypes.audio=Je.parseConfig(t.connectSettings,h,e,i)))}static processAudioConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"audio/*",...(null==s?void 0:s.files)||{}};t.fileTypes.audio=Je.parseConfig(t.connectSettings,n,e,i)}static processGifConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"image/gif",...(null==s?void 0:s.files)||{}};t.fileTypes.gifs=Je.parseConfig(t.connectSettings,n,e,i)}static processCamera(t,e,i,s){var n,o,r,a;const l={acceptedFormats:"image/*",...(null==(n=t.fileTypes.images)?void 0:n.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.camera=Je.parseConfig(t.connectSettings,l,e,i),"object"==typeof i&&(t.camera.modalContainerStyle=i.modalContainerStyle,i.files&&((o=t.camera).files??(o.files={}),t.camera.files.format=null==(r=i.files)?void 0:r.format,t.camera.files.dimensions=null==(a=i.files)?void 0:a.dimensions))):s||(t.fileTypes.images=Je.parseConfig(t.connectSettings,l,e,i)))}static processImagesConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"image/*",...(null==s?void 0:s.files)||{}};t.fileTypes.images=Je.parseConfig(t.connectSettings,n,e,i)}static populateDefaultFileIO(t,e){var i,s;t&&(t.files??(t.files={}),(i=t.files).acceptedFormats??(i.acceptedFormats=e),(s=t.files).maxNumberOfFiles??(s.maxNumberOfFiles=1))}static set(t,e,i){Je.populateDefaultFileIO(null==i?void 0:i.audio,".4a,.mp3,.webm,.mp4,.mpga,.wav,.mpeg,.m4a"),Je.populateDefaultFileIO(null==i?void 0:i.images,".png,.jpg");const s=le.createNew(t.remarkable);Je.processImagesConfig(e,s,t.images,null==i?void 0:i.images),Je.processCamera(e,s,t.camera,t.images),Je.processGifConfig(e,s,t.gifs,null==i?void 0:i.gifs),Je.processAudioConfig(e,s,t.audio,null==i?void 0:i.audio),Je.processMicrophone(e,s,t.microphone,t.audio),Je.processMixedFiles(e,s,t.mixedFiles)}}class Ue{constructor(t,e,i){var s,n,o,r,a;this.rawBody={},this.validateKeyProperty=!1,this.canSendMessage=Ue.canSendMessage,this.connectSettings={},this.fileTypes={},this.completionsHandlers={},this.streamHandlers={},this.deepChat=t,this.demo=i,Object.assign(this.rawBody,null==(s=t.connect)?void 0:s.additionalBodyProps),this.totalMessagesMaxCharLength=null==(n=null==t?void 0:t.requestBodyLimits)?void 0:n.totalMessagesMaxCharLength,this.maxMessages=null==(o=null==t?void 0:t.requestBodyLimits)?void 0:o.maxMessages,Je.set(t,this,e),t.connect&&(this.connectSettings=t.connect),this.demo&&((r=this.connectSettings).url??(r.url=qe.URL)),this.connectSettings.websocket&&Be.setup(this),this.stream=(null==(a=this.deepChat.connect)?void 0:a.stream)||O.checkForStream(this.deepChat),t.loadHistory&&De.addErrorPrefix(this)}static canSendMessage(t,e,i){return!!i||(!(!t||""===t.trim())||!!(e&&e.length>0))}verifyKey(t,e){}static createCustomFormDataBody(t,e,i){const s=new FormData;i.forEach((t=>s.append("files",t))),Object.keys(t).forEach((e=>s.append(e,String(t[e]))));let n=0;e.slice(0,e.length-1).forEach((t=>{s.append(`message${n+=1}`,JSON.stringify(t))}));const o=e[e.length-1];return o.text&&(delete o.files,s.append(`message${n+=1}`,JSON.stringify(o))),s}getServiceIOByType(t){if(t.type.startsWith("audio")&&this.fileTypes.audio)return this.fileTypes.audio;if(t.type.startsWith("image")){if(this.fileTypes.gifs&&t.type.endsWith("/gif"))return this.fileTypes.gifs;if(this.fileTypes.images)return this.fileTypes.images;if(this.camera)return this.camera}return this.fileTypes.mixedFiles}async request(t,e,i=!0){return this.stream&&!Ne.isSimulation(this.stream)?Ne.request(this,t,e,i):Fe.request(this,t,e,i)}async callAPIWithText(t,e){var i,s,n,o;const r={messages:e,...this.rawBody};let a=!1;null!=(i=this.connectSettings.headers)&&i["Content-Type"]||((s=this.connectSettings).headers??(s.headers={}),(n=this.connectSettings.headers)["Content-Type"]??(n["Content-Type"]="application/json"),a=!0),await this.request(r,t),a&&(null==(o=this.connectSettings.headers)||delete o["Content-Type"])}async callApiWithFiles(t,e,i){const s=Ue.createCustomFormDataBody(this.rawBody,e,i),n=this.connectSettings,o=this.getServiceIOByType(i[0]);this.connectSettings=(null==o?void 0:o.connect)||this.connectSettings,await this.request(s,t,!1),this.connectSettings=n}async callServiceAPI(t,e,i){i?this.callApiWithFiles(t,e,i):this.callAPIWithText(t,e)}async callAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=$e.processMessages(e.messageToElements.map((([t])=>t)),this.maxMessages,this.totalMessagesMaxCharLength);if(!this.connectSettings.websocket||this.connectSettings.handler&&this.connectSettings.url===qe.URL)this.callServiceAPI(e,i,t.files);else{const t={messages:i,...this.rawBody};Be.sendWebsocket(this,t,e,!1)}}async extractResultData(t){if(t.error)throw t.error;return t.result?O.handleResponseProperty(t):Oe.validateResponseFormat(t,!!this.stream)?t:void 0}isDirectConnection(){return!1}isWebModel(){return!1}isCustomView(){return!1}}class Ve extends Ue{constructor(t,e,i,s,n){var o;super(t,n),this.insertKeyPlaceholderText="API Key",this.keyHelpUrl="",Object.assign(this.rawBody,null==(o=t.connect)?void 0:o.additionalBodyProps),this.keyVerificationDetails=e,this.buildHeadersFunc=i,s&&this.setApiKeyProperties(s),this.connectSettings=this.buildConnectSettings(this.key||"",t.connect)}setApiKeyProperties(t){this.key=t.key,t.validateKeyProperty&&(this.validateKeyProperty=t.validateKeyProperty)}buildConnectSettings(t,e){const i=e??{};return i.headers??(i.headers={}),Object.assign(i.headers,this.buildHeadersFunc(t)),i}keyAuthenticated(t,e){this.connectSettings=this.buildConnectSettings(e,this.connectSettings),this.key=e,t()}verifyKey(t,e){const{url:i,method:s,handleVerificationResult:n,createHeaders:o,body:r}=this.keyVerificationDetails,a=(null==o?void 0:o(t))||this.buildHeadersFunc(t);Fe.verifyKey(t,i,a,s,this.keyAuthenticated.bind(this,e.onSuccess),e.onFail,e.onLoad,n,r)}isDirectConnection(){return!0}}class He{static waitForPropertiesToBeUpdatedBeforeRender(t){t._propUpdated_=!1,setTimeout((()=>{t._propUpdated_?He.waitForPropertiesToBeUpdatedBeforeRender(t):(t._waitingToRender_=!1,t.onRender())}))}static attemptRender(t){t._propUpdated_=!0,t._waitingToRender_||(t._waitingToRender_=!0,He.waitForPropertiesToBeUpdatedBeforeRender(t))}}const Ke=class t extends HTMLElement{constructor(){super(),this._waitingToRender_=!1,this._propUpdated_=!1,Object.keys(t._attributeToProperty_).forEach((e=>{const i=t._attributeToProperty_[e];this.constructPropertyAccessors(i),this.hasOwnProperty(e)||this.constructPropertyAccessors(i,e)}))}static get observedAttributes(){return Object.keys(t._attributes_)||[]}constructPropertyAccessors(t,e){let i;Object.defineProperty(this,e||t,{get:function(){return i},set:function(s){i=s,e?this[t]=s:He.attemptRender(this)}})}attributeChangedCallback(e,i,s){if(i===s)return;const n=t._attributes_[e](s);this[t._attributeToProperty_[e]]=n}onRender(){}};Ke._attributes_={},Ke._attributeToProperty_={};let Ge=Ke;class Ze{static createSVGElement(t){return(new DOMParser).parseFromString(t,"image/svg+xml").documentElement}}const We=class t{static changeVisibility(e,i,s,n){n.target.id===t.VISIBLE_ICON_ID?(i.style.display="none",s.style.display="block",e.type="password"):(i.style.display="block",s.style.display="none",e.type="text")}static createIconElement(t,e){const i=Ze.createSVGElement(t);return i.id=e,i.classList.add("visibility-icon"),i}static create(e){const i=document.createElement("div");i.id="visibility-icon-container";const s=t.createIconElement('<?xml version="1.0" standalone="no"?>\n<svg version="1.1"\n\txmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n\txmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0.9em" height="0.9em"\n\tviewBox="0 0 1200 1200" enable-background="new 0 0 1200 1200">\n\t\t<path id="path6686" inkscape:connector-curvature="0" d="M779.843,599.925c0,95.331-80.664,172.612-180.169,172.612\n\t\t\tc-99.504,0-180.168-77.281-180.168-172.612c0-95.332,80.664-172.612,180.168-172.612\n\t\t\tC699.179,427.312,779.843,504.594,779.843,599.925z M600,240.521c-103.025,0.457-209.814,25.538-310.904,73.557\n\t\t\tc-75.058,37.122-148.206,89.496-211.702,154.141C46.208,501.218,6.431,549,0,599.981c0.76,44.161,48.13,98.669,77.394,131.763\n\t\t\tc59.543,62.106,130.786,113.018,211.702,154.179c94.271,45.751,198.616,72.092,310.904,73.557\n\t\t\tc103.123-0.464,209.888-25.834,310.866-73.557c75.058-37.122,148.243-89.534,211.74-154.179\n\t\t\tc31.185-32.999,70.962-80.782,77.394-131.763c-0.76-44.161-48.13-98.671-77.394-131.764\n\t\t\tc-59.543-62.106-130.824-112.979-211.74-154.141C816.644,268.36,712.042,242.2,600,240.521z M599.924,329.769\n\t\t\tc156.119,0,282.675,120.994,282.675,270.251c0,149.256-126.556,270.25-282.675,270.25S317.249,749.275,317.249,600.02\n\t\t\tC317.249,450.763,443.805,329.769,599.924,329.769L599.924,329.769z"/>\n</svg>\n',t.VISIBLE_ICON_ID);s.style.display="none",i.appendChild(s);const n=t.createIconElement('<?xml version="1.0" standalone="no"?>\n<svg version="1.1"\n\txmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n\txmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0.9em" height="0.9em"\n\tviewBox="0 0 1200 1200" enable-background="new 0 0 1200 1200">\n\t\t<path d="\n\t\t\tM669.727,273.516c-22.891-2.476-46.15-3.895-69.727-4.248c-103.025,0.457-209.823,25.517-310.913,73.536\n\t\t\tc-75.058,37.122-148.173,89.529-211.67,154.174C46.232,529.978,6.431,577.76,0,628.74c0.76,44.162,48.153,98.67,77.417,131.764\n\t\t\tc59.543,62.106,130.754,113.013,211.67,154.174c2.75,1.335,5.51,2.654,8.276,3.955l-75.072,131.102l102.005,60.286l551.416-960.033\n\t\t\tl-98.186-60.008L669.727,273.516z M902.563,338.995l-74.927,129.857c34.47,44.782,54.932,100.006,54.932,159.888\n\t\t\tc0,149.257-126.522,270.264-282.642,270.264c-6.749,0-13.29-0.728-19.922-1.172l-49.585,85.84c22.868,2.449,45.99,4.233,69.58,4.541\n\t\t\tc103.123-0.463,209.861-25.812,310.84-73.535c75.058-37.122,148.246-89.529,211.743-154.174\n\t\t\tc31.186-32.999,70.985-80.782,77.417-131.764c-0.76-44.161-48.153-98.669-77.417-131.763\n\t\t\tc-59.543-62.106-130.827-113.013-211.743-154.175C908.108,341.478,905.312,340.287,902.563,338.995L902.563,338.995z\n\t\t\tM599.927,358.478c6.846,0,13.638,0.274,20.361,0.732l-58.081,100.561c-81.514,16.526-142.676,85.88-142.676,168.897\n\t\t\tc0,20.854,3.841,40.819,10.913,59.325c0.008,0.021-0.008,0.053,0,0.074l-58.228,100.854\n\t\t\tc-34.551-44.823-54.932-100.229-54.932-160.182C317.285,479.484,443.808,358.477,599.927,358.478L599.927,358.478z M768.896,570.513\n\t\t\tL638.013,797.271c81.076-16.837,141.797-85.875,141.797-168.603C779.81,608.194,775.724,588.729,768.896,570.513L768.896,570.513z"\n\t\t\t/>\n</svg>\n',"not-visible-icon");return i.appendChild(n),i.onclick=t.changeVisibility.bind(this,e,s,n),i}};We.VISIBLE_ICON_ID="visible-icon";let Xe=We;class Ye{static createCautionText(){const t=document.createElement("a");return t.classList.add("insert-key-input-help-text"),t.innerText="Please exercise CAUTION when inserting your API key outside of deepchat.dev or localhost!!",t}static createHelpLink(t){const e=document.createElement("a");return e.classList.add("insert-key-input-help-text"),e.href=t,e.innerText="Find more info here",e.target="_blank",e}static createFailText(){const t=document.createElement("div");return t.id="insert-key-input-invalid-text",t.style.display="none",t}static createHelpTextContainer(t,e=!0){const i=document.createElement("div");i.id="insert-key-help-text-container";const s=document.createElement("div");s.id="insert-key-help-text-contents";const n=Ye.createFailText();if(s.appendChild(n),t){const e=Ye.createHelpLink(t);s.appendChild(e)}if(!0===e){const t=Ye.createCautionText();s.appendChild(t)}return i.appendChild(s),{helpTextContainerElement:i,failTextElement:n}}static onFail(t,e,i,s){t.classList.replace("insert-key-input-valid","insert-key-input-invalid"),i.innerText=s,i.style.display="block",e.innerText="Start",t.classList.remove("loading")}static onLoad(t,e){t.classList.add("loading"),e.innerHTML='<div id="loading-key"></div>'}static verifyKey(t,e,i){const s=t.value.trim();i.verifyKey(s,e)}static addVerificationEvents(t,e,i,s,n){const o={onSuccess:s,onFail:Ye.onFail.bind(this,t,e,i),onLoad:Ye.onLoad.bind(this,t,e)},r=Ye.verifyKey.bind(this,t,o,n);e.onclick=r,t.onkeydown=e=>{!t.classList.contains("loading")&&e.key===c.ENTER&&r()}}static createStartButton(){const t=document.createElement("div");return t.id="start-button",t.innerText="Start",t}static onInputFocus(t){t.target.classList.replace("insert-key-input-invalid","insert-key-input-valid")}static createInput(t){const e=document.createElement("div");e.id="insert-key-input-container";const i=document.createElement("input");return i.id="insert-key-input",i.placeholder=t||"API Key",i.type="password",i.classList.add("insert-key-input-valid"),i.onfocus=Ye.onInputFocus,e.appendChild(i),e}static createContents(t,e){var i;const s=document.createElement("div");s.id="insert-key-contents";const n=Ye.createInput(e.insertKeyPlaceholderText),o=n.children[0],r=Xe.create(o);n.appendChild(r),s.appendChild(n);const a=Ye.createStartButton(),{helpTextContainerElement:l,failTextElement:c}=Ye.createHelpTextContainer(e.keyHelpUrl,null==(i=e.deepChat._insertKeyViewStyles)?void 0:i.displayCautionText);return s.appendChild(a),s.appendChild(l),Ye.addVerificationEvents(o,a,c,t,e),s}static createElements(t,e){const i=document.createElement("div");i.id="insert-key-view";const s=Ye.createContents(t,e);return i.appendChild(s),i}static render(t,e,i){const s=Ye.createElements(e,i);t.replaceChildren(s)}}const Qe=class t{static enableButtons(e,i,s=0){window.webLLM?(e&&(e.disabled=!1),i&&(i.disabled=!1)):s<4*si.MODULE_SEARCH_LIMIT_S&&setTimeout((()=>t.enableButtons(e,i,s+1)),250)}static setUpInitial(e,i,s,n){const o=(null==i?void 0:i.downloadClass)||t.DOWNLOAD_BUTTON_CLASS,r=(null==i?void 0:i.uploadClass)||t.UPLOAD_BUTTON_CLASS,a=(null==i?void 0:i.fileInputClass)||t.FILE_INPUT_CLASS;return setTimeout((()=>{const i=null==s?void 0:s.getElementsByClassName(o)[0],n=null==s?void 0:s.getElementsByClassName(a)[0],l=null==s?void 0:s.getElementsByClassName(r)[0];i&&(i.onclick=()=>e()),n&&(n.onchange=()=>{n.files&&n.files.length>0&&e(n.files)}),l&&(l.onclick=()=>n.click()),(i||l)&&t.enableButtons(i,l)})),(null==i?void 0:i.initialHtml)||`<div>\n Download or upload a web model that will run entirely on your browser: <br/> \n <button disabled class="${o} deep-chat-button deep-chat-web-model-button">Download</button>\n ${n?"":`<input type="file" class="${a}" hidden multiple />\n <button disabled class="${r} deep-chat-button deep-chat-web-model-button">Upload</button>`}\n </div>`}static exportFile(t){const e=document.createElement("a");for(let i=0;i<t.length/4;i+=1)setTimeout((()=>{const s=4*i;for(let i=s;i<Math.min(s+4,t.length);i+=1){const s=URL.createObjectURL(t[i]);e.href=s,e.download=t[i].name,document.body.appendChild(e),e.click(),URL.revokeObjectURL(s)}}),500*i)}static setUpAfterLoad(e,i,s,n){const o=(null==i?void 0:i.exportFilesClass)||t.EXPORT_BUTTON_CLASS;return setTimeout((()=>{const i=null==s?void 0:s.getElementsByClassName(o)[0];i&&(i.onclick=()=>t.exportFile(e))})),(null==i?void 0:i.afterLoadHtml)||`<div>\n Model loaded successfully and has been cached for future requests.\n ${n?"":`<br/> <button style="margin-top: 5px" class="${o} deep-chat-button">Export</button>`}\n </div>`}};Qe.DOWNLOAD_BUTTON_CLASS="deep-chat-download-button",Qe.UPLOAD_BUTTON_CLASS="deep-chat-upload-button",Qe.FILE_INPUT_CLASS="deep-chat-file-input",Qe.EXPORT_BUTTON_CLASS="deep-chat-export-button";let ti=Qe;const ei={model_list:[{model_url:"https://huggingface.co/mlc-ai/Llama-2-7b-chat-hf-q4f32_1-MLC/resolve/main/",local_id:"Llama-2-7b-chat-hf-q4f32_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-7b-chat-hf/Llama-2-7b-chat-hf-q4f32_1-ctx4k_cs1k-webgpu.wasm",vram_required_MB:9109.03,low_resource_required:!1},{model_url:"https://huggingface.co/mlc-ai/Llama-2-7b-chat-hf-q4f16_1-MLC/resolve/main/",local_id:"Llama-2-7b-chat-hf-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-7b-chat-hf/Llama-2-7b-chat-hf-q4f16_1-ctx4k_cs1k-webgpu.wasm",vram_required_MB:6749.02,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/Llama-2-7b-chat-hf-q4f16_1-MLC/resolve/main/",local_id:"Llama-2-7b-chat-hf-q4f16_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-7b-chat-hf/Llama-2-7b-chat-hf-q4f16_1-ctx1k-webgpu.wasm",vram_required_MB:4618.52,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/Llama-2-13b-chat-hf-q4f16_1-MLC/resolve/main/",local_id:"Llama-2-13b-chat-hf-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-13b-chat-hf/Llama-2-13b-chat-hf-q4f16_1-ctx4k_cs1k-webgpu.wasm",vram_required_MB:11814.09,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/Llama-2-70b-chat-hf-q4f16_1-MLC/resolve/main/",local_id:"Llama-2-70b-chat-hf-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-70b-chat-hf/Llama-2-70b-chat-hf-q4f16_1-ctx4k_cs1k-webgpu.wasm",vram_required_MB:43729.05,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/RedPajama-INCITE-Chat-3B-v1-q4f16_1-MLC/resolve/main/",local_id:"RedPajama-INCITE-Chat-3B-v1-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/RedPajama-INCITE-Chat-3B-v1/RedPajama-INCITE-Chat-3B-v1-q4f16_1-ctx2k-webgpu.wasm",vram_required_MB:2972.09,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/RedPajama-INCITE-Chat-3B-v1-q4f32_1-MLC/resolve/main/",local_id:"RedPajama-INCITE-Chat-3B-v1-q4f32_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/RedPajama-INCITE-Chat-3B-v1/RedPajama-INCITE-Chat-3B-v1-q4f32_1-ctx2k-webgpu.wasm",vram_required_MB:3928.09,low_resource_required:!1},{model_url:"https://huggingface.co/mlc-ai/RedPajama-INCITE-Chat-3B-v1-q4f16_1-MLC/resolve/main/",local_id:"RedPajama-INCITE-Chat-3B-v1-q4f16_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/RedPajama-INCITE-Chat-3B-v1/RedPajama-INCITE-Chat-3B-v1-q4f16_1-ctx1k-webgpu.wasm",vram_required_MB:2041.09,low_resource_required:!0,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/RedPajama-INCITE-Chat-3B-v1-q4f32_1-MLC/resolve/main/",local_id:"RedPajama-INCITE-Chat-3B-v1-q4f32_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/RedPajama-INCITE-Chat-3B-v1/RedPajama-INCITE-Chat-3B-v1-q4f32_1-ctx1k-webgpu.wasm",vram_required_MB:2558.09,low_resource_required:!0},{model_url:"https://huggingface.co/mlc-ai/WizardMath-7B-V1.1-q4f16_1-MLC/resolve/main/",local_id:"WizardMath-7B-V1.1-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Mistral-7B-Instruct-v0.2/Mistral-7B-Instruct-v0.2-q4f16_1-sw4k_cs1k-webgpu.wasm",vram_required_MB:6079.02,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/Mistral-7B-Instruct-v0.2-q4f16_1-MLC/resolve/main/",local_id:"Mistral-7B-Instruct-v0.2-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Mistral-7B-Instruct-v0.2/Mistral-7B-Instruct-v0.2-q4f16_1-sw4k_cs1k-webgpu.wasm",vram_required_MB:6079.02,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/OpenHermes-2.5-Mistral-7B-q4f16_1-MLC/resolve/main/",local_id:"OpenHermes-2.5-Mistral-7B-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Mistral-7B-Instruct-v0.2/Mistral-7B-Instruct-v0.2-q4f16_1-sw4k_cs1k-webgpu.wasm",vram_required_MB:6079.02,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/NeuralHermes-2.5-Mistral-7B-q4f16_1-MLC/resolve/main/",local_id:"NeuralHermes-2.5-Mistral-7B-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Mistral-7B-Instruct-v0.2/Mistral-7B-Instruct-v0.2-q4f16_1-sw4k_cs1k-webgpu.wasm",vram_required_MB:6079.02,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/TinyLlama-1.1B-Chat-v0.4-q0f16-MLC/resolve/main/",local_id:"TinyLlama-1.1B-Chat-v0.4-q0f16",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/TinyLlama-1.1B-Chat-v0.4/TinyLlama-1.1B-Chat-v0.4-q0f16-ctx2k-webgpu.wasm",vram_required_MB:5063.52,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/TinyLlama-1.1B-Chat-v0.4-q0f32-MLC/resolve/main/",local_id:"TinyLlama-1.1B-Chat-v0.4-q0f32",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/TinyLlama-1.1B-Chat-v0.4/TinyLlama-1.1B-Chat-v0.4-q0f32-ctx2k-webgpu.wasm",vram_required_MB:5394.53,low_resource_required:!1},{model_url:"https://huggingface.co/mlc-ai/TinyLlama-1.1B-Chat-v0.4-q4f16_1-MLC/resolve/main/",local_id:"TinyLlama-1.1B-Chat-v0.4-q4f16_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/TinyLlama-1.1B-Chat-v0.4/TinyLlama-1.1B-Chat-v0.4-q4f16_1-ctx1k-webgpu.wasm",vram_required_MB:899.11,low_resource_required:!0,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/TinyLlama-1.1B-Chat-v0.4-q4f32_1-MLC/resolve/main/",local_id:"TinyLlama-1.1B-Chat-v0.4-q4f32_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/TinyLlama-1.1B-Chat-v0.4/TinyLlama-1.1B-Chat-v0.4-q4f32_1-ctx1k-webgpu.wasm",vram_required_MB:992.11,low_resource_required:!0}],use_web_worker:!0},ii=class t extends Ue{constructor(e){var i,s;super(e),this._isModelLoaded=!1,this._isModelLoading=!1,this._loadOnFirstMessage=!1,this._webModel={},this.permittedErrorPrefixes=[t.MULTIPLE_MODELS_ERROR,t.WEB_LLM_NOT_FOUND_ERROR,t.GENERIC_ERROR],this._conversationHistory=[],"object"==typeof e.webModel&&(this._webModel=e.webModel),null!=(i=this._webModel.load)&&i.clearCache&&t.clearAllCache(),this.findModelInWindow(e),this.canSendMessage=this.canSubmit.bind(this),this._chatEl=null==(s=e.shadowRoot)?void 0:s.children[0],e.history&&t.setUpHistory(this._conversationHistory,e.history)}setUpMessages(t){this._messages=t,this._removeIntro=()=>{t.removeIntroductoryMessage(),this._removeIntro=void 0}}static setUpHistory(t,e){e.forEach(((i,s)=>{if(i.role===Se.USER_ROLE&&i.text){const n=e[s+1];null!=n&&n.text&&n.role!==Se.USER_ROLE&&t.push([i.text,n.text])}}))}findModelInWindow(e,i=0){var s;window.webLLM?this.configureInit(this.shouldAddIntroMessage(e.introMessage)):i>t.MODULE_SEARCH_LIMIT_S?(null==(s=this._messages)||s.addNewErrorMessage("service",t.WEB_LLM_NOT_FOUND_ERROR),console.error("The deep-chat-web-llm module has not been attached to the window object. Please see the following guide:"),console.error("https://deepchat.dev/examples/externalModules")):setTimeout((()=>this.findModelInWindow(e,i+1)),1e3)}shouldAddIntroMessage(t){var e;return!t&&this._webModel&&!1!==(null==(e=this._webModel.introMessage)?void 0:e.displayed)}scrollToTop(t){var e;!1!==(null==(e=this._webModel.introMessage)?void 0:e.autoScroll)&&setTimeout((()=>{var t,e;null!=(t=this._messages)&&t.elementRef&&x.scrollToTop(null==(e=this._messages)?void 0:e.elementRef)}),t)}getIntroMessage(t){if(!this.shouldAddIntroMessage(t)||!this._chatEl)return;const e=ti.setUpInitial(this.init.bind(this),this._webModel.introMessage,this._chatEl,!!this._webModel.worker);return this.scrollToTop(1),{role:Se.AI_ROLE,html:e,sendUpdate:!1}}async configureInit(t){const{load:e}=this._webModel;if(e){if(e.onInit)return void this.init();if(e.onMessage)return void(this._loadOnFirstMessage=!0)}t||this.init()}async init(t){var e;null==(e=this._messages)||e.removeError();const i=this.attemptToCreateChat();i&&await this.loadModel(i,t)}attemptToCreateChat(){var e;if(t.chat)return null==(e=this._messages)||e.addNewErrorMessage("service",t.MULTIPLE_MODELS_ERROR),void console.error(t.MULTIPLE_MODELS_ERROR);if(this._isModelLoaded||this._isModelLoading)return;const{worker:i}=this._webModel;return ei.use_web_worker&&i?new window.webLLM.ChatWorkerClient(i):new window.webLLM.ChatModule}getConfig(){var e;let i=t.DEFAULT_MODEL;this._webModel.model&&(i=this._webModel.model);const s=JSON.parse(JSON.stringify(ei));if(this._webModel.urls){const t=s.model_list.find((t=>t.local_id=i));t&&(this._webModel.urls.model&&(t.model_url=this._webModel.urls.model),this._webModel.urls.wasm&&(t.model_lib_url=this._webModel.urls.wasm))}return null!=(e=this._webModel.load)&&e.skipCache&&(s.use_cache=!1),{model:i,appConfig:s}}async loadModel(e,i){var s,n,o,r,a,l,c;this.scrollToTop(),t.chat=e,this._isModelLoading=!0;let h=!1===(null==(s=this._webModel.introMessage)?void 0:s.displayed);let u;t.chat.setInitProgressCallback((t=>{var e;null==(e=this._messages)||e.addNewMessage({html:`<div>${t.text}</div>`,overwrite:!0,sendUpdate:!1}),h&&(setTimeout((()=>{var t;return x.scrollToBottom(null==(t=this._messages)?void 0:t.elementRef)})),h=!1)}));try{const{model:e,appConfig:s}=this.getConfig(),n={};this._webModel.instruction&&(n.conv_config={system:this._webModel.instruction}),this._conversationHistory.length>0&&(n.conversation_history=this._conversationHistory),u=await t.chat.reload(e,n,s,i)}catch(t){return this.unloadChat(t)}if(null==(o=(n=this.deepChat)._validationHandler)||o.call(n),null!=(r=this._webModel.introMessage)&&r.removeAfterLoad)!1===this._webModel.introMessage.displayed?null==(l=this._messages)||l.removeLastMessage():null==(c=this._removeIntro)||c.call(this);else{const t=ti.setUpAfterLoad(u,this._webModel.introMessage,this._chatEl,!!this._webModel.worker);null==(a=this._messages)||a.addNewMessage({html:t,overwrite:!0,sendUpdate:!1})}this._isModelLoaded=!0,this._isModelLoading=!1}async unloadChat(e){var i;null==(i=this._messages)||i.addNewErrorMessage("service",t.GENERIC_ERROR),console.error(e),this._isModelLoaded=!1,this._isModelLoading=!1,t.chat&&(await t.chat.unload(),t.chat=void 0)}async immediateResp(e,i,s){const n={text:await s.generate(i,void 0,0)},o=await t.processResponse(this.deepChat,e,n);o&&o.forEach((t=>e.addNewMessage(t))),this.completionsHandlers.onFinish()}async streamResp(e,i,s){this.streamHandlers.abortStream.abort=()=>{s.interruptGenerate()},this.streamHandlers.onOpen();const n=new Te(e);await s.generate(i,(async(i,s)=>{const o=await t.processResponse(this.deepChat,e,{text:s});o&&n.upsertStreamedMessage({text:o[0].text,overwrite:!0})})),n.finaliseStreamedMessage(),this.streamHandlers.onClose()}async generateRespByType(t,e,i,s){var n;try{i?await this.streamResp(t,e,s):await this.immediateResp(t,e,s)}catch(t){null==(n=this._messages)||n.addNewErrorMessage("service"),console.log(t)}}async generateResp(t,e,i){const s=e[e.length-1].text,{body:n,error:o}=await Oe.processRequestInterceptor(this.deepChat,{body:{text:s}}),r=!!this.stream;try{if(o)Oe.displayError(t,new Error(o)),(r?this.streamHandlers.onClose:this.completionsHandlers.onFinish)();else if(n&&n.text)this.generateRespByType(t,n.text,!!this.stream,i);else{const e=y.INVALID_MODEL_REQUEST({body:n},!1);console.error(e);const i=r?this.streamHandlers.onClose:this.completionsHandlers.onFinish;Oe.onInterceptorError(t,e,i)}}catch(t){this.unloadChat(t)}}async callServiceAPI(e,i){var s,n;if(!this._isModelLoaded){if(!this._loadOnFirstMessage)return;await this.init()}!t.chat||this._isModelLoading||(null!=(s=this._webModel.introMessage)&&s.removeAfterMessage&&(null==(n=this._removeIntro)||n.call(this)),e.addLoadingMessage(),this.generateResp(e,i,t.chat))}canSubmit(t){return!(null==t||!t.trim()||this._isModelLoading)&&(!!this._loadOnFirstMessage||!!this._isModelLoaded)}static async processResponse(t,e,i){var s,n;const o=await(null==(s=t.responseInterceptor)?void 0:s.call(t,i))||i;if(null!=(n=t.connect)&&n.stream&&Array.isArray(o)&&o.length>1)return void console.error(y.INVALID_STREAM_ARRAY_RESPONSE);const r=Array.isArray(o)?o:[o],a=r.find((t=>"string"==typeof t.error));if(a)Oe.displayError(e,new Error(a.error));else{if(!r.find((t=>!t||!t.text)))return r;{const s=y.INVALID_MODEL_RESPONSE(i,!!t.responseInterceptor,o);Oe.displayError(e,new Error(s))}}}isWebModel(){return!0}static clearAllCache(){t.clearCache("webllm/model"),t.clearCache("webllm/wasm")}static clearCache(t){caches.open(t).then((t=>{t.keys().then((e=>{e.forEach((e=>{t.delete(e)}))}))}))}};ii.GENERIC_ERROR="Error, please check the [troubleshooting](https://deepchat.dev/docs/webModel#troubleshooting) section of documentation for help.",ii.MULTIPLE_MODELS_ERROR="Cannot run multiple web models",ii.WEB_LLM_NOT_FOUND_ERROR="WebLLM module not found",ii.DEFAULT_MODEL="Llama-2-7b-chat-hf-q4f32_1",ii.MODULE_SEARCH_LIMIT_S=5;let si=ii;class ni{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,s){const n=t;Array.isArray(n.error)&&"Error in `parameters`: field required"===n.error[0]?i(e):s(y.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api-inference.huggingface.co/models/gpt2",method:"POST",handleVerificationResult:ni.handleVerificationResult}}}const oi=class t extends Ve{constructor(e,i,s,n,o,r){super(e,ni.buildKeyVerificationDetails(),ni.buildHeaders,o,r),this.insertKeyPlaceholderText="Hugging Face Token",this.keyHelpUrl="https://huggingface.co/settings/tokens",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Hugging Face</b></div>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>',this.permittedErrorPrefixes=["Authorization header"],this.url=`${t.URL_PREFIX}${s}`,this.textInputPlaceholderText=i,"object"==typeof n&&(n.model&&(this.url=`${t.URL_PREFIX}${n.model}`),n.options&&(this.rawBody.options=n.options),n.parameters&&(this.rawBody.parameters=n.parameters))}preprocessBody(t,e,i){const s=JSON.parse(JSON.stringify(t)),n=e[e.length-1].text;if(n)return s.options??(s.options={}),s.options.wait_for_model=!0,{inputs:n,...s}}async callServiceAPI(t,e,i){if(!this.connectSettings)throw new Error("Request settings have not been set up");const s=this.preprocessBody(this.rawBody,e,i);Fe.request(this,s,t)}};oi.URL_PREFIX="https://api-inference.huggingface.co/models/";let ri=oi;class ai extends ri{constructor(t,e,i,s,n,o){super(t,e,i,s,n,o),this.isTextInputDisabled=!0,this.canSendMessage=ai.canSendFile}static canSendFile(t,e){return!(null==e||!e[0])}preprocessBody(t,e,i){return i[0]}async callServiceAPI(t,e,i){if(!this.connectSettings)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");Fe.poll(this,i[0],t,!1)}}class li extends ai{constructor(t){var e,i,s;super(t,"Attach an audio file","ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.audioClassification,null==(s=t.directConnection)?void 0:s.huggingFace,{audio:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.label)||""}}}class ci extends ai{constructor(t){var e,i,s;super(t,"Attach an image file","google/vit-base-patch16-224",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.imageClassification,null==(s=t.directConnection)?void 0:s.huggingFace,{images:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.label)||""}}}const hi="data:image/png;base64,";class ui{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,s){t.message?s(y.INVALID_KEY):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.stability.ai/v1/engines/list",method:"GET",handleVerificationResult:ui.handleVerificationResult}}}class di extends Ve{constructor(t,e,i,s,n){super(t,e,i,s,n),this.insertKeyPlaceholderText="Stability AI API Key",this.keyHelpUrl="https://platform.stability.ai/docs/getting-started/authentication",this.permittedErrorPrefixes=["Incorrect","invalid_"]}}class pi extends di{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=null==i?void 0:i.stabilityAI;super(t,ui.buildKeyVerificationDetails(),ui.buildHeaders,s,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}),this.url="https://api.stability.ai/v1/generation/esrgan-v1-x2plus/image-to-image/upscale",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI</b></div>\n <div style="width: 100%; text-align: center; margin-left: -10px; margin-top: 5px"><b>Image to Image Upscale</b></div>\n <p>Upload an image to generate a new one with higher resolution.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageUpscale;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/image-to-image/upscale`),pi.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=pi.canSendFileMessage}static cleanConfig(t){delete t.engine_id}static canSendFileMessage(t,e){return!(null==e||!e[0])}createFormDataBody(t,e){const i=new FormData;return i.append("image",e),Object.keys(t).forEach((e=>{i.append(e,String(t[e]))})),i}async callServiceAPI(t,e,i){if(!this.connectSettings)throw new Error("Request settings have not been set up");if(!i)throw new Error("Image was not found");const s=this.createFormDataBody(this.rawBody,i[0]);Oe.tempRemoveContentHeader(this.connectSettings,Fe.request.bind(this,this,s,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${hi}${t.base64}`,type:"image"})))}}}class mi extends di{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=null==i?void 0:i.stabilityAI;super(t,ui.buildKeyVerificationDetails(),ui.buildHeaders,s,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.url="https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/image-to-image/masking",this._maskSource="MASK_IMAGE_WHITE",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI</b></div>\n <div style="width: 100%; text-align: center; margin-left: -10px; margin-top: 5px"><b>Image to Image Masking</b></div>\n <p>Upload an image, its mask image to create a new one based on the changes you have described for the mask area.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageMasking;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/image-to-image/masking`),void 0!==n.weight&&null!==n.weight&&(this._imageWeight=n.weight),void 0!==n.mask_source&&null!==n.mask_source&&(this._maskSource=n.mask_source),mi.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=mi.canSendFileTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendFileTextMessage(t,e){return!(null==e||!e[0]||!t||""===t.trim())}createFormDataBody(t,e,i,s){const n=new FormData;return n.append("init_image",e),n.append("mask_source",String(this._maskSource)),n.append("mask_image",i),s&&""!==s&&n.append("text_prompts[0][text]",s),void 0!==this._imageWeight&&null!==this._imageWeight&&n.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach((e=>{n.append(e,String(t[e]))})),void 0===n.get("weight")&&n.append("weight",String(1)),n}async callServiceAPI(t,e,i){var s,n;if(!this.connectSettings)throw new Error("Request settings have not been set up");if(!i||!i[0]||!i[1])throw new Error("Image was not found");const o=null==(n=null==(s=e[e.length-1])?void 0:s.text)?void 0:n.trim(),r=this.createFormDataBody(this.rawBody,i[0],i[1],o);Oe.tempRemoveContentHeader(this.connectSettings,Fe.request.bind(this,this,r,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${hi}${t.base64}`,type:"image"})))}}}class vi extends ai{constructor(t){var e,i,s;super(t,"Attach an audio file","facebook/wav2vec2-large-960h-lv60-self",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.audioSpeechRecognition,null==(s=t.directConnection)?void 0:s.huggingFace,{audio:{}})}async extractPollResultData(t){if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:t.text||""}}}class fi extends ri{constructor(t){var e,i,s;super(t,"Once upon a time","gpt2",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.textGeneration,null==(s=t.directConnection)?void 0:s.huggingFace)}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.generated_text)||""}}}class gi extends ri{constructor(t){var e,i,s;const n=null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.questionAnswer;super(t,"Ask a question","bert-large-uncased-whole-word-masking-finetuned-squad",n,null==(s=t.directConnection)?void 0:s.huggingFace),this.permittedErrorPrefixes=["Authorization header","Error in"],this.context=n.context}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return{inputs:{question:i,context:this.context,options:{wait_for_model:!0}}}}async extractResultData(t){if(t.error)throw t.error;return{text:t.answer||""}}}class bi extends ri{constructor(t){var e,i,s;super(t,"Insert text to summarize","facebook/bart-large-cnn",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.summarization,null==(s=t.directConnection)?void 0:s.huggingFace)}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.summary_text)||""}}}class yi extends ri{constructor(t){var e,i,s;super(t,"Ask me anything!","facebook/blenderbot-400M-distill",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.conversation,null==(s=t.directConnection)?void 0:s.huggingFace),this.maxMessages??(this.maxMessages=-1)}processMessages(t){const e=t.filter((t=>t.text)),i=e[e.length-1].text,s=e.slice(0,e.length-1);if(!i)return;return{past_user_inputs:s.filter((t=>"user"===t.role)).map((t=>t.text)),generated_responses:s.filter((t=>"ai"===t.role)).map((t=>t.text)),mostRecentMessageText:i}}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=this.processMessages(e);if(s)return i.options??(i.options={}),i.options.wait_for_model=!0,{inputs:{past_user_inputs:s.past_user_inputs,generated_responses:s.generated_responses,text:s.mostRecentMessageText},...i}}async extractResultData(t){if(t.error)throw t.error;return{text:t.generated_text||""}}}class wi extends di{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=i.stabilityAI;super(t,ui.buildKeyVerificationDetails(),ui.buildHeaders,s,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/image-to-image",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI: Image to Image</b></div>\n <p>Upload an image to create a new one with the changes you have described.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=i.stabilityAI)?void 0:e.imageToImage;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/text-to-image`),void 0!==n.weight&&null!==n.weight&&(this._imageWeight=n.weight),wi.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=wi.canSendFileTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendFileTextMessage(t,e){return!(null==e||!e[0]||!t||""===t.trim())}createFormDataBody(t,e,i){const s=new FormData;return s.append("init_image",e),i&&""!==i&&s.append("text_prompts[0][text]",i),void 0!==this._imageWeight&&null!==this._imageWeight&&s.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach((e=>{s.append(e,String(t[e]))})),void 0===s.get("weight")&&s.append("weight",String(1)),s}async callServiceAPI(t,e,i){var s,n;if(!this.connectSettings)throw new Error("Request settings have not been set up");if(!i)throw new Error("Image was not found");const o=null==(n=null==(s=e[e.length-1])?void 0:s.text)?void 0:n.trim(),r=this.createFormDataBody(this.rawBody,i[0],o);Oe.tempRemoveContentHeader(this.connectSettings,Fe.request.bind(this,this,r,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${hi}${t.base64}`,type:"image"})))}}}class xi extends ri{constructor(t){var e,i,s;super(t,"Insert text to translate","Helsinki-NLP/opus-tatoeba-en-ja",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.translation,null==(s=t.directConnection)?void 0:s.huggingFace)}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.translation_text)||""}}}class ki extends di{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=i.stabilityAI;super(t,ui.buildKeyVerificationDetails(),ui.buildHeaders,s),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/text-to-image",this.textInputPlaceholderText="Describe an image",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI: Text to Image</b></div>\n <p>Insert text to generate an image.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=i.stabilityAI)?void 0:e.textToImage;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/text-to-image`),void 0!==n.weight&&null!==n.weight&&(this._imageWeight=n.weight),ki.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=ki.canSendTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendTextMessage(t){return!(!t||""===t.trim())}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s={text:e};return this._imageWeight&&(s.weight=this._imageWeight),i.text_prompts=[s],i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e[e.length-1].text);Fe.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${hi}${t.base64}`,type:"image"})))}}}class _i extends ri{constructor(t){var e,i,s;super(t,"The goal of life is [MASK].","bert-base-uncased",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.fillMask,null==(s=t.directConnection)?void 0:s.huggingFace),this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Hugging Face</b></div>\n <p>Insert a sentence with the word [MASK] and the model will try to fill it for you. E.g. I want [MASK].</p>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>',this.permittedErrorPrefixes=["Authorization header","No mask_token"]}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.sequence)||""}}}const Si=class t{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,s){const n=t;n.error?"invalid_api_key"===n.error.code?s(y.INVALID_KEY):s(y.CONNECTION_FAILED):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.openai.com/v1/models",method:"GET",handleVerificationResult:t.handleVerificationResult}}static async directFetch(t,e,i,s=!0){t.connectSettings.method=i;const n=await Oe.fetch(t,t.connectSettings.headers,s,e).then((t=>Oe.processResponseByType(t)));if(n.error)throw n.error.message;return n}};Si.FUNCTION_TOOL_RESP_ERROR="Response object must either be {response: string}[] for each individual function or {text: string} for a direct response, see https://deepchat.dev/docs/directConnection/OpenAI#FunctionHandler.",Si.FUNCTION_TOOL_RESP_ARR_ERROR="Arrays are not accepted in handler responses";let Ai=Si;const Ti=class t{static async storeFiles(t,e,i,s){const n=t.connectSettings.headers;if(!n)return;t.url=s;const o=n[Oe.CONTENT_TYPE];delete n[Oe.CONTENT_TYPE];const r=i.map((async e=>{const i=new FormData;return i.append("purpose","assistants"),i.append("file",e),new Promise((e=>{e(Ai.directFetch(t,i,"POST",!1))}))}));try{const t=(await Promise.all(r)).map((t=>({id:t.id,name:t.filename})));return n[Oe.CONTENT_TYPE]=o,t}catch(i){throw n[Oe.CONTENT_TYPE]=o,Oe.displayError(e,i),t.completionsHandlers.onFinish(),i}}static getType(t,e){const{path:i}=t[e];return!i||i.endsWith("png")?"image":"any"}static async getFiles(e,i,s,n){const o=i.map((({fileId:t})=>(e.url=`${s}${t}${n}`,new Promise((t=>{t(Ai.directFetch(e,void 0,"GET",!1))}))))),r=(await Promise.all(o)).map(((e,s)=>new Promise((n=>{const o=new FileReader;o.readAsDataURL(e),o.onload=e=>{n({src:e.target.result,name:i[s].name,type:t.getType(i,s)})}}))));return await Promise.all(r)}static getFileName(t){const e=t.split("/");return e[e.length-1]}static async getFilesAndNewText(e,i,s,n,o){var r,a;let l;const{getFilesPrefix:c,getFilesPostfix:h}=s;return i.length>0&&(l=await t.getFiles(e,i,c,h),null!=(r=null==o?void 0:o.text)&&r.value&&l.forEach(((t,e)=>{var s;if(!t.src)return;const n=i[e].path;null!=(s=null==o?void 0:o.text)&&s.value&&n&&(o.text.value=o.text.value.replace(n,t.src))}))),null!=(a=null==o?void 0:o.text)&&a.value?{text:o.text.value,role:n}:{files:l,role:n}}static getFileDetails(e,i){var s;const n=[];return null!=(s=null==i?void 0:i.text)&&s.value&&e.content.forEach((e=>{var i,s;null==(s=null==(i=e.text)?void 0:i.annotations)||s.forEach((e=>{var i;e.text&&e.text.startsWith("sandbox:")&&null!=(i=e.file_path)&&i.file_id&&n.push({path:e.text,fileId:e.file_path.file_id,name:t.getFileName(e.text)})}))})),null!=i&&i.image_file&&n.push({fileId:i.image_file.file_id}),n}static async getFilesAndText(e,i,s,n){const o=t.getFileDetails(i,n);return await t.getFilesAndNewText(e,o,s,i.role,n)}static parseResult(t,e){let i=[];if(e)i=t.data;else for(let e=0;e<t.data.length;e+=1){const s=t.data[e];if("assistant"!==s.role)break;i.push(s)}return i.reverse()}static parseMessages(e,i,s){const n=[];return i.forEach((async i=>{i.content.filter((t=>!!t.text||!!t.image_file)).sort((t=>t.text?-1:t.image_file?1:0)).forEach((async o=>{n.push(t.getFilesAndText(e,i,s,o))}))})),Promise.all(n)}static async processStreamMessages(e,i,s){return t.parseMessages(e,[{content:i,role:"assistant"}],s)}static async processAPIMessages(e,i,s,n){const o=t.parseResult(i,s);return t.parseMessages(e,o,n)}};Ti.FILES_WITH_TEXT_ERROR="content with type `text` must have `text` values",Ti.FUNCTION_TOOL_RESP_ERROR="Response must contain an array of strings for each individual function/tool_call, see https://deepchat.dev/docs/directConnection/OpenAI/#assistant-functions.";let Mi=Ti;const Oi=class t extends Ve{constructor(t,e,i,s,n,o){if(super(t,s,n,o),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.url="",this.permittedErrorPrefixes=["Incorrect","Please send text",De.FAILED_ERROR_MESSAGE],this.shouldFetchHistory=!1,this.searchedForThreadId=!1,this.config={},this.newAssistantDetails={model:"gpt-4"},this.waitingForStreamResponse=!1,this.isSSEStream=!1,this.urlSegments=i,"object"==typeof e){this.config=e;const{new_assistant:t,thread_id:i,load_thread_history:s}=this.config;Object.assign(this.newAssistantDetails,t),i&&(this.sessionId=i),s&&(this.shouldFetchHistory=!0)}this.maxMessages=1,this.isSSEStream=!(!this.stream||"object"==typeof this.stream&&this.stream.simulation)}async fetchHistoryFunc(){setTimeout((()=>this.deepChat.disableSubmitButton()),2);try{const t=await this.getThreadMessages(this.sessionId,!0);return this.deepChat.disableSubmitButton(!1),t}catch{return[{error:"Failed to fetch history"}]}}static processImageMessage(t,e){const i=null==e?void 0:e.filter((t=>M.isImageFileExtension(t.name))).map((t=>({type:"image_file",image_file:{file_id:t.id}})));if(i&&i.length>0)return t.text&&t.text.length>0&&i.push({type:"text",text:t.text}),{content:i,role:"user"}}static processAttachmentsMessage(t,e,i){return{attachments:e.map((t=>({tools:[{type:i}],file_id:t.id}))),content:[{type:"text",text:t.text}],role:"user"}}processMessage(e,i){const s=this.totalMessagesMaxCharLength||-1,n=$e.getCharacterLimitMessages(e,s)[0];if(i&&i.length>0){let e=this.filesToolType;if("function"==typeof this.filesToolType){const t=this.filesToolType(i.map((({name:t})=>t)));"code_interpreter"===t||"file_search"===t||"images"===t?e=t:(console.error(`Tool type "${t}" is not valid`),console.error('Expected "code_interpreter" or "file_search" or "images". Going to default to "images"'))}if("file_search"===e)return t.processAttachmentsMessage(n,i,"file_search");if("code_interpreter"===e)return t.processAttachmentsMessage(n,i,"code_interpreter");if(i.find((({name:t})=>!M.isImageFileExtension(t))))console.error("The uploaded files contained a non-image file"),console.error('Make sure only images can be uploaded or define a "code_interpreter" or "file_search" value in the "files_tool_type" property'),console.warn('Make sure your existing assistant supports these "tools" or specify them in the "new_assistant" property');else{const e=t.processImageMessage(n,i);if(e)return e}}return{content:n.text||"",role:"user"}}createNewThreadMessages(t,e,i){const s=JSON.parse(JSON.stringify(t)),n=this.processMessage(e,i);return s.thread={messages:[n]},s}callService(t,e,i){if(this.messages=t,this.sessionId){this.url=`${this.urlSegments.threadsPrefix}/${this.sessionId}/messages${this.urlSegments.createMessagePostfix}`;const s=this.processMessage(e,i);Fe.request(this,s,t)}else{this.url=`${this.urlSegments.threadsPrefix}/runs${this.urlSegments.threadsPosfix}`;const s=this.createNewThreadMessages(this.rawBody,e,i);this.isSSEStream?this.createStreamRun(s):Fe.request(this,s,t)}}async callServiceAPI(t,e,i){var s;if(this.waitingForStreamResponse=!1,!this.connectSettings)throw new Error("Request settings have not been set up");(s=this.rawBody).assistant_id??(s.assistant_id=this.config.assistant_id||await this.createNewAssistant()),this.searchedForThreadId||this.searchPreviousMessagesForThreadId(t.messageToElements);const n=i?await Mi.storeFiles(this,t,i,this.urlSegments.storeFiles):void 0;this.connectSettings.method="POST",this.callService(t,e,n)}async createNewAssistant(){try{this.url=this.urlSegments.newAssistantUrl;const t=await Ai.directFetch(this,JSON.parse(JSON.stringify(this.newAssistantDetails)),"POST");return this.config.assistant_id=t.id,this.config.assistant_id}catch(t){console.error(t),console.error("Failed to create a new assistant")}}searchPreviousMessagesForThreadId(t){const e=t.find((([t])=>t._sessionId));e&&(this.sessionId=e[0]._sessionId),this.searchedForThreadId=!0}async extractResultData(t){var e;if(this.waitingForStreamResponse||this.isSSEStream&&this.sessionId)return await this.handleStream(t);if(t.error)throw t.error.message.startsWith(Mi.FILES_WITH_TEXT_ERROR)?Error("Please send text with your file(s)"):t.error.message;await this.assignThreadAndRun(t);const i=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs/${this.run_id}${this.urlSegments.threadsPosfix}`,s={method:"GET",headers:null==(e=this.connectSettings)?void 0:e.headers};return Fe.executePollRequest(this,i,s,this.messages),{makingAnotherRequest:!0}}async assignThreadAndRun(t){if(this.sessionId){this.url=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs${this.urlSegments.threadsPosfix}`;const t=await Ai.directFetch(this,JSON.parse(JSON.stringify(this.rawBody)),"POST");this.run_id=t.id}else this.sessionId=t.thread_id,this.run_id=t.id,this.messages&&this.messages.messageToElements.length>0&&(this.messages.messageToElements[this.messages.messageToElements.length-1][0]._sessionId=this.sessionId)}async getThreadMessages(t,e=!1){var i,s;this.url=`${this.urlSegments.threadsPrefix}/${t}/messages?${this.urlSegments.listMessagesPostfix}`;let n=await Ai.directFetch(this,{},"GET");return!e&&this.deepChat.responseInterceptor&&(n=await(null==(s=(i=this.deepChat).responseInterceptor)?void 0:s.call(i,n))),Mi.processAPIMessages(this,n,e,this.urlSegments)}async extractPollResultData(e){var i;const{status:s,required_action:n}=e;if("queued"===s||"in_progress"===s)return{timeoutMS:t.POLLING_TIMEOUT_MS};if("completed"===s&&this.messages){const t=await this.getThreadMessages(e.thread_id),{text:i,files:s}=t.shift();return setTimeout((()=>{t.forEach((t=>this.deepChat.addMessage(t)))})),{text:i,_sessionId:this.sessionId,files:s}}const o=null==(i=null==n?void 0:n.submit_tool_outputs)?void 0:i.tool_calls;if("requires_action"===s&&o)return await this.handleTools(o);throw Error(`Thread run status: ${s}`)}async handleTools(e){if(!this.functionHandler)throw Error("Please define the `function_handler` property inside the [openAI](https://deepchat.dev/docs/directConnection/openAI#Assistant) object.");const i=e.map((t=>({name:t.function.name,arguments:t.function.arguments}))),s=await this.functionHandler(i);if(!Array.isArray(s)||e.length!==s.length)throw Error(Mi.FUNCTION_TOOL_RESP_ERROR);const n=await Promise.all(s);if(n.find((t=>"string"!=typeof t)))throw Error(Mi.FUNCTION_TOOL_RESP_ERROR);const o=n.map(((t,i)=>({tool_call_id:e[i].id,output:t}))),r=`${this.urlSegments.threadsPrefix}/${this.sessionId}`,a=`/runs/${this.run_id}/submit_tool_outputs${this.urlSegments.threadsPosfix}`;return this.url=`${r}${a}`,this.isSSEStream?await this.createStreamRun({tool_outputs:o}):await Ai.directFetch(this,{tool_outputs:o},"POST"),{timeoutMS:t.POLLING_TIMEOUT_MS}}async handleStream(t){var e,i;const s=null==(i=null==(e=t.required_action)?void 0:e.submit_tool_outputs)?void 0:i.tool_calls;if("requires_action"===t.status&&s)return this.run_id=t.id,await this.handleTools(s);if(this.waitingForStreamResponse)return this.parseStreamResult(t);if(this.isSSEStream&&this.sessionId){this.url=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs${this.urlSegments.threadsPosfix}`;const t=JSON.parse(JSON.stringify(this.rawBody));this.createStreamRun(t)}return{makingAnotherRequest:!0}}async parseStreamResult(t){var e,i,s,n,o;if(t.content&&t.content.length>0&&this.messages){const s=t.content.find((t=>t.text));if(null!=(e=null==s?void 0:s.text)&&e.annotations&&s.text.annotations.length>0){const e=t.content.find((t=>!!t.text))||t.content[0],s=Mi.getFilesAndText.bind(this,this,{role:"assistant",content:t.content},this.urlSegments,e);return null==(i=this.messageStream)||i.endStreamAfterFileDownloaded(this.messages,s),{text:""}}}if(null!=(s=t.delta)&&s.content){if(t.delta.content.length>1){const e=t.delta.content.find((t=>t.text));if(null!=(n=null==e?void 0:e.text)&&n.annotations&&0===e.text.annotations.length){const e=await Mi.processStreamMessages(this,t.delta.content,this.urlSegments);return{text:e[0].text,files:e[1].files}}}return{text:null==(o=t.delta.content[0].text)?void 0:o.value}}return!this.sessionId&&t.thread_id&&(this.sessionId=t.thread_id),{makingAnotherRequest:!0}}async createStreamRun(t){t.stream=!0,this.waitingForStreamResponse=!0,this.messageStream=await Ne.request(this,t,this.messages,!0,!0)}};Oi.POLLING_TIMEOUT_MS=500;let ji=Oi;class Ci extends ji{constructor(t){var e,i,s,n,o;const r=JSON.parse(JSON.stringify(t.directConnection)),a=r.openAI,l=null==(e=r.openAI)?void 0:e.assistant;if(super(t,l,Ci.buildUrlSegments(l),Ai.buildKeyVerificationDetails(),Ai.buildHeaders,a),(i=this.connectSettings).headers??(i.headers={}),(s=this.connectSettings.headers)["OpenAI-Beta"]??(s["OpenAI-Beta"]="assistants=v2"),this.shouldFetchHistory&&this.sessionId&&(this.fetchHistory=this.fetchHistoryFunc.bind(this)),"object"==typeof l){const{function_handler:e,files_tool_type:i}=null==(o=null==(n=t.directConnection)?void 0:n.openAI)?void 0:o.assistant;e&&(this.functionHandler=e),i&&(this.filesToolType=i)}}static buildUrlSegments(t){const e="object"==typeof t&&t.custom_base_url||"https://api.openai.com/v1";return{threadsPrefix:`${e}/threads`,threadsPosfix:"",newAssistantUrl:`${e}/assistants`,createMessagePostfix:"",listMessagesPostfix:"order=desc",storeFiles:`${e}/files`,getFilesPrefix:`${e}/files/`,getFilesPostfix:"/content"}}}class Ei{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json",accept:"application/json"}}static handleVerificationResult(t,e,i,s){var n;null!=(n=t.message)&&n.includes("invalid request: prompt must be at least 1 token long")?i(e):s(y.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api.cohere.ai/v1/generate",method:"POST",handleVerificationResult:Ei.handleVerificationResult,body:JSON.stringify({prompt:""})}}}class Ii extends Ve{constructor(t,e,i,s,n){super(t,Ei.buildKeyVerificationDetails(),Ei.buildHeaders,n),this.insertKeyPlaceholderText="Cohere API Key",this.keyHelpUrl="https://dashboard.cohere.ai/api-keys",this.permittedErrorPrefixes=["invalid"],this.url=e,this.textInputPlaceholderText=i,s&&"object"==typeof s&&Object.assign(this.rawBody,s)}}class Pi extends Ii{constructor(t){var e,i,s;super(t,"https://api.cohere.ai/v1/generate","Once upon a time",null==(i=null==(e=t.directConnection)?void 0:e.cohere)?void 0:i.textGeneration,null==(s=t.directConnection)?void 0:s.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e[e.length-1].text;if(s)return{prompt:s,...i}}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Fe.request(this,i,t)}async extractResultData(t){var e;if(t.message)throw t.message;return{text:(null==(e=t.generations)?void 0:e[0].text)||""}}}const Ni=class{static buildHeaders(t){return{"api-key":t,"Content-Type":"application/json"}}static buildKeyVerificationDetails(t){return{url:`${t.endpoint}/openai/models?api-version=${t.version}`,method:"GET",handleVerificationResult:Ai.handleVerificationResult}}static validateURLDetails(t){const{endpoint:e,version:i,deploymentId:s}=t;return e&&i&&s}};Ni.URL_DETAILS_ERROR_MESSAGE="Please define the Azure URL Details. [More Information](https://deepchat.dev/docs/directConnection/Azure)";let Ri=Ni;const qi=class t extends ji{constructor(e){var i,s,n,o,r,a,l,c;const h=JSON.parse(JSON.stringify(e.directConnection)),u=h.azure,d=null==(i=h.azure)?void 0:i.openAI,p=(null==d?void 0:d.urlDetails)||{},m=`${null==(s=null==d?void 0:d.urlDetails)?void 0:s.endpoint}/openai/`,v=`?api-version=${null==(n=null==d?void 0:d.urlDetails)?void 0:n.version}`,f={threadsPrefix:`${m}${t.THREAD_RESOURCE}`,threadsPosfix:v,newAssistantUrl:`${m}${t.NEW_ASSISTANT_RESOURCE}${v}`,createMessagePostfix:v,listMessagesPostfix:`order=desc&api-version=${null==(o=null==d?void 0:d.urlDetails)?void 0:o.version}`,storeFiles:`${m}files${v}`,getFilesPrefix:`${m}files/`,getFilesPostfix:`/content${v}`};if(super(e,null==d?void 0:d.assistant,f,Ri.buildKeyVerificationDetails(p),Ri.buildHeaders,u),this.permittedErrorPrefixes=[Ri.URL_DETAILS_ERROR_MESSAGE],this.insertKeyPlaceholderText="Azure OpenAI API Key",this.keyHelpUrl="https://learn.microsoft.com/en-us/answers/questions/1193991/how-to-get-the-value-of-openai-api-key",this.isTextInputDisabled=!1,"object"==typeof(null==d?void 0:d.assistant)){const{function_handler:t,files_tool_type:i}=null==(l=null==(a=null==(r=e.directConnection)?void 0:r.azure)?void 0:a.openAI)?void 0:l.assistant;t&&(this.functionHandler=t),i&&(this.filesToolType=i)}Ri.validateURLDetails(p)?(c=this.connectSettings).headers??(c.headers={}):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout((()=>{e.addMessage({error:Ri.URL_DETAILS_ERROR_MESSAGE})})))}};qi.THREAD_RESOURCE="threads",qi.NEW_ASSISTANT_RESOURCE="assistants";let Bi=qi;class Li extends Ii{constructor(t){var e,i,s;super(t,"https://api.cohere.ai/v1/summarize","Insert text to summarize",null==(i=null==(e=t.directConnection)?void 0:e.cohere)?void 0:i.summarization,null==(s=t.directConnection)?void 0:s.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e[e.length-1].text;if(s)return{text:s,...i}}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Fe.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.summary||""}}}class Fi{static addAttributes(t){t.role="button",t.setAttribute("tabindex","0")}static addAriaBusy(t){t.setAttribute("aria-busy","true")}static removeAriaBusy(t){t.removeAttribute("aria-busy")}static addAriaDisabled(t){t.setAttribute("aria-disabled","true")}static removeAriaDisabled(t){t.removeAttribute("aria-disabled")}static removeAriaAttributes(t){Fi.removeAriaBusy(t),Fi.removeAriaDisabled(t)}}const zi='<?xml version="1.0" encoding="iso-8859-1"?>\n<svg height="1.4em" width="1.4em" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"\n\t viewBox="0 0 490.9 490.9" xml:space="preserve">\n\t<g>\n\t\t<g>\n\t\t\t<path d="M245.5,322.9c53,0,96.2-43.2,96.2-96.2V96.2c0-53-43.2-96.2-96.2-96.2s-96.2,43.2-96.2,96.2v130.5\n\t\t\t\tC149.3,279.8,192.5,322.9,245.5,322.9z M173.8,96.2c0-39.5,32.2-71.7,71.7-71.7s71.7,32.2,71.7,71.7v130.5\n\t\t\t\tc0,39.5-32.2,71.7-71.7,71.7s-71.7-32.2-71.7-71.7V96.2z"/>\n\t\t\t<path d="M94.4,214.5c-6.8,0-12.3,5.5-12.3,12.3c0,85.9,66.7,156.6,151.1,162.8v76.7h-63.9c-6.8,0-12.3,5.5-12.3,12.3\n\t\t\t\ts5.5,12.3,12.3,12.3h152.3c6.8,0,12.3-5.5,12.3-12.3s-5.5-12.3-12.3-12.3h-63.9v-76.7c84.4-6.3,151.1-76.9,151.1-162.8\n\t\t\t\tc0-6.8-5.5-12.3-12.3-12.3s-12.3,5.5-12.3,12.3c0,76.6-62.3,138.9-138.9,138.9s-138.9-62.3-138.9-138.9\n\t\t\t\tC106.6,220,101.2,214.5,94.4,214.5z"/>\n\t\t</g>\n\t</g>\n</svg>\n';class Di{static createTextElement(t){const e=document.createElement("div");return e.classList.add("text-button"),e.innerText=t,e}static createElement(t,e){return e?Di.createTextElement(t):Ze.createSVGElement(t)}static createCustomElement(t,e){var i,s,n,o;const r=null==e?void 0:e[t];return null!=(i=null==r?void 0:r.svg)&&i.content?Di.createElement(null==(s=null==r?void 0:r.svg)?void 0:s.content,!1):null!=(n=null==r?void 0:r.text)&&n.content?Di.createElement(null==(o=null==r?void 0:r.text)?void 0:o.content,!0):void 0}static processElement(t,e){null!=e&&e.classList.contains("text-button")||t.classList.add("input-button-svg")}static createSpecificStateElement(t,e,i){let s;return i&&(s=Di.createCustomElement(e,i)),Di.processElement(t,s),s}static createInnerElement(t,e,i,s,n=!1){var o,r;return(!n||null!=(r=null==(o=null==s?void 0:s[i])?void 0:o.svg)&&r.content)&&Di.createSpecificStateElement(t,i,s)||e}}class $i{static unsetAllCSS(t,e){var s,n;e.container&&i.unsetAllCSSMouseStates(t,e.container),null!=(s=e.svg)&&s.styles&&i.unsetAllCSSMouseStates(t.children[0],e.svg.styles),null!=(n=e.text)&&n.styles&&i.unsetAllCSSMouseStates(t.children[0],e.text.styles)}static unsetActionCSS(t,e){var s,n;e.container&&i.unsetActivityCSSMouseStates(t,e.container),null!=(s=e.svg)&&s.styles&&i.unsetActivityCSSMouseStates(t.children[0],e.svg.styles),null!=(n=e.text)&&n.styles&&i.unsetActivityCSSMouseStates(t.children[0],e.text.styles)}static setElementsCSS(t,e,i){var s,n,o,r,a;Object.assign(t.style,null==(s=e.container)?void 0:s[i]),Object.assign(t.children[0].style,null==(o=null==(n=e.svg)?void 0:n.styles)?void 0:o[i]),Object.assign(t.children[0].style,null==(a=null==(r=e.text)?void 0:r.styles)?void 0:a[i])}static setElementCssUpToState(t,e,i){$i.setElementsCSS(t,e,"default"),"default"!==i&&($i.setElementsCSS(t,e,"hover"),"hover"!==i&&$i.setElementsCSS(t,e,"click"))}}class Ji{constructor(t,e,i,s){this._mouseState={state:"default"},Fi.addAttributes(t),this.elementRef=t,this._customStyles=i,this.position=e,this.dropupText=s}buttonMouseLeave(t){this._mouseState.state="default",t&&($i.unsetAllCSS(this.elementRef,t),$i.setElementsCSS(this.elementRef,t,"default"))}buttonMouseEnter(t){this._mouseState.state="hover",t&&$i.setElementsCSS(this.elementRef,t,"hover")}buttonMouseUp(t){t&&$i.unsetActionCSS(this.elementRef,t),this.buttonMouseEnter(t)}buttonMouseDown(t){this._mouseState.state="click",t&&$i.setElementsCSS(this.elementRef,t,"click")}setEvents(t){this.elementRef.onmousedown=this.buttonMouseDown.bind(this,t),this.elementRef.onmouseup=this.buttonMouseUp.bind(this,t),this.elementRef.onmouseenter=this.buttonMouseEnter.bind(this,t),this.elementRef.onmouseleave=this.buttonMouseLeave.bind(this,t)}unsetCustomStateStyles(t){if(this._customStyles)for(let e=0;e<t.length;e+=1){const i=t[e],s=i&&this._customStyles[i];s&&$i.unsetActionCSS(this.elementRef,s)}}reapplyStateStyle(t,e){if(!this._customStyles)return;e&&this.unsetCustomStateStyles(e);const i=this._customStyles[t];i&&$i.setElementCssUpToState(this.elementRef,i,this._mouseState.state),this.setEvents(i)}}const Ui=class t extends Ji{constructor(t){super(document.createElement("div"),void 0,t),this.isActive=!1,this._innerElements=this.createInnerElements(this._customStyles),this.changeToDefault()}createInnerElements(e){var i,s;const n=Ze.createSVGElement((null==(s=null==(i=null==e?void 0:e.default)?void 0:i.svg)?void 0:s.content)||t.EMPTY_SVG);return{default:this.createInnerElement(n,"default",e),active:this.createInnerElement(n,"active",e),unavailable:this.createInnerElement(n,"unavailable",e)}}createInnerElement(t,e,i){return Di.createSpecificStateElement(this.elementRef,e,i)||t}changeToActive(){this.elementRef.replaceChildren(this._innerElements.active),this.reapplyStateStyle("active",["unavailable","default"]),this.isActive=!0}changeToDefault(){var t,e,i,s;this.elementRef.replaceChildren(this._innerElements.default),null!=(t=this._customStyles)&&t.active&&$i.unsetAllCSS(this.elementRef,null==(e=this._customStyles)?void 0:e.active),null!=(i=this._customStyles)&&i.unavailable&&$i.unsetAllCSS(this.elementRef,null==(s=this._customStyles)?void 0:s.unavailable),this.reapplyStateStyle("default",["active","unavailable"]),this.isActive=!1}changeToUnavailable(){var t,e,i,s;this.elementRef.replaceChildren(this._innerElements.unavailable),null!=(t=this._customStyles)&&t.active&&$i.unsetAllCSS(this.elementRef,null==(e=this._customStyles)?void 0:e.active),null!=(i=this._customStyles)&&i.default&&$i.unsetAllCSS(this.elementRef,null==(s=this._customStyles)?void 0:s.default),this.reapplyStateStyle("unavailable",["default","active"]),this.isActive=!1}};Ui.EMPTY_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"></svg>';let Vi=Ui;class Hi{static setPropertyValueIfDoesNotExist(t,e,i){const s=e[0];1===e.length?t[s]??(t[s]=i):(t[s]??(t[s]={}),e.shift(),Hi.setPropertyValueIfDoesNotExist(t[s],e,i))}static setPropertyValue(t,e,i){const s=e[0];1===e.length?t[s]=i:(t[s]??(t[s]={}),e.shift(),Hi.setPropertyValue(t[s],e,i))}static getObjectValue(t,e){const i=t[e[0]];return void 0===i||1===e.length?i:Hi.getObjectValue(i,e.slice(1))}static overwritePropertyObjectFromAnother(t,e,i){const s=Hi.getObjectValue(e,i);if(s){const e={...s,...Hi.getObjectValue(t,i)||{}};Hi.setPropertyValue(t,i,e)}}static isJson(t){try{return JSON.stringify(t),!0}catch{return!1}}static assignPropertyFromOneToAnother(t,e,i){e[t]??(e[t]={}),Object.assign(e[t],null==i?void 0:i[t])}}const Ki='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <title>play</title>\n <path d="M5.92 24.096q0 1.088 0.928 1.728 0.512 0.288 1.088 0.288 0.448 0 0.896-0.224l16.16-8.064q0.48-0.256 0.8-0.736t0.288-1.088-0.288-1.056-0.8-0.736l-16.16-8.064q-0.448-0.224-0.896-0.224-0.544 0-1.088 0.288-0.928 0.608-0.928 1.728v16.16z"></path>\n</svg>',Gi='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n<title>stop</title>\n<path d="M5.92 24.096q0 0.832 0.576 1.408t1.44 0.608h16.128q0.832 0 1.44-0.608t0.576-1.408v-16.16q0-0.832-0.576-1.44t-1.44-0.576h-16.128q-0.832 0-1.44 0.576t-0.576 1.44v16.16z"></path>\n</svg>',Zi=class t extends Ve{constructor(e){var i,s,n,o;const r=JSON.parse(JSON.stringify(e.directConnection)),a=t.getKey(e);super(e,Ai.buildKeyVerificationDetails(),Ai.buildHeaders,{key:a}),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this._muteButton=null,this._toggleButton=null,this._errorElement=null,this._loadingElement=null,this._pc=null,this._mediaStream=null,this._isMuted=!1;const l=null==(i=r.openAI)?void 0:i.realtime;if("object"==typeof l){this._avatarConfig=l.avatar,this._ephemeralKey=l.ephemeralKey,this._errorConfig=l.error,this._loadingConfig=l.loading,Object.assign(this.rawBody,l.config);const{function_handler:t}=(null==(n=null==(s=e.directConnection)?void 0:s.openAI)?void 0:n.realtime).config||{};t&&(this._functionHandler=t)}(o=this.rawBody).model??(o.model="gpt-4o-realtime-preview-2024-12-17"),this._avatarConfig=t.buildAvatarConfig(l),this._buttonsConfig=t.buildButtonsConfig(l),this._avatarEl=t.createAvatar(this._avatarConfig),this._containerEl=this.createContainer(),this._deepChat=e}static getKey(t){const e=t.directConnection.openAI;if(null!=e&&e.key)return e.key;const i=null==e?void 0:e.realtime;return"object"==typeof i&&(i.ephemeralKey||i.fetchEphemeralKey)?"placeholder":void 0}setUpView(t,e){t.style.display="none",e.appendChild(this._containerEl),this.setup()}async setup(){var t;const e=null==(t=this._deepChat.directConnection)?void 0:t.openAI;if(!e)return;const i=null==e?void 0:e.realtime;if("object"!=typeof i||!i.autoStart&&!i.autoFetchEphemeralKey)return;const s=this.key||e.key;(i.fetchEphemeralKey||s)&&i.autoStart&&(this.changeToUnavailable(),this.displayLoading()),this.fetchEphemeralKey(i.autoStart)}async fetchEphemeralKey(t){var e;const i=null==(e=this._deepChat.directConnection)?void 0:e.openAI,s="object"==typeof(null==i?void 0:i.realtime)?null==i?void 0:i.realtime.fetchEphemeralKey:void 0,n=null==i?void 0:i.realtime,o=this.key||i.key;if("object"==typeof n){if(!this._ephemeralKey)try{if(s){const t=s();t.then&&(this._retrievingEphemeralKey=t),this._ephemeralKey=await t}else o&&(this._retrievingEphemeralKey=this.getEphemeralKey(o),this._ephemeralKey=await this._retrievingEphemeralKey)}catch(t){this.displayFailedToRetrieveEphemeralKey(t)}this._ephemeralKey&&(t?this.init(this._ephemeralKey):this.changeToAvailable())}else if(o)try{this._retrievingEphemeralKey=this.getEphemeralKey(o),this._ephemeralKey=await this._retrievingEphemeralKey,t&&this.init(this._ephemeralKey)}catch(t){this.displayFailedToRetrieveEphemeralKey(t)}}async getEphemeralKey(t){return(await(await fetch("https://api.openai.com/v1/realtime/sessions",{method:"POST",body:JSON.stringify(this.rawBody),headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}})).json()).client_secret.value}static buildAvatarConfig(t){const e="object"==typeof t&&t.avatar?JSON.parse(JSON.stringify(t.avatar)):{};return e.maxScale=e.maxScale&&e.maxScale>=1?e.maxScale:2.5,e}static buildButtonsConfig(t){var e,i,s,n,o,r,a,l,c,h,u,d;const p="object"==typeof t&&t.buttons?JSON.parse(JSON.stringify(t.buttons)):{};return null!=(s=null==(i=null==(e=p.microphone)?void 0:e.default)?void 0:i.text)&&s.content||(p.microphone??(p.microphone={}),(n=p.microphone).default??(n.default={}),(o=p.microphone.default).svg??(o.svg={}),p.microphone.default.svg.content=zi),null!=(l=null==(a=null==(r=p.toggle)?void 0:r.default)?void 0:a.text)&&l.content||(p.toggle??(p.toggle={}),(c=p.toggle).default??(c.default={}),(h=p.toggle.default).svg??(h.svg={}),p.toggle.default.svg.content=Ki,(u=p.toggle).active??(u.active={}),(d=p.toggle.active).svg??(d.svg={}),p.toggle.active.svg.content=Gi),p}createContainer(){const t=document.createElement("div");return t.id="deep-chat-openai-realtime-container",t.appendChild(this.createAvatarContainer()),t.appendChild(this.createButtonsContainer()),t.appendChild(this.createError()),t}createAvatarContainer(){var t,e;const i=document.createElement("div");return i.id="deep-chat-openai-realtime-avatar-container",Object.assign(i.style,null==(e=null==(t=this._avatarConfig)?void 0:t.styles)?void 0:e.container),i.appendChild(this._avatarEl),i}static createAvatar(t){var e;const i=document.createElement("img");return i.id="deep-chat-openai-realtime-avatar",Object.assign(i.style,null==(e=null==t?void 0:t.styles)?void 0:e.avatar),i.src=(null==t?void 0:t.src)||be,i}createButtonsContainer(){var e;const i=document.createElement("div");i.id="deep-chat-openai-realtime-buttons-container",Object.assign(i.style,null==(e=this._buttonsConfig)?void 0:e.container),this._muteButton=this.createMuteButton();const s=t.createButtonContainer(this._muteButton.elementRef);this._toggleButton=this.createToggleButton();const n=t.createButtonContainer(this._toggleButton.elementRef);return i.appendChild(s),i.appendChild(n),i.appendChild(this.createLoading()),i}static createButtonContainer(t){const e=document.createElement("div");return e.classList.add("deep-chat-openai-realtime-button-container"),e.appendChild(t),e}createMuteButton(){var e;const i=new Vi(null==(e=this._buttonsConfig)?void 0:e.microphone);return i.elementRef.classList.replace("input-button-svg","deep-chat-openai-realtime-button"),i.elementRef.classList.add(t.BUTTON_DEFAULT,"deep-chat-openai-realtime-mute"),i.elementRef.onclick=()=>{i.isActive?(this.toggleMute(!0),i.elementRef.classList.replace(t.MUTE_ACTIVE,t.BUTTON_DEFAULT),i.changeToDefault(),this._isMuted=!1):(this.toggleMute(!1),i.elementRef.classList.replace(t.BUTTON_DEFAULT,t.MUTE_ACTIVE),Fi.removeAriaAttributes(i.elementRef),i.changeToActive(),this._isMuted=!0)},i}toggleMute(t){var e;null==(e=this._mediaStream)||e.getAudioTracks().forEach((e=>e.enabled=t))}createToggleButton(){var e;const i=new Vi(null==(e=this._buttonsConfig)?void 0:e.toggle);return i.elementRef.classList.replace("input-button-svg","deep-chat-openai-realtime-button"),i.elementRef.classList.add(t.BUTTON_DEFAULT,"deep-chat-openai-realtime-toggle"),i.elementRef.onclick=async()=>{var t;if(i.isActive)i.changeToDefault(),this.stop();else try{if(this._ephemeralKey)this.displayLoading(),await this.init(this._ephemeralKey);else if(this._retrievingEphemeralKey){this.displayLoading();const e=await this._retrievingEphemeralKey;null!=(t=this._toggleButton)&&t.isActive&&await this.init(e)}else this.displayLoading(),await this.fetchEphemeralKey(!0)}catch(t){console.error("Failed to start conversation:",t),this.displayError("Error"),this.hideLoading()}},i}async init(t){const e=new RTCPeerConnection;this._pc=e;const i=document.createElement("audio");i.autoplay=!0;const s=new AudioContext,n=s.createAnalyser();n.fftSize=256;const o=new Uint8Array(n.frequencyBinCount);this._pc.ontrack=async t=>{if(t.streams[0]){i.srcObject=t.streams[0];const e=s.createMediaStreamSource(t.streams[0]);"suspended"===s.state&&await s.resume(),e.connect(n),this.monitorFrequencies(n,o)}else console.error("No streams found in the ontrack event."),this.displayError("Error")},await navigator.mediaDevices.getUserMedia({audio:!0}).then((t=>{var i;e===this._pc&&(this._mediaStream=t,null==(i=this._pc)||i.addTrack(this._mediaStream.getTracks()[0]),this._isMuted&&this.toggleMute(!1))})).catch((t=>{console.error("Error accessing microphone:",t),this.displayError("Error")}));const r=this._pc.createDataChannel("oai-events");r.addEventListener("message",(async t=>{var e;const i=JSON.parse(t.data);if("session.created"===i.type)this.removeUnavailable(),this._toggleButton&&(Fi.removeAriaAttributes(this._toggleButton.elementRef),this._toggleButton.changeToActive()),this.hideLoading();else if("response.done"===i.type){const i=null==(e=JSON.parse(t.data).response.output)?void 0:e[0];if("function_call"===(null==i?void 0:i.type)){const{name:t,call_id:e}=i;try{await this.handleTool(t,i.arguments,e,r)}catch(t){this.stopOnError(t)}}}else"error"===i.type?this.stopOnError(i.error.message):"invalid_request_error"===i.type?this.stopOnError(i.message):i.type}));try{const i=await this._pc.createOffer();if(e!==this._pc||(await this._pc.setLocalDescription(i),e!==this._pc))return;const s=await fetch("https://api.openai.com/v1/realtime",{method:"POST",body:i.sdp,headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/sdp"}});if(e!==this._pc)return;const n={type:"answer",sdp:await s.text()};if(e!==this._pc||(await this._pc.setRemoteDescription(n),e!==this._pc))return}catch(t){console.error(t),this.displayError("Error")}}monitorFrequencies(t,e){const i=()=>{var s;t.getByteFrequencyData(e);const n=1+e.reduce(((t,e)=>t+e),0)/(255*e.length)*100/100*((null==(s=this._avatarConfig)?void 0:s.maxScale)-1);this._avatarEl.style.transform=`scale(${n})`,requestAnimationFrame(i)};i()}stopOnError(t){this.stop(),console.error(t),this.displayError("Error")}stop(){var t;null==(t=this._mediaStream)||t.getTracks().forEach((t=>t.stop())),this._mediaStream=null,this._pc&&(this._pc.close(),this._pc=null)}changeToUnavailable(){this._muteButton&&t.changeButtonToUnavailable(this._muteButton),this._toggleButton&&t.changeButtonToUnavailable(this._toggleButton)}static changeButtonToUnavailable(e){e.elementRef.classList.add(t.UNAVAILABLE),Fi.removeAriaBusy(e.elementRef),Fi.addAriaDisabled(e.elementRef),e.changeToUnavailable()}changeToAvailable(){this._muteButton&&t.changeButtonToAvailable(this._muteButton),this._toggleButton&&t.changeButtonToAvailable(this._toggleButton)}static changeButtonToAvailable(e){t.removeButtonUnavailable(e),e.changeToDefault()}removeUnavailable(){this._muteButton&&t.removeButtonUnavailable(this._muteButton),this._toggleButton&&t.removeButtonUnavailable(this._toggleButton)}static removeButtonUnavailable(e){Fi.removeAriaDisabled(e.elementRef),e.elementRef.classList.remove(t.UNAVAILABLE)}createError(){var t;const e=document.createElement("div");return e.id="deep-chat-openai-realtime-error",Object.assign(e.style,null==(t=this._errorConfig)?void 0:t.style),this._errorElement=e,e}displayFailedToRetrieveEphemeralKey(t){console.error("Failed to retrieve ephemeral key"),console.error(t),this.displayError("Error")}displayError(t){var e;this._errorElement&&(this._errorElement.style.display="block",this._errorElement.textContent=(null==(e=this._errorConfig)?void 0:e.text)||t,this.changeToUnavailable())}createLoading(){var t,e;const i=document.createElement("div");return i.id="deep-chat-openai-realtime-loading",this._loadingElement=i,null!=(t=this._loadingConfig)&&t.html&&(this._loadingElement.innerHTML=this._loadingConfig.html),Object.assign(i.style,null==(e=this._loadingConfig)?void 0:e.style),i.style.display="none",i}displayLoading(){var e,i,s;this._toggleButton&&(this._toggleButton.changeToActive(),this._toggleButton.elementRef.classList.add(t.BUTTON_LOADING),Fi.removeAriaDisabled(this._toggleButton.elementRef),Fi.addAriaBusy(this._toggleButton.elementRef)),("boolean"!=typeof(null==(e=this._loadingConfig)?void 0:e.display)||this._loadingConfig.display)&&this._loadingElement&&(this._loadingElement.style.display="block",null!=(i=this._loadingConfig)&&i.html||(this._loadingElement.textContent=(null==(s=this._loadingConfig)?void 0:s.text)||"Loading"))}hideLoading(){this._toggleButton&&(this._toggleButton.elementRef.classList.remove(t.BUTTON_LOADING),Fi.removeAriaBusy(this._toggleButton.elementRef)),this._loadingElement&&(this._loadingElement.style.display="none")}async handleTool(t,e,i,s){if(!this._functionHandler)throw Error("Please define the `function_handler` property inside the [openAI](https://deepchat.dev/docs/directConnection/openAI#Realtime) object.");const n=await this._functionHandler({name:t,arguments:e});if("object"!=typeof n||!Hi.isJson(n))throw Error('The `function_handler` response must be a JSON object, e.g. {response: "My response"}');if("generate_horoscope"===t){const t=JSON.stringify({type:"conversation.item.create",item:{type:"function_call_output",call_id:i,output:JSON.stringify(n)}});s.send(t);const e={type:"response.create"};s.send(JSON.stringify(e))}}isCustomView(){return!0}};Zi.BUTTON_DEFAULT="deep-chat-openai-realtime-button-default",Zi.BUTTON_LOADING="deep-chat-openai-realtime-button-loading",Zi.MUTE_ACTIVE="deep-chat-openai-realtime-mute-active",Zi.UNAVAILABLE="deep-chat-openai-realtime-button-unavailable";let Wi=Zi;const Xi=class t extends Ve{constructor(e){var i,s,n;const o=JSON.parse(JSON.stringify(e.directConnection)),r=null==o?void 0:o.openAI;super(e,Ai.buildKeyVerificationDetails(),Ai.buildHeaders,r),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/audio/speech",this.permittedErrorPrefixes=["Invalid"],this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI : Text To Speech</b></div>\n <p>Generate an audio file based on your text input.</p>\n <p>Click <a href="https://platform.openai.com/docs/guides/text-to-speech">here</a> for more information.</p>';const a=null==(i=null==o?void 0:o.openAI)?void 0:i.textToSpeech;"object"==typeof a&&Object.assign(this.rawBody,a),(s=this.rawBody).model??(s.model=t.DEFAULT_MODEL),(n=this.rawBody).voice??(n.voice=t.DEFAULT_VOIDE),this.textInputPlaceholderText="Insert text to generate audio",this.rawBody.response_format="mp3"}preprocessBody(t,e){var i,s;const n=JSON.parse(JSON.stringify(t)),o=null==(s=null==(i=e[e.length-1])?void 0:i.text)?void 0:s.trim();return o&&""!==o&&(n.input=o),n}async callServiceAPI(t,e){var i;if(null==(i=this.connectSettings)||!i.headers)throw new Error("Request settings have not been set up");this.url=this.connectSettings.url||this.url;const s=this.preprocessBody(this.rawBody,e);Fe.request(this,s,t)}async extractResultData(t){if(t instanceof Blob)return new Promise((e=>{const i=new FileReader;i.readAsDataURL(t),i.onload=t=>{e({files:[{src:t.target.result,type:"audio"}]})}}));if(t.error)throw t.error.message;return{error:"error"}}};Xi.DEFAULT_MODEL="tts-1",Xi.DEFAULT_VOIDE="alloy";let Yi=Xi;const Qi=class t extends Ve{constructor(e){var i,s;const n=JSON.parse(JSON.stringify(e.directConnection)),o=null==n?void 0:n.openAI;super(e,Ai.buildKeyVerificationDetails(),Ai.buildHeaders,o,{audio:{}}),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI : Speech To Text</b></div>\n <p><b>Upload an audio file</b> to transcribe it into text. You can optionally provide text to guide the audio\n processing.\n <p>Click <a href="https://platform.openai.com/docs/guides/speech-to-text">here</a> for more info.</p>',this.url="",this.permittedErrorPrefixes=["Invalid"],this.textInputPlaceholderText="Upload an audio file",this._service_url=t.AUDIO_TRANSCRIPTIONS_URL;const r=null==(i=null==n?void 0:n.openAI)?void 0:i.audio;"object"==typeof r&&(this.processConfig(r),t.cleanConfig(r),Object.assign(this.rawBody,r)),(s=this.rawBody).model??(s.model=t.DEFAULT_MODEL),this.rawBody.response_format="json",this.canSendMessage=t.canSendFileMessage}static canSendFileMessage(t,e){return!(null==e||!e[0])}processConfig(e){null!=e&&e.type&&"translation"===e.type&&(this._service_url=t.AUDIO_TRANSLATIONS_URL,delete e.language)}static cleanConfig(t){delete t.type}static createFormDataBody(t,e){const i=new FormData;return i.append("file",e),Object.keys(t).forEach((e=>{i.append(e,String(t[e]))})),i}preprocessBody(t,e){var i,s;const n=JSON.parse(JSON.stringify(t)),o=null==(s=null==(i=e[e.length-1])?void 0:i.text)?void 0:s.trim();return o&&""!==o&&(n.prompt=o),n}async callServiceAPI(e,i,s){var n;if(null==(n=this.connectSettings)||!n.headers)throw new Error("Request settings have not been set up");if(null==s||!s[0])throw new Error("No file was added");this.url=this.connectSettings.url||this._service_url;const o=this.preprocessBody(this.rawBody,i),r=t.createFormDataBody(o,s[0]);Oe.tempRemoveContentHeader(this.connectSettings,Fe.request.bind(this,this,r,e),!1)}async extractResultData(t){if(t.error)throw t.error.message;return{text:t.text}}};Qi.AUDIO_TRANSCRIPTIONS_URL="https://api.openai.com/v1/audio/transcriptions",Qi.AUDIO_TRANSLATIONS_URL="https://api.openai.com/v1/audio/translations",Qi.DEFAULT_MODEL="whisper-1";let ts=Qi;class es{static buildTextToSpeechHeaders(t,e){return{"Ocp-Apim-Subscription-Key":e,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":t}}static buildSpeechToTextHeaders(t){return{"Ocp-Apim-Subscription-Key":t,Accept:"application/json"}}static handleSpeechVerificationResult(t,e,i,s){t.error?s(y.INVALID_KEY):i(e)}static buildSpeechKeyVerificationDetails(t){return{url:`https://${t}.api.cognitive.microsoft.com/sts/v1.0/issuetoken`,method:"POST",createHeaders:t=>({"Ocp-Apim-Subscription-Key":`${t}`}),handleVerificationResult:es.handleSpeechVerificationResult}}static buildSummarizationHeader(t){return{"Ocp-Apim-Subscription-Key":t,"Content-Type":"application/json"}}static handleLanguageVerificationResult(t,e,i,s){var n;"401"===(null==(n=t.error)?void 0:n.code)?s(y.INVALID_KEY):i(e)}static buildLanguageKeyVerificationDetails(t){return{url:`${t}/language/analyze-text/jobs?api-version=2022-10-01-preview`,method:"POST",createHeaders:t=>({"Ocp-Apim-Subscription-Key":`${t}`}),handleVerificationResult:es.handleLanguageVerificationResult}}static handleTranslationVerificationResult(t,e,i,s){t.json().then((t=>{Array.isArray(t)||401e3!==t.error.code?i(e):s(y.INVALID_KEY)}))}static buildTranslationKeyVerificationDetails(t){return{url:"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es",method:"POST",createHeaders:e=>es.buildTranslationHeaders(t,e),handleVerificationResult:es.handleTranslationVerificationResult}}static buildTranslationHeaders(t,e){const i={"Ocp-Apim-Subscription-Key":e,"Content-Type":"application/json"};return t&&(i["Ocp-Apim-Subscription-Region"]=t),i}}class is extends Ve{constructor(t,e,i,s,n){super(t,es.buildLanguageKeyVerificationDetails(i),e,s,n),this.insertKeyPlaceholderText="Azure Language Subscription Key",this.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",this.permittedErrorPrefixes=["Access"]}}const ss=class t extends is{constructor(e){var i,s,n,o;const r=null==(s=null==(i=e.directConnection)?void 0:i.azure)?void 0:s.summarization,a=null==(n=e.directConnection)?void 0:n.azure;super(e,es.buildSummarizationHeader,r.endpoint,a),this.permittedErrorPrefixes=[t.ENDPOINT_ERROR_MESSAGE],this.url="",this.textInputPlaceholderText="Insert text to summarize",this.isTextInputDisabled=!1,r.endpoint?((o=this.rawBody).language??(o.language="en"),Object.assign(this.rawBody,r),this.url=`${r.endpoint}/language/analyze-text/jobs?api-version=2022-10-01-preview`):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout((()=>{e.addMessage({error:t.ENDPOINT_ERROR_MESSAGE})})))}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return{analysisInput:{documents:[{id:"1",language:t.language,text:i}]},tasks:[{kind:"ExtractiveSummarization"}]}}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Fe.request(this,i,t),this.messages=t}async extractResultData(t){var e;if(t.error)throw t.error.message;if(this.messages&&this.completionsHandlers){const i=t.headers.get("operation-location"),s={method:"GET",headers:null==(e=this.connectSettings)?void 0:e.headers};Fe.executePollRequest(this,i,s,this.messages)}return{makingAnotherRequest:!0}}async extractPollResultData(t){if(t.error)throw t.error;if("running"===t.status)return{timeoutMS:2e3};if(t.errors.length>0)throw t.errors[0];if(t.tasks.items[0].results.errors.length>0)throw t.tasks.items[0].results.errors[0];let e="";for(const i of t.tasks.items[0].results.documents[0].sentences)e+=i.text;return{text:e||""}}};ss.ENDPOINT_ERROR_MESSAGE="Please define the azure endpoint. [More Information](https://deepchat.dev/docs/directConnection/Azure#Summarization)";let ns=ss;class os{static async poll(t,e){const i={authorization:t,"content-type":"application/json"},s=`https://api.assemblyai.com/v2/transcript/${(await(await fetch("https://api.assemblyai.com/v2/transcript",{method:"POST",body:JSON.stringify({audio_url:e}),headers:i})).json()).id}`;let n;for(;!n;){const t=await(await fetch(s,{headers:i})).json();if("completed"===t.status)n=t;else{if("error"===t.status)throw new Error(`Transcription failed: ${t.error}`);await new Promise((t=>setTimeout(t,3e3)))}}return n}static buildHeaders(t){return{Authorization:t,"Content-Type":"application/octet-stream"}}static handleVerificationResult(t,e,i,s){const n=t;n.error?"invalid_api_key"===n.error.code?s(y.INVALID_KEY):s(y.CONNECTION_FAILED):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.assemblyai.com/v2/upload",method:"POST",handleVerificationResult:os.handleVerificationResult}}}class rs extends Ve{constructor(t){var e;const i=null==(e=t.directConnection)?void 0:e.assemblyAI;super(t,os.buildKeyVerificationDetails(),os.buildHeaders,i,{audio:{}}),this.insertKeyPlaceholderText="AssemblyAI API Key",this.keyHelpUrl="https://www.assemblyai.com/app/account",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>AssemblyAI Audio</b></div>\n <p><b>Upload an audio file</b> to transcribe it into text.\n <p>\n Click <a href="https://www.assemblyai.com/docs/Guides/transcribing_an_audio_file#get-started">here</a> for more info.\n </p>',this.url="https://api.assemblyai.com/v2/upload",this.isTextInputDisabled=!0,this.textInputPlaceholderText="Upload an audio file",this.permittedErrorPrefixes=["Authentication","Invalid"],this.canSendMessage=rs.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])}async callServiceAPI(t,e,i){var s;if(null==(s=this.connectSettings)||!s.headers)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");Fe.request(this,i[0],t,!1)}async extractResultData(t){var e,i;if(t.error)throw t.error;const s=null==(i=null==(e=this.connectSettings)?void 0:e.headers)?void 0:i.Authorization;return{text:(await os.poll(s,t.upload_url)).text}}}class as extends Ve{constructor(t,e,i,s,n){super(t,es.buildSpeechKeyVerificationDetails(i),e,s,n),this.insertKeyPlaceholderText="Azure Speech Subscription Key",this.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal"}}const ls=class t extends as{constructor(e){var i,s,n,o,r,a;const l=null==(s=null==(i=e.directConnection)?void 0:i.azure)?void 0:s.textToSpeech,c=null==(n=e.directConnection)?void 0:n.azure;super(e,es.buildTextToSpeechHeaders.bind({},(null==l?void 0:l.outputFormat)||"audio-16khz-128kbitrate-mono-mp3"),l.region,c),this.permittedErrorPrefixes=[t.REGION_ERROR_MESSAGE],this.introPanelMarkUp=`\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Azure Text To Speech</b></div>\n <p>Insert text to synthesize it to audio.\n <p>\n Click <a href="${t.HELP_LINK}">here</a> for more info.\n </p>`,this.isTextInputDisabled=!1,this.url="",l.region?(Object.assign(this.rawBody,l),(o=this.rawBody).lang??(o.lang="en-US"),(r=this.rawBody).name??(r.name="en-US-JennyNeural"),(a=this.rawBody).gender??(a.gender="Female"),this.url=`https://${l.region}.tts.speech.microsoft.com/cognitiveservices/v1`):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout((()=>{e.addMessage({error:t.REGION_ERROR_MESSAGE})})))}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return`<speak version='1.0' xml:lang='${t.lang}'>\n <voice xml:lang='${t.lang}' xml:gender='${t.gender}' name='${t.name}'>\n ${i}\n </voice>\n </speak>`}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Fe.request(this,i,t,!1)}async extractResultData(t){return new Promise((e=>{const i=new FileReader;i.readAsDataURL(t),i.onload=t=>{e({files:[{src:t.target.result,type:"audio"}]})}}))}};ls.HELP_LINK="https://learn.microsoft.com/en-GB/azure/cognitive-services/speech-service/get-started-text-to-speech?tabs=windows%2Cterminal&pivots=programming-language-rest",ls.REGION_ERROR_MESSAGE="Please define a region config property. [More Information](https://deepchat.dev/docs/directConnection/Azure#TextToSpeech)";let cs=ls;const hs=class t extends as{constructor(e){var i,s,n;const o=null==(s=null==(i=e.directConnection)?void 0:i.azure)?void 0:s.speechToText,r=null==(n=e.directConnection)?void 0:n.azure;if(super(e,es.buildSpeechToTextHeaders,o.region,r,{audio:{files:{acceptedFormats:".wav,.ogg"}}}),this.permittedErrorPrefixes=[t.REGION_ERROR_MESSAGE],this.introPanelMarkUp=`\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Azure Speech To Text</b></div>\n <p><b>Upload a .wav or .ogg audio file</b> to transcribe it into text.\n <p>\n Click <a href="${t.HELP_LINK}">here</a> for more info.\n </p>`,this.url="",this.isTextInputDisabled=!0,this.textInputPlaceholderText="Upload an audio file",o.region){this.canSendMessage=t.canFileSendMessage;const e=o.lang||"en-US";this.url=`https://${o.region}.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=${e}&format=detailed`,this.recordAudio=void 0}else this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout((()=>{e.addMessage({error:t.REGION_ERROR_MESSAGE})}))}static canFileSendMessage(t,e){return!(null==e||!e[0])}async callServiceAPI(t,e,i){var s,n;if(null==(s=this.connectSettings)||!s.headers)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");null!=(n=this.connectSettings)&&n.headers&&(this.connectSettings.headers["Content-Type"]=i[0].name.toLocaleLowerCase().endsWith(".wav")?"audio/wav; codecs=audio/pcm; samplerate=16000":"audio/ogg; codecs=opus"),Fe.request(this,i[0],t,!1)}async extractResultData(t){if(t.error)throw t.error;return{text:t.DisplayText||""}}};hs.HELP_LINK="https://learn.microsoft.com/en-GB/azure/cognitive-services/speech-service/get-started-text-to-speech?tabs=windows%2Cterminal&pivots=programming-language-rest",hs.REGION_ERROR_MESSAGE="Please define a region config property. [More Information](https://deepchat.dev/docs/directConnection/Azure#SpeechToText)";let us=hs;class ds extends Ve{constructor(t){var e,i,s;const n=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.translation,o=null==(s=t.directConnection)?void 0:s.azure;super(t,es.buildTranslationKeyVerificationDetails(n.region),es.buildTranslationHeaders.bind({},null==n?void 0:n.region),o),this.insertKeyPlaceholderText="Azure Translate Subscription Key",this.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",this.url="",this.url=`https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=${n.language||"es"}`}preprocessBody(t){const e=t[t.length-1].text;if(e)return[{Text:e}]}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(e);Fe.request(this,i,t)}async extractResultData(t){var e;if(Array.isArray(t))return{text:(null==(e=t[0].translations)?void 0:e[0].text)||""};throw t.error}}class ps extends Ve{constructor(t,e,i,s,n){var o,r,a,l;const c=JSON.parse(JSON.stringify(t.directConnection));super(t,e||Ai.buildKeyVerificationDetails(),i||Ai.buildHeaders,s||c.openAI),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/chat/completions",this.permittedErrorPrefixes=["Incorrect"],this.asyncCallInProgress=!1,this._systemMessage=ps.generateSystemMessage("You are a helpful assistant.");const h=n||(null==(o=c.openAI)?void 0:o.chat);if("object"==typeof h){h.system_prompt&&(this._systemMessage=ps.generateSystemMessage(h.system_prompt));const{function_handler:e}=null==(a=null==(r=t.directConnection)?void 0:r.openAI)?void 0:a.chat;e&&(this._functionHandler=e),this.cleanConfig(h),Object.assign(this.rawBody,h)}this.maxMessages??(this.maxMessages=-1),(l=this.rawBody).model??(l.model="gpt-4o")}static generateSystemMessage(t){return{role:"system",content:t}}cleanConfig(t){delete t.system_prompt,delete t.function_handler}static getContent(t){if(t.files&&t.files.length>0){const e=t.files.map((t=>({type:"image_url",image_url:{url:t.src}})));return t.text&&t.text.trim().length>0&&e.unshift({type:"text",text:t.text}),e}return t.text}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=$e.getCharacterLimitMessages(e,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.content.length:-1).map((t=>({content:ps.getContent(t),role:t.role===Se.USER_ROLE?"user":"assistant"})));return e.find((t=>t.files&&t.files.length>0))&&(i.max_tokens??(i.max_tokens=300)),i.messages=[this._systemMessage,...s],i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e),s=this.stream;s&&("object"!=typeof s||!s.simulation)||i.stream?(i.stream=!0,Ne.request(this,i,t)):Fe.request(this,i,t)}async extractResultData(t,e,i){var s,n,o,r;if(t.error)throw t.error.message;return null!=(n=null==(s=t.choices)?void 0:s[0])&&n.delta?this.extractStreamResult(t.choices[0],e,i):null!=(r=null==(o=t.choices)?void 0:o[0])&&r.message?t.choices[0].message.tool_calls?this.handleTools(t.choices[0].message,e,i):{text:t.choices[0].message.content}:{text:""}}async extractStreamResult(t,e,i){const{delta:s,finish_reason:n}=t;if("tool_calls"===n){this.asyncCallInProgress=!0;const t={tool_calls:this._streamToolCalls};return this._streamToolCalls=void 0,this.handleTools(t,e,i)}return null!=s&&s.tool_calls&&(this._streamToolCalls?s.tool_calls.forEach(((t,e)=>{this._streamToolCalls&&(this._streamToolCalls[e].function.arguments+=t.function.arguments)})):this._streamToolCalls=s.tool_calls),{text:(null==s?void 0:s.content)||""}}async handleTools(t,e,i){var s,n,o,r,a;if(!(t.tool_calls&&e&&i&&this._functionHandler))throw Error("Please define the `function_handler` property inside the [openAI](https://deepchat.dev/docs/directConnection/openAI#Chat) object.");const l=JSON.parse(JSON.stringify(i)),c=t.tool_calls.map((t=>({name:t.function.name,arguments:t.function.arguments}))),h=await(null==(s=this._functionHandler)?void 0:s.call(this,c));if(!Array.isArray(h)){if(h.text){const t={text:h.text},e=await(null==(o=(n=this.deepChat).responseInterceptor)?void 0:o.call(n,t))||t;if(Array.isArray(e))throw Error(Ai.FUNCTION_TOOL_RESP_ARR_ERROR);return e}throw Error(Ai.FUNCTION_TOOL_RESP_ERROR)}const u=await Promise.all(h);if(l.messages.push({tool_calls:t.tool_calls,role:"assistant",content:null}),!u.find((({response:t})=>"string"!=typeof t))&&c.length===u.length){u.forEach(((e,i)=>{var s;const n=null==(s=t.tool_calls)?void 0:s[i];null==l||l.messages.push({role:"tool",tool_call_id:null==n?void 0:n.id,name:null==n?void 0:n.function.name,content:e.response})})),delete l.tools,delete l.tool_choice,delete l.stream;try{let t=await(null==e?void 0:e(l).then((t=>Oe.processResponseByType(t))));if(t=await(null==(a=(r=this.deepChat).responseInterceptor)?void 0:a.call(r,t))||t,t.error)throw t.error.message;return{text:t.choices[0].message.content||""}}catch(t){throw this.asyncCallInProgress=!1,t}}throw Error(Ai.FUNCTION_TOOL_RESP_ERROR)}}class ms extends ps{constructor(t){var e,i,s,n,o,r,a;const l=JSON.parse(JSON.stringify(t.directConnection)),c=l.azure,h=(null==(i=null==(e=l.azure)?void 0:e.openAI)?void 0:i.urlDetails)||{},u=null==(n=null==(s=l.azure)?void 0:s.openAI)?void 0:n.chat;if(super(t,Ri.buildKeyVerificationDetails(h),Ri.buildHeaders,c,u),this.permittedErrorPrefixes=[Ri.URL_DETAILS_ERROR_MESSAGE],this.isTextInputDisabled=!1,"object"==typeof u){const{function_handler:e}=null==(a=null==(r=null==(o=t.directConnection)?void 0:o.azure)?void 0:r.openAI)?void 0:a.chat;e&&(this._functionHandler=e)}Ri.validateURLDetails(h)?this.url=ms.buildURL(h):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout((()=>{t.addMessage({error:Ri.URL_DETAILS_ERROR_MESSAGE})})))}static buildURL(t){const{endpoint:e,deploymentId:i,version:s}=t;return`${e}/openai/deployments/${i}/completions?api-version=${s}`}}const vs=class t extends Ve{constructor(e){var i;const{directConnection:s}=e,n=null==s?void 0:s.openAI;super(e,Ai.buildKeyVerificationDetails(),Ai.buildHeaders,n,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI DALL·E</b></div>\n <p><b>Insert text</b> to generate an image.</p>\n <p><b>Upload 1</b> PNG image to generate its variation and optionally insert text to specify the change.</p>\n <p><b>Upload 2</b> PNG images where the second is a copy of the first with a transparent area where the edit should\n take place and text to specify the edit.</p>\n <p>Click <a href="https://platform.openai.com/docs/guides/images/introduction">here</a> for more info.</p>',this.url="",this.permittedErrorPrefixes=["Incorrect","Invalid input image"];const o=null==(i=null==s?void 0:s.openAI)?void 0:i.images;if(this.camera){const t="object"==typeof o&&o.size?Number.parseInt(o.size):1024;this.camera.files={dimensions:{width:t,height:t}}}"object"==typeof o&&Object.assign(this.rawBody,o),this.canSendMessage=t.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])||!(!t||""===t.trim())}static createFormDataBody(t,e,i){const s=new FormData;return s.append("image",e),i&&s.append("mask",i),Object.keys(t).forEach((e=>{s.append(e,String(t[e]))})),s}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t));return e&&""!==e&&(i.prompt=e),i}callApiWithImage(e,i,s){var n,o;let r;const a=null==(o=null==(n=i[i.length-1])?void 0:n.text)?void 0:o.trim();if(s[1]||a&&""!==a){this.url=t.IMAGE_EDIT_URL;const e=this.preprocessBody(this.rawBody,a);r=t.createFormDataBody(e,s[0],s[1])}else this.url=t.IMAGE_VARIATIONS_URL,r=t.createFormDataBody(this.rawBody,s[0]);Oe.tempRemoveContentHeader(this.connectSettings,Fe.request.bind(this,this,r,e),!1)}async callServiceAPI(e,i,s){var n;if(null==(n=this.connectSettings)||!n.headers)throw new Error("Request settings have not been set up");if(null!=s&&s[0])this.callApiWithImage(e,i,s);else{if(!this.connectSettings)throw new Error("Request settings have not been set up");this.url=t.IMAGE_GENERATION_URL;const s=this.preprocessBody(this.rawBody,i[i.length-1].text);Fe.request(this,s,e)}}async extractResultData(t){if(t.error)throw t.error.message;return{files:t.data.map((t=>t.url?{src:t.url,type:"image"}:{src:`${hi}${t.b64_json}`,type:"image"}))}}};vs.IMAGE_GENERATION_URL="https://api.openai.com/v1/images/generations",vs.IMAGE_VARIATIONS_URL="https://api.openai.com/v1/images/variations",vs.IMAGE_EDIT_URL="https://api.openai.com/v1/images/edits";let fs=vs;class gs extends Ii{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=null==(e=i.cohere)?void 0:e.chat;super(t,"https://api.cohere.ai/v1/chat","Ask me anything!",s,i.cohere),"object"==typeof s&&Object.assign(this.rawBody,s),this.maxMessages??(this.maxMessages=-1)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e.filter((t=>t.text));return i.query=s[s.length-1].text,i.chat_history=s.slice(0,s.length-1).map((t=>({text:t.text,user_name:"ai"===t.role?"CHATBOT":"USER"}))),i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Fe.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.text}}}class bs{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json",accept:"application/json"}}static handleVerificationResult(t,e,i,s){var n;null!=(n=t.message)&&n.includes("invalid request: prompt must be at least 1 token long")?i(e):s(y.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api.mistral.ai/v1/models",method:"GET",handleVerificationResult:bs.handleVerificationResult}}}class ys extends Ve{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)).mistral;super(t,bs.buildKeyVerificationDetails(),bs.buildHeaders,i),this.insertKeyPlaceholderText="Mistral API Key",this.keyHelpUrl="https://console.mistral.ai/api-keys/",this.url="https://api.mistral.ai/v1/chat/completions",this.permittedErrorPrefixes=["invalid"],i&&(this.cleanConfig(i),Object.assign(this.rawBody,i)),this.maxMessages??(this.maxMessages=-1),(e=this.rawBody).model??(e.model="open-mistral-7b")}cleanConfig(t){delete t.key}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e.filter((t=>t.text));return i.messages=s.slice(0,s.length-1).map((t=>({text:t.text,user_name:"ai"===t.role?"system":"user"}))),i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Fe.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.text}}}class ws{static create(t){const{directConnection:e,connect:i,demo:s,webModel:n}=t;if(n)return new si(t);if(e){if(e.openAI)return e.openAI.images?new fs(t):e.openAI.speechToText?new ts(t):e.openAI.textToSpeech?new Yi(t):e.openAI.assistant?new Ci(t):e.openAI.realtime?new Wi(t):new ps(t);if(e.assemblyAI)return new rs(t);if(e.cohere)return e.cohere.textGeneration?new Pi(t):e.cohere.summarization?new Li(t):new gs(t);if(e.huggingFace)return e.huggingFace.textGeneration?new fi(t):e.huggingFace.summarization?new bi(t):e.huggingFace.translation?new xi(t):e.huggingFace.fillMask?new _i(t):e.huggingFace.questionAnswer?new gi(t):e.huggingFace.audioSpeechRecognition?new vi(t):e.huggingFace.audioClassification?new li(t):e.huggingFace.imageClassification?new ci(t):new yi(t);if(e.azure){if(e.azure.openAI){if(e.azure.openAI.chat)return new ms(t);if(e.azure.openAI.assistant)return new Bi(t)}if(e.azure.speechToText)return new us(t);if(e.azure.textToSpeech)return new cs(t);if(e.azure.summarization)return new ns(t);if(e.azure.translation)return new ds(t)}if(e.stabilityAI)return e.stabilityAI.imageToImage?new wi(t):e.stabilityAI.imageToImageUpscale?new pi(t):e.stabilityAI.imageToImageMasking?new mi(t):new ki(t);if(e.mistral)return new ys(t)}return i&&Object.keys(i).length>0&&!s?new Ue(t):new Ue(t,void 0,s||!0)}}const xs=class{};xs.attibutes={string:t=>t,number:t=>parseFloat(t),boolean:t=>"true"===t,object:t=>JSON.parse(t),array:t=>JSON.parse(t),function:t=>new Function(`return ${t}`)()};let ks=xs;function _s(t){return function(e,i){Object.defineProperty(e,i,{});const s=e.constructor,n=i.toLocaleLowerCase();s._attributes_[n]=ks.attibutes[t],s._attributeToProperty_[n]=i}}class Ss{constructor(t,e,i){this._isDisplayed=!1,t?(this._elementRef=this.createIntroPanelWithChild(t,i),this._isDisplayed=!0):e&&(this._elementRef=this.createInternalIntroPanel(e,i),this._isDisplayed=!0)}static createIntroPanel(t){const e=document.createElement("div");return e.classList.add("intro-panel"),Object.assign(e.style,t),e}createIntroPanelWithChild(t,e){const i=Ss.createIntroPanel(e);return"none"===t.style.display&&(t.style.display="block"),i.appendChild(t),i}createInternalIntroPanel(t,e){const i=Ss.createIntroPanel(e);return i.id="internal-intro-panel",i.innerHTML=t,i}hide(){this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="none",this._isDisplayed=!1)}display(){!this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="",this._isDisplayed=!0)}}const As=class t{static createImage(t,e,i){const s=new Image;return s.src=t.src,i&&M.scrollDownOnImageLoad(s.src,e),M.processContent("image",s,s.src,t.name)}static createImageMessage(e,i,s,n){const o=t.createImage(i,e.elementRef,!n&&!e.focusMode),r=e.createNewMessageElement("",s);return r.bubbleElement.appendChild(o),r.bubbleElement.classList.add(t.IMAGE_BUBBLE_CLASS),{type:"image",elements:r}}static createAudioElement(t,e){const i=document.createElement("audio");return i.src=t.src,i.classList.add("audio-player"),i.controls=!0,l.IS_SAFARI&&(i.classList.add("audio-player-safari"),i.classList.add(e===Se.USER_ROLE?"audio-player-safari-right":"audio-player-safari-left")),i}static createNewAudioMessage(e,i,s,n){const o=t.createAudioElement(i,s),r=e.createMessageElementsOnOrientation("",s,n);return r.bubbleElement.appendChild(o),r.bubbleElement.classList.add(t.AUDIO_BUBBLE_CLASS),{type:"audio",elements:r}}static createAnyFile(t){const e=document.createElement("div");e.classList.add("any-file-message-contents");const i=document.createElement("div");i.classList.add("any-file-message-icon-container");const s=Ze.createSVGElement('<?xml version="1.0" encoding="iso-8859-1"?>\n<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" \n\t viewBox="50 30 420 450" xml:space="preserve">\n<g filter="brightness(0) saturate(100%) invert(16%) sepia(0%) saturate(1942%) hue-rotate(215deg) brightness(99%) contrast(93%)">\n\t<g>\n\t\t<path d="M447.933,103.629c-0.034-3.076-1.224-6.09-3.485-8.352L352.683,3.511c-0.004-0.004-0.007-0.005-0.011-0.008\n\t\t\tC350.505,1.338,347.511,0,344.206,0H89.278C75.361,0,64.04,11.32,64.04,25.237v461.525c0,13.916,11.32,25.237,25.237,25.237\n\t\t\th333.444c13.916,0,25.237-11.32,25.237-25.237V103.753C447.96,103.709,447.937,103.672,447.933,103.629z M356.194,40.931\n\t\t\tl50.834,50.834h-49.572c-0.695,0-1.262-0.567-1.262-1.262V40.931z M423.983,486.763c0,0.695-0.566,1.261-1.261,1.261H89.278\n\t\t\tc-0.695,0-1.261-0.566-1.261-1.261V25.237c0-0.695,0.566-1.261,1.261-1.261h242.94v66.527c0,13.916,11.322,25.239,25.239,25.239\n\t\t\th66.527V486.763z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,164.014H149.912c-6.62,0-11.988,5.367-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,169.381,368.707,164.014,362.088,164.014z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,236.353H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,241.721,368.707,236.353,362.088,236.353z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,308.691H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C374.076,314.06,368.707,308.691,362.088,308.691z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M256,381.031H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988H256\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C267.988,386.398,262.62,381.031,256,381.031z"/>\n\t</g>\n</g>\n</svg>');s.classList.add("any-file-message-icon"),i.appendChild(s);const n=document.createElement("div");return n.classList.add("any-file-message-text"),n.textContent=t.name||M.DEFAULT_FILE_NAME,e.appendChild(i),e.appendChild(n),M.processContent("any",e,t.src,n.textContent)}static createNewAnyFileMessage(e,i,s,n){const o=e.createMessageElementsOnOrientation("",s,n),r=t.createAnyFile(i);return o.bubbleElement.classList.add(t.ANY_FILE_BUBBLE_CLASS),o.bubbleElement.appendChild(r),{type:"file",elements:o}}static createMessages(e,i,s,n=!1){return i.map((i=>(i.ref&&(i=M.removeFileRef(i)),M.isAudioFile(i)?t.createNewAudioMessage(e,i,s,n):M.isImageFile(i)?t.createImageMessage(e,i,s,n):t.createNewAnyFileMessage(e,i,s,n))))}static addMessages(e,i,s,n){t.createMessages(e,i,s,n).forEach((({type:t,elements:i})=>{M.addMessage(e,i,t,s,n)}))}};As.IMAGE_BUBBLE_CLASS="image-message",As.AUDIO_BUBBLE_CLASS="audio-message",As.ANY_FILE_BUBBLE_CLASS="any-file-message";let Ts=As;class Ms{static removeElements(t,e){if(!e)return;const i=t.findIndex((t=>t===e));t.splice(i,1),null==e||e.outerContainer.remove()}static removeFilesMessages(t,e){var i;null==(i=e[1].files)||i.forEach((e=>{Ms.removeElements(t.messageElementRefs,e)})),delete e[0].files,delete e[1].files}static removeTextHTMLMessage(t,e,i){const s=e[1][i];Ms.removeElements(t.messageElementRefs,s),delete e[0][i],delete e[1][i]}static updateHTMLMessage(t,e,i){var s,n,o;if(e[1].html)R.overwriteElements(t,i,e[1].html);else{const r=R.create(t,i,e[0].role),a=(null==(n=e[1].files)?void 0:n[(null==(s=e[1].files)?void 0:s.length)-1])||e[1].text,{nextSibling:l}=a.outerContainer;null==(o=null==l?void 0:l.parentElement)||o.insertBefore(r.outerContainer,l),t.messageElementRefs.splice(t.messageElementRefs.length-1,1);const c=t.messageElementRefs.findIndex((t=>t===a));t.messageElementRefs.splice(c+1,0,r),e[1].html=r}e[0].html=i}static updateFileMessages(t,e,i){var s,n;const o=e[0].role,r=Ts.createMessages(t,i,o),a=e[1].html,l=(null==(n=e[1].files)?void 0:n[(null==(s=e[1].files)?void 0:s.length)-1])||e[1].text,c=a||l;let h=t.messageElementRefs.findIndex((t=>t===c));l&&(h+=1);const u=(null==a?void 0:a.outerContainer)||(null==l?void 0:l.outerContainer.nextSibling);r.forEach((({type:e,elements:i},s)=>{var n;M.setElementProps(t,i,e,o),null==(n=u.parentElement)||n.insertBefore(i.outerContainer,u),t.messageElementRefs.splice(t.messageElementRefs.length-1,1),t.messageElementRefs.splice(h+s,0,i)})),Ms.removeFilesMessages(t,e),e[1].files=r.map((({elements:t})=>t)),e[0].files=i}static updateTextMessage(t,e,i){var s,n;if(e[1].text)t.renderText(e[1].text.bubbleElement,i);else{const o=t.createElements(i,e[0].role),r=(null==(s=e[1].files)?void 0:s[0])||e[1].html;null==(n=r.outerContainer.parentElement)||n.insertBefore(o.outerContainer,r.outerContainer);const a=t.messageElementRefs.findIndex((t=>t===r));t.messageElementRefs.splice(a,0,o),e[1].text=o}e[0].text=i}static isElementActive(t){var e,i;return js.isActiveElement(null==(e=t.text)?void 0:e.bubbleElement.classList)||js.isActiveElement(null==(i=t.html)?void 0:i.bubbleElement.classList)}static update(t,e,i){const s=t.messageToElements[i];if(s){if(Ms.isElementActive(s[1]))return console.error("Cannot update a message that is being streamed");e.text&&Ms.updateTextMessage(t,s,e.text),e.files?Ms.updateFileMessages(t,s,e.files):Ms.removeFilesMessages(t,s),e.html&&Ms.updateHTMLMessage(t,s,e.html),!e.text&&s[1].text&&Ms.removeTextHTMLMessage(t,s,"text"),!e.html&&s[1].html&&Ms.removeTextHTMLMessage(t,s,"html");const{messageElementRefs:i,avatars:n,names:o}=t;Se.classifyRoleMessages(i),Se.resetAllRoleElements(i,!!n,!!o)}else console.error("Message index not found. Please use the `getMessages` method to find the correct index")}}class Os{static getText(t,e){var i;if(!(t.directConnection||t.connect||t.webModel||t.demo))return"Connect to any API using the [connect](https://deepchat.dev/docs/connect#connect-1) property or a popular service via [directConnection](https://deepchat.dev/docs/directConnection/#directConnection).\n Host AI entirely on your browser via a [webModel](https://deepchat.dev/docs/webModel).\n To get started checkout the [Start](https://deepchat.dev/start) page and live code [examples](https://deepchat.dev/examples/frameworks).\n To remove this message set the [demo](https://deepchat.dev/docs/demo#demo) property to true.";if(t.directConnection){if(!e.isDirectConnection())return"Please define a valid service inside\n the [directConnection](https://deepchat.dev/docs/directConnection/#directConnection) object.";const s=null==(i=t.directConnection.openAI)?void 0:i.chat;if("object"==typeof s&&s.tools&&!s.function_handler)return"Please define the `function_handler` property inside the openAI [chat](https://deepchat.dev/docs/directConnection/openAI#Chat) object."}else if(t.connect&&!t.connect.url&&!t.connect.handler)return"Please define a `url` or a `handler` property inside the [connect](https://deepchat.dev/docs/connect#connect-1) object.";return null}}class js extends fe{constructor(t,e,i){var s,n;super(t);const{permittedErrorPrefixes:o,introPanelMarkUp:r,demo:a}=e;this._errorMessageOverrides=null==(s=t.errorMessages)?void 0:s.overrides,this._onClearMessages=he.onClearMessages.bind(this,t),this._onError=he.onError.bind(this,t),this._isLoadingMessageAllowed=js.getDefaultDisplayLoadingMessage(t,e),"object"==typeof t.displayLoadingBubble&&t.displayLoadingBubble.toggle&&(t.displayLoadingBubble.toggle=this.setLoadingToggle.bind(this)),this._permittedErrorPrefixes=o,this.addSetupMessageIfNeeded(t,e)||this.populateIntroPanel(i,r,t.introPanelStyle),a&&this.prepareDemo(O.processDemo(a),t.loadHistory),this.addIntroductoryMessages(t,e),new De(t,this,e),this._displayServiceErrorMessages=null==(n=t.errorMessages)?void 0:n.displayServiceErrorMessages,t.getMessages=()=>JSON.parse(JSON.stringify(this.messageToElements.map((([t])=>t)))),t.clearMessages=this.clearMessages.bind(this,e),t.refreshMessages=this.refreshTextMessages.bind(this,t.remarkable),t.scrollToBottom=x.scrollToBottom.bind(this,this.elementRef),t.addMessage=(t,e)=>{this.addAnyMessage({...t,sendUpdate:!!e},!e)},t.updateMessage=(t,e)=>Ms.update(this,t,e),e.isWebModel()&&e.setUpMessages(this),t.textToSpeech&&_.processConfig(t.textToSpeech,(t=>{this.textToSpeech=t}))}static getDefaultDisplayLoadingMessage(t,e){return e.websocket?!!t.displayLoadingBubble:("object"==typeof t.displayLoadingBubble||t.displayLoadingBubble)??!0}setLoadingToggle(){const t=this.messageElementRefs[this.messageElementRefs.length-1];fe.isLoadingMessage(t)?this.removeLastMessage():this.addLoadingMessage(!0)}prepareDemo(t,e){var i;if("object"==typeof t){if(!e&&t.displayLoading){const{history:e}=t.displayLoading;null!=e&&e.small&&de.addMessage(this,!1),null!=e&&e.full&&de.addMessage(this)}t.displayErrors&&(t.displayErrors.default&&this.addNewErrorMessage("",""),t.displayErrors.service&&this.addNewErrorMessage("service",""),t.displayErrors.speechToText&&this.addNewErrorMessage("speechToText","")),null!=(i=t.displayLoading)&&i.message&&this.addLoadingMessage(),t.response&&(this.customDemoResponse=t.response)}}addSetupMessageIfNeeded(t,e){const i=Os.getText(t,e);if(i){const t=this.createAndAppendNewMessageElement(i,Se.AI_ROLE);this.applyCustomStyles(t,Se.AI_ROLE,!1)}return!!i}addIntroductoryMessages(t,e){null!=t&&t.shadowRoot&&(this._introMessage=t.introMessage);let i=this._introMessage;null!=e&&e.isWebModel()&&(i??(i=e.getIntroMessage(i)));const s=!(null!=t&&t.history||!(null!=t&&t.loadHistory||null!=e&&e.fetchHistory));i&&(Array.isArray(i)?i.forEach(((t,e)=>{if(0!==e){const t=this.messageElementRefs[this.messageElementRefs.length-1].innerContainer;Se.hideRoleElements(t,!!this.avatars,!!this.names)}this.addIntroductoryMessage(t,s)})):this.addIntroductoryMessage(i,s))}addIntroductoryMessage(t,e){var i;let s;return null!=t&&t.text?s=this.createAndAppendNewMessageElement(t.text,Se.AI_ROLE):null!=t&&t.html&&(s=R.add(this,t.html,Se.AI_ROLE,this.messageElementRefs)),s&&(this.applyCustomStyles(s,Se.AI_ROLE,!1,null==(i=this.messageStyles)?void 0:i.intro),s.outerContainer.classList.add(fe.INTRO_CLASS),e&&(s.outerContainer.style.display="none")),s}removeIntroductoryMessage(){const t=this.messageElementRefs[0];t.outerContainer.classList.contains(fe.INTRO_CLASS)&&(t.outerContainer.remove(),this.messageElementRefs.shift())}addAnyMessage(t,e=!1,i=!1){return t.error?this.addNewErrorMessage("service",t.error,i):this.addNewMessage(t,e,i)}tryAddTextMessage(t,e,i,s=!1,n=!1){!i.ignoreText&&void 0!==t.text&&null!==i.text&&(this.addNewTextMessage(t.text,t.role,e,n),!s&&this.textToSpeech&&t.role!==Se.USER_ROLE&&_.speak(t.text,this.textToSpeech))}tryAddFileMessages(t,e=!1){t.files&&Array.isArray(t.files)&&Ts.addMessages(this,t.files,t.role,e)}tryAddHTMLMessage(t,e,i=!1){if(void 0!==t.html&&null!==t.html){const s=R.add(this,t.html,t.role,this.messageElementRefs,e,i);I.isElementTemporary(s)&&delete t.html}}addNewMessage(t,e=!1,i=!1){const s=js.createMessageContent(t),n={status:t.overwrite};return i?(this.tryAddHTMLMessage(s,n,i),this.tryAddFileMessages(s,i),this.tryAddTextMessage(s,n,t,e,i)):(this.tryAddTextMessage(s,n,t,e,i),this.tryAddFileMessages(s,i),this.tryAddHTMLMessage(s,n,i)),this.isValidMessageContent(s)&&!i&&this.updateStateOnMessage(s,t.overwrite,t.sendUpdate,e),s}isValidMessageContent(t){return t.text||t.html||t.files&&t.files.length>0}updateStateOnMessage(t,e,i=!0,s=!1){if(!e){const e=Se.generateMessageBody(t,this.messageElementRefs);this.messageToElements.push([t,e])}i&&this.sendClientUpdate(t,s)}removeMessageOnError(){const t=this.messageElementRefs[this.messageElementRefs.length-1],e=null==t?void 0:t.bubbleElement;(null!=e&&e.classList.contains(Te.MESSAGE_CLASS)&&""===e.textContent||js.isTemporaryElement(t))&&this.removeLastMessage()}addNewErrorMessage(t,e,i=!1){var s,n,o,r,a;this.removeMessageOnError();const l=this.getPermittedMessage(e)||(null==(s=this._errorMessageOverrides)?void 0:s[t])||(null==(n=this._errorMessageOverrides)?void 0:n.default)||"Error, please try again.",c=this.createMessageElementsOnOrientation(l,"error",i);Se.hideRoleElements(c.innerContainer,!!this.avatars,!!this.names);const{bubbleElement:h,outerContainer:u}=c;h.classList.add(Se.ERROR_MESSAGE_TEXT_CLASS),this.renderText(h,l);const d=ce.extractParticularSharedStyles(["fontSize","fontFamily"],null==(o=this.messageStyles)?void 0:o.default);ce.applyCustomStylesToElements(c,!1,d),ce.applyCustomStylesToElements(c,!1,null==(r=this.messageStyles)?void 0:r.error),i||this.appendOuterContainerElemet(u),this.textToSpeech&&_.speak(l,this.textToSpeech),null==(a=this._onError)||a.call(this,l)}static checkPermittedErrorPrefixes(t,e){for(let i=0;i<t.length;i+=1)if(e.startsWith(t[i]))return e}static extractErrorMessages(t){return Array.isArray(t)?t:t instanceof Error?[t.message]:"string"==typeof t?[t]:"object"==typeof t&&t.error?[t.error]:[]}getPermittedMessage(t){if(t){const e=js.extractErrorMessages(t);for(let t=0;t<e.length;t+=1){const i=e[t];if("string"==typeof i){if(this._displayServiceErrorMessages)return i;if(this._permittedErrorPrefixes){const t=js.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,i);if(t)return t}}}}}removeError(){this.isLastMessageError()&&Se.getLastMessageElement(this.elementRef).remove()}addDefaultLoadingMessage(){const t=this.createMessageElements("",Se.AI_ROLE),{bubbleElement:e}=t;t.bubbleElement.classList.add(A.DOTS_CONTAINER_CLASS);const i=document.createElement("div");return i.classList.add("loading-message-dots"),e.appendChild(i),A.setDots(e,this.messageStyles),t}addLoadingMessage(t=!1){var e,i,s,n,o,r;const a=this.messageElementRefs[this.messageElementRefs.length-1];if(fe.isLoadingMessage(a)||!t&&!this._isLoadingMessageAllowed)return;const l=null==(s=null==(i=null==(e=this.messageStyles)?void 0:e.loading)?void 0:i.message)?void 0:s.html,c=l?R.createElements(this,l,Se.AI_ROLE,!1):this.addDefaultLoadingMessage();this.appendOuterContainerElemet(c.outerContainer),c.bubbleElement.classList.add(A.BUBBLE_CLASS),this.applyCustomStyles(c,Se.AI_ROLE,!1,null==(r=null==(o=null==(n=this.messageStyles)?void 0:n.loading)?void 0:o.message)?void 0:r.styles),this.focusMode||x.scrollToBottom(this.elementRef)}populateIntroPanel(t,e,i){(t||e)&&(this._introPanel=new Ss(t,e,i),this._introPanel._elementRef&&(P.apply(this,this._introPanel._elementRef),this.elementRef.appendChild(this._introPanel._elementRef)))}async addMultipleFiles(t){return Promise.all((t||[]).map((t=>new Promise((e=>{if(t.type&&"any"!==t.type){const i=new FileReader;i.readAsDataURL(t.file),i.onload=()=>{e({src:i.result,type:t.type,ref:t.file})}}else{const i=t.file.name||M.DEFAULT_FILE_NAME;e({name:i,type:"any",ref:t.file})}})))))}static isActiveElement(t){return!!t&&(t.contains(A.BUBBLE_CLASS)||t.contains(de.CLASS)||t.contains(Te.MESSAGE_CLASS))}clearMessages(t,e){var i,s;const n=[];this.messageElementRefs.forEach((t=>{js.isActiveElement(t.bubbleElement.classList)?n.push(t):t.outerContainer.remove()})),Array.from(this.elementRef.children).forEach((t=>{var e;const i=null==(e=t.children[0])?void 0:e.children[0];null!=i&&i.classList.contains(Se.ERROR_MESSAGE_TEXT_CLASS)&&t.remove()})),this.messageElementRefs=n;const o=this.messageToElements.filter((t=>t[1].text&&js.isActiveElement(t[1].text.bubbleElement.classList)||t[1].html&&js.isActiveElement(t[1].html.bubbleElement.classList)));this.messageToElements.splice(0,this.messageToElements.length,...o),!1!==e&&(null!=(i=this._introPanel)&&i._elementRef&&this._introPanel.display(),this.addIntroductoryMessages()),null==(s=this._onClearMessages)||s.call(this),delete t.sessionId}}const Cs=class t{static adjustInputPadding(t,e){e["inside-left"].length>0&&t.classList.add("text-input-inner-left-adjustment"),e["inside-right"].length>0&&t.classList.add("text-input-inner-right-adjustment")}static adjustForOutsideButton(e,i,s){0===s["outside-right"].length&&s["outside-left"].length>0?(e[0].classList.add(t.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS)):0===s["outside-left"].length&&s["outside-right"].length>0&&(e[3].classList.add(t.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS))}static adjustOutsideSubmit(e,i,s){if(!(s["inside-left"].length>0||s["inside-right"].length>0)){if(0===s["outside-right"].length&&s["outside-left"].length>0)return e[0].classList.add(t.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),s["outside-left"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")));if(0===s["outside-left"].length&&s["outside-right"].length>0)return e[3].classList.add(t.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),s["outside-right"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")))}}static set(e,i,s,n){!!t.adjustOutsideSubmit(i,s,n)||t.adjustForOutsideButton(i,s,n),t.adjustInputPadding(e,n)}};Cs.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS="text-input-container-left-adjustment",Cs.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS="text-input-container-right-adjustment",Cs.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS="text-input-container-left-small-adjustment",Cs.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS="text-input-container-right-small-adjustment";let Es=Cs;class Is{static create(){return Array.from({length:4}).map(((t,e)=>{const i=document.createElement("div");return i.classList.add("input-button-container"),(0===e||3===e)&&i.classList.add("outer-button-container"),(1===e||2===e)&&i.classList.add("inner-button-container"),i}))}static add(t,e){t.insertBefore(e[1],t.firstChild),t.insertBefore(e[0],t.firstChild),t.appendChild(e[2]),t.appendChild(e[3])}static getContainerIndex(t){return"outside-left"===t?0:"inside-left"===t?1:"inside-right"===t?2:3}static addButton(t,e,i){e.classList.add(i);const s=Is.getContainerIndex(i);t[s].appendChild(e),3===s&&e.classList.add("outside-right")}}const Ps=["camera","gifs","images","audio","mixedFiles","submit","microphone"],Ns='<?xml version="1.0" standalone="no"?>\n<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">\n<svg xmlns="http://www.w3.org/2000/svg" stroke="currentColor" fill="none" stroke-width="1" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round">\n <line x1="22" y1="2" x2="11" y2="14"></line>\n <polygon points="22 2 15 22 11 14 2 10 22 2"></polygon>\n</svg>\n';class Rs{static applyCustomStylesToDefault(t,e){var i,s;for(const n of Object.keys(t)){(i=t[n]).item??(i.item={});for(const i of["default","hover","click"])Hi.assignPropertyFromOneToAnother(i,t[n].item,null==(s=e[n])?void 0:s.item);Hi.assignPropertyFromOneToAnother("iconContainer",t[n],e[n]),Hi.assignPropertyFromOneToAnother("text",t[n],e[n])}}static createDropupStyles(t={}){return Rs.applyCustomStylesToDefault({default:{item:{}},active:{item:{}},disabled:{}},t),t}}const qs=class t{static addItemEvents(t,e,i,s){j.add(e,s),e.addEventListener("click",(()=>{i.click()})),e.addEventListener("mouseenter",(e=>{t.highlightedItem=e.target})),e.addEventListener("mouseleave",(()=>{t.highlightedItem=void 0}))}static createItemText(t,e){const i=document.createElement("div");return Object.assign(i.style,e),i.classList.add("dropup-menu-item-text"),i.textContent=t||"File",i}static createItemIcon(t,e){const i=document.createElement("div");return Object.assign(i.style,e),i.classList.add("dropup-menu-item-icon"),i.appendChild(t.children[0]),i}static populateItem(e,i,s,n){const o=e.children[0];o.classList.contains("text-button")?i.appendChild(t.createItemText(o.textContent,null==n?void 0:n.text)):(i.appendChild(t.createItemIcon(e,null==n?void 0:n.iconContainer)),i.appendChild(t.createItemText(s,null==n?void 0:n.text)))}static createItem(e,s,n){var o;const{elementRef:r,dropupText:a}=s,l=document.createElement("div");if(Object.assign(l.style,null==(o=null==n?void 0:n.item)?void 0:o.default),t.populateItem(r,l,a,n),l.classList.add(t.MENU_ITEM_CLASS),r.classList.contains(Fs.BUTTON_CLASS))s.setDropupItem(l);else{const s=i.processStateful((null==n?void 0:n.item)||{});t.addItemEvents(e,l,r,s)}return l}};qs.MENU_ITEM_CLASS="dropup-menu-item",qs.DISABLED_ITEM_CLASS="dropup-menu-item-disabled",qs.ACTIVE_ITEM_CLASS="dropup-menu-item-active";let Bs=qs;const Ls=class t extends Ji{constructor(e,i){var s,n;const o=(null==(s=null==e?void 0:e.dropupItem)?void 0:s.text)||`Custom ${i}`;super(t.createButtonElement(),null==e?void 0:e.position,null==e?void 0:e.styles,o),this._state="default",this._innerElements=this.createInnerElements(this._customStyles),this._onClick=e.onClick,this._dropupStyles=Rs.createDropupStyles(null==(n=e.dropupItem)?void 0:n.styles),this.setSetState(e),this.addClickListener(),this.changeState(e.initialState,!0)}static createButtonElement(){const e=document.createElement("div");return e.classList.add("input-button"),e.classList.add(t.BUTTON_CLASS),e}createInnerElements(t){var e,i,s,n;const o=Ze.createSVGElement(Ns);o.id="submit-icon";const r=null!=(i=null==(e=null==t?void 0:t.default)?void 0:e.svg)&&i.content?Ze.createSVGElement(null==(n=null==(s=null==t?void 0:t.default)?void 0:s.svg)?void 0:n.content):o;return{default:this.createInnerElement(r,"default",t),active:this.createInnerElement(r,"active",t),disabled:this.createInnerElement(r,"disabled",t)}}createInnerElement(t,e,i){return Di.createSpecificStateElement(this.elementRef,e,i)||t}setSetState(t){t.setState={setDefault:()=>{this.changeToDefault()},setActive:()=>{this.changeToActive()},setDisabled:()=>{this.changeToDisabled()}}}addClickListener(){this.elementRef.addEventListener("click",(()=>{var t;const e=null==(t=this._onClick)?void 0:t.call(this,this._state);("default"===e||"active"===e||"disabled"===e)&&this.changeState(e)}))}changeState(t,e){"disabled"===t?this.changeToDisabled(e):"active"===t?this.changeToActive(e):this.changeToDefault(e)}assignDropupItemStyle(t){var e;this.elementRef.parentElement&&this._originalElementRef&&(this.elementRef=P.replaceElementWithNewClone(this.elementRef,this._originalElementRef)),Object.assign(this.elementRef.style,null==(e=null==t?void 0:t.item)?void 0:e.default);const s=i.processStateful((null==t?void 0:t.item)||{});j.add(this.elementRef,s),this.addClickListener();const n=this.elementRef.children[0];n.classList.contains("text-button")||Object.assign(n.style,null==t?void 0:t.iconContainer)}changeToDefault(t){var e,i,s,n;!t&&"default"===this._state||(this.elementRef.classList.contains(Bs.MENU_ITEM_CLASS)?(this.assignDropupItemStyle(this._dropupStyles.default),this.elementRef.classList.remove(Bs.DISABLED_ITEM_CLASS),this.elementRef.classList.remove(Bs.ACTIVE_ITEM_CLASS)):(this.elementRef.replaceChildren(this._innerElements.default),null!=(e=this._customStyles)&&e.active&&$i.unsetAllCSS(this.elementRef,null==(i=this._customStyles)?void 0:i.active),null!=(s=this._customStyles)&&s.disabled&&$i.unsetAllCSS(this.elementRef,null==(n=this._customStyles)?void 0:n.disabled),this.reapplyStateStyle("default",["active","disabled"])),Fi.removeAriaDisabled(this.elementRef),this._state="default")}changeToActive(t){!t&&"active"===this._state||(this.elementRef.classList.contains(Bs.MENU_ITEM_CLASS)?(this.assignDropupItemStyle(this._dropupStyles.active),this.elementRef.classList.remove(Bs.DISABLED_ITEM_CLASS),this.elementRef.classList.add(Bs.ACTIVE_ITEM_CLASS)):(this.elementRef.replaceChildren(this._innerElements.active),this.reapplyStateStyle("active",["disabled","default"])),Fi.removeAriaDisabled(this.elementRef),this._state="active")}changeToDisabled(t){var e,i,s,n;!t&&"disabled"===this._state||(this.elementRef.classList.contains(Bs.MENU_ITEM_CLASS)?(this.assignDropupItemStyle(this._dropupStyles.disabled),this.elementRef.classList.remove(Bs.ACTIVE_ITEM_CLASS),this.elementRef.classList.add(Bs.DISABLED_ITEM_CLASS)):(this.elementRef.replaceChildren(this._innerElements.disabled),null!=(e=this._customStyles)&&e.active&&$i.unsetAllCSS(this.elementRef,null==(i=this._customStyles)?void 0:i.active),null!=(s=this._customStyles)&&s.default&&$i.unsetAllCSS(this.elementRef,null==(n=this._customStyles)?void 0:n.default),this.reapplyStateStyle("disabled",["default","active"])),Fi.addAriaDisabled(this.elementRef),this._state="disabled")}setDropupItem(t){this.elementRef=t,this._originalElementRef=t.cloneNode(!0),this.changeState(this._state,!0)}};Ls.INDICATOR_PREFIX="custom",Ls.BUTTON_CLASS="custom-button";let Fs=Ls;class zs{static focusItemWhenOnEdge(t,e){const i=e?t.children[0]:t.children[t.children.length-1];zs.focusSiblingItem(i,t,e,!0)}static focusSiblingItem(t,e,i,s=!1){const n=s?t:t[i?"nextSibling":"previousSibling"];n?(t.dispatchEvent(new MouseEvent("mouseleave")),n.dispatchEvent(new MouseEvent("mouseenter"))):(t.dispatchEvent(new MouseEvent("mouseleave")),zs.focusItemWhenOnEdge(e,i))}}class Ds{constructor(t,e){var i;this._isOpen=!0,this._styles=e,this.elementRef=Ds.createElement(null==(i=this._styles)?void 0:i.container),this.close(),setTimeout((()=>this.addWindowEvents(t)))}static createElement(t){const e=document.createElement("div");return e.id="dropup-menu",Object.assign(e.style,t),e}open(){this.elementRef.style.display="block",this._isOpen=!0}close(){this._isOpen&&(this.elementRef.style.display="none",this._isOpen=!1)}toggle(){this._isOpen?this.close():this.open()}addItem(t){const e=Bs.createItem(this,t,this._styles);this.elementRef.appendChild(e)}addWindowEvents(t){this.clickEvent=this.windowClick.bind(this,t),window.addEventListener("click",this.clickEvent),this.keyDownEvent=this.windowKeyDown.bind(this,t),window.addEventListener("keydown",this.keyDownEvent)}windowClick(t,e){var i;!t.isConnected&&this.clickEvent?window.removeEventListener("click",this.clickEvent):t.parentElement!==(null==(i=e.target.shadowRoot)?void 0:i.children[0])&&this.close()}windowKeyDown(t,e){var i,s,n;!t.isConnected&&this.keyDownEvent?window.removeEventListener("keydown",this.keyDownEvent):this._isOpen&&(e.key===c.ESCAPE?(this.close(),null==(i=this.highlightedItem)||i.dispatchEvent(new MouseEvent("mouseleave"))):e.key===c.ENTER?(null==(s=this.highlightedItem)||s.click(),null==(n=this.highlightedItem)||n.dispatchEvent(new MouseEvent("mouseleave"))):e.key===c.ARROW_DOWN?zs.focusSiblingItem(this.highlightedItem||this.elementRef.children[this.elementRef.children.length-1],this.elementRef,!0):e.key===c.ARROW_UP&&zs.focusSiblingItem(this.highlightedItem||this.elementRef.children[0],this.elementRef,!1))}}const $s=class t extends Ji{constructor(e,i){var s;super(t.createButtonElement(),void 0,{styles:null==(s=null==i?void 0:i.button)?void 0:s.styles});const n=this.createInnerElements(this._customStyles);this._menu=new Ds(e,null==i?void 0:i.menu),this.addClickEvent(),this.buttonContainer=t.createButtonContainer(),this.elementRef.appendChild(n.styles),this.buttonContainer.appendChild(this.elementRef),this.elementRef.classList.add(t.BUTTON_ICON_CLASS,"upload-file-button"),this.elementRef.children[0].id="dropup-icon",this.buttonContainer.appendChild(this._menu.elementRef),this.reapplyStateStyle("styles"),this.addContainerEvents(e)}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}createInnerElements(e){return{styles:this.createInnerElement(t.createSVGIconElement(),"styles",e)}}createInnerElement(t,e,i){return Di.createSpecificStateElement(this.elementRef,e,i)||t}static createSVGIconElement(){return Ze.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <path d="M16 0c-8.836 0-16 7.163-16 16s7.163 16 16 16c8.837 0 16-7.163 16-16s-7.163-16-16-16zM16 30.032c-7.72 0-14-6.312-14-14.032s6.28-14 14-14 14 6.28 14 14-6.28 14.032-14 14.032zM23 15h-6v-6c0-0.552-0.448-1-1-1s-1 0.448-1 1v6h-6c-0.552 0-1 0.448-1 1s0.448 1 1 1h6v6c0 0.552 0.448 1 1 1s1-0.448 1-1v-6h6c0.552 0 1-0.448 1-1s-0.448-1-1-1z"></path>\n</svg>')}addClickEvent(){this.elementRef.onclick=this._menu.toggle.bind(this._menu)}static createButtonContainer(){const t=document.createElement("div");return t.id="dropup-container",t}addItem(t){this._menu.addItem(t)}addContainerEvents(e){e.addEventListener("click",(e=>{const i=e.target.classList;!i.contains(t.BUTTON_ICON_CLASS)&&!i.contains(Bs.DISABLED_ITEM_CLASS)&&this._menu.close()}))}static getPosition(t,e){var i,s;return null!=(i=null==e?void 0:e.button)&&i.position?null==(s=null==e?void 0:e.button)?void 0:s.position:t["outside-left"].length>0&&0===t["outside-right"].length?"outside-right":"outside-left"}};$s.BUTTON_ICON_CLASS="dropup-icon";let Js=$s;class Us{static addToDropup(t,e,i,s){const n=new Js(i,s);Ps.forEach((t=>{const i=e["dropup-menu"].findIndex((e=>e.buttonType===t)),s=e["dropup-menu"][i];s&&(n.addItem(s.button),e["dropup-menu"].splice(i,1))})),e["dropup-menu"].forEach((({button:t})=>n.addItem(t)));const o=Js.getPosition(e,s);Is.addButton(t,n.buttonContainer,o),e[o].push({})}static addToSideContainer(t,e){["inside-left","inside-right","outside-left","outside-right"].forEach((i=>{const s=i;e[s].forEach((e=>{Is.addButton(t,e.button.elementRef,s)}))}))}static setPosition(t,e,i){const s={...t[e],buttonType:e};i.push(s),delete t[e]}static createPositionsToButtonsObj(){return{"dropup-menu":[],"outside-left":[],"inside-left":[],"inside-right":[],"outside-right":[]}}static generatePositionToButtons(t){const e=Us.createPositionsToButtonsObj();Object.keys(t).forEach((i=>{var s;const n=null==(s=t[i])?void 0:s.button.position;n&&Us.setPosition(t,i,e[n])})),0===e["inside-right"].length&&t.submit&&Us.setPosition(t,"submit",e["inside-right"]),0===e["outside-right"].length&&(t.submit?Us.setPosition(t,"submit",e["outside-right"]):t.microphone?Us.setPosition(t,"microphone",e["outside-right"]):t.camera?Us.setPosition(t,"camera",e["outside-right"]):t[`${Fs.INDICATOR_PREFIX}1`]&&Us.setPosition(t,`${Fs.INDICATOR_PREFIX}1`,e["outside-right"])),t.submit&&Us.setPosition(t,"submit",0===e["outside-left"].length?e["outside-left"]:e["inside-right"]),t.microphone&&Us.setPosition(t,"microphone",0===e["outside-left"].length?e["outside-left"]:e["inside-right"]);const i=Object.keys(t);return i.length>1||e["dropup-menu"].length>0?(Ps.forEach((i=>{t[i]&&e["dropup-menu"].push({...t[i],buttonType:i})})),i.forEach((i=>{const s=i;s.startsWith(Fs.INDICATOR_PREFIX)&&t[s]&&e["dropup-menu"].push({...t[s],customType:s})}))):1===i.length&&Us.setPosition(t,i[0],0===e["outside-right"].length?e["outside-right"]:e["outside-left"]),e}static addButtons(t,e,i,s){const n=Us.generatePositionToButtons(e);return Us.addToSideContainer(t,n),n["dropup-menu"].length>0&&Us.addToDropup(t,n,i,s),n}}const Vs={images:{id:"upload-images-icon",svgString:'<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">\n <path d="M20,15.2928932 L20,5.5 C20,4.67157288 19.3284271,4 18.5,4 L5.5,4 C4.67157288,4 4,4.67157288 4,5.5 L4,12.2928932 L7.14644661,9.14644661 C7.34170876,8.95118446 7.65829124,8.95118446 7.85355339,9.14644661 L13.5,14.7928932 L16.1464466,12.1464466 C16.3417088,11.9511845 16.6582912,11.9511845 16.8535534,12.1464466 L20,15.2928932 Z M20,16.7071068 L16.5,13.2071068 L13.8535534,15.8535534 C13.6582912,16.0488155 13.3417088,16.0488155 13.1464466,15.8535534 L7.5,10.2071068 L4,13.7071068 L4,18.5 C4,19.3284271 4.67157288,20 5.5,20 L18.5,20 C19.3284271,20 20,19.3284271 20,18.5 L20,16.7071068 Z M3,5.5 C3,4.11928813 4.11928813,3 5.5,3 L18.5,3 C19.8807119,3 21,4.11928813 21,5.5 L21,18.5 C21,19.8807119 19.8807119,21 18.5,21 L5.5,21 C4.11928813,21 3,19.8807119 3,18.5 L3,5.5 Z M15,6 L17,6 C17.5522847,6 18,6.44771525 18,7 L18,9 C18,9.55228475 17.5522847,10 17,10 L15,10 C14.4477153,10 14,9.55228475 14,9 L14,7 C14,6.44771525 14.4477153,6 15,6 Z M15,7 L15,9 L17,9 L17,7 L15,7 Z"/>\n</svg>\n',dropupText:"Image"},gifs:{id:"upload-gifs-icon",svgString:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 5.9266752 5.6408391" height="21.31971" width="22.4">\n <g>\n <path d="m 5.2564627,1.548212 c -3.1136005,-0.4796804 -1.5568006,-0.2398402 0,0 z M 2.0001198,2.0922063 c 0.1556781,0 0.2657489,0.020893 0.3917849,0.080366 0.081154,0.038347 0.1153492,0.134065 0.076377,0.2138602 -0.038973,0.07979 -0.1363527,0.1134129 -0.2175069,0.075091 -0.078199,-0.036919 -0.1407455,-0.048792 -0.250655,-0.048792 -0.2260486,0 -0.3921482,0.2042182 -0.3921482,0.4801409 0,0.2761822 0.1663188,0.4810688 0.3921482,0.4810688 0.1117901,0 0.2064255,-0.046133 0.255659,-0.1284198 l 0.00162,-0.00389 V 3.0534032 l -0.098011,1.75e-4 c -0.081844,0 -0.1495979,-0.059305 -0.1612403,-0.1365887 l -0.00175,-0.023683 c 0,-0.08047 0.060311,-0.1470874 0.1389194,-0.1585331 l 0.024085,-0.00195 h 0.2612303 c 0.081842,0 0.149598,0.059305 0.1612404,0.1365891 l 0.00175,0.023683 -3.398e-4,0.3968809 v 0 l -0.00168,0.014211 v 0 l -0.00553,0.023034 v 0 l -0.00532,0.014145 c -0.098178,0.22826 -0.3236506,0.3528713 -0.5706303,0.3528713 -0.4240855,0 -0.7181621,-0.3622714 -0.7181621,-0.8016063 0,-0.4391857 0.2940275,-0.8006848 0.7181621,-0.8006848 z m 1.2034759,0.031275 c 0.081843,0 0.1495977,0.059305 0.1612403,0.1365891 l 0.00175,0.023683 v 1.2211775 c 0,0.088516 -0.07298,0.1602721 -0.1630073,0.1602721 -0.081841,0 -0.1495972,-0.059305 -0.1612397,-0.1365892 L 3.040589,3.5049308 V 2.2837527 c 0,-0.088516 0.07298,-0.1602721 0.1630067,-0.1602714 z m 0.7813442,0 0.5209469,0.00195 c 0.090025,3.048e-4 0.1627543,0.072306 0.1624458,0.1608234 -2.809e-4,0.08047 -0.06083,0.1468798 -0.1394772,0.158066 l -0.024092,0.00195 -0.3575326,-0.0013 v 0.4497782 l 0.2928918,2.27e-4 c 0.081842,0 0.1495979,0.059305 0.1612403,0.136589 l 0.00175,0.023683 c 0,0.080469 -0.06031,0.1470871 -0.1389193,0.1585393 l -0.024092,0.00195 -0.2928919,-2.336e-4 1.563e-4,0.2860316 c 0,0.080471 -0.06031,0.1470873 -0.1389193,0.1585395 l -0.024085,0.00195 c -0.081843,0 -0.1495979,-0.059305 -0.1612403,-0.1365826 l -0.00175,-0.023691 V 2.2841354 c 2.798e-4,-0.08047 0.060829,-0.1468797 0.1394758,-0.1580594 z"/>\n <path d="m 5.0894191,1.0943261 c 0,-0.21918999 -0.177687,-0.39686999 -0.396876,-0.39686999 h -3.43959 c -0.2191879,0 -0.391262,0.1777519 -0.3968759,0.39686999 l -0.027082,3.4379266 c 0.040152,0.2939927 0.4235456,0.409415 0.4235456,0.409415 l 3.4785583,-0.00851 c 0,0 0.3008506,-0.1402998 0.3236271,-0.4201576 0.042911,-0.5272495 0.034693,-1.6106146 0.034693,-3.4186761 z m -4.49792494,0 c 0,-0.36530999 0.29614504,-0.66145999 0.66145894,-0.66145999 h 3.43959 c 0.365314,0 0.66146,0.29615 0.66146,0.66145999 v 3.43959 c 0,0.36532 -0.296146,0.66146 -0.66146,0.66146 h -3.43959 c -0.3653139,0 -0.66145894,-0.29614 -0.66145894,-0.66146 z"/>\n </g>\n</svg>\n',dropupText:"GIF"},audio:{id:"upload-audio-icon",svgString:'<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="-49.49 -49.49 593.87 593.87" stroke-width="3.95908" transform="rotate(0)">\n <g stroke-width="0"></g>\n <g stroke-linecap="round" stroke-linejoin="round" stroke-width="0.98977"></g>\n <g>\n <g>\n <g>\n <path d="M163.205,76.413v293.301c-3.434-3.058-7.241-5.867-11.486-8.339c-21.38-12.452-49.663-15.298-77.567-7.846 c-49.038,13.096-80.904,54.519-71.038,92.337c4.019,15.404,14.188,28.221,29.404,37.087c13.553,7.894,29.87,11.933,47.115,11.933 c9.962,0,20.231-1.356,30.447-4.087c42.74-11.406,72.411-44.344,72.807-77.654h0.011v-0.162c0.002-0.166,0-0.331,0-0.496V187.072 l290.971-67.3v178.082c-3.433-3.055-7.238-5.863-11.481-8.334c-21.385-12.452-49.654-15.308-77.567-7.846 c-49.038,13.087-80.904,54.519-71.038,92.356c4.019,15.385,14.183,28.212,29.404,37.067c13.548,7.894,29.875,11.933,47.115,11.933 c9.962,0,20.231-1.356,30.452-4.087c42.74-11.413,72.411-44.346,72.804-77.654h0.004v-0.065c0.003-0.236,0.001-0.469,0-0.704V0 L163.205,76.413z M104.999,471.779c-22.543,6.038-45.942,3.846-62.572-5.846c-10.587-6.163-17.591-14.817-20.255-25.038 c-7.144-27.375,18.452-58.029,57.062-68.346c8.409-2.25,16.938-3.346,25.188-3.346c13.87,0,26.962,3.115,37.389,9.192 c10.587,6.163,17.591,14.817,20.255,25.029c0.809,3.102,1.142,6.248,1.139,9.4v0.321h0.014 C162.99,437.714,139.082,462.678,104.999,471.779z M182.898,166.853V92.067l290.971-67.298v74.784L182.898,166.853z M415.677,399.923c-22.558,6.038-45.942,3.837-62.587-5.846c-10.587-6.163-17.587-14.817-20.25-25.019 c-7.144-27.385,18.452-58.058,57.058-68.365c8.414-2.25,16.942-3.346,25.192-3.346c13.875,0,26.962,3.115,37.385,9.192 c10.596,6.163,17.596,14.817,20.26,25.029v0.01c0.796,3.05,1.124,6.144,1.135,9.244v0.468h0.02 C473.668,365.851,449.763,390.814,415.677,399.923z">\n </path>\n </g>\n </g>\n </g>\n</svg>',dropupText:"Audio"},mixedFiles:{id:"upload-mixed-files-icon",svgString:'<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n<title>file</title>\n<path d="M20 10.9696L11.9628 18.5497C10.9782 19.4783 9.64274 20 8.25028 20C6.85782 20 5.52239 19.4783 4.53777 18.5497C3.55315 17.6211 3 16.3616 3 15.0483C3 13.7351 3.55315 12.4756 4.53777 11.547L12.575 3.96687C13.2314 3.34779 14.1217 3 15.05 3C15.9783 3 16.8686 3.34779 17.525 3.96687C18.1814 4.58595 18.5502 5.4256 18.5502 6.30111C18.5502 7.17662 18.1814 8.01628 17.525 8.63535L9.47904 16.2154C9.15083 16.525 8.70569 16.6989 8.24154 16.6989C7.77738 16.6989 7.33224 16.525 7.00403 16.2154C6.67583 15.9059 6.49144 15.4861 6.49144 15.0483C6.49144 14.6106 6.67583 14.1907 7.00403 13.8812L14.429 6.88674" stroke="#000000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>',dropupText:"File"}};class Hs extends Ji{constructor(t){"dropup-menu"===(null==t?void 0:t.position)&&(t.position="outside-right"),super(Hs.createMicrophoneElement(),null==t?void 0:t.position,t),this.isActive=!1,this._innerElements=this.createInnerElements(this._customStyles),this.changeToDefault()}createInnerElements(t){const e=Hs.createSVGIconElement();return{default:this.createInnerElement(e,"default",t),active:this.createInnerElement(e,"active",t),unsupported:this.createInnerElement(e,"unsupported",t),commandMode:this.createInnerElement(e,"commandMode",t)}}createInnerElement(t,e,i){return Di.createSpecificStateElement(this.elementRef,e,i)||t}static createMicrophoneElement(){const t=document.createElement("div");return t.id="microphone-button",t.classList.add("input-button"),t}static createSVGIconElement(){const t=Ze.createSVGElement(zi);return t.id="microphone-icon",t}changeToActive(){this.elementRef.replaceChildren(this._innerElements.active),this.toggleIconFilter("active"),this.reapplyStateStyle("active",["default","commandMode"]),this.isActive=!0}changeToDefault(){this.elementRef.replaceChildren(this._innerElements.default),this.toggleIconFilter("default"),this.reapplyStateStyle("default",["active","commandMode"]),this.isActive=!1}changeToCommandMode(){this.elementRef.replaceChildren(this._innerElements.unsupported),this.toggleIconFilter("command"),this.reapplyStateStyle("commandMode",["active"])}changeToUnsupported(){this.elementRef.replaceChildren(this._innerElements.unsupported),this.elementRef.classList.add("unsupported-microphone"),this.reapplyStateStyle("unsupported",["active"])}toggleIconFilter(t){const e=this.elementRef.children[0];if("svg"===e.tagName.toLocaleLowerCase())switch(t){case"default":e.classList.remove("active-microphone-icon","command-microphone-icon"),e.classList.add("default-microphone-icon");break;case"active":e.classList.remove("default-microphone-icon","command-microphone-icon"),e.classList.add("active-microphone-icon");break;case"command":e.classList.remove("active-microphone-icon","default-microphone-icon"),e.classList.add("command-microphone-icon")}}}function Ks(t){return t&&t.h&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Gs,Zs,Ws,Xs={},Ys={},Qs={},tn={},en={};function sn(){if(Gs)return en;Gs=1,Object.defineProperty(en,"h",{value:!0}),en.Text=void 0;class t{static capitalize(e){return e.replace(t.FIRST_CHAR_REGEX,(t=>t.toUpperCase()))}static lineBreak(e){return e.replace(t.DOUBLE_LINE,"<p></p>").replace(t.ONE_LINE,"<br>")}static isCharDefined(t){return void 0!==t&&" "!==t&&" "!==t&&"\n"!==t&&""!==t}static breakupIntoWordsArr(t){return t.split(/(\W+)/)}}return en.Text=t,t.FIRST_CHAR_REGEX=/\S/,t.DOUBLE_LINE=/\n\n/g,t.ONE_LINE=/\n/g,en}function nn(){if(Zs)return tn;Zs=1,Object.defineProperty(tn,"h",{value:!0}),tn.Translate=void 0;const t=sn();return tn.Translate=class{static translate(e,i){const s=t.Text.breakupIntoWordsArr(e);for(let t=0;t<s.length;t+=1)i[s[t]]&&(s[t]=i[s[t]]);return s.join("")}},tn}var on,rn={};function an(){if(on)return rn;on=1,Object.defineProperty(rn,"h",{value:!0}),rn.Browser=void 0;class t{}return rn.Browser=t,t.IS_SAFARI=()=>(void 0===t._IS_SAFARI&&(t._IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),t._IS_SAFARI),rn}var ln,cn={},hn={};var un,dn={};var pn,mn={},vn={};function fn(){if(pn)return vn;pn=1,Object.defineProperty(vn,"h",{value:!0}),vn.AutoScroll=void 0;class t{static changeStateIfNeeded(t,e){e&&!t.isCursorAtEnd&&(t.endPadding="",t.scrollingSpan.innerHTML="&nbsp;")}static scrollGeneric(t,e){t.isCursorAtEnd?e.scrollTop=e.scrollHeight:t.scrollingSpan.scrollIntoView({block:"nearest"})}static scrollSafariPrimitiveToEnd(t){t.scrollLeft=t.scrollWidth,t.scrollTop=t.scrollHeight}static isElementOverflown(t){return t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth}static isRequired(e,i){return e&&t.isElementOverflown(i)}}return vn.AutoScroll=t,vn}var gn,bn={};function yn(){if(gn)return bn;gn=1,Object.defineProperty(bn,"h",{value:!0}),bn.Elements=void 0;return bn.Elements=class{static isPrimitiveElement(t){return"INPUT"===t.tagName||"TEXTAREA"===t.tagName}static createInterimSpan(){const t=document.createElement("span");return t.style.color="grey",t.style.pointerEvents="none",t}static createGenericSpan(){const t=document.createElement("span");return t.style.pointerEvents="none",t}static appendSpans(t,e){if(t.spansPopulated=!0,t.insertInCursorLocation&&document.activeElement===e){const e=window.getSelection();if(null!=e&&e.focusNode){const i=e.getRangeAt(0);return i.insertNode(t.scrollingSpan),i.insertNode(t.interimSpan),i.insertNode(t.finalSpan),i.collapse(!1),e.removeAllRanges(),void e.addRange(i)}}e.appendChild(t.finalSpan),e.appendChild(t.interimSpan),e.appendChild(t.scrollingSpan)}static applyCustomColors(t,e){e.interim&&(t.interimSpan.style.color=e.interim),e.final&&(t.finalSpan.style.color=e.final)}static isInsideShadowDOM(t){return t.getRootNode()instanceof ShadowRoot}},bn}var wn,xn,kn={};function _n(){if(wn)return kn;wn=1,Object.defineProperty(kn,"h",{value:!0}),kn.Cursor=void 0;class t{static setOffsetForGeneric(e,i,s=0){let n=0;for(let o=0;o<e.childNodes.length;o+=1){const r=e.childNodes[o];if(r.childNodes.length>0){const e=t.setOffsetForGeneric(r,i,s);if(-1===e)return-1;s+=e}else if(null!==r.textContent){if(s+r.textContent.length>i){const t=document.createRange();t.setStart(r,i-s),t.collapse(!0);const n=window.getSelection();return null==n||n.removeAllRanges(),null==n||n.addRange(t),e.focus(),-1}s+=r.textContent.length,n+=r.textContent.length}}return n}static focusEndOfGeneric(t){const e=document.createRange();e.selectNodeContents(t),e.collapse(!1);const i=window.getSelection();i&&(i.removeAllRanges(),i.addRange(e))}static setOffsetForSafariGeneric(e,i){const s=window.getSelection();if(s){const n=t.getGenericElementCursorOffset(e,s,!0);t.setOffsetForGeneric(e,n+i)}}static setOffsetForPrimitive(t,e,i){i&&t.blur(),t.setSelectionRange(e,e),t.focus()}static getGenericElementCursorOffset(t,e,i){let s=0;if(e.rangeCount>0){const n=e.getRangeAt(0),o=n.cloneRange();o.selectNodeContents(t),i?o.setEnd(n.startContainer,n.startOffset):o.setEnd(n.endContainer,n.endOffset),s=o.toString().length}return s}}return kn.Cursor=t,kn}function Sn(){if(xn)return mn;xn=1,Object.defineProperty(mn,"h",{value:!0}),mn.CommandUtils=void 0;const t=fn(),e=yn(),i=an(),s=_n(),n=sn();class o{static processCommand(t,e){return(!e||!e.caseSensitive)&&(t=t.toLowerCase()),!1===(null==e?void 0:e.substrings)?n.Text.breakupIntoWordsArr(t):t}static process(t){var e;return!0===(null===(e=t.settings)||void 0===e?void 0:e.caseSensitive)?t:Object.keys(t).reduce(((e,i)=>{const s=t[i];return e[i]="string"==typeof s?o.processCommand(s,t.settings):s,e}),{})}static toggleCommandModeOn(t){var e;t.isWaitingForCommand=!0,null===(e=t.onCommandModeTrigger)||void 0===e||e.call(t,!0)}static toggleCommandModeOff(t){var e;t.isWaitingForCommand&&(null===(e=t.onCommandModeTrigger)||void 0===e||e.call(t,!1),t.isWaitingForCommand=!1)}static setText(n,r,a,l){o.toggleCommandModeOff(n),e.Elements.isPrimitiveElement(l)?(l.value=a,n.isTargetInShadow||s.Cursor.setOffsetForPrimitive(l,a.length,!0),i.Browser.IS_SAFARI()&&n.autoScroll&&t.AutoScroll.scrollSafariPrimitiveToEnd(l)):(l.textContent=a,n.isTargetInShadow||s.Cursor.focusEndOfGeneric(l),setTimeout((()=>t.AutoScroll.scrollGeneric(n,l)))),n.resetRecording(r)}static checkIfMatchesSubstring(t,e){return e.includes(t)}static checkIfMatchesWord(t,e,i){const s=t;for(let t=i.length-1;t>=0;t-=1){let e=t,n=s.length-1;for(;i[e]===s[n]&&n>=0;)e-=1,n-=1;if(n<0)return!0}return!1}static execCommand(t,e,i,s,r){var a,l,c;const h=t.commands;if(!h||!s||!i)return;const u=!0===(null===(a=h.settings)||void 0===a?void 0:a.caseSensitive)?e:e.toLowerCase(),d=n.Text.breakupIntoWordsArr(u),p=!1===(null===(l=h.settings)||void 0===l?void 0:l.substrings)?o.checkIfMatchesWord:o.checkIfMatchesSubstring;if(h.commandMode&&p(h.commandMode,u,d))return t.setInterimColorToFinal(),setTimeout((()=>o.toggleCommandModeOn(t))),{doNotProcessTranscription:!1};if(!h.commandMode||t.isWaitingForCommand){if(h.stop&&p(h.stop,u,d))return o.toggleCommandModeOff(t),setTimeout((()=>t.stop())),{doNotProcessTranscription:!1};if(h.pause&&p(h.pause,u,d))return o.toggleCommandModeOff(t),t.setInterimColorToFinal(),setTimeout((()=>{var e;t.isPaused=!0,null===(e=t.onPauseTrigger)||void 0===e||e.call(t,!0)})),{doNotProcessTranscription:!1};if(h.resume&&p(h.resume,u,d))return t.isPaused=!1,null===(c=t.onPauseTrigger)||void 0===c||c.call(t,!1),o.toggleCommandModeOff(t),t.resetRecording(i),{doNotProcessTranscription:!0};if(h.reset&&p(h.reset,u,d))return void 0!==r&&o.setText(t,i,r,s),{doNotProcessTranscription:!0};if(h.removeAllText&&p(h.removeAllText,u,d))return o.setText(t,i,"",s),{doNotProcessTranscription:!0}}}}return mn.CommandUtils=o,mn}var An,Tn={};var Mn,On,jn,Cn={};function En(){if(On)return cn;On=1,Object.defineProperty(cn,"h",{value:!0}),cn.Speech=void 0;const t=function(){if(ln)return hn;ln=1,Object.defineProperty(hn,"h",{value:!0}),hn.EventListeners=void 0;class t{static getElementIfFocusedOnAvailable(t,e){return Array.isArray(t)?t.find((t=>e===t)):e===t?t:void 0}static keyDownWindow(e){e.element&&t.getElementIfFocusedOnAvailable(e.element,document.activeElement)&&(null!==t.KEY_DOWN_TIMEOUT&&clearTimeout(t.KEY_DOWN_TIMEOUT),t.KEY_DOWN_TIMEOUT=setTimeout((()=>{t.KEY_DOWN_TIMEOUT=null,this.resetRecording(e)}),500))}static mouseDownWindow(e,i){this.mouseDownElement=t.getElementIfFocusedOnAvailable(e,i.target)}static mouseUpWindow(t){this.mouseDownElement&&this.resetRecording(t),this.mouseDownElement=void 0}static add(e,i){const s=void 0===(null==i?void 0:i.insertInCursorLocation)||(null==i?void 0:i.insertInCursorLocation);null!=i&&i.element&&s&&(e.mouseDownEvent=t.mouseDownWindow.bind(e,i.element),document.addEventListener("mousedown",e.mouseDownEvent),e.mouseUpEvent=t.mouseUpWindow.bind(e,i),document.addEventListener("mouseup",e.mouseUpEvent),e.keyDownEvent=t.keyDownWindow.bind(e,i),document.addEventListener("keydown",e.keyDownEvent))}static remove(t){document.removeEventListener("mousedown",t.mouseDownEvent),document.removeEventListener("mouseup",t.mouseUpEvent),document.removeEventListener("keydown",t.keyDownEvent)}}return hn.EventListeners=t,t.KEY_DOWN_TIMEOUT=null,hn}(),e=(un||(un=1,Object.defineProperty(dn,"h",{value:!0}),dn.PreResultUtils=void 0,dn.PreResultUtils=class{static process(t,e,i,s,n){const o=null==s?void 0:s(e,i);return!!o&&(setTimeout((()=>{o.restart?t.resetRecording(n):o.stop&&t.stop()})),(o.stop||o.restart)&&o.removeNewText)}}),dn),i=Sn(),s=fn(),n=function(){if(An)return Tn;An=1,Object.defineProperty(Tn,"h",{value:!0}),Tn.Highlight=void 0;const t=yn(),e=_n();class i{static setStateForPrimitive(t,e){let i,s;null!==e.selectionStart&&(i=e.selectionStart),null!==e.selectionEnd&&(s=e.selectionEnd),t.isHighlighted=i!==s}static setStateForGeneric(t,i){const s=window.getSelection();if(null!=s&&s.focusNode){const n=e.Cursor.getGenericElementCursorOffset(i,s,!0),o=e.Cursor.getGenericElementCursorOffset(i,s,!1);t.isHighlighted=n!==o}}static setState(e,s){document.activeElement===s&&(t.Elements.isPrimitiveElement(s)?i.setStateForPrimitive(e,s):i.setStateForGeneric(e,s))}static removeForGeneric(t,i){const s=window.getSelection();if(s){const n=e.Cursor.getGenericElementCursorOffset(i,s,!0);s.deleteFromDocument(),e.Cursor.setOffsetForGeneric(i,n),t.isHighlighted=!1}}static removeForPrimitive(t,i){const s=i.selectionStart,n=i.selectionEnd,o=i.value;if(s&&n){const r=o.substring(0,s)+o.substring(n);i.value=r,e.Cursor.setOffsetForPrimitive(i,s,t.autoScroll)}t.isHighlighted=!1}}return Tn.Highlight=i,Tn}(),o=yn(),r=function(){if(Mn)return Cn;Mn=1,Object.defineProperty(Cn,"h",{value:!0}),Cn.Padding=void 0;const t=yn(),e=_n(),i=sn();class s{static setStateForPrimitiveElement(t,e){if(document.activeElement===e&&null!==e.selectionStart){const s=e.selectionStart,n=e.value[s-1],o=null===e.selectionEnd?s:e.selectionEnd,r=e.value[o];return i.Text.isCharDefined(n)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),i.Text.isCharDefined(r)&&(t.endPadding=" ",t.numberOfSpacesAfterNewText=1),void(t.isCursorAtEnd=e.value.length===o)}const s=e.value[e.value.length-1];i.Text.isCharDefined(s)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),t.isCursorAtEnd=!0}static setStateForGenericElement(t,s){var n,o,r;if(document.activeElement===s){const a=window.getSelection();if(null!=a&&a.focusNode){const l=e.Cursor.getGenericElementCursorOffset(s,a,!0),c=null===(n=s.textContent)||void 0===n?void 0:n[l-1],h=e.Cursor.getGenericElementCursorOffset(s,a,!1),u=null===(o=s.textContent)||void 0===o?void 0:o[h];return i.Text.isCharDefined(c)&&(t.startPadding=" "),i.Text.isCharDefined(u)&&(t.endPadding=" "),void(t.isCursorAtEnd=(null===(r=s.textContent)||void 0===r?void 0:r.length)===h)}}const a=s.innerText.charAt(s.innerText.length-1);i.Text.isCharDefined(a)&&(t.startPadding=" "),t.isCursorAtEnd=!0}static setState(e,i){t.Elements.isPrimitiveElement(i)?s.setStateForPrimitiveElement(e,i):s.setStateForGenericElement(e,i)}static adjustStateAfterRecodingPrimitiveElement(t,e){t.primitiveTextRecorded=!0,t.insertInCursorLocation&&document.activeElement===e&&(null!==e.selectionEnd&&(t.endPadding=t.endPadding+e.value.slice(e.selectionEnd)),null!==e.selectionStart)?t.startPadding=e.value.slice(0,e.selectionStart)+t.startPadding:t.startPadding=e.value+t.startPadding}static adjustSateForNoTextPrimitiveElement(t){1===t.numberOfSpacesBeforeNewText&&(t.startPadding=t.startPadding.substring(0,t.startPadding.length-1),t.numberOfSpacesBeforeNewText=0),1===t.numberOfSpacesAfterNewText&&(t.endPadding=t.endPadding.substring(1),t.numberOfSpacesAfterNewText=0)}}return Cn.Padding=s,Cn}(),a=an(),l=_n(),c=sn();return cn.Speech=class{constructor(){this.finalTranscript="",this.interimSpan=o.Elements.createInterimSpan(),this.finalSpan=o.Elements.createGenericSpan(),this.scrollingSpan=o.Elements.createGenericSpan(),this.isCursorAtEnd=!1,this.spansPopulated=!1,this.startPadding="",this.endPadding="",this.numberOfSpacesBeforeNewText=0,this.numberOfSpacesAfterNewText=0,this.isHighlighted=!1,this.primitiveTextRecorded=!1,this.recognizing=!1,this._displayInterimResults=!0,this.insertInCursorLocation=!0,this.autoScroll=!0,this.isRestarting=!1,this.isPaused=!1,this.isWaitingForCommand=!1,this.isTargetInShadow=!1,this.cannotBeStopped=!1,this.resetState()}prepareBeforeStart(e){var s,n;if(null!=e&&e.element)if(t.EventListeners.add(this,e),Array.isArray(e.element)){const t=e.element.find((t=>t===document.activeElement))||e.element[0];if(!t)return;this.prepare(t)}else this.prepare(e.element);void 0!==(null==e?void 0:e.displayInterimResults)&&(this._displayInterimResults=e.displayInterimResults),null!=e&&e.textColor&&(this._finalTextColor=null===(s=null==e?void 0:e.textColor)||void 0===s?void 0:s.final,o.Elements.applyCustomColors(this,e.textColor)),void 0!==(null==e?void 0:e.insertInCursorLocation)&&(this.insertInCursorLocation=e.insertInCursorLocation),void 0!==(null==e?void 0:e.autoScroll)&&(this.autoScroll=e.autoScroll),this._onResult=null==e?void 0:e.onResult,this._onPreResult=null==e?void 0:e.onPreResult,this._onStart=null==e?void 0:e.onStart,this._onStop=null==e?void 0:e.onStop,this._onError=null==e?void 0:e.onError,this.onCommandModeTrigger=null==e?void 0:e.onCommandModeTrigger,this.onPauseTrigger=null==e?void 0:e.onPauseTrigger,this._options=e,null!==(n=this._options)&&void 0!==n&&n.commands&&(this.commands=i.CommandUtils.process(this._options.commands))}prepare(t){r.Padding.setState(this,t),n.Highlight.setState(this,t),this.isTargetInShadow=o.Elements.isInsideShadowDOM(t),o.Elements.isPrimitiveElement(t)?(this._primitiveElement=t,this._originalText=this._primitiveElement.value):(this._genericElement=t,this._originalText=this._genericElement.textContent)}resetRecording(t){this.isRestarting=!0,this.stop(!0),this.resetState(!0),this.start(t,!0)}updateElements(t,s,n){var o;const r=c.Text.capitalize(s);if(this.finalTranscript===r&&""===t)return;e.PreResultUtils.process(this,n,""===t,this._onPreResult,this._options)&&(t="",n="");const a=this.commands&&i.CommandUtils.execCommand(this,n,this._options,this._primitiveElement||this._genericElement,this._originalText);if(a){if(a.doNotProcessTranscription)return;t="",n=""}if(this.isPaused||this.isWaitingForCommand)return;null===(o=this._onResult)||void 0===o||o.call(this,n,""===t),this.finalTranscript=r,this._displayInterimResults||(t="");const l=""===this.finalTranscript&&""===t;this._primitiveElement?this.updatePrimitiveElement(this._primitiveElement,t,l):this._genericElement&&this.updateGenericElement(this._genericElement,t,l)}updatePrimitiveElement(t,e,i){this.isHighlighted&&n.Highlight.removeForPrimitive(this,t),this.primitiveTextRecorded||r.Padding.adjustStateAfterRecodingPrimitiveElement(this,t),i&&r.Padding.adjustSateForNoTextPrimitiveElement(this);const o=this.startPadding+this.finalTranscript+e;if(t.value=o+this.endPadding,!this.isTargetInShadow){const e=o.length+this.numberOfSpacesAfterNewText;l.Cursor.setOffsetForPrimitive(t,e,this.autoScroll)}this.autoScroll&&a.Browser.IS_SAFARI()&&this.isCursorAtEnd&&s.AutoScroll.scrollSafariPrimitiveToEnd(t)}updateGenericElement(t,e,i){this.isHighlighted&&n.Highlight.removeForGeneric(this,t),this.spansPopulated||o.Elements.appendSpans(this,t);const r=(i?"":this.startPadding)+c.Text.lineBreak(this.finalTranscript);this.finalSpan.innerHTML=r;const h=s.AutoScroll.isRequired(this.autoScroll,t);s.AutoScroll.changeStateIfNeeded(this,h);const u=c.Text.lineBreak(e)+(i?"":this.endPadding);this.interimSpan.innerHTML=u,a.Browser.IS_SAFARI()&&this.insertInCursorLocation&&l.Cursor.setOffsetForSafariGeneric(t,r.length+u.length),h&&s.AutoScroll.scrollGeneric(this,t),i&&(this.scrollingSpan.innerHTML="")}finalise(e){this._genericElement&&(e?(this.finalSpan=o.Elements.createGenericSpan(),this.setInterimColorToFinal(),this.interimSpan=o.Elements.createInterimSpan(),this.scrollingSpan=o.Elements.createGenericSpan()):this._genericElement.textContent=this._genericElement.textContent,this.spansPopulated=!1),t.EventListeners.remove(this)}setInterimColorToFinal(){this.interimSpan.style.color=this._finalTextColor||"black"}resetState(t){this._primitiveElement=void 0,this._genericElement=void 0,this.finalTranscript="",this.finalSpan.innerHTML="",this.interimSpan.innerHTML="",this.scrollingSpan.innerHTML="",this.startPadding="",this.endPadding="",this.isHighlighted=!1,this.primitiveTextRecorded=!1,this.numberOfSpacesBeforeNewText=0,this.numberOfSpacesAfterNewText=0,t||(this.stopTimeout=void 0)}setStateOnStart(){var t;this.recognizing=!0,this.isRestarting?this.isRestarting=!1:null===(t=this._onStart)||void 0===t||t.call(this)}setStateOnStop(){var t;this.recognizing=!1,this.isRestarting||null===(t=this._onStop)||void 0===t||t.call(this)}setStateOnError(t){var e;null===(e=this._onError)||void 0===e||e.call(this,t),this.recognizing=!1}},cn}function In(){if(jn)return Ys;jn=1,Object.defineProperty(Ys,"h",{value:!0}),Ys.WebSpeech=void 0;const t=function(){if(Ws)return Qs;Ws=1,Object.defineProperty(Qs,"h",{value:!0}),Qs.WebSpeechTranscript=void 0;const t=nn();return Qs.WebSpeechTranscript=class{static extract(e,i,s){let n="";for(let o=e.resultIndex;o<e.results.length;++o){let r=e.results[o][0].transcript;s&&(r=t.Translate.translate(r,s)),e.results[o].isFinal?i+=r:n+=r}return{interimTranscript:n,finalTranscript:i,newText:n||i}}static extractSafari(e,i,s){let n="";for(let i=e.resultIndex;i<e.results.length;++i){let o=e.results[i][0].transcript;s&&(o=t.Translate.translate(o,s)),n+=o}return{interimTranscript:"",finalTranscript:n,newText:n}}},Qs}(),e=an(),i=En();class s extends i.Speech{constructor(){super()}start(i){var s;void 0===this._extractText&&(this._extractText=e.Browser.IS_SAFARI()?t.WebSpeechTranscript.extractSafari:t.WebSpeechTranscript.extract),this.validate()&&(this.prepareBeforeStart(i),this.instantiateService(i),null===(s=this._service)||void 0===s||s.start(),this._translations=null==i?void 0:i.translations)}validate(){return!!s.getAPI()||(this.error("Speech Recognition is unsupported"),!1)}instantiateService(t){var e,i;const n=s.getAPI();this._service=new n,this._service.continuous=!0,this._service.interimResults=null===(e=null==t?void 0:t.displayInterimResults)||void 0===e||e,this._service.lang=(null===(i=null==t?void 0:t.language)||void 0===i?void 0:i.trim())||"en-US",this.setEvents()}setEvents(){this._service&&(this._service.onstart=()=>{this.setStateOnStart()},this._service.onerror=t=>{e.Browser.IS_SAFARI()&&"Another request is started"===t.message||"aborted"===t.error&&this.isRestarting||"no-speech"!==t.error&&this.error(t.message||t.error)},this._service.onaudioend=()=>{this.setStateOnStop()},this._service.onend=()=>{this._stopping=!1},this._service.onresult=t=>{if(typeof t.results>"u"&&this._service)this._service.onend=null,this._service.stop();else if(this._extractText&&!this._stopping){const{interimTranscript:e,finalTranscript:i,newText:s}=this._extractText(t,this.finalTranscript,this._translations);this.updateElements(e,i,s)}})}stop(t){var e;this._stopping=!0,null===(e=this._service)||void 0===e||e.stop(),this.finalise(t)}static getAPI(){return window.webkitSpeechRecognition||window.SpeechRecognition}error(t){console.error(t),this.setStateOnError(t),this.stop()}}return Ys.WebSpeech=s,Ys}var Pn,Nn={};var Rn,qn={},Bn={};var Ln,Fn,zn={},Dn={};function $n(){if(Fn)return zn;Fn=1,Object.defineProperty(zn,"h",{value:!0}),zn.AzureSpeechConfig=void 0;const t=(Ln||(Ln=1,Object.defineProperty(Dn,"h",{value:!0}),Dn.README_URL=void 0,Dn.README_URL="https://github.com/OvidijusParsiunas/speech-to-element"),Dn);class e{static validateOptions(e,i){return i?i.subscriptionKey||i.token||i.retrieveToken?!!i.region||(e(`Please define a 'region' property - more info: ${t.README_URL}`),!1):(e(`Please define a 'subscriptionKey', 'token' or 'retrieveToken' property - more info: ${t.README_URL}`),!1):(e(`Please provide subscription details - more info: ${t.README_URL}`),!1)}static async getNewSpeechConfig(t,e){if(e.region)return e.subscriptionKey?t.fromSubscription(e.subscriptionKey.trim(),e.region.trim()):e.token?t.fromAuthorizationToken(e.token.trim(),e.region.trim()):e.retrieveToken?e.retrieveToken().then((i=>e.region?t.fromAuthorizationToken((null==i?void 0:i.trim())||"",e.region.trim()):null)).catch((t=>(console.error(t),null))):null}static process(t,e){e.endpointId&&(t.endpointId=e.endpointId.trim()),e.language&&(t.speechRecognitionLanguage=e.language.trim())}static async get(t,i){const s=await e.getNewSpeechConfig(t,i);return s&&e.process(s,i),s}}return zn.AzureSpeechConfig=e,zn}var Jn,Un={};var Vn,Hn={};var Kn,Gn,Zn,Wn={};function Xn(){if(Gn)return qn;Gn=1,Object.defineProperty(qn,"h",{value:!0}),qn.Azure=void 0;const t=(Rn||(Rn=1,Object.defineProperty(Bn,"h",{value:!0}),Bn.PreventConnectionStop=void 0,Bn.PreventConnectionStop=class{static applyPrevention(t){clearTimeout(t._manualConnectionStopPrevention),t.cannotBeStopped=!0,t._manualConnectionStopPrevention=setTimeout((()=>{t.cannotBeStopped=!1}),800)}static clearPrevention(t){clearTimeout(t._manualConnectionStopPrevention),t.cannotBeStopped=!1}}),Bn),e=$n(),i=function(){if(Jn)return Un;Jn=1,Object.defineProperty(Un,"h",{value:!0}),Un.StopTimeout=void 0;class t{static set(t){t.stopTimeout=setTimeout((()=>t.stop()),t.stopTimeoutMS)}static reset(e,i){e.stopTimeoutMS=i||t.DEFAULT_MS,t.stop(e),t.set(e)}static stop(t){t.stopTimeout&&clearTimeout(t.stopTimeout)}}return Un.StopTimeout=t,t.DEFAULT_MS=2e4,Un}(),s=(Vn||(Vn=1,Object.defineProperty(Hn,"h",{value:!0}),Hn.AzureAudioConfig=void 0,Hn.AzureAudioConfig=class{static get(t,e){return e?t.fromMicrophoneInput(e):t.fromDefaultMicrophoneInput()}}),Hn),n=function(){if(Kn)return Wn;Kn=1,Object.defineProperty(Wn,"h",{value:!0}),Wn.AzureTranscript=void 0;const t=nn();return Wn.AzureTranscript=class{static extract(e,i,s,n){return n&&(e=t.Translate.translate(e,n)),s?{interimTranscript:"",finalTranscript:i+e,newText:e}:{interimTranscript:e,finalTranscript:i,newText:e}}},Wn}(),o=En();class r extends o.Speech{constructor(){super(...arguments),this._newTextPadding=""}start(e,s){this._newTextPadding="",void 0===this.stopTimeout&&i.StopTimeout.reset(this,null==e?void 0:e.stopAfterSilenceMs),this.prepareBeforeStart(e),this.startAsync(e),s||t.PreventConnectionStop.applyPrevention(this)}async startAsync(t){var e;this.validate(t)&&(await this.instantiateService(t),this._translations=null==t?void 0:t.translations,null===(e=this._service)||void 0===e||e.startContinuousRecognitionAsync((()=>{}),this.error))}validate(t){return r.getAPI()?e.AzureSpeechConfig.validateOptions(this.error.bind(this),t):(this.moduleNotFound(),!1)}async instantiateService(t){const i=r.getAPI(),n=s.AzureAudioConfig.get(i.AudioConfig,t.deviceId),o=await e.AzureSpeechConfig.get(i.SpeechConfig,t);if(o){let e;if(t.autoLanguage&&t.autoLanguage.languages.length>0){const{type:s,languages:r}=t.autoLanguage,a=r.slice(0,"Continuous"===s?10:4),l=i.AutoDetectSourceLanguageConfig.fromLanguages(a);"Continuous"===s&&(l.mode=1),e=i.SpeechRecognizer.FromConfig(o,l,n)}else e=new i.SpeechRecognizer(o,n);this.setEvents(e),this._service=e,t.retrieveToken&&this.retrieveTokenInterval(t.retrieveToken)}else this.error("Unable to contact Azure server")}setEvents(t){t.recognizing=this.onRecognizing.bind(this),t.recognized=this.onRecognized.bind(this),t.sessionStarted=this.onSessionStarted.bind(this),t.canceled=this.onCanceled.bind(this),t.sessionStopped=this.onSessionStopped.bind(this)}onRecognizing(t,e){if(this._stopping)return;const{interimTranscript:s,finalTranscript:o,newText:r}=n.AzureTranscript.extract(this._newTextPadding+e.result.text,this.finalTranscript,!1,this._translations);i.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(s,o,r)}onRecognized(t,e){const s=e.result;switch(s.reason){case window.SpeechSDK.ResultReason.Canceled:break;case window.SpeechSDK.ResultReason.RecognizedSpeech:if(s.text&&!this._stopping){const{interimTranscript:t,finalTranscript:e,newText:o}=n.AzureTranscript.extract(this._newTextPadding+s.text,this.finalTranscript,!0,this._translations);i.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(t,e,o),""!==e&&(this._newTextPadding=" ")}}}onCanceled(t,e){e.reason===window.SpeechSDK.CancellationReason.Error&&this.error(e.errorDetails)}onSessionStarted(){t.PreventConnectionStop.clearPrevention(this),this.setStateOnStart()}onSessionStopped(){this._retrieveTokenInterval||clearInterval(this._retrieveTokenInterval),this._stopping=!1,this.setStateOnStop()}retrieveTokenInterval(t){this._retrieveTokenInterval=setInterval((()=>{null==t||t().then((t=>{this._service&&(this._service.authorizationToken=(null==t?void 0:t.trim())||"")})).catch((t=>{this.error(t)}))}),1e4)}stop(t){var e;!t&&this._retrieveTokenInterval&&clearInterval(this._retrieveTokenInterval),this._stopping=!0,null===(e=this._service)||void 0===e||e.stopContinuousRecognitionAsync(),i.StopTimeout.stop(this),this.finalise(t)}static getAPI(){return window.SpeechSDK}moduleNotFound(){console.error("speech recognition module not found:"),console.error("please install the 'microsoft-cognitiveservices-speech-sdk' npm package or add a script tag: <script src=\"https://aka.ms/csspeech/jsbrowserpackageraw\"><\/script>"),this.setStateOnError("speech recognition module not found")}error(t){this._retrieveTokenInterval&&clearInterval(this._retrieveTokenInterval),console.error(t),this.setStateOnError(t),this.stop()}}return qn.Azure=r,qn}const Yn=Ks(function(){if(Zn)return Xs;Zn=1,Object.defineProperty(Xs,"h",{value:!0});const t=In(),e=Sn(),i=function(){if(Pn)return Nn;Pn=1,Object.defineProperty(Nn,"h",{value:!0}),Nn.GlobalState=void 0;class t{static doubleClickDetector(){return!!t.doubleClickPending||(t.doubleClickPending=!0,setTimeout((()=>{t.doubleClickPending=!1}),300),!1)}}return Nn.GlobalState=t,t.doubleClickPending=!1,Nn}(),s=Xn();class n{static toggle(t,e){var s,o;const r=t.toLocaleLowerCase().trim();null!==(s=i.GlobalState.service)&&void 0!==s&&s.recognizing?this.stop():"webspeech"===r?n.startWebSpeech(e):"azure"===r?n.startAzure(e):(console.error("service not found - must be either 'webspeech' or 'azure'"),null===(o=null==e?void 0:e.onError)||void 0===o||o.call(e,"service not found - must be either 'webspeech' or 'azure'"))}static startWebSpeech(e){n.stop()||(i.GlobalState.service=new t.WebSpeech,i.GlobalState.service.start(e))}static isWebSpeechSupported(){return!!t.WebSpeech.getAPI()}static startAzure(t){var e;n.stop()||null!==(e=i.GlobalState.service)&&void 0!==e&&e.cannotBeStopped||(i.GlobalState.service=new s.Azure,i.GlobalState.service.start(t))}static stop(){var t;return!!i.GlobalState.doubleClickDetector()||(!(null===(t=i.GlobalState.service)||void 0===t)&&t.recognizing&&i.GlobalState.service.stop(),!1)}static endCommandMode(){i.GlobalState.service&&e.CommandUtils.toggleCommandModeOff(i.GlobalState.service)}}return Xs.default=n,Xs}());class Qn{constructor(t,e){this.silenceMS=2e3,this.stop=!0,"boolean"==typeof e&&!1===e&&(this.stop=!1),"number"==typeof t&&(this.silenceMS=t)}setSilenceTimeout(t,e){this._silenceTimeout=setTimeout((()=>{var i;null==(i=t.submit)||i.call(t),Yn.stop(),this.stop||setTimeout(e,eo.MICROPHONE_RESET_TIMEOUT_MS)}),this.silenceMS)}clearSilenceTimeout(){this._silenceTimeout&&clearTimeout(this._silenceTimeout)}resetSilenceTimeout(t,e){this.clearSilenceTimeout(),this.setSilenceTimeout(t,e)}onPause(t,e,i){t?this.resetSilenceTimeout(e,i):this.clearSilenceTimeout()}}const to=class t extends Hs{constructor(t,e,i){const s="object"==typeof t.speechToText?t.speechToText:{};super(null==s?void 0:s.button);const{serviceName:n,processedConfig:o}=this.processConfiguration(e,t.speechToText);if(this._addErrorMessage=i,"webspeech"!==n||Yn.isWebSpeechSupported()){const i=!t.textInput||!t.textInput.disabled;this.elementRef.onclick=this.buttonClick.bind(this,e,i,n,o)}else this.changeToUnsupported();setTimeout((()=>{this._validationHandler=t._validationHandler}))}processConfiguration(e,i){var s;const n="object"==typeof i?i:{},o="object"==typeof n.webSpeech?n.webSpeech:{},r=n.azure||{},a={displayInterimResults:n.displayInterimResults??void 0,textColor:n.textColor??void 0,translations:n.translations??void 0,commands:n.commands??void 0,events:n.events??void 0,...o,...r},l=null==(s=n.commands)?void 0:s.submit;return l&&(a.onPreResult=t=>t.toLowerCase().includes(l)?(setTimeout((()=>{var t;return null==(t=e.submit)?void 0:t.call(e)})),Yn.endCommandMode(),{restart:!0,removeNewText:!0}):null),n.submitAfterSilence&&(this._silenceSubmit=new Qn(n.submitAfterSilence,n.stopAfterSubmit)),{serviceName:t.getServiceName(n),processedConfig:a}}static getServiceName(t){return t.azure?"azure":"webspeech"}buttonClick(t,e,i,s){const n=null==s?void 0:s.events;t.removePlaceholderStyle(),Yn.toggle(i,{insertInCursorLocation:!1,element:e?t.inputElementRef:void 0,onError:()=>{var t;this.onError(),null==(t=this._silenceSubmit)||t.clearSilenceTimeout()},onStart:()=>{var t;this.changeToActive(),null==(t=null==n?void 0:n.onStart)||t.call(n)},onStop:()=>{var t,e,i;null==(t=this._validationHandler)||t.call(this),null==(e=this._silenceSubmit)||e.clearSilenceTimeout(),this.changeToDefault(),null==(i=null==n?void 0:n.onStop)||i.call(n)},onPauseTrigger:e=>{var i,s;null==(i=this._silenceSubmit)||i.onPause(e,t,this.elementRef.onclick),null==(s=null==n?void 0:n.onPauseTrigger)||s.call(n,e)},onPreResult:(t,e)=>{var i;null==(i=null==n?void 0:n.onPreResult)||i.call(n,t,e)},onResult:(e,i)=>{var s,o,r;i&&(null==(s=this._validationHandler)||s.call(this)),null==(o=this._silenceSubmit)||o.resetSilenceTimeout(t,this.elementRef.onclick),null==(r=null==n?void 0:n.onResult)||r.call(n,e,i)},onCommandModeTrigger:t=>{var e;this.onCommandModeTrigger(t),null==(e=null==n?void 0:n.onCommandModeTrigger)||e.call(n,t)},...s})}onCommandModeTrigger(t){t?this.changeToCommandMode():this.changeToActive()}onError(){this._addErrorMessage("speechToText","speech input error")}static toggleSpeechAfterSubmit(e,i=!0){e.click(),i||setTimeout((()=>e.click()),t.MICROPHONE_RESET_TIMEOUT_MS)}};to.MICROPHONE_RESET_TIMEOUT_MS=300;let eo=to;class io{constructor(t,e,i,s){this._attachments=[],this._fileCountLimit=99,this._acceptedFormat="",e.maxNumberOfFiles&&(this._fileCountLimit=e.maxNumberOfFiles),this._toggleContainerDisplay=i,this._fileAttachmentsContainerRef=s,e.acceptedFormats&&(this._acceptedFormat=e.acceptedFormats),setTimeout((()=>{this._validationHandler=t._validationHandler}))}attemptAddFile(t,e){return!!io.isFileTypeValid(t,this._acceptedFormat)&&(this.addAttachmentBasedOnType(t,e,!0),!0)}static isFileTypeValid(t,e){if(""===e)return!0;const i=e.split(",");for(let e=0;e<i.length;e++){const s=i[e].trim();if(t.type===s)return!0;if(s.startsWith(".")){const e=s.slice(1);if(t.name.endsWith(e))return!0}else{if(t.name.endsWith(s))return!0;if(s.endsWith("/*")&&t.type.startsWith(s.slice(0,-2)))return!0}}return!1}static getTypeFromBlob(t){const{type:e}=t;return e.startsWith("image")?"image":e.startsWith("audio")?"audio":"any"}addAttachmentBasedOnType(t,e,i){const s=io.getTypeFromBlob(t);if("image"===s){const s=io.createImageAttachment(e);this.addFileAttachment(t,"image",s,i)}else if("audio"===s){const s=no.createAudioAttachment(e);this.addFileAttachment(t,"audio",s,i)}else{const e=io.createAnyFileAttachment(t.name);this.addFileAttachment(t,"any",e,i)}}static createImageAttachment(t){const e=new Image;return e.src=t,e.classList.add("image-attachment"),e}static createAnyFileAttachment(t){const e=document.createElement("div");e.classList.add("border-bound-attachment"),l.IS_SAFARI&&e.classList.add("border-bound-attachment-safari");const i=document.createElement("div");i.classList.add("any-file-attachment-text");const s=document.createElement("div");return s.classList.add("file-attachment-text-container"),s.appendChild(i),i.textContent=t,e.appendChild(s),e}addFileAttachment(t,e,i,s){var n;const o=io.createContainer(i);if(this._attachments.length>=this._fileCountLimit){const t=this._attachments[this._attachments.length-1].removeButton;null==t||t.click();const e=this._fileAttachmentsContainerRef.children;this._fileAttachmentsContainerRef.insertBefore(o,e[0])}else this._fileAttachmentsContainerRef.appendChild(o);const r={file:t,attachmentContainerElement:o,fileType:e};return s&&(r.removeButton=this.createRemoveAttachmentButton(r),o.appendChild(r.removeButton)),this._toggleContainerDisplay(!0),this._attachments.push(r),this._fileAttachmentsContainerRef.scrollTop=this._fileAttachmentsContainerRef.scrollHeight,null==(n=this._validationHandler)||n.call(this),r}static createContainer(t){const e=document.createElement("div");return e.classList.add("file-attachment"),e.appendChild(t),e}createRemoveAttachmentButton(t){const e=document.createElement("div");e.classList.add("remove-file-attachment-button"),e.onclick=this.removeAttachment.bind(this,t);const i=document.createElement("div");return i.classList.add("x-icon"),i.innerText="×",e.appendChild(i),e}removeAttachment(t){var e;const i=this._attachments.findIndex((e=>e===t)),s=this._attachments[i].attachmentContainerElement;this._attachments.splice(i,1),no.stopAttachmentPlayback(s),s.remove(),this._toggleContainerDisplay(!1),null==(e=this._validationHandler)||e.call(this)}getFiles(){return Array.from(this._attachments).map((t=>({file:t.file,type:t.fileType})))}removeAllAttachments(){this._attachments.forEach((t=>{setTimeout((()=>{var e;return null==(e=t.removeButton)?void 0:e.click()}))}))}}const so=class t extends io{constructor(t,e,i,s){super(t,e,i,s)}static createAudioContainer(){const t=document.createElement("div");return t.classList.add("border-bound-attachment","audio-attachment-icon-container"),l.IS_SAFARI&&t.classList.add("border-bound-attachment-safari"),t}static addAudioElements(t,e){const i=t.parentElement?x.cloneElement(t):t,s=document.createElement("audio");s.src=e;const n=Ze.createSVGElement(Ki);n.classList.add("attachment-icon","play-icon");const o=Ze.createSVGElement(Gi);o.classList.add("attachment-icon","stop-icon"),i.replaceChildren(n),s.onplay=()=>{i.replaceChildren(o)},s.onpause=()=>{i.replaceChildren(n),s.currentTime=0},s.onended=()=>{i.replaceChildren(n)},i.onclick=()=>{s.paused?s.play():s.pause()}}static createAudioAttachment(e){const i=t.createAudioContainer();return t.addAudioElements(i,e),i}createTimer(e,i){let s=0;const n=void 0!==i&&i<t.TIMER_LIMIT_S?i:t.TIMER_LIMIT_S;return setInterval((()=>{var t;s+=1,s===n&&(null==(t=this.stopPlaceholderCallback)||t.call(this),this.clearTimer()),600===s&&e.classList.add("audio-placeholder-text-4-digits");const i=Math.floor(s/60),o=(s%60).toString().padStart(2,"0");e.textContent=`${i}:${o}`}),1e3)}createPlaceholderAudioAttachment(e){const i=t.createAudioContainer(),s=document.createElement("div");s.classList.add("audio-placeholder-text-3-digits");const n=document.createElement("div");n.classList.add("file-attachment-text-container","audio-placeholder-text-3-digits-container"),n.appendChild(s);const o=Ze.createSVGElement(Gi);return o.classList.add("attachment-icon","stop-icon","not-removable-attachment-icon"),s.textContent="0:00",this._activePlaceholderTimer=this.createTimer(s,e),i.appendChild(n),this.addPlaceholderAudioAttachmentEvents(i,o,n),i}addPlaceholderAudioAttachmentEvents(t,e,i){t.addEventListener("mouseenter",(()=>t.replaceChildren(e)));t.addEventListener("mouseleave",(()=>t.replaceChildren(i)));t.addEventListener("click",(()=>{var t;return null==(t=this.stopPlaceholderCallback)?void 0:t.call(this)}))}addPlaceholderAttachment(t,e){const i=this.createPlaceholderAudioAttachment(e);this._activePlaceholderAttachment=this.addFileAttachment(new File([],""),"audio",i,!1),this.stopPlaceholderCallback=t}completePlaceholderAttachment(e,i){const s=this._activePlaceholderAttachment;s&&(s.file=e,t.addAudioElements(s.attachmentContainerElement.children[0],i),s.removeButton=this.createRemoveAttachmentButton(s),s.attachmentContainerElement.appendChild(s.removeButton),this._activePlaceholderAttachment=void 0,this.clearTimer())}removePlaceholderAttachment(){this._activePlaceholderAttachment&&(this.removeAttachment(this._activePlaceholderAttachment),this._activePlaceholderAttachment=void 0,this.clearTimer())}clearTimer(){void 0!==this._activePlaceholderTimer&&(clearInterval(this._activePlaceholderTimer),this._activePlaceholderTimer=void 0,this.stopPlaceholderCallback=void 0)}static stopAttachmentPlayback(t){var e,i,s;null!=(s=null==(i=null==(e=t.children[0])?void 0:e.children)?void 0:i[0])&&s.classList.contains("stop-icon")&&t.children[0].click()}};so.TIMER_LIMIT_S=5999;let no=so;class oo{static create(t,e,i,s,n){return"audio"===n?new no(t,e,i,s):new io(t,e,i,s)}}class ro{constructor(t,e,i){this._fileAttachmentsTypes=[],this.elementRef=this.createAttachmentContainer();const s="object"==typeof i&&!!i.displayFileAttachmentContainer;this.toggleContainerDisplay(s),t.appendChild(this.elementRef),e&&Object.assign(this.elementRef.style,e)}addType(t,e,i){const s=oo.create(t,e,this.toggleContainerDisplay.bind(this),this.elementRef,i);return this._fileAttachmentsTypes.push(s),s}createAttachmentContainer(){const t=document.createElement("div");return t.id="file-attachment-container",t}toggleContainerDisplay(t){t?this.elementRef.style.display="block":0===this.elementRef.children.length&&(this.elementRef.style.display="none")}getAllFileData(){const t=this._fileAttachmentsTypes.map((t=>t.getFiles())).flat();return t.length>0?t:void 0}async completePlaceholders(){await Promise.all(this._fileAttachmentsTypes.map((async t=>{var e;return null==(e=t.stopPlaceholderCallback)?void 0:e.call(t)})))}static addFilesToType(t,e){t.forEach((t=>{const i=new FileReader;i.readAsDataURL(t),i.onload=i=>{for(let s=0;s<e.length&&!e[s].attemptAddFile(t,i.target.result);s+=1);}}))}addFilesToAnyType(t){ro.addFilesToType(t,this._fileAttachmentsTypes)}removeAllFiles(){this._fileAttachmentsTypes.forEach((t=>t.removeAllAttachments())),this.elementRef.replaceChildren(),this.toggleContainerDisplay(!1)}getNumberOfTypes(){return this._fileAttachmentsTypes.length}}const ao=class t{constructor(e,i,s){this._isOpen=!1,this._contentRef=t.createModalContent(i,null==s?void 0:s.backgroundColor),this._buttonPanel=t.createButtonPanel(null==s?void 0:s.backgroundColor),this._elementRef=t.createContainer(this._contentRef,s),this._elementRef.appendChild(this._buttonPanel),e.appendChild(this._elementRef),this._backgroundPanelRef=t.createDarkBackgroundPanel(),e.appendChild(this._backgroundPanelRef),this.addWindowEvents(e)}isOpen(){return this._isOpen}static createContainer(t,e){const i=document.createElement("div");return i.classList.add("modal"),i.appendChild(t),e&&delete e.backgroundColor,Object.assign(i.style,e),i}static createModalContent(t,e){const i=document.createElement("div");return i.classList.add(...t),e&&(i.style.backgroundColor=e),document.createElement("div").appendChild(i),i}static createButtonPanel(t){const e=document.createElement("div");return e.classList.add("modal-button-panel"),t&&(e.style.backgroundColor=t),e}static createDarkBackgroundPanel(){const t=document.createElement("div");return t.id="modal-background-panel",t}addButtons(...t){t.forEach((t=>{Fi.addAttributes(t),this._buttonPanel.appendChild(t)}))}static createTextButton(t){const e=document.createElement("div");return e.classList.add("modal-button"),e.textContent=t,e}static createSVGButton(t){const e=document.createElement("div");e.classList.add("modal-button","modal-svg-button");const i=Ze.createSVGElement(t);return i.classList.add("modal-svg-button-icon"),e.appendChild(i),e}close(){this._elementRef.classList.remove("show-modal"),this._elementRef.classList.add("hide-modal"),this._backgroundPanelRef.classList.remove("show-modal-background"),this._backgroundPanelRef.classList.add("hide-modal-background"),this._isOpen=!1,setTimeout((()=>{this._elementRef.style.display="none",this._backgroundPanelRef.style.display="none"}),t.MODAL_CLOSE_TIMEOUT_MS)}displayModalElements(){this._elementRef.style.display="flex",this._elementRef.classList.remove("hide-modal"),this._elementRef.classList.add("show-modal"),this._backgroundPanelRef.style.display="block",this._backgroundPanelRef.classList.remove("hide-modal-background"),this._backgroundPanelRef.classList.add("show-modal-background"),this._isOpen=!0}openTextModal(t){this._contentRef.innerHTML=t,this.displayModalElements()}addCloseButton(e,i,s){const n=i?t.createSVGButton(e):t.createTextButton(e);return this.addButtons(n),n.onclick=()=>{this.close(),setTimeout((()=>{null==s||s()}),140)},n}static createTextModalFunc(e,i,s){var n;if("object"==typeof i&&null!=(n=i.files)&&n.infoModal){const n=new t(e,["modal-content"],i.files.infoModal.containerStyle);return n.addCloseButton("OK",!1,s),n.openTextModal.bind(n,i.infoModalTextMarkUp||"")}}addWindowEvents(t){this.keyDownEvent=this.windowKeyDown.bind(this,t),window.addEventListener("keydown",this.keyDownEvent)}windowKeyDown(t,e){var i,s;!t.isConnected&&this.keyDownEvent?window.removeEventListener("keydown",this.keyDownEvent):this._isOpen&&(e.key===c.ESCAPE?(this.close(),null==(i=this.extensionCloseCallback)||i.call(this)):e.key===c.ENTER&&(this.close(),null==(s=this.extensionCloseCallback)||s.call(this)))}};ao.MODAL_CLOSE_TIMEOUT_MS=190;let lo=ao;class co extends Ji{constructor(t,e,i,s,n,o){var r,a,l,c,h,u,d,p,m;const v=null==(r=null==i?void 0:i.button)?void 0:r.position,f=(null==(c=null==(l=null==(a=null==i?void 0:i.button)?void 0:a.styles)?void 0:l.text)?void 0:c.content)||o;super(co.createButtonElement(),v,i.button,f);const g="dropup-menu"===v,b=this.createInnerElements(s,n,this._customStyles,g);this._inputElement=co.createInputElement(null==(h=null==i?void 0:i.files)?void 0:h.acceptedFormats),this.addClickEvent(t,i),this.elementRef.replaceChildren(b.styles),this.reapplyStateStyle("styles"),this._fileAttachmentsType=e,this._openModalOnce=!1===(null==(d=null==(u=i.files)?void 0:u.infoModal)?void 0:d.openModalOnce)||null==(m=null==(p=i.files)?void 0:p.infoModal)?void 0:m.openModalOnce}createInnerElements(t,e,i,s=!1){const n=co.createSVGIconElement(t,e);return{styles:Di.createInnerElement(this.elementRef,n,"styles",i,s)}}triggerImportPrompt(t){t.onchange=this.import.bind(this,t),t.click()}import(t){ro.addFilesToType(Array.from(t.files||[]),[this._fileAttachmentsType]),t.value=""}static createInputElement(t){const e=document.createElement("input");return e.type="file",e.accept=t||"",e.hidden=!0,e.multiple=!0,e}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button","upload-file-button"),t}static createSVGIconElement(t,e){const i=Ze.createSVGElement(e);return i.id=t,i}addClickEvent(t,e){const i=this.triggerImportPrompt.bind(this,this._inputElement),s=lo.createTextModalFunc(t,e,i);this.elementRef.onclick=this.click.bind(this,s)}click(t){!t||void 0!==this._openModalOnce&&!0!==this._openModalOnce?this.triggerImportPrompt(this._inputElement):(t(),!0===this._openModalOnce&&(this._openModalOnce=!1))}}class ho{static create(t,e,i){const s=ho.createElement(i);ho.addEvents(s,t,e),t.appendChild(s)}static createElement(t){const e=document.createElement("div");return e.id="drag-and-drop","object"==typeof t&&Object.assign(e.style,t),e}static addEvents(t,e,i){e.ondragenter=e=>{e.preventDefault(),ho.display(t)},t.ondragleave=e=>{e.preventDefault(),ho.hide(t)},t.ondragover=t=>{t.preventDefault()},t.ondrop=e=>{e.preventDefault(),ho.uploadFile(i,e),ho.hide(t)}}static uploadFile(t,e){var i;const s=null==(i=e.dataTransfer)?void 0:i.files;s&&t.addFilesToAnyType(Array.from(s))}static display(t){t.style.display="block"}static hide(t){t.style.display="none"}static isEnabled(t,e){return(void 0===e||!1!==e)&&(!!e||t.getNumberOfTypes()>0)}}class uo{static validate(t,e,i,s,n){const o=t(i,s,n);return o?e.changeToSubmitIcon():e.changeToDisabledIcon(),o}static async useValidationFunc(t,e,i,s){const n=e.isTextInputEmpty()?"":e.inputElementRef.textContent;await i.completePlaceholders();const o=i.getAllFileData(),r=null==o?void 0:o.map((t=>t.file));return uo.validate(t,s,n,r)}static async useValidationFuncProgrammatic(t,e,i){var s;const n=null==(s=e.files)?void 0:s.map((t=>t.file));return uo.validate(t,i,e.text,n,!0)}static validateWebsocket(t,e){const{websocket:i,connectSettings:s}=t;return!(i&&s.url!==qe.URL&&!Be.canSendMessage(i))||(e.changeToDisabledIcon(),!1)}static attach(t,e,i,s,n){const o=t.validateInput||O.processValidateInput(t);t._validationHandler=async t=>{if(n.status.loadingActive||n.status.requestInProgress||!0===e.isSubmitProgrammaticallyDisabled||!uo.validateWebsocket(e,n))return!1;const r=o||e.canSendMessage;return r?t?uo.useValidationFuncProgrammatic(r,t,n):uo.useValidationFunc(r,i,s,n):null}}}class po{static getFileName(t,e){const i=new Date;return`${t}-${String(i.getHours()).padStart(2,"0")}-${String(i.getMinutes()).padStart(2,"0")}-${String(i.getSeconds()).padStart(2,"0")}.${e}`}}class mo extends Hs{constructor(t,e){var i,s;super(e.button),this._waitingForBrowserApproval=!1,this._audioType=t,this._extension=(null==(i=e.files)?void 0:i.format)||"mp3",this._maxDurationSeconds=null==(s=e.files)?void 0:s.maxDurationSeconds,this.elementRef.onclick=this.buttonClick.bind(this)}buttonClick(){this._waitingForBrowserApproval||(this.isActive?this.stop():(this._waitingForBrowserApproval=!0,this.record()))}stop(){return new Promise((t=>{var e,i;this.changeToDefault(),null==(e=this._mediaRecorder)||e.stop(),null==(i=this._mediaStream)||i.getTracks().forEach((t=>t.stop())),setTimeout((()=>{t()}),10)}))}record(){navigator.mediaDevices.getUserMedia({audio:!0}).then((t=>{this.changeToActive(),this._mediaRecorder=new MediaRecorder(t),this._audioType.addPlaceholderAttachment(this.stop.bind(this),this._maxDurationSeconds),this._mediaStream=t,this._mediaRecorder.addEventListener("dataavailable",(t=>{this.createFile(t)})),this._mediaRecorder.start()})).catch((t=>{console.error(t),this.stop()})).finally((()=>{this._waitingForBrowserApproval=!1}))}createFile(t){const e=new Blob([t.data],{type:`audio/${this._extension}`}),i=po.getFileName(this._newFilePrefix||"audio",this._extension),s=new File([e],i,{type:e.type}),n=new FileReader;n.readAsDataURL(s),n.onload=t=>{this._audioType.completePlaceholderAttachment(s,t.target.result)}}}class vo{static resetSubmit(t,e){e?t.unsetCustomStateStyles(["loading","submit"]):t.unsetCustomStateStyles(["stop","loading","submit"]),t.reapplyStateStyle("submit")}static overwriteDefaultStyleWithSubmit(t,e){if(!t.submit)return;const i=JSON.parse(JSON.stringify(t[e]||{}));Hi.overwritePropertyObjectFromAnother(i,t.submit,["container","default"]),Hi.overwritePropertyObjectFromAnother(i,t.submit,["text","styles","default"]),Hi.overwritePropertyObjectFromAnother(i,t.submit,["svg","styles","default"]),t[e]=i}static setUpDisabledButton(t){Hi.setPropertyValueIfDoesNotExist(t,["submit","container","default","backgroundColor"],""),Hi.setPropertyValueIfDoesNotExist(t,["disabled","container","default","backgroundColor"],"unset"),Hi.setPropertyValueIfDoesNotExist(t.submit,["svg","styles","default","filter"],""),Hi.setPropertyValueIfDoesNotExist(t.disabled,["svg","styles","default","filter"],"brightness(0) saturate(100%) invert(70%) sepia(0%) saturate(5564%) hue-rotate(207deg) brightness(100%) contrast(97%)"),vo.overwriteDefaultStyleWithSubmit(t,"disabled")}static process(t){const e=JSON.parse(JSON.stringify(t||{}));return vo.overwriteDefaultStyleWithSubmit(e,"loading"),vo.overwriteDefaultStyleWithSubmit(e,"stop"),null!=t&&t.alwaysEnabled||vo.setUpDisabledButton(e),e}}const fo=class t extends Ji{constructor(e,i,s,n,o,r){const a=vo.process(e.submitButtonStyles);super(t.createButtonContainerElement(),null==a?void 0:a.position,a),this._isSVGLoadingIconOverriden=!1,this.status={requestInProgress:!1,loadingActive:!1},this._messages=s,this._textInput=i,this._fileAttachments=o,this._innerElements=this.createInnerElements(),this._abortStream=new AbortController,this._stopClicked={listener:()=>{}},this._serviceIO=n,this._alwaysEnabled=!(null==a||!a.alwaysEnabled),e.disableSubmitButton=this.disableSubmitButton.bind(this,n),this.attemptOverwriteLoadingStyle(e),r.microphone&&this.setUpSpeechToText(r.microphone.button,e.speechToText),setTimeout((()=>{var t;this._validationHandler=e._validationHandler,this.assignHandlers(this._validationHandler),null==(t=this._validationHandler)||t.call(this)}))}createInnerElements(){const{submit:e,loading:i,stop:s}=this.createCustomElements(),n=e||t.createSubmitIconElement();return{submit:n,loading:i||t.createLoadingIconElement(),stop:s||t.createStopIconElement(),disabled:this.createDisabledIconElement(n)}}createCustomElements(){const t=Di.createSpecificStateElement(this.elementRef,"submit",this._customStyles),e={loading:void 0,stop:void 0};return Object.keys(e).forEach((t=>{const i=t,s=Di.createCustomElement(i,this._customStyles);s&&(e[i]=s)})),e.submit=t,e}static createButtonContainerElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSubmitIconElement(){const t=Ze.createSVGElement(Ns);return t.id="submit-icon",t}static createLoadingIconElement(){const t=document.createElement("div");return t.classList.add("loading-submit-button"),t}static createStopIconElement(){const t=document.createElement("div");return t.id="stop-icon",t}createDisabledIconElement(t){return Di.createCustomElement("disabled",this._customStyles)||t.cloneNode(!0)}attemptOverwriteLoadingStyle(t){var e,i,s,n,o,r,a,l,c;if(!(null!=(i=null==(e=this._customStyles)?void 0:e.submit)&&i.svg||null!=(o=null==(n=null==(s=this._customStyles)?void 0:s.loading)?void 0:n.svg)&&o.content||null!=(l=null==(a=null==(r=this._customStyles)?void 0:r.loading)?void 0:a.text)&&l.content||void 0!==t.displayLoadingBubble&&!0!==t.displayLoadingBubble)){const e=document.createElement("style");e.textContent="\n .loading-button > * {\n filter: brightness(0) saturate(100%) invert(72%) sepia(0%) saturate(3044%) hue-rotate(322deg) brightness(100%)\n contrast(96%) !important;\n }",null==(c=t.shadowRoot)||c.appendChild(e),this._isSVGLoadingIconOverriden=!0}}assignHandlers(t){this._serviceIO.completionsHandlers={onFinish:this.resetSubmit.bind(this,t)},this._serviceIO.streamHandlers={onOpen:this.changeToStopIcon.bind(this),onClose:this.resetSubmit.bind(this,t),abortStream:this._abortStream,stopClicked:this._stopClicked};const{stream:e}=this._serviceIO;"object"==typeof e&&"number"==typeof e.simulation&&(this._serviceIO.streamHandlers.simulationInterim=e.simulation)}setUpSpeechToText(t,e){this._microphoneButton=t,this._stopSTTAfterSubmit="object"==typeof e&&e.stopAfterSubmit}resetSubmit(t){this.status.requestInProgress=!1,this.status.loadingActive=!1,t()}async submitFromInput(){await this._fileAttachments.completePlaceholders();const t=this._fileAttachments.getAllFileData();if(this._textInput.isTextInputEmpty())this.attemptSubmit({text:"",files:t});else{const e=this._textInput.inputElementRef.innerText.trim();this.attemptSubmit({text:e,files:t})}}async programmaticSubmit(t){"string"==typeof t&&(t=O.processSubmitUserMessage(t));const e={text:t.text};t.files&&(e.files=Array.from(t.files).map((t=>({file:t,type:io.getTypeFromBlob(t)})))),setTimeout((()=>this.attemptSubmit(e,!0)))}async attemptSubmit(t,e=!1){var i,s,n,o;if(!1===await(null==(i=this._validationHandler)?void 0:i.call(this,e?t:void 0)))return;this.changeToLoadingIcon(),this._textInput.clear(),"boolean"!=typeof this._messages.focusMode&&null!=(s=this._messages.focusMode)&&s.fade&&await me.fadeAnimation(this._messages.elementRef,this._messages.focusMode.fade),await this.addNewMessage(t),this._serviceIO.isWebModel()||this._messages.addLoadingMessage();const r=null==(n=t.files)?void 0:n.map((t=>t.file)),a={text:""===t.text?void 0:t.text,files:r};await this._serviceIO.callAPI(a,this._messages),null==(o=this._fileAttachments)||o.removeAllFiles()}async addNewMessage({text:t,files:e}){const i={role:Se.USER_ROLE};t&&(i.text=t),e&&(i.files=await this._messages.addMultipleFiles(e)),this._serviceIO.sessionId&&(i._sessionId=this._serviceIO.sessionId),Object.keys(i).length>0&&this._messages.addNewMessage(i)}stopStream(){var t;this._abortStream.abort(),null==(t=this._stopClicked)||t.listener(),this._validationHandler&&this.resetSubmit(this._validationHandler)}changeToStopIcon(){this._serviceIO.websocket||(this.elementRef.classList.remove(t.LOADING_CLASS,t.DISABLED_CLASS,t.SUBMIT_CLASS),Fi.removeAriaAttributes(this.elementRef),this.elementRef.replaceChildren(this._innerElements.stop),this.reapplyStateStyle("stop",["loading","submit"]),this.elementRef.onclick=this.stopStream.bind(this),this.status.loadingActive=!1)}changeToLoadingIcon(){this._serviceIO.websocket||(this._isSVGLoadingIconOverriden||this.elementRef.replaceChildren(this._innerElements.loading),this.elementRef.classList.remove(t.SUBMIT_CLASS,t.DISABLED_CLASS),Fi.removeAriaDisabled(this.elementRef),this.elementRef.classList.add(t.LOADING_CLASS),Fi.addAriaBusy(this.elementRef),this.reapplyStateStyle("loading",["submit"]),this.elementRef.onclick=()=>{},this.status.requestInProgress=!0,this.status.loadingActive=!0)}changeToSubmitIcon(){this.elementRef.classList.contains(t.SUBMIT_CLASS)||(this.elementRef.classList.remove(t.LOADING_CLASS,t.DISABLED_CLASS),Fi.removeAriaAttributes(this.elementRef),this.elementRef.classList.add(t.SUBMIT_CLASS),this.elementRef.replaceChildren(this._innerElements.submit),vo.resetSubmit(this,this.status.loadingActive),this.elementRef.onclick=()=>{var t;this.submitFromInput(),null!=(t=this._microphoneButton)&&t.isActive&&eo.toggleSpeechAfterSubmit(this._microphoneButton.elementRef,!!this._stopSTTAfterSubmit)})}changeToDisabledIcon(e=!1){this._alwaysEnabled&&!e?this.changeToSubmitIcon():this.elementRef.classList.contains(t.DISABLED_CLASS)||(this.elementRef.classList.remove(t.LOADING_CLASS,t.SUBMIT_CLASS),Fi.removeAriaBusy(this.elementRef),this.elementRef.classList.add(t.DISABLED_CLASS),Fi.addAriaDisabled(this.elementRef),this.elementRef.replaceChildren(this._innerElements.disabled),this.reapplyStateStyle("disabled",["submit"]),this.elementRef.onclick=()=>{})}disableSubmitButton(t,e){var i;t.isSubmitProgrammaticallyDisabled=!1!==e,!this.status.requestInProgress&&!this.status.loadingActive&&(!1===e?null==(i=this._validationHandler)||i.call(this):this.changeToDisabledIcon(!0))}};fo.SUBMIT_CLASS="submit-button",fo.LOADING_CLASS="loading-button",fo.DISABLED_CLASS="disabled-button";let go=fo;class bo extends lo{constructor(t,e,i,s){super(t,["modal-content","modal-camera-content"],i),this._stopped=!1,this._format="image/png",this._canvas=document.createElement("canvas"),this._canvas.classList.add("camera-modal-canvas");const{captureButton:n,submitButton:o}=this.addButtonsAndTheirEvents(e);this._captureButton=n,this._submitButton=o,this._captureIcon=this._captureButton.children[0],this._refreshIcon=Ze.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">\n <path d="M27.1 14.313V5.396L24.158 8.34c-2.33-2.325-5.033-3.503-8.11-3.503C9.902 4.837 4.901 9.847 4.899 16c.001 6.152 5.003 11.158 11.15 11.16 4.276 0 9.369-2.227 10.836-8.478l.028-.122h-3.23l-.022.068c-1.078 3.242-4.138 5.421-7.613 5.421a8 8 0 0 1-5.691-2.359A7.993 7.993 0 0 1 8 16.001c0-4.438 3.611-8.049 8.05-8.049 2.069 0 3.638.58 5.924 2.573l-3.792 3.789H27.1z"/>\n</svg>\n'),this._refreshIcon.classList.add("modal-svg-button-icon","modal-svg-refresh-icon"),"jpeg"===(null==s?void 0:s.format)&&(this._format="image/jpeg"),null!=s&&s.dimensions&&(this._dimensions=s.dimensions),this._contentRef.appendChild(this._canvas),this.extensionCloseCallback=this.stop}addButtonsAndTheirEvents(t){const e=lo.createSVGButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <title>capture</title>\n <path d="M0 16q0 3.264 1.28 6.208t3.392 5.12 5.12 3.424 6.208 1.248 6.208-1.248 5.12-3.424 3.392-5.12 1.28-6.208-1.28-6.208-3.392-5.12-5.088-3.392-6.24-1.28q-3.264 0-6.208 1.28t-5.12 3.392-3.392 5.12-1.28 6.208zM4 16q0-3.264 1.6-6.016t4.384-4.352 6.016-1.632 6.016 1.632 4.384 4.352 1.6 6.016-1.6 6.048-4.384 4.352-6.016 1.6-6.016-1.6-4.384-4.352-1.6-6.048z"></path>\n</svg>\n');e.classList.add("modal-svg-camera-button"),e.children[0].classList.add("modal-svg-camera-icon");const i=this.addCloseButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="M195.2 195.2a64 64 0 0 1 90.496 0L512 421.504 738.304 195.2a64 64 0 0 1 90.496 90.496L602.496 512 828.8 738.304a64 64 0 0 1-90.496 90.496L512 602.496 285.696 828.8a64 64 0 0 1-90.496-90.496L421.504 512 195.2 285.696a64 64 0 0 1 0-90.496z"/>\n</svg>',!0);i.classList.add("modal-svg-close-button"),i.children[0].classList.add("modal-svg-close-icon");const s=lo.createSVGButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M4.89163 13.2687L9.16582 17.5427L18.7085 8" stroke="#000000" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>');return s.classList.add("modal-svg-submit-button"),this.addButtons(e,s),this.addButtonEvents(e,i,s,t),{captureButton:e,submitButton:s}}addButtonEvents(t,e,i,s){t.onclick=()=>{this.capture()},e.addEventListener("click",this.stop.bind(this)),i.onclick=()=>{const t=this.getFile();t&&ro.addFilesToType([t],[s]),this.stop(),this.close()}}stop(){this._mediaStream&&this._mediaStream.getTracks().forEach((t=>t.stop())),this._stopped=!0,setTimeout((()=>{this._captureButton.replaceChildren(this._captureIcon),this._captureButton.classList.replace("modal-svg-refresh-button","modal-svg-camera-button");const t=this._canvas.getContext("2d");null==t||t.clearRect(0,0,this._canvas.width,this._canvas.height)}),lo.MODAL_CLOSE_TIMEOUT_MS)}start(){this._dataURL=void 0,this._submitButton.classList.add("modal-svg-submit-disabled"),this._stopped=!1,navigator.mediaDevices.getUserMedia({video:this._dimensions||!0}).then((t=>{if(this._mediaStream=t,!this.isOpen())return this.stop();const e=document.createElement("video");e.srcObject=t,e.play(),requestAnimationFrame(this.updateCanvas.bind(this,e,this._canvas))})).catch((t=>{console.error(t),this.stop(),this.close()}))}capture(){this._dataURL?(this._captureButton.replaceChildren(this._captureIcon),this._captureButton.classList.replace("modal-svg-refresh-button","modal-svg-camera-button"),this._submitButton.classList.add("modal-svg-submit-disabled"),this._dataURL=void 0):(this._captureButton.replaceChildren(this._refreshIcon),this._captureButton.classList.replace("modal-svg-camera-button","modal-svg-refresh-button"),this._submitButton.classList.remove("modal-svg-submit-disabled"),this._dataURL=this._canvas.toDataURL())}getFile(){if(this._dataURL){const t=atob(this._dataURL.split(",")[1]),e=new Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);const i=new Uint8Array(e),s=new Blob([i],{type:this._format}),n="image/jpeg"===this._format?"jpeg":"png",o=po.getFileName(this._newFilePrefix||"photo",n);return new File([s],o,{type:s.type})}}updateCanvas(t,e){if(!this._stopped){if(!this._dataURL){e.width=t.videoWidth,e.height=t.videoHeight;const i=e.getContext("2d");null==i||i.drawImage(t,0,0,e.width,e.height)}requestAnimationFrame(this.updateCanvas.bind(this,t,e))}}openCameraModal(t){this.displayModalElements(),t.start()}static createCameraModalFunc(t,e,i,s){const n=new bo(t,e,i,s);return n.openCameraModal.bind(n,n)}}class yo extends Ji{constructor(t,e,i){var s,n,o,r;const a=null==(s=null==i?void 0:i.button)?void 0:s.position,l=(null==(r=null==(o=null==(n=null==i?void 0:i.button)?void 0:n.styles)?void 0:o.text)?void 0:r.content)||"Photo";super(yo.createButtonElement(),a,(null==i?void 0:i.button)||{},l);const c=this.createInnerElements(this._customStyles,"dropup-menu"===a);i&&this.addClickEvent(t,e,i.modalContainerStyle,i.files),this.elementRef.classList.add("upload-file-button"),this.elementRef.appendChild(c.styles),this.reapplyStateStyle("styles")}createInnerElements(t,e=!1){return{styles:Di.createInnerElement(this.elementRef,yo.createSVGIconElement(),"styles",t,e)}}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSVGIconElement(){const t=Ze.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <path d="M29 7h-4.599l-2.401-4h-12l-2.4 4h-4.6c-1 0-3 1-3 2.969v16.031c0 1.657 1.5 3 2.792 3h26.271c1.313 0 2.938-1.406 2.938-2.968v-16.032c0-1-1-3-3-3zM30 26.032c0 0.395-0.639 0.947-0.937 0.969h-26.265c-0.232-0.019-0.797-0.47-0.797-1v-16.031c0-0.634 0.851-0.953 1-0.969h5.732l2.4-4h9.802l1.785 3.030 0.55 0.97h5.731c0.705 0 0.99 0.921 1 1v16.032zM16 10c-3.866 0-7 3.134-7 7s3.134 7 7 7 7-3.134 7-7-3.134-7-7-7zM16 22c-2.757 0-5-2.243-5-5s2.243-5 5-5 5 2.243 5 5-2.243 5-5 5z"></path>\n</svg>');return t.id="camera-icon",t}addClickEvent(t,e,i,s){const n=bo.createCameraModalFunc(t,e,i,s);this.elementRef.onclick=n}}class wo{constructor(t,e,i,s){var n;this.elementRef=wo.createPanelElement(t.inputAreaStyle);const o={},r=this.createFileUploadComponents(t,i,s,o),a=new m(t,i,r);t.speechToText&&!o.microphone&&(o.microphone={button:new eo(t,a,e.addNewErrorMessage.bind(e))});const l=new go(t,a,e,i,r,o);a.submit=l.submitFromInput.bind(l),uo.attach(t,i,a,r,l),t.submitUserMessage=l.programmaticSubmit.bind(l),o.submit={button:l},null==(n=t.customButtons)||n.forEach(((t,e)=>{o[`${Fs.INDICATOR_PREFIX}${e+1}`]={button:new Fs(t,e)}})),wo.addElements(this.elementRef,a,o,s,r,t.dropupStyles)}static createPanelElement(t){const e=document.createElement("div");return e.id="input",Object.assign(e.style,t),e}createFileUploadComponents(t,e,i,s){var n,o,r,a;const l=new ro(this.elementRef,t.attachmentContainerStyle,e.demo);if(wo.createUploadButtons(t,e.fileTypes||{},l,i,s),null!=(n=e.camera)&&n.files){const n=(null==(o=s.images)?void 0:o.fileType)||l.addType(t,e.camera.files,"images");s.camera={button:new yo(i,n,e.camera)}}if(null!=(r=e.recordAudio)&&r.files){const i=(null==(a=s.audio)?void 0:a.fileType)||l.addType(t,e.recordAudio.files,"audio");s.microphone={button:new mo(i,e.recordAudio)}}return ho.isEnabled(l,t.dragAndDrop)&&ho.create(i,l,t.dragAndDrop),l}static createUploadButtons(t,e,i,s,n){Object.keys(e).forEach((o=>{const r=o,a=e[r];if(a.files){const e=i.addType(t,a.files,r),{id:o,svgString:l,dropupText:c}=Vs[r],h=new co(s,e,a,o,l,c);n[r]={button:h,fileType:e}}}))}static addElements(t,e,i,s,n,o){x.addElements(t,e.elementRef);const r=Is.create(),a=Us.addButtons(r,i,s,o);Es.set(e.inputElementRef,r,n.elementRef,a),Is.add(t,r)}}class xo{static createElements(t,e,i){const s=document.createElement("div");s.id="chat-view";const n=new js(t,e,i);e.websocket&&Be.createConnection(e,n);const o=new wo(t,n,e,s);return x.addElements(s,n.elementRef,o.elementRef),s}static render(t,e,i,s){const n=xo.createElements(t,i,s);e.replaceChildren(n),i.isCustomView()&&i.setUpView(n,e)}}var ko=Object.defineProperty,_o=(t,e,i,s)=>{for(var n,o=void 0,r=t.length-1;r>=0;r--)(n=t[r])&&(o=n(e,i,o)||o);return o&&ko(e,i,o),o};class So extends Ge{constructor(){super(),this.getMessages=()=>[],this.submitUserMessage=()=>console.warn("submitUserMessage failed - please wait for chat view to render before calling this property."),this.addMessage=()=>console.warn("addMessage failed - please wait for chat view to render before calling this property."),this.updateMessage=()=>{},this.clearMessages=()=>{},this.focusInput=()=>v.focusFromParentElement(this._elementRef),this.refreshMessages=()=>{},this.scrollToBottom=()=>{},this.disableSubmitButton=()=>{},this.setPlaceholderText=()=>{},this._hasBeenRendered=!1,this._auxiliaryStyleApplied=!1,this._elementRef=document.createElement("div"),this._elementRef.id="container",this.attachShadow({mode:"open"}).appendChild(this._elementRef),r.apply('#validate-property-key-view{height:100%;position:relative;display:flex;justify-content:center;align-items:center;padding:8px}#loading-validate-key-property{display:inline-block;width:50px;height:50px}#loading-validate-key-property:after{content:" ";display:block;width:38px;height:38px;margin:1px;border-radius:50%;border:5px solid #5fb2ff;border-color:#5fb2ff transparent #5fb2ff transparent;animation:loading-spinner 1.4s linear infinite}#deep-chat-openai-realtime-container{height:100%;width:100%}#deep-chat-openai-realtime-avatar-container{height:60%;width:100%;display:flex;justify-content:center;align-items:center}#deep-chat-openai-realtime-avatar{border-radius:50%;height:110px;border:1px solid rgb(215,215,215);padding:8px;-webkit-user-select:none;user-select:none;margin-top:20px}#deep-chat-openai-realtime-buttons-container{height:40%;display:flex;position:relative}.deep-chat-openai-realtime-button-container{height:100%;width:50%;display:flex;justify-content:center;align-items:center}.deep-chat-openai-realtime-button{width:70px;height:70px;border-radius:50%;display:flex;justify-content:center;align-items:center;cursor:pointer}.deep-chat-openai-realtime-button-default{background-color:#e3e3e3}.deep-chat-openai-realtime-button-default:hover{background-color:#d4d4d4}.deep-chat-openai-realtime-button-default:active{background-color:#c5c5c5}.deep-chat-openai-realtime-button-loading{opacity:.7;pointer-events:none}.deep-chat-openai-realtime-mute-active{background-color:#ffe7e7}.deep-chat-openai-realtime-mute-active:hover{background-color:#ffdede}.deep-chat-openai-realtime-mute-active:active{background-color:#ffd2d2}.deep-chat-openai-realtime-mute>*{height:30px;width:30px}.deep-chat-openai-realtime-mute-active>*{filter:brightness(0) saturate(100%) invert(35%) sepia(60%) saturate(1360%) hue-rotate(325deg) brightness(95%) contrast(92%)}.deep-chat-openai-realtime-toggle>*{height:32px;width:32px;padding-left:3px;filter:brightness(0) saturate(100%) invert(22%) sepia(0%) saturate(4537%) hue-rotate(208deg) brightness(105%) contrast(91%)}.deep-chat-openai-realtime-button-unavailable{opacity:.45;pointer-events:none}#deep-chat-openai-realtime-error{color:red;position:absolute;top:calc(50% + 40px);left:50%;transform:translate(-50%,-50%);font-size:17px}#deep-chat-openai-realtime-loading{position:absolute;font-size:15px;top:50%;left:50%;transform:translate(-50%,-50%)}#insert-key-view{height:100%;position:relative}#insert-key-contents{text-align:center;position:absolute;top:44%;left:50%;transform:translate(-50%,-50%);width:82%;display:flex;max-width:700px}#insert-key-title{margin-bottom:15px}#insert-key-input-container{margin-right:2.7em;width:calc(100% - 80px)}#insert-key-input{padding:.3em 1.7em .3em .3em;border-width:1px;border-style:solid;border-radius:3px;width:100%;font-size:inherit}.insert-key-input-valid{border-color:gray}.insert-key-input-invalid{border-color:red}#visibility-icon-container{position:relative;float:right;cursor:pointer;-webkit-user-select:none;user-select:none}.visibility-icon{filter:brightness(0) saturate(100%) invert(63%) sepia(1%) saturate(9%) hue-rotate(43deg) brightness(98%) contrast(92%);position:absolute;right:-1.7em;top:-1.43em}#visible-icon{top:-1.4em}.visibility-icon:hover{filter:unset}.visibility-icon>*{pointer-events:none}#start-button{border:1px solid grey;color:#454545;border-radius:4px;width:3em;display:flex;justify-content:center;align-items:center;cursor:pointer;padding:.28em .3em;-webkit-user-select:none;user-select:none;background-color:#fff}#start-button:hover{background-color:#f2f2f2}#start-button:active{background-color:#d2d2d2}#insert-key-help-text-container{width:100%;position:absolute;margin-top:32px;margin-bottom:20px}#insert-key-help-text-contents{width:100%;position:absolute}#insert-key-input-invalid-text{display:block;margin-top:1em;margin-bottom:.5em;color:red}.insert-key-input-help-text{display:block;margin-top:16px}#loading-key{display:inline-block;width:16px;height:16px}#loading-key:after{content:" ";display:block;width:11px;height:11px;margin:1px;border-radius:50%;border:2px solid #0084ff;border-color:#0084ff transparent #0084ff transparent;animation:loading-spinner 1.2s linear infinite}#error-view{color:red;font-size:1.2em;line-height:1.3em;margin-top:-5px;text-align:center;height:100%;display:flex;justify-content:center;align-items:center;padding-left:8px;padding-right:8px}@keyframes loading-spinner{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.intro-panel{position:absolute;display:flex;justify-content:center;right:0;bottom:0;left:0;margin:auto;height:fit-content;top:-2.5em}#internal-intro-panel{width:250px;height:min-content;display:block;border-radius:5px;overflow:auto;border:1px solid rgb(203,203,203);padding:10px;max-height:calc(100% - 6.8em)}#internal-intro-panel>p{margin-block-start:.8em;margin-block-end:.8em}pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}/*!\n Theme: a11y-dark\n Author: @ericwbailey\n Maintainer: @ericwbailey\n\n Based on the Tomorrow Night Eighties theme: https://github.com/isagalaev/highlight.js/blob/master/src/styles/tomorrow-night-eighties.css\n*/.hljs{background:#2b2b2b;color:#f8f8f2}.hljs-comment,.hljs-quote{color:#d4d0ab}.hljs-deletion,.hljs-name,.hljs-regexp,.hljs-selector-class,.hljs-selector-id,.hljs-tag,.hljs-template-variable,.hljs-variable{color:#ffa07a}.hljs-built_in,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-type{color:#f5ab35}.hljs-attribute{color:gold}.hljs-addition,.hljs-bullet,.hljs-string,.hljs-symbol{color:#abe338}.hljs-section,.hljs-title{color:#00e0e0}.hljs-keyword,.hljs-selector-tag{color:#dcc6e0}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}@media screen and (-ms-high-contrast: active){.hljs-addition,.hljs-attribute,.hljs-built_in,.hljs-bullet,.hljs-comment,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-quote,.hljs-string,.hljs-symbol,.hljs-type{color:highlight}.hljs-keyword,.hljs-selector-tag{font-weight:700}}#messages{overflow:auto}.outer-message-container:last-child{margin-bottom:5px}.inner-message-container{display:flex;margin-left:auto;margin-right:auto;width:calc(97.5% - 24px);max-width:100%}.message-bubble{margin-top:10px;word-wrap:break-word;width:fit-content;max-width:60%;border-radius:10px;padding:.42em .55em;height:fit-content;line-height:1.26em}.user-message-text{color:#fff;background-color:#0084ff;margin-right:0;margin-left:auto}.ai-message-text{color:#000;background-color:#e4e6eb;margin-left:0;margin-right:auto}.deep-chat-last-group-messages-active{height:100%}.loading-history-message-full-view{position:absolute;height:70%;width:100%;display:flex;align-items:center}.loading-history-message-small{height:20px;margin-bottom:30px}.loading-history-message-small>div>div{scale:.6}.loading-history-message{margin-top:0;width:100%;max-width:100%;display:flex;justify-content:center;background-color:unset}.loading-history{width:70px}.loading-history div{position:absolute;width:var(--loading-history-width);height:var(--loading-history-height);margin:var(--loading-history-margin);border:var(--loading-history-border);border-radius:50%;animation:loading-spinner 1.2s cubic-bezier(.5,0,.5,1) infinite;border-color:var(--loading-history-color) transparent transparent transparent}.loading-history div:nth-child(1){animation-delay:-.45s}.loading-history div:nth-child(2){animation-delay:-.3s}.loading-history div:nth-child(3){animation-delay:-.15s}.html-message{max-width:unset}.error-message-text{margin:14px auto 10px;background-color:#f4c0c0;color:#474747;text-align:center;max-width:95%}.deep-chat-loading-message-dots-container{width:1em;padding:.6em .75em .6em 1.3em}.loading-message-dots{position:relative;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite linear alternate;animation-delay:.5s}.loading-message-dots:before,.loading-message-dots:after{content:"";display:inline-block;position:absolute;top:0}.loading-message-dots:before{left:-.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite alternate;animation-delay:0s}.loading-message-dots:after{left:.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite alternate;animation-delay:1s}@keyframes loading-message-dots{0%{background-color:var(--loading-message-color)}50%,to{background-color:var(--loading-message-color-fade)}}.message-bubble>p:first-child{margin-top:0}.message-bubble>p:last-child{margin-bottom:0}pre{overflow:auto;display:block;word-break:break-all;word-wrap:break-word;border-radius:7px;background:#2b2b2b;color:#f8f8f2;margin-top:.8em;margin-bottom:.8em;padding:.6em;font-size:.9em;line-height:1.5em}.image-message{padding:0;display:flex;background-color:#ddd}.image-message>*,.image-message>*>*{width:100%;border-radius:8px;display:flex}.audio-message{width:60%;max-width:300px;height:2.2em;max-height:54px;padding:0;background-color:unset}.audio-player{width:100%;height:100%}.audio-player-safari{height:fit-content;width:40px}.audio-player-safari-left{float:left}.audio-player-safari-right{float:right}.any-file-message{padding:1px}.any-file-message-contents{display:flex}.any-file-message-icon-container{width:1.3em;min-width:1.3em;position:relative;border-radius:4px;margin-left:6px;margin-right:2px}.any-file-message-icon{background-color:#fff;border-radius:4px;position:absolute;width:1em;height:1.25em;padding:1px;margin-top:auto;margin-bottom:auto;top:0;bottom:0}.any-file-message-text{padding-top:5px;overflow-wrap:anywhere;padding-bottom:5px;padding-right:7px}.message-bubble>a{color:inherit}.left-item-position{margin-right:10px}.right-item-position{margin-left:10px}.avatar{padding-top:5px;width:1.5em;height:1.5em;border-radius:1px}.avatar-container{margin-top:9px}.name{margin-top:16px;font-size:15px}#drag-and-drop{position:absolute;display:none;z-index:10;height:calc(100% - 10px);width:calc(100% - 10px);background-color:#70c6ff4d;border:5px dashed #6dafff}#file-attachment-container{position:absolute;height:3.6em;width:calc(80% - 4px);top:-2.5em;border-radius:5px;overflow:auto;text-align:left;background-color:#d7d7d73b;padding-left:4px}.file-attachment{width:2.85em;height:2.85em;display:inline-flex;margin-right:.6em;margin-bottom:.44em;margin-top:4px;position:relative;background-color:#fff;border-radius:5px}.image-attachment{width:100%;height:100%;object-fit:cover;border-radius:5px}.border-bound-attachment{width:calc(100% - 2px);height:calc(100% - 2px);border:1px solid #c3c3c3;border-radius:5px;overflow:hidden}.border-bound-attachment-safari{width:calc(100% - 1px);height:calc(100% - 1px)}.audio-attachment-icon-container{cursor:pointer}.audio-attachment-icon-container:hover{background-color:#f8f8f8}.attachment-icon{left:0;right:0;bottom:0;top:2px;margin:auto;position:absolute;width:25px;-webkit-user-select:none;user-select:none}.not-removable-attachment-icon{top:0;right:0;bottom:0;left:0}.play-icon{filter:brightness(0) saturate(100%) invert(17%) sepia(0%) saturate(1392%) hue-rotate(67deg) brightness(98%) contrast(97%)}.stop-icon{filter:brightness(0) saturate(100%) invert(29%) sepia(90%) saturate(1228%) hue-rotate(198deg) brightness(93%) contrast(98%)}.audio-placeholder-text-3-digits{padding-left:.26rem}.audio-placeholder-text-4-digits{padding-left:.1rem}.any-file-attachment{padding:2px 0}.file-attachment-text-container{position:absolute;width:inherit;display:flex;align-items:center;height:100%;top:-1px}.audio-placeholder-text-3-digits-container{padding-top:1px;cursor:default}.any-file-attachment-text{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;padding-left:.13em;margin-left:auto;margin-right:auto}.remove-file-attachment-button{height:1.25em;width:1.25em;border:1px solid #cfcfcf;border-radius:25px;background-color:#fff;top:-4px;right:-5px;position:absolute;display:flex;justify-content:center;cursor:pointer;-webkit-user-select:none;user-select:none}.remove-file-attachment-button:hover{background-color:#e4e4e4}.remove-file-attachment-button:active{background-color:#d7d7d7}.x-icon{color:#4e4e4e;top:-.075em;position:relative;font-size:1.05em}.modal{display:none;flex-direction:column;align-items:center;justify-content:center;position:absolute;width:80%;max-width:420px;max-height:80%;margin:auto;top:0;right:0;bottom:0;left:0;z-index:2}.modal-content{border-top:1px solid rgb(217,217,217);border-left:1px solid rgb(217,217,217);border-right:1px solid rgb(217,217,217);border-top-left-radius:inherit;border-top-right-radius:inherit;background-color:#fff;overflow-y:auto;height:fit-content;max-height:calc(100% - 3.3em);width:100%}.modal-content>p{margin-left:1em;margin-right:1em}.modal-content>ul{margin-right:1em}.modal-button-panel{height:3.3em;border:1px solid;border-color:rgb(223,223,223) rgb(217,217,217) rgb(217,217,217);border-bottom-left-radius:inherit;border-bottom-right-radius:inherit;background-color:#fff;text-align:center;justify-content:center;display:flex;width:100%}.modal-button{min-width:2.5em;text-align:center;color:#fff;border-radius:5px;padding:.4em .4em .3em;height:1.25em;background-color:#3279b2;top:0;bottom:0;cursor:pointer;-webkit-user-select:none;user-select:none;margin:auto .31em}.modal-button:hover{background-color:#276da7}.modal-button:active{background-color:#1b5687}.modal-svg-button{padding:0 0 2px;width:2em;height:1.8em}.modal-svg-button-icon{width:100%;height:100%;filter:brightness(0) saturate(100%) invert(100%) sepia(15%) saturate(4%) hue-rotate(346deg) brightness(101%) contrast(102%)}#modal-background-panel{position:absolute;width:100%;height:100%;background-color:#00000042;z-index:1;display:none}.show-modal-background{animation:fadeInBackground .3s ease-in-out}@keyframes fadeInBackground{0%{opacity:0}to{opacity:1}}.show-modal{animation:fadeInModal .3s ease-in-out}@keyframes fadeInModal{0%{opacity:0;scale:.95}to{opacity:1;scale:1}}.hide-modal-background{animation:fadeOutBackground .2s ease-in-out}@keyframes fadeOutBackground{0%{opacity:1}to{opacity:0}}.hide-modal{animation:fadeOutModal .2s ease-in-out}@keyframes fadeOutModal{0%{opacity:1;scale:1}to{opacity:0;scale:.95}}.modal-camera-content{overflow:hidden;text-align:center;border:unset;height:100%;background-color:#2a2a2a;display:flex;justify-content:center}.camera-modal-canvas{max-width:100%;max-height:100%;margin-top:auto;margin-bottom:auto}.modal-svg-submit-button{background-color:green}.modal-svg-submit-button:hover{background-color:#007500}.modal-svg-submit-button:active{background-color:#006500}.modal-svg-submit-disabled{pointer-events:none;background-color:#747474}.modal-svg-close-button{height:1.56em;padding-top:.37em;padding-bottom:0;background-color:#c13e3e}.modal-svg-close-button:hover{background-color:#b43434}.modal-svg-close-button:active{background-color:#972929}.modal-svg-close-icon{width:80%;height:80%}.modal-svg-camera-button{height:1.6em;padding-top:.38em;padding-bottom:0}.modal-svg-camera-icon{height:76%}.modal-svg-refresh-icon{height:105%}.modal-svg-refresh-button{height:1.66em;padding-top:.11em;padding-bottom:.21em}.input-button-container{position:relative;z-index:1}.inside-right{position:absolute;right:calc(10% + .35em);bottom:.85em}.inside-left{position:absolute;left:calc(10% + .35em);bottom:.85em}.outside-left{position:absolute;right:calc(11px - .55em);bottom:.88em}.outside-right{position:absolute;left:calc(11px - .55em);bottom:.88em}#upload-images-icon{position:absolute;pointer-events:none;width:1.45em;height:1.45em;left:.11em;bottom:.08em;filter:brightness(0) saturate(100%) invert(43%) sepia(0%) saturate(740%) hue-rotate(77deg) brightness(99%) contrast(92%)}#upload-gifs-icon{position:absolute;pointer-events:none;width:1.5em;height:1.48em;left:.07em;bottom:.08em;filter:brightness(0) saturate(100%) invert(49%) sepia(0%) saturate(2586%) hue-rotate(12deg) brightness(93%) contrast(90%)}#upload-audio-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.17em;bottom:.2em;filter:brightness(0) saturate(100%) invert(15%) sepia(0%) saturate(337%) hue-rotate(125deg) brightness(91%) contrast(94%);transform:scaleX(.95)}#camera-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.23em;bottom:.2em;filter:brightness(0) saturate(100%) invert(52%) sepia(0%) saturate(161%) hue-rotate(164deg) brightness(91%) contrast(92%);transform:scaleX(.95)}#upload-mixed-files-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.2em;filter:brightness(0) saturate(100%) invert(53%) sepia(0%) saturate(36%) hue-rotate(74deg) brightness(98%) contrast(93%);transform:scaleX(.95)}#interim-text{color:gray}#microphone-button{padding-top:.5px}.outer-button-container>#microphone-button{padding-bottom:1px}#microphone-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.25em}.default-microphone-icon{filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%)}.active-microphone-icon{filter:brightness(0) saturate(100%) invert(10%) sepia(97%) saturate(7495%) hue-rotate(0deg) brightness(101%) contrast(107%);border-radius:10px}.command-microphone-icon{filter:brightness(0) saturate(100%) invert(42%) sepia(96%) saturate(1067%) hue-rotate(77deg) brightness(99%) contrast(102%)}.unsupported-microphone{display:none}#submit-icon{height:100%;filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%);width:1.21em}#stop-icon{background-color:#acacac;position:absolute;width:.95em;height:.95em;left:.35em;bottom:.35em;border-radius:2px}.submit-button-enlarged{scale:1.1;margin-right:.3em;margin-left:.3em}.loading-submit-button{position:relative;left:calc(-9990px + .275em);width:.22em;height:.22em;border-radius:5px;background-color:#848484;color:#848484;box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484;animation:loading-submit-button 1.5s infinite linear;bottom:-.75em}@keyframes loading-submit-button{0%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}16.667%{box-shadow:9990px -6px #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}33.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}50%{box-shadow:9990px 0 #848484,calc(9990px + .44em) -6px 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}66.667%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}83.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) -6px 0 0 #848484}to{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}}.input-button{border-radius:4px;cursor:pointer;margin-bottom:.2em;-webkit-user-select:none;user-select:none}.input-button-svg{width:1.65em;height:1.65em}.input-button:hover,.input-button:focus-visible{background-color:#9c9c9c2e}.input-button:active{background-color:#9c9c9c5e}.input-button:active:not(:hover){background-color:transparent}.loading-button{cursor:auto}.loading-button:hover{background-color:unset}.text-button{filter:unset!important;display:flex;justify-content:center;align-items:center;margin-left:4px;margin-right:4px;height:1.6em}#text-input-container{background-color:#fff;width:80%;display:flex;border:1px solid #0000001a;border-radius:5px;margin-top:.8em;margin-bottom:.8em;box-shadow:#959da533 0 1px 12px;overflow-y:auto;max-height:200px;position:relative}.text-input-container-left-adjustment{margin-left:1.5em}.text-input-container-right-adjustment{margin-right:1.5em}.text-input-container-left-small-adjustment{margin-left:1.1em}.text-input-container-left-small-adjustment>.outside-left{right:calc(14px - .55em)}.text-input-container-right-small-adjustment{margin-right:1.1em}.text-input-container-right-small-adjustment>.outside-right{left:calc(14px - .55em)}#text-input{text-align:left;outline:none;word-wrap:break-word;line-break:auto}.text-input-styling{padding:.4em .5em;overflow:overlay;width:100%}.text-input-inner-left-adjustment{padding-left:2.2em}.text-input-inner-right-adjustment{padding-right:2em}.text-input-disabled{pointer-events:none;-webkit-user-select:none;user-select:none}[contenteditable]:empty:before{content:attr(deep-chat-placeholder-text);pointer-events:none}[contenteditable][textcolor]:empty:before{color:gray}.outside-right>#dropup-menu,.inside-right>#dropup-menu{right:0}#dropup-icon{position:absolute;pointer-events:none;width:1.16em;height:1.2em;left:.265em;bottom:.43em;filter:brightness(0) saturate(100%) invert(54%) sepia(0%) saturate(724%) hue-rotate(6deg) brightness(92%) contrast(90%)}#dropup-menu{background-color:#fff;position:absolute;transform:translateY(-100%);border-radius:5px;z-index:1;top:-.49em;box-shadow:#0003 -1px 2px 10px,#0000001a 0 2px 4px;cursor:pointer;-webkit-user-select:none;user-select:none}.dropup-menu-item{height:1.4em;padding:.28em .84em .28em .35em;display:flex;position:relative}.dropup-menu-item:hover,.dropup-menu-item:focus-visible{background-color:#f3f3f3}.dropup-menu-item:active{background-color:#ebebeb}.dropup-menu-item:active:not(:hover){background-color:transparent}.dropup-menu-item:first-child{padding-top:.49em;border-top-left-radius:inherit;border-top-right-radius:inherit}.dropup-menu-item:last-child{padding-bottom:.45em;border-bottom-left-radius:inherit;border-bottom-right-radius:inherit}.dropup-menu-item-icon{width:1.39em;position:relative;margin-right:.56em}.dropup-menu-item-icon>svg{bottom:0!important;top:0!important;margin-bottom:auto;margin-top:auto}.dropup-menu-item-text{margin-top:.08em;width:max-content}.dropup-menu-item-active{background-color:#edf7ff;color:#0285ff}.dropup-menu-item-active:hover,.dropup-menu-item-active:focus-visible{background-color:#def0ff}.dropup-menu-item-active:active{background-color:#d2eaff}.dropup-menu-item-active>.dropup-menu-item-icon{filter:brightness(0) saturate(100%) invert(32%) sepia(34%) saturate(4196%) hue-rotate(196deg) brightness(107%) contrast(104%)}.dropup-menu-item-disabled{color:#aeaeae;cursor:auto}.dropup-menu-item-disabled>div{pointer-events:none}.dropup-menu-item-disabled:hover,.dropup-menu-item-disabled:focus-visible{background-color:transparent}.dropup-menu-item-disabled:active{background-color:transparent}.dropup-menu-item-disabled>.dropup-menu-item-icon{filter:brightness(0) saturate(100%) invert(67%) sepia(0%) saturate(818%) hue-rotate(28deg) brightness(102%) contrast(100%)}#input{width:100%;display:inline-flex;text-align:center;margin-left:auto;margin-right:auto;margin-top:auto;position:relative;justify-content:center}#chat-view{height:100%;display:grid;grid-template-columns:100%}::-webkit-scrollbar{width:9px;height:9px}::-webkit-scrollbar-thumb{background-color:#d0d0d0;border-radius:5px}::-webkit-scrollbar-track{background-color:#f2f2f2}.deep-chat-web-model-button{margin-top:10px;margin-bottom:5px;margin-left:1px}:host{all:initial;display:table-cell}#container{height:inherit;width:inherit;overflow:hidden}',this.shadowRoot),setTimeout((()=>{this._hasBeenRendered||this.onRender()}),20)}changeToChatView(){this._activeService&&(this._activeService.validateKeyProperty=!1),this.onRender()}onRender(){n.attemptAppendStyleSheetToHead(this.style),O.processConnect(this),(!this._activeService||this._activeService.demo)&&(this._activeService=ws.create(this)),this.auxiliaryStyle&&!this._auxiliaryStyleApplied&&(r.apply(this.auxiliaryStyle,this.shadowRoot),this._auxiliaryStyleApplied=!0),r.applyDefaultStyleToComponent(this.style,this.chatStyle),O.checkForContainerStyles(this,this._elementRef),this._activeService.key&&this._activeService.validateKeyProperty?e.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):this._activeService instanceof Ve&&!this._activeService.key?this._activeService instanceof Ve&&Ye.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):(this._childElement??(this._childElement=this.children[0]),xo.render(this,this._elementRef,this._activeService,this._childElement)),this._hasBeenRendered||he.onRender(this),this._hasBeenRendered=!0}disconnectedCallback(){si.chat=void 0}}_o([_s("object")],So.prototype,"connect"),_o([_s("object")],So.prototype,"directConnection"),_o([_s("object")],So.prototype,"webModel"),_o([_s("object")],So.prototype,"requestBodyLimits"),_o([_s("function")],So.prototype,"requestInterceptor"),_o([_s("function")],So.prototype,"responseInterceptor"),_o([_s("function")],So.prototype,"validateInput"),_o([_s("function")],So.prototype,"loadHistory"),_o([_s("object")],So.prototype,"chatStyle"),_o([_s("object")],So.prototype,"attachmentContainerStyle"),_o([_s("object")],So.prototype,"dropupStyles"),_o([_s("object")],So.prototype,"inputAreaStyle"),_o([_s("object")],So.prototype,"textInput"),_o([_s("object")],So.prototype,"submitButtonStyles"),_o([_s("object")],So.prototype,"customButtons"),_o([_s("string")],So.prototype,"auxiliaryStyle"),_o([_s("array")],So.prototype,"history"),_o([_s("object")],So.prototype,"introMessage"),_o([_s("object")],So.prototype,"avatars"),_o([_s("object")],So.prototype,"names"),_o([_s("object")],So.prototype,"displayLoadingBubble"),_o([_s("object")],So.prototype,"errorMessages"),_o([_s("object")],So.prototype,"messageStyles"),_o([_s("object")],So.prototype,"textToSpeech"),_o([_s("object")],So.prototype,"speechToText"),_o([_s("object")],So.prototype,"images"),_o([_s("object")],So.prototype,"gifs"),_o([_s("object")],So.prototype,"camera"),_o([_s("object")],So.prototype,"audio"),_o([_s("object")],So.prototype,"microphone"),_o([_s("object")],So.prototype,"mixedFiles"),_o([_s("object")],So.prototype,"dragAndDrop"),_o([_s("object")],So.prototype,"introPanelStyle"),_o([_s("object")],So.prototype,"htmlClassUtilities"),_o([_s("object")],So.prototype,"remarkable"),_o([_s("object")],So.prototype,"focusMode"),_o([_s("function")],So.prototype,"onMessage"),_o([_s("function")],So.prototype,"onClearMessages"),_o([_s("function")],So.prototype,"onComponentRender"),_o([_s("function")],So.prototype,"onError"),_o([_s("object")],So.prototype,"demo"),_o([_s("object")],So.prototype,"_insertKeyViewStyles"),customElements.define("deep-chat",So);export{So as DeepChat};
1
+ class t{static render(t,e){const i=document.createElement("div");i.id="error-view",i.innerText=e,t.replaceChildren(i)}}class e{static onLoad(t){t.innerHTML='<div id="loading-validate-key-property"></div>'}static createElements(){const t=document.createElement("div");return t.id="validate-property-key-view",t}static render(i,s,n){const o=e.createElements(),r={onSuccess:s,onFail:t.render.bind(this,i,"Your 'key' has failed authentication"),onLoad:e.onLoad.bind(this,o)};n.key&&n.verifyKey(n.key,r),i.replaceChildren(o)}}class i{static unsetStyle(t,e){const i=Object.keys(e).reduce(((t,e)=>(t[e]="",t)),{});Object.assign(t.style,i)}static unsetActivityCSSMouseStates(t,e){e.click&&i.unsetStyle(t,e.click),e.hover&&i.unsetStyle(t,e.hover)}static unsetAllCSSMouseStates(t,e){i.unsetActivityCSSMouseStates(t,e),e.default&&i.unsetStyle(t,e.default)}static processStateful(t){const e=t.default||{},i=Object.assign(JSON.parse(JSON.stringify(e)),null==t?void 0:t.hover);return{default:e,hover:i,click:Object.assign(JSON.parse(JSON.stringify(i)),null==t?void 0:t.click)}}static mergeStatefulStyles(t){const e={default:{},hover:{},click:{}};return t.forEach((t=>{e.default=Object.assign(e.default,t.default),e.hover=Object.assign(e.hover,t.hover),e.click=Object.assign(e.click,t.click)})),e}static overwriteDefaultWithAlreadyApplied(t,e){Object.keys(t.default||[]).forEach((i=>{var s;const n=i;e.style[n]&&null!=(s=t.default)&&s[n]&&(t.default[i]=e.style[n])}))}static applyToStyleIfNotDefined(t,e){for(const i in e){const s=e[i];""===t[i]&&s&&(t[i]=s)}}}const s=class t{static attemptAppendStyleSheetToHead(e){if(e.fontFamily&&e.fontFamily!==t.DEFAULT_FONT_FAMILY)return;const i=document.getElementsByTagName("head")[0];if(!Array.from(i.getElementsByTagName("link")).some((e=>e.getAttribute("href")===t.FONT_URL))){const e=document.createElement("link");e.rel="stylesheet",e.href=t.FONT_URL,i.appendChild(e)}}};s.FONT_URL="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap",s.DEFAULT_FONT_FAMILY="'Inter', sans-serif, Avenir, Helvetica, Arial";let n=s;const o=class t{static apply(e,i){if(i)try{t.applyStyleSheet(e,i)}catch{t.addStyleElement(e,i)}}static applyStyleSheet(t,e){const i=new CSSStyleSheet;i.replaceSync(t),e.adoptedStyleSheets.push(i)}static addStyleElement(t,e){const i=document.createElement("style");i.innerHTML=t,e.appendChild(i)}static applyDefaultStyleToComponent(e,s){s&&i.applyToStyleIfNotDefined(e,s),i.applyToStyleIfNotDefined(e,t.DEFAULT_COMPONENT_STYLE)}};o.DEFAULT_COMPONENT_STYLE={height:"350px",width:"320px",borderTop:"1px solid #cacaca",borderRight:"1px solid #cacaca",borderLeft:"1px solid #cacaca",borderBottom:"1px solid #cacaca",fontFamily:n.DEFAULT_FONT_FAMILY,fontSize:"0.9rem",backgroundColor:"white",position:"relative",overflow:"hidden"};let r=o;const a=class{};a.IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),a.IS_CHROMIUM=window.chrome;let l=a;var c=(t=>(t.ESCAPE="Escape",t.ENTER="Enter",t.TAB="Tab",t.ARROW_UP="ArrowUp",t.ARROW_DOWN="ArrowDown",t.ARROW_RIGHT="ArrowRight",t.ARROW_LEFT="ArrowLeft",t.BACKSPACE="Backspace",t.DELETE="Delete",t.META="Meta",t.CONTROL="Control",t))(c||{});const h=class t{static add(e,i,s,n){void 0!==s&&e.addEventListener("keydown",t.onKeyDown.bind(this,s)),e.oninput=t.onInput.bind(this,s,n),e.addEventListener("paste",(t=>{var e;t.preventDefault(),null!=(e=t.clipboardData)&&e.files.length&&i.addFilesToAnyType(Array.from(t.clipboardData.files))}))}static onKeyDown(e,i){const s=i.target.textContent;s&&s.length>=e&&!t.PERMITTED_KEYS.has(i.key)&&!t.isKeyCombinationPermitted(i)&&i.preventDefault()}static isKeyCombinationPermitted(t){return"a"===t.key&&(t.ctrlKey||t.metaKey)}static onInput(t,e,i){const s=i.target,n=s.textContent||"";void 0!==t&&n.length>t&&(s.textContent=n.substring(0,t),v.focusEndOfInput(s)),null==e||e()}};h.PERMITTED_KEYS=new Set([c.BACKSPACE,c.DELETE,c.ARROW_RIGHT,c.ARROW_LEFT,c.ARROW_DOWN,c.ARROW_UP,c.META,c.CONTROL,c.ENTER]);let u=h;class d{static sanitizePastedTextContent(t){var e,i;t.preventDefault();const s=null==(e=t.clipboardData)?void 0:e.getData("text/plain");s&&(null==(i=document.execCommand)||i.call(document,"insertText",!1,s))}}const p=class t{constructor(e,i,s){var n,o;const r=t.processConfig(i,e.textInput);this.elementRef=t.createContainerElement(null==(n=null==r?void 0:r.styles)?void 0:n.container),this._config=r,this.inputElementRef=this.createInputElement(),this.elementRef.appendChild(this.inputElementRef),e.setPlaceholderText=this.setPlaceholderText.bind(this),e.setPlaceholderText((null==(o=this._config.placeholder)?void 0:o.text)||"Ask me anything!"),setTimeout((()=>{u.add(this.inputElementRef,s,this._config.characterLimit,e._validationHandler)}))}static processConfig(t,e){var i;return e??(e={}),e.disabled??(e.disabled=t.isTextInputDisabled),e.placeholder??(e.placeholder={}),(i=e.placeholder).text??(i.text=t.textInputPlaceholderText),e}static createContainerElement(t){const e=document.createElement("div");return e.id="text-input-container",Object.assign(e.style,t),e}static preventAutomaticScrollUpOnNewLine(t){let e;t.addEventListener("keydown",(()=>{e=window.scrollY})),t.addEventListener("input",(()=>{e!==window.scrollY&&window.scrollTo({top:e})}))}clear(){var t;const e=window.scrollY;this.inputElementRef.classList.contains("text-input-disabled")||(Object.assign(this.inputElementRef.style,null==(t=this._config.placeholder)?void 0:t.style),this.inputElementRef.textContent="",v.focusEndOfInput(this.inputElementRef)),l.IS_CHROMIUM&&window.scrollTo({top:e})}createInputElement(){var e,i,s,n;const o=document.createElement("div");return o.id=t.TEXT_INPUT_ID,o.classList.add("text-input-styling"),o.role="textbox",l.IS_CHROMIUM&&t.preventAutomaticScrollUpOnNewLine(o),"boolean"==typeof this._config.disabled&&!0===this._config.disabled?(o.contentEditable="false",o.classList.add("text-input-disabled"),o.setAttribute("aria-disabled","true")):(o.contentEditable="true",o.removeAttribute("aria-disabled"),this.addEventListeners(o)),Object.assign(o.style,null==(e=this._config.styles)?void 0:e.text),Object.assign(o.style,null==(i=this._config.placeholder)?void 0:i.style),null!=(n=null==(s=this._config.placeholder)?void 0:s.style)&&n.color||o.setAttribute("textcolor",""),o}removePlaceholderStyle(){var t,e,s,n;!this.inputElementRef.classList.contains("text-input-disabled")&&null!=(t=this._config.placeholder)&&t.style&&(i.unsetStyle(this.inputElementRef,null==(e=this._config.placeholder)?void 0:e.style),Object.assign(this.inputElementRef.style,null==(n=null==(s=this._config)?void 0:s.styles)?void 0:n.text))}addEventListeners(t){var e,i;null!=(e=this._config.styles)&&e.focus&&(t.onfocus=()=>{var t;return Object.assign(this.elementRef.style,null==(t=this._config.styles)?void 0:t.focus)},t.onblur=this.onBlur.bind(this,this._config.styles.focus,null==(i=this._config.styles)?void 0:i.container)),t.addEventListener("keydown",this.onKeydown.bind(this)),t.addEventListener("input",this.onInput.bind(this)),t.addEventListener("paste",d.sanitizePastedTextContent)}onBlur(t,e){i.unsetStyle(this.elementRef,t),e&&Object.assign(this.elementRef.style,e)}onKeydown(t){var e;t.key===c.ENTER&&!t.ctrlKey&&!t.shiftKey&&(t.preventDefault(),null==(e=this.submit)||e.call(this))}onInput(){var t;this.isTextInputEmpty()?Object.assign(this.inputElementRef.style,null==(t=this._config.placeholder)?void 0:t.style):this.removePlaceholderStyle()}setPlaceholderText(t){this.inputElementRef.setAttribute("deep-chat-placeholder-text",t),this.inputElementRef.setAttribute("aria-label",t)}isTextInputEmpty(){return""===this.inputElementRef.textContent}};p.TEXT_INPUT_ID="text-input";let m=p;class v{static focusEndOfInput(t){const e=document.createRange();e.selectNodeContents(t),e.collapse(!1);const i=window.getSelection();null==i||i.removeAllRanges(),null==i||i.addRange(e)}static focusFromParentElement(t){const e=t.querySelector(`#${m.TEXT_INPUT_ID}`);e&&(l.IS_SAFARI&&e.focus(),v.focusEndOfInput(e))}}function f(t){return t.charAt(0).toUpperCase()+t.slice(1)}function g(t,e,i,s){const n=`\n${f(e)} message: ${JSON.stringify(t)} \n`,o=i?`${f(e)} message after interceptor: ${function(t){return t&&JSON.stringify(t)}(s)} \n`:"";return n+o}const b="Make sure the events are using {text: string} or {html: string} format.\nYou can also augment them using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor",y={INVALID_KEY:"Invalid API Key",CONNECTION_FAILED:"Failed to connect",INVALID_RESPONSE:function(t,e,i,s){return`${g(t,e,i,s)}Make sure the ${e} message is using the Response format: https://deepchat.dev/docs/connect/#Response \nYou can also augment it using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor`},INVALID_MODEL_REQUEST:function(t,e){const i="request";return`${g(t,i,e)}Make sure the ${i} message is using the {body: {text: string}} format, e.g: {body: {text: "Model Response"}}`},INVALID_MODEL_RESPONSE:function(t,e,i){const s="response";return`${g(t,s,e,i)}Make sure the ${s} message is using the {text: string} format, e.g: {text: "Model Response"}`},INVALID_STREAM_ARRAY_RESPONSE:"Multi-response arrays are not supported for streaming",INVALID_STREAM_EVENT:b,INVALID_STREAM_EVENT_MIX:"Cannot mix {text: string} and {html: string} responses.",NO_VALID_STREAM_EVENTS_SENT:`No valid stream events were sent.\n${b}`},w=class t{static addElements(t,...e){e.forEach((e=>t.appendChild(e)))}static isScrollbarAtBottomOfElement(e){const i=e.scrollHeight,s=e.clientHeight;return e.scrollTop>=i-s-t.CODE_SNIPPET_GENERATION_JUMP}static cloneElement(t){const e=t.cloneNode(!0);return t.parentNode.replaceChild(e,t),e}static scrollToBottom(t,e=!1){e?t.scrollTo({left:0,top:t.scrollHeight,behavior:"smooth"}):t.scrollTop=t.scrollHeight}static scrollToTop(t){t.scrollTop=0}};w.CODE_SNIPPET_GENERATION_JUMP=.5;let x=w;const k=class t{static speak(t,e){if(window.SpeechSynthesisUtterance){const i=new SpeechSynthesisUtterance(t);Object.assign(i,e),speechSynthesis.speak(i)}}static processConfig(e,i){const s={};setTimeout((()=>{if("object"==typeof e&&(e.lang&&(s.lang=e.lang),e.pitch&&(s.pitch=e.pitch),e.rate&&(s.rate=e.rate),e.volume&&(s.volume=e.volume),e.voiceName)){const t=window.speechSynthesis.getVoices().find((t=>{var i;return t.name.toLocaleLowerCase()===(null==(i=e.voiceName)?void 0:i.toLocaleLowerCase())}));t&&(s.voice=t)}i(s)}),t.LOAD_VOICES_MS)}};k.LOAD_VOICES_MS=200;let _=k;const S=class t{static colorToHex(t){const e=document.createElement("div");return e.style.color=t,document.body.appendChild(e),`#${window.getComputedStyle(e).color.match(/\d+/g).map((t=>parseInt(t).toString(16).padStart(2,"0"))).join("")}`}static setDots(e,i){var s,n,o,r;if(null!=(r=null==(o=null==(n=null==(s=null==i?void 0:i.loading)?void 0:s.message)?void 0:n.styles)?void 0:o.bubble)&&r.color){const s=t.colorToHex(i.loading.message.styles.bubble.color);e.style.setProperty("--loading-message-color",s),e.style.setProperty("--loading-message-color-fade",`${s}33`)}else e.style.setProperty("--loading-message-color","#848484"),e.style.setProperty("--loading-message-color-fade","#55555533")}static setRing(e,i){const{color:s,width:n,height:o,margin:r,border:a}=i||{};if(s){const i=t.colorToHex(s);e.style.setProperty("--loading-history-color",i)}else e.style.setProperty("--loading-history-color","#dbdbdb");e.style.setProperty("--loading-history-height",o||"57px"),e.style.setProperty("--loading-history-width",n||"57px"),e.style.setProperty("--loading-history-margin",r||"7px"),e.style.setProperty("--loading-history-border",a||"6px solid")}};S.BUBBLE_CLASS="deep-chat-loading-message-bubble",S.DOTS_CONTAINER_CLASS="deep-chat-loading-message-dots-container";let A=S;const T=class t{static setElementProps(e,i,s,n){var o;"loading"!==s&&(e.applyCustomStyles(i,n,!0,null==(o=e.messageStyles)?void 0:o[s]),i.bubbleElement.classList.add(t.FILE_BUBBLE_CLASS))}static addMessage(e,i,s,n,o){t.setElementProps(e,i,s,n),o||(e.appendOuterContainerElemet(i.outerContainer),e.focusMode||(e.elementRef.scrollTop=e.elementRef.scrollHeight))}static wrapInLink(e,i,s){const n=document.createElement("a");return n.href=i,n.download=s||t.DEFAULT_FILE_NAME,n.target="_blank",n.appendChild(e),n}static isNonLinkableDataUrl(t,e){return!(!e.startsWith("data")||"image"===t)&&("any"===t&&e.startsWith("data:text/javascript")||!e.startsWith("data:image")&&!e.startsWith("data:application"))}static processContent(e,i,s,n){return!s||t.isNonLinkableDataUrl(e,s)?i:t.wrapInLink(i,s,n)}static waitToLoadThenScroll(t){setTimeout((()=>{t.scrollTop=t.scrollHeight}),60)}static scrollDownOnImageLoad(e,i){if(e.startsWith("data"))t.waitToLoadThenScroll(i);else try{fetch(e,{mode:"no-cors"}).catch((()=>{})).finally((()=>{t.waitToLoadThenScroll(i)}))}catch{i.scrollTop=i.scrollHeight}}static reAddFileRefToObject(t,e){var i;null==(i=t.files)||i.forEach(((t,i)=>{var s;t.ref&&null!=(s=e.message.files)&&s[i]&&(e.message.files[i].ref=t.ref)}))}static removeFileRef(t){const e={...t};return delete e.ref,e}static isAudioFile(t){const{type:e,src:i}=t;return"audio"===e||(null==i?void 0:i.startsWith("data:audio"))||i&&/\.(mp3|ogg|wav|aac|webm|4a)$/i.test(i)}static isImageFile(e){const{type:i,src:s}=e;return"image"===i||(null==s?void 0:s.startsWith("data:image"))||s&&t.isImageFileExtension(s)}static isImageFileExtension(t){return/\.(jpg|jpeg|png|gif|bmp)$/i.test(t)}};T.DEFAULT_FILE_NAME="file",T.FILE_BUBBLE_CLASS="file-message";let M=T;class O{static checkForContainerStyles(t,e){const i=t.containerStyle;i&&(Object.assign(e.style,i),console.error("The containerStyle property is deprecated since version 1.3.14."),console.error("Please change to using the style property instead: https://deepchat.dev/docs/styles#style"))}static handleResponseProperty(t){return console.error("The {result: ....} response object type is deprecated since version 1.3.0."),console.error("Please change to using the new response object: https://deepchat.dev/docs/connect#Response"),t.result}static processHistory(t){const e=t.initialMessages;if(e)return console.error("The initialMessages property is deprecated since version 2.0.0."),console.error("Please change to using the history property instead: https://deepchat.dev/docs/messages/#history"),e}static processHistoryFile(t){const e=t.file;e&&(console.error("The file property in MessageContent is deprecated since version 1.3.17."),console.error("Please change to using the files array property: https://deepchat.dev/docs/messages/#MessageContent"),t.files=[e])}static processValidateInput(t){const e=t.validateMessageBeforeSending;if(e)return console.error("The validateMessageBeforeSending property is deprecated since version 1.3.24."),console.error("Please change to using validateInput: https://deepchat.dev/docs/interceptors#validateInput"),e}static processSubmitUserMessage(t){return console.error("The submitUserMessage(text: string) argument string type is deprecated since version 1.4.4."),console.error("Please change to using the new argument type: https://deepchat.dev/docs/methods#submitUserMessage"),{text:t}}static flagHTMLUpdateClass(t){var e;null!=(e=t.children[0])&&e.classList.contains("deep-chat-update-message")&&(console.error('The "deep-chat-update-message" html class is deprecated since version 1.4.4.'),console.error("Please change to using {..., overwrite: true} object: https://deepchat.dev/docs/connect#Response"))}static processConnect(t){const e=t;e.request&&(e.connect?Object.assign(e.connect,e.request):e.connect=e.request,console.error("The request property is deprecated since version 2.0.0."),console.error("Please see the connect object: https://deepchat.dev/docs/connect#connect-1"))}static checkForStream(t){const e=t.stream;if(e)return console.error("The stream property has been moved to the connect object in version 2.0.0."),console.error("Please see the connect object: https://deepchat.dev/docs/connect#connect-1"),e}static fireOnNewMessage(t,e){var i;const s=t;s.onNewMessage&&(console.error("The onNewMessage event has been deprecated since version 2.0.0."),console.error("Please see the onMessage event: https://deepchat.dev/docs/events#onMessage"),null==(i=s.onNewMessage)||i.call(s,e)),t.dispatchEvent(new CustomEvent("new-message",{detail:e}))}static processFileConfigConnect(t){const e=t;e.request&&(console.error("The request property in file configuration is deprecated since version 2.0.0."),console.error("Please use the connect property instead: https://deepchat.dev/docs/files"),e.connect||(e.connect=e.request))}static processMessageStyles(t){if(!t)return;const e=JSON.parse(JSON.stringify(t)),i=e.loading;return i&&(i.outerContainer||i.innerContainer||i.bubble||i.media)&&(console.error("The loading message styles are defined using LoadingMessageStyles interface since version 2.1.0."),console.error("Check it out here: https://deepchat.dev/docs/messages/styles#LoadingMessageStyles"),e.loading={message:{styles:i}}),e}static processDemo(t){return"boolean"==typeof t||t.displayLoadingBubble&&(console.error("The demo displayLoadingBubble property is deprecated since version 2.1.0."),console.error("Please use displayLoading instead: https://deepchat.dev/docs/demo#demo"),t.displayLoading={message:!0}),t}}class j{static mouseUp(t,e){i.unsetAllCSSMouseStates(t,e),Object.assign(t.style,e.default),Object.assign(t.style,e.hover)}static mouseDown(t,e){Object.assign(t.style,e.click)}static mouseLeave(t,e){i.unsetAllCSSMouseStates(t,e),Object.assign(t.style,e.default)}static mouseEnter(t,e){Object.assign(t.style,e.hover)}static add(t,e){t.addEventListener("mouseenter",j.mouseEnter.bind(this,t,e)),t.addEventListener("mouseleave",j.mouseLeave.bind(this,t,e)),t.addEventListener("mousedown",j.mouseDown.bind(this,t,e)),t.addEventListener("mouseup",j.mouseUp.bind(this,t,e))}}const C={"deep-chat-button":{styles:{default:{backgroundColor:"white",padding:"5px",paddingLeft:"7px",paddingRight:"7px",border:"1px solid #c2c2c2",borderRadius:"6px",cursor:"pointer"},hover:{backgroundColor:"#fafafa"},click:{backgroundColor:"#f1f1f1"}}}},E=Object.keys(C);class I{static applySuggestionEvent(t,e){setTimeout((()=>{e.addEventListener("click",(()=>{var i,s;null==(s=t.submitUserMessage)||s.call(t,{text:(null==(i=e.textContent)?void 0:i.trim())||""})}))}))}static isElementTemporary(t){var e;return!!t&&(null==(e=t.bubbleElement.children[0])?void 0:e.classList.contains("deep-chat-temporary-message"))}static doesElementContainDeepChatClass(t){return E.find((e=>t.classList.contains(e)))}static applyEvents(t,e){const i=C[e].events;Object.keys(i||[]).forEach((e=>{t.addEventListener(e,null==i?void 0:i[e])}))}static getProcessedStyles(t,e,s){const n=Array.from(e.classList).reduce(((e,i)=>{var s;const n=null==(s=t[i])?void 0:s.styles;return n&&t[i].styles&&e.push(n),e}),[]),o=C[s].styles;if(o){const t=JSON.parse(JSON.stringify(o));t.default&&i.overwriteDefaultWithAlreadyApplied(t,e),n.unshift(t)}const r=i.mergeStatefulStyles(n);return i.processStateful(r)}static applyDeepChatUtilities(t,e,i){E.forEach((t=>{const s=i.getElementsByClassName(t);Array.from(s||[]).forEach((i=>{const s=I.getProcessedStyles(e,i,t);P.applyStylesToElement(i,s),I.applyEvents(i,t)}))}));const s=i.getElementsByClassName("deep-chat-suggestion-button");Array.from(s).forEach((e=>I.applySuggestionEvent(t,e)))}}class P{static applyStylesToElement(t,e){const s=i.processStateful(e);j.add(t,s),Object.assign(t.style,s.default)}static applyEventsToElement(t,e){Object.keys(e).forEach((i=>{const s=e[i];s&&t.addEventListener(i,s)}))}static applyClassUtilitiesToElement(t,e){const{events:i,styles:s}=e;i&&P.applyEventsToElement(t,i),s&&!I.doesElementContainDeepChatClass(t)&&P.applyStylesToElement(t,s)}static applyCustomClassUtilities(t,e){Object.keys(t).forEach((i=>{const s=e.getElementsByClassName(i);Array.from(s).forEach((e=>{t[i]&&P.applyClassUtilitiesToElement(e,t[i])}))}))}static apply(t,e){I.applyDeepChatUtilities(t,t.htmlClassUtilities,e),P.applyCustomClassUtilities(t.htmlClassUtilities,e)}static traverseNodes(t,e){t.nodeType===Node.ELEMENT_NODE&&e.push(t.outerHTML),t.childNodes.forEach((t=>{P.traverseNodes(t,e)}))}static splitHTML(t){const e=(new DOMParser).parseFromString(t,"text/html"),i=[];return e.body.childNodes.forEach((t=>{P.traverseNodes(t,i)})),i}static replaceElementWithNewClone(t,e){var i;const s=(e||t).cloneNode(!0);return null==(i=t.parentNode)||i.replaceChild(s,t),s}}const N=class t{static addElement(t,e){t.appendOuterContainerElemet(e),t.focusMode||(t.elementRef.scrollTop=t.elementRef.scrollHeight)}static createElements(e,i,s,n){const o=e.createMessageElementsOnOrientation("",s,n);return o.bubbleElement.classList.add(t.HTML_BUBBLE_CLASS),o.bubbleElement.innerHTML=i,o}static overwriteElements(t,e,i){i.bubbleElement.innerHTML=e,P.apply(t,i.outerContainer),O.flagHTMLUpdateClass(i.bubbleElement)}static overwrite(e,i,s,n){const{messageToElements:o}=e,r=Se.overwriteMessage(o,n,i,s,"html",t.HTML_BUBBLE_CLASS);return r&&t.overwriteElements(e,i,r),r}static create(e,i,s,n=!1){var o;const r=t.createElements(e,i,s,n);return Se.fillEmptyMessageElement(r.bubbleElement,i),P.apply(e,r.outerContainer),O.flagHTMLUpdateClass(r.bubbleElement),e.applyCustomStyles(r,s,!1,null==(o=e.messageStyles)?void 0:o.html),r}static add(e,i,s,n,o,r=!1){if(null!=o&&o.status){const t=this.overwrite(e,i,s,n);if(t)return t;o.status=!1}const a=document.createElement("div");if(a.innerHTML=i,I.isElementTemporary({outerContainer:a,bubbleElement:a,innerContainer:a})&&e.messageElementRefs.length>0)return;const l=t.create(e,i,s,r);return r||t.addElement(e,l.outerContainer),l}};N.HTML_BUBBLE_CLASS="html-message";let R=N;var q;function B(t){return(q=q||document.createElement("textarea")).innerHTML="&"+t+";",q.value}var L=Object.prototype.hasOwnProperty;function F(t){return[].slice.call(arguments,1).forEach((function(e){if(e){if("object"!=typeof e)throw new TypeError(e+"must be object");Object.keys(e).forEach((function(i){t[i]=e[i]}))}})),t}var z=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function D(t){return t.indexOf("\\")<0?t:t.replace(z,"$1")}function $(t){return!(t>=55296&&t<=57343||t>=64976&&t<=65007||!(65535&~t)||65534==(65535&t)||t>=0&&t<=8||11===t||t>=14&&t<=31||t>=127&&t<=159||t>1114111)}function J(t){if(t>65535){var e=55296+((t-=65536)>>10),i=56320+(1023&t);return String.fromCharCode(e,i)}return String.fromCharCode(t)}var U=/&([a-z#][a-z0-9]{1,31});/gi,V=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;function H(t,e){var i=0,s=B(e);return e!==s?s:35===e.charCodeAt(0)&&V.test(e)&&$(i="x"===e[1].toLowerCase()?parseInt(e.slice(2),16):parseInt(e.slice(1),10))?J(i):t}function K(t){return t.indexOf("&")<0?t:t.replace(U,H)}var G=/[&<>"]/,Z=/[&<>"]/g,W={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function X(t){return W[t]}function Y(t){return G.test(t)?t.replace(Z,X):t}var Q={};function tt(t,e){return++e>=t.length-2?e:"paragraph_open"===t[e].type&&t[e].tight&&"inline"===t[e+1].type&&0===t[e+1].content.length&&"paragraph_close"===t[e+2].type&&t[e+2].tight?tt(t,e+2):e}Q.blockquote_open=function(){return"<blockquote>\n"},Q.blockquote_close=function(t,e){return"</blockquote>"+et(t,e)},Q.code=function(t,e){return t[e].block?"<pre><code>"+Y(t[e].content)+"</code></pre>"+et(t,e):"<code>"+Y(t[e].content)+"</code>"},Q.fence=function(t,e,i,s,n){var o,r,a=t[e],l="",c=i.langPrefix;if(a.params){if(r=(o=a.params.split(/\s+/g)).join(" "),function(t,e){return!!t&&L.call(t,e)}(n.rules.fence_custom,o[0]))return n.rules.fence_custom[o[0]](t,e,i,s,n);l=' class="'+c+Y(K(D(r)))+'"'}return"<pre><code"+l+">"+(i.highlight&&i.highlight.apply(i.highlight,[a.content].concat(o))||Y(a.content))+"</code></pre>"+et(t,e)},Q.fence_custom={},Q.heading_open=function(t,e){return"<h"+t[e].hLevel+">"},Q.heading_close=function(t,e){return"</h"+t[e].hLevel+">\n"},Q.hr=function(t,e,i){return(i.xhtmlOut?"<hr />":"<hr>")+et(t,e)},Q.bullet_list_open=function(){return"<ul>\n"},Q.bullet_list_close=function(t,e){return"</ul>"+et(t,e)},Q.list_item_open=function(){return"<li>"},Q.list_item_close=function(){return"</li>\n"},Q.ordered_list_open=function(t,e){var i=t[e];return"<ol"+(i.order>1?' start="'+i.order+'"':"")+">\n"},Q.ordered_list_close=function(t,e){return"</ol>"+et(t,e)},Q.paragraph_open=function(t,e){return t[e].tight?"":"<p>"},Q.paragraph_close=function(t,e){var i=!(t[e].tight&&e&&"inline"===t[e-1].type&&!t[e-1].content);return(t[e].tight?"":"</p>")+(i?et(t,e):"")},Q.link_open=function(t,e,i){var s=t[e].title?' title="'+Y(K(t[e].title))+'"':"",n=i.linkTarget?' target="'+i.linkTarget+'"':"";return'<a href="'+Y(t[e].href)+'"'+s+n+">"},Q.link_close=function(){return"</a>"},Q.image=function(t,e,i){var s=' src="'+Y(t[e].src)+'"',n=t[e].title?' title="'+Y(K(t[e].title))+'"':"";return"<img"+s+(' alt="'+(t[e].alt?Y(K(D(t[e].alt))):"")+'"')+n+(i.xhtmlOut?" /":"")+">"},Q.table_open=function(){return"<table>\n"},Q.table_close=function(){return"</table>\n"},Q.thead_open=function(){return"<thead>\n"},Q.thead_close=function(){return"</thead>\n"},Q.tbody_open=function(){return"<tbody>\n"},Q.tbody_close=function(){return"</tbody>\n"},Q.tr_open=function(){return"<tr>"},Q.tr_close=function(){return"</tr>\n"},Q.th_open=function(t,e){var i=t[e];return"<th"+(i.align?' style="text-align:'+i.align+'"':"")+">"},Q.th_close=function(){return"</th>"},Q.td_open=function(t,e){var i=t[e];return"<td"+(i.align?' style="text-align:'+i.align+'"':"")+">"},Q.td_close=function(){return"</td>"},Q.strong_open=function(){return"<strong>"},Q.strong_close=function(){return"</strong>"},Q.em_open=function(){return"<em>"},Q.em_close=function(){return"</em>"},Q.del_open=function(){return"<del>"},Q.del_close=function(){return"</del>"},Q.ins_open=function(){return"<ins>"},Q.ins_close=function(){return"</ins>"},Q.mark_open=function(){return"<mark>"},Q.mark_close=function(){return"</mark>"},Q.sub=function(t,e){return"<sub>"+Y(t[e].content)+"</sub>"},Q.sup=function(t,e){return"<sup>"+Y(t[e].content)+"</sup>"},Q.hardbreak=function(t,e,i){return i.xhtmlOut?"<br />\n":"<br>\n"},Q.softbreak=function(t,e,i){return i.breaks?i.xhtmlOut?"<br />\n":"<br>\n":"\n"},Q.text=function(t,e){return Y(t[e].content)},Q.htmlblock=function(t,e){return t[e].content},Q.htmltag=function(t,e){return t[e].content},Q.abbr_open=function(t,e){return'<abbr title="'+Y(K(t[e].title))+'">'},Q.abbr_close=function(){return"</abbr>"},Q.footnote_ref=function(t,e){var i=Number(t[e].id+1).toString(),s="fnref"+i;return t[e].subId>0&&(s+=":"+t[e].subId),'<sup class="footnote-ref"><a href="#fn'+i+'" id="'+s+'">['+i+"]</a></sup>"},Q.footnote_block_open=function(t,e,i){return(i.xhtmlOut?'<hr class="footnotes-sep" />\n':'<hr class="footnotes-sep">\n')+'<section class="footnotes">\n<ol class="footnotes-list">\n'},Q.footnote_block_close=function(){return"</ol>\n</section>\n"},Q.footnote_open=function(t,e){return'<li id="fn'+Number(t[e].id+1).toString()+'" class="footnote-item">'},Q.footnote_close=function(){return"</li>\n"},Q.footnote_anchor=function(t,e){var i="fnref"+Number(t[e].id+1).toString();return t[e].subId>0&&(i+=":"+t[e].subId),' <a href="#'+i+'" class="footnote-backref">↩</a>'},Q.dl_open=function(){return"<dl>\n"},Q.dt_open=function(){return"<dt>"},Q.dd_open=function(){return"<dd>"},Q.dl_close=function(){return"</dl>\n"},Q.dt_close=function(){return"</dt>\n"},Q.dd_close=function(){return"</dd>\n"};var et=Q.getBreak=function(t,e){return(e=tt(t,e))<t.length&&"list_item_close"===t[e].type?"":"\n"};function it(){this.rules=F({},Q),this.getBreak=Q.getBreak}function st(){this.t=[],this.i=null}function nt(t,e,i,s,n){this.src=t,this.env=s,this.options=i,this.parser=e,this.tokens=n,this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache=[],this.isInLabel=!1,this.linkLevel=0,this.linkContent="",this.labelUnmatchedScopes=0}function ot(t,e){var i,s,n,o=-1,r=t.posMax,a=t.pos,l=t.isInLabel;if(t.isInLabel)return-1;if(t.labelUnmatchedScopes)return t.labelUnmatchedScopes--,-1;for(t.pos=e+1,t.isInLabel=!0,i=1;t.pos<r;){if(91===(n=t.src.charCodeAt(t.pos)))i++;else if(93===n&&0===--i){s=!0;break}t.parser.skipToken(t)}return s?(o=t.pos,t.labelUnmatchedScopes=0):t.labelUnmatchedScopes=i-1,t.pos=a,t.isInLabel=l,o}function rt(t,e,i,s){var n,o,r,a,l,c;if(42!==t.charCodeAt(0)||91!==t.charCodeAt(1)||-1===t.indexOf("]:")||((o=ot(n=new nt(t,e,i,s,[]),1))<0||58!==t.charCodeAt(o+1)))return-1;for(a=n.posMax,r=o+2;r<a&&10!==n.src.charCodeAt(r);r++);return l=t.slice(2,o),0===(c=t.slice(o+2,r).trim()).length?-1:(s.abbreviations||(s.abbreviations={}),typeof s.abbreviations[":"+l]>"u"&&(s.abbreviations[":"+l]=c),r)}function at(t){var e=K(t);try{e=decodeURI(e)}catch{}return encodeURI(e)}function lt(t,e){var i,s,n,o=e,r=t.posMax;if(60===t.src.charCodeAt(e)){for(e++;e<r;){if(10===(i=t.src.charCodeAt(e)))return!1;if(62===i)return n=at(D(t.src.slice(o+1,e))),!!t.parser.validateLink(n)&&(t.pos=e+1,t.linkContent=n,!0);92===i&&e+1<r?e+=2:e++}return!1}for(s=0;e<r&&!(32===(i=t.src.charCodeAt(e))||i<32||127===i);)if(92===i&&e+1<r)e+=2;else{if(40===i&&++s>1||41===i&&--s<0)break;e++}return!(o===e||(n=D(t.src.slice(o,e)),!t.parser.validateLink(n)))&&(t.linkContent=n,t.pos=e,!0)}function ct(t,e){var i,s=e,n=t.posMax,o=t.src.charCodeAt(e);if(34!==o&&39!==o&&40!==o)return!1;for(e++,40===o&&(o=41);e<n;){if((i=t.src.charCodeAt(e))===o)return t.pos=e+1,t.linkContent=D(t.src.slice(s+1,e)),!0;92===i&&e+1<n?e+=2:e++}return!1}function ht(t){return t.trim().replace(/\s+/g," ").toUpperCase()}function ut(t,e,i,s){var n,o,r,a,l,c,h,u,d;if(91!==t.charCodeAt(0)||-1===t.indexOf("]:")||((o=ot(n=new nt(t,e,i,s,[]),0))<0||58!==t.charCodeAt(o+1)))return-1;for(a=n.posMax,r=o+2;r<a&&(32===(l=n.src.charCodeAt(r))||10===l);r++);if(!lt(n,r))return-1;for(h=n.linkContent,c=r=n.pos,r+=1;r<a&&(32===(l=n.src.charCodeAt(r))||10===l);r++);for(r<a&&c!==r&&ct(n,r)?(u=n.linkContent,r=n.pos):(u="",r=c);r<a&&32===n.src.charCodeAt(r);)r++;return r<a&&10!==n.src.charCodeAt(r)?-1:(d=ht(t.slice(1,o)),typeof s.references[d]>"u"&&(s.references[d]={title:u,href:h}),r)}it.prototype.renderInline=function(t,e,i){for(var s=this.rules,n=t.length,o=0,r="";n--;)r+=s[t[o].type](t,o++,e,i,this);return r},it.prototype.render=function(t,e,i){for(var s=this.rules,n=t.length,o=-1,r="";++o<n;)"inline"===t[o].type?r+=this.renderInline(t[o].children,e,i):r+=s[t[o].type](t,o,e,i,this);return r},st.prototype.o=function(t){for(var e=this.t.length,i=-1;e--;)if(this.t[++i].name===t)return i;return-1},st.prototype.l=function(){var t=this,e=[""];t.t.forEach((function(t){t.enabled&&t.alt.forEach((function(t){e.indexOf(t)<0&&e.push(t)}))})),t.i={},e.forEach((function(e){t.i[e]=[],t.t.forEach((function(i){i.enabled&&(e&&i.alt.indexOf(e)<0||t.i[e].push(i.fn))}))}))},st.prototype.at=function(t,e,i){var s=this.o(t),n=i||{};if(-1===s)throw new Error("Parser rule not found: "+t);this.t[s].fn=e,this.t[s].alt=n.alt||[],this.i=null},st.prototype.before=function(t,e,i,s){var n=this.o(t),o=s||{};if(-1===n)throw new Error("Parser rule not found: "+t);this.t.splice(n,0,{name:e,enabled:!0,fn:i,alt:o.alt||[]}),this.i=null},st.prototype.after=function(t,e,i,s){var n=this.o(t),o=s||{};if(-1===n)throw new Error("Parser rule not found: "+t);this.t.splice(n+1,0,{name:e,enabled:!0,fn:i,alt:o.alt||[]}),this.i=null},st.prototype.push=function(t,e,i){var s=i||{};this.t.push({name:t,enabled:!0,fn:e,alt:s.alt||[]}),this.i=null},st.prototype.enable=function(t,e){t=Array.isArray(t)?t:[t],e&&this.t.forEach((function(t){t.enabled=!1})),t.forEach((function(t){var e=this.o(t);if(e<0)throw new Error("Rules manager: invalid rule name "+t);this.t[e].enabled=!0}),this),this.i=null},st.prototype.disable=function(t){(t=Array.isArray(t)?t:[t]).forEach((function(t){var e=this.o(t);if(e<0)throw new Error("Rules manager: invalid rule name "+t);this.t[e].enabled=!1}),this),this.i=null},st.prototype.getRules=function(t){return null===this.i&&this.l(),this.i[t]||[]},nt.prototype.pushPending=function(){this.tokens.push({type:"text",content:this.pending,level:this.pendingLevel}),this.pending=""},nt.prototype.push=function(t){this.pending&&this.pushPending(),this.tokens.push(t),this.pendingLevel=this.level},nt.prototype.cacheSet=function(t,e){for(var i=this.cache.length;i<=t;i++)this.cache.push(0);this.cache[t]=e},nt.prototype.cacheGet=function(t){return t<this.cache.length?this.cache[t]:0};var dt=" \n()[]'\".,!?-";function pt(t){return t.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1")}var mt=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,vt=/\((c|tm|r|p)\)/gi,ft={c:"©",r:"®",p:"§",tm:"™"};function gt(t){return t.indexOf("(")<0?t:t.replace(vt,(function(t,e){return ft[e.toLowerCase()]}))}var bt=/['"]/,yt=/['"]/g,wt=/[-\s()\[\]]/;function xt(t,e){return!(e<0||e>=t.length)&&!wt.test(t[e])}function kt(t,e,i){return t.substr(0,e)+i+t.substr(e+1)}var _t=[["block",function(t){t.inlineMode?t.tokens.push({type:"inline",content:t.src.replace(/\n/g," ").trim(),level:0,lines:[0,1],children:[]}):t.block.parse(t.src,t.options,t.env,t.tokens)}],["abbr",function(t){var e,i,s,n,o=t.tokens;if(!t.inlineMode)for(e=1,i=o.length-1;e<i;e++)if("paragraph_open"===o[e-1].type&&"inline"===o[e].type&&"paragraph_close"===o[e+1].type){for(s=o[e].content;s.length&&!((n=rt(s,t.inline,t.options,t.env))<0);)s=s.slice(n).trim();o[e].content=s,s.length||(o[e-1].tight=!0,o[e+1].tight=!0)}}],["references",function(t){var e,i,s,n,o=t.tokens;if(t.env.references=t.env.references||{},!t.inlineMode)for(e=1,i=o.length-1;e<i;e++)if("inline"===o[e].type&&"paragraph_open"===o[e-1].type&&"paragraph_close"===o[e+1].type){for(s=o[e].content;s.length&&!((n=ut(s,t.inline,t.options,t.env))<0);)s=s.slice(n).trim();o[e].content=s,s.length||(o[e-1].tight=!0,o[e+1].tight=!0)}}],["inline",function(t){var e,i,s,n=t.tokens;for(i=0,s=n.length;i<s;i++)"inline"===(e=n[i]).type&&t.inline.parse(e.content,t.options,t.env,e.children)}],["footnote_tail",function(t){var e,i,s,n,o,r,a,l,c,h=0,u=!1,d={};if(t.env.footnotes&&(t.tokens=t.tokens.filter((function(t){return"footnote_reference_open"===t.type?(u=!0,l=[],c=t.label,!1):"footnote_reference_close"===t.type?(u=!1,d[":"+c]=l,!1):(u&&l.push(t),!u)})),t.env.footnotes.list)){for(r=t.env.footnotes.list,t.tokens.push({type:"footnote_block_open",level:h++}),e=0,i=r.length;e<i;e++){for(t.tokens.push({type:"footnote_open",id:e,level:h++}),r[e].tokens?((a=[]).push({type:"paragraph_open",tight:!1,level:h++}),a.push({type:"inline",content:"",level:h,children:r[e].tokens}),a.push({type:"paragraph_close",tight:!1,level:--h})):r[e].label&&(a=d[":"+r[e].label]),t.tokens=t.tokens.concat(a),o="paragraph_close"===t.tokens[t.tokens.length-1].type?t.tokens.pop():null,n=r[e].count>0?r[e].count:1,s=0;s<n;s++)t.tokens.push({type:"footnote_anchor",id:e,subId:s,level:h});o&&t.tokens.push(o),t.tokens.push({type:"footnote_close",level:--h})}t.tokens.push({type:"footnote_block_close",level:--h})}}],["abbr2",function(t){var e,i,s,n,o,r,a,l,c,h,u,d,p=t.tokens;if(t.env.abbreviations)for(t.env.abbrRegExp||(d="(^|["+dt.split("").map(pt).join("")+"])("+Object.keys(t.env.abbreviations).map((function(t){return t.substr(1)})).sort((function(t,e){return e.length-t.length})).map(pt).join("|")+")($|["+dt.split("").map(pt).join("")+"])",t.env.abbrRegExp=new RegExp(d,"g")),h=t.env.abbrRegExp,i=0,s=p.length;i<s;i++)if("inline"===p[i].type)for(e=(n=p[i].children).length-1;e>=0;e--)if("text"===(o=n[e]).type){for(l=0,r=o.content,h.lastIndex=0,c=o.level,a=[];u=h.exec(r);)h.lastIndex>l&&a.push({type:"text",content:r.slice(l,u.index+u[1].length),level:c}),a.push({type:"abbr_open",title:t.env.abbreviations[":"+u[2]],level:c++}),a.push({type:"text",content:u[2],level:c}),a.push({type:"abbr_close",level:--c}),l=h.lastIndex-u[3].length;a.length&&(l<r.length&&a.push({type:"text",content:r.slice(l),level:c}),p[i].children=n=[].concat(n.slice(0,e),a,n.slice(e+1)))}}],["replacements",function(t){var e,i,s,n,o;if(t.options.typographer)for(o=t.tokens.length-1;o>=0;o--)if("inline"===t.tokens[o].type)for(e=(n=t.tokens[o].children).length-1;e>=0;e--)"text"===(i=n[e]).type&&(s=gt(s=i.content),mt.test(s)&&(s=s.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---([^-]|$)/gm,"$1—$2").replace(/(^|\s)--(\s|$)/gm,"$1–$2").replace(/(^|[^-\s])--([^-\s]|$)/gm,"$1–$2")),i.content=s)}],["smartquotes",function(t){var e,i,s,n,o,r,a,l,c,h,u,d,p,m,v,f,g;if(t.options.typographer)for(g=[],v=t.tokens.length-1;v>=0;v--)if("inline"===t.tokens[v].type)for(f=t.tokens[v].children,g.length=0,e=0;e<f.length;e++)if("text"===(i=f[e]).type&&!bt.test(i.text)){for(a=f[e].level,p=g.length-1;p>=0&&!(g[p].level<=a);p--);g.length=p+1,o=0,r=(s=i.content).length;t:for(;o<r&&(yt.lastIndex=o,n=yt.exec(s),n);)if(l=!xt(s,n.index-1),o=n.index+1,m="'"===n[0],(c=!xt(s,o))||l){if(u=!c,d=!l)for(p=g.length-1;p>=0&&(h=g[p],!(g[p].level<a));p--)if(h.single===m&&g[p].level===a){h=g[p],m?(f[h.token].content=kt(f[h.token].content,h.pos,t.options.quotes[2]),i.content=kt(i.content,n.index,t.options.quotes[3])):(f[h.token].content=kt(f[h.token].content,h.pos,t.options.quotes[0]),i.content=kt(i.content,n.index,t.options.quotes[1])),g.length=p;continue t}u?g.push({token:e,pos:n.index,single:m,level:a}):d&&m&&(i.content=kt(i.content,n.index,"’"))}else m&&(i.content=kt(i.content,n.index,"’"))}}]];function St(){this.options={},this.ruler=new st;for(var t=0;t<_t.length;t++)this.ruler.push(_t[t][0],_t[t][1])}function At(t,e,i,s,n){var o,r,a,l,c,h,u;for(this.src=t,this.parser=e,this.options=i,this.env=s,this.tokens=n,this.bMarks=[],this.eMarks=[],this.tShift=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.parentType="root",this.ddIndent=-1,this.level=0,this.result="",h=0,u=!1,a=l=h=0,c=(r=this.src).length;l<c;l++){if(o=r.charCodeAt(l),!u){if(32===o){h++;continue}u=!0}(10===o||l===c-1)&&(10!==o&&l++,this.bMarks.push(a),this.eMarks.push(l),this.tShift.push(h),u=!1,h=0,a=l+1)}this.bMarks.push(r.length),this.eMarks.push(r.length),this.tShift.push(0),this.lineMax=this.bMarks.length-1}function Tt(t,e){var i,s,n;return(s=t.bMarks[e]+t.tShift[e])>=(n=t.eMarks[e])||42!==(i=t.src.charCodeAt(s++))&&45!==i&&43!==i||s<n&&32!==t.src.charCodeAt(s)?-1:s}function Mt(t,e){var i,s=t.bMarks[e]+t.tShift[e],n=t.eMarks[e];if(s+1>=n||((i=t.src.charCodeAt(s++))<48||i>57))return-1;for(;;){if(s>=n)return-1;if(!((i=t.src.charCodeAt(s++))>=48&&i<=57)){if(41===i||46===i)break;return-1}}return s<n&&32!==t.src.charCodeAt(s)?-1:s}St.prototype.process=function(t){var e,i,s;for(e=0,i=(s=this.ruler.getRules("")).length;e<i;e++)s[e](t)},At.prototype.isEmpty=function(t){return this.bMarks[t]+this.tShift[t]>=this.eMarks[t]},At.prototype.skipEmptyLines=function(t){for(var e=this.lineMax;t<e&&!(this.bMarks[t]+this.tShift[t]<this.eMarks[t]);t++);return t},At.prototype.skipSpaces=function(t){for(var e=this.src.length;t<e&&32===this.src.charCodeAt(t);t++);return t},At.prototype.skipChars=function(t,e){for(var i=this.src.length;t<i&&this.src.charCodeAt(t)===e;t++);return t},At.prototype.skipCharsBack=function(t,e,i){if(t<=i)return t;for(;t>i;)if(e!==this.src.charCodeAt(--t))return t+1;return t},At.prototype.getLines=function(t,e,i,s){var n,o,r,a,l,c=t;if(t>=e)return"";if(c+1===e)return o=this.bMarks[c]+Math.min(this.tShift[c],i),r=s?this.eMarks[c]+1:this.eMarks[c],this.src.slice(o,r);for(a=new Array(e-t),n=0;c<e;c++,n++)(l=this.tShift[c])>i&&(l=i),l<0&&(l=0),o=this.bMarks[c]+l,r=c+1<e||s?this.eMarks[c]+1:this.eMarks[c],a[n]=this.src.slice(o,r);return a.join("")};var Ot={};["article","aside","button","blockquote","body","canvas","caption","col","colgroup","dd","div","dl","dt","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","hr","iframe","li","map","object","ol","output","p","pre","progress","script","section","style","table","tbody","td","textarea","tfoot","th","tr","thead","ul","video"].forEach((function(t){Ot[t]=!0}));var jt=/^<([a-zA-Z]{1,15})[\s\/>]/,Ct=/^<\/([a-zA-Z]{1,15})[\s>]/;function Et(t,e){var i=t.bMarks[e]+t.blkIndent,s=t.eMarks[e];return t.src.substr(i,s-i)}function It(t,e){var i,s,n=t.bMarks[e]+t.tShift[e],o=t.eMarks[e];return n>=o||126!==(s=t.src.charCodeAt(n++))&&58!==s||n===(i=t.skipSpaces(n))||i>=o?-1:i}var Pt=[["code",function(t,e,i){var s,n;if(t.tShift[e]-t.blkIndent<4)return!1;for(n=s=e+1;s<i;)if(t.isEmpty(s))s++;else{if(!(t.tShift[s]-t.blkIndent>=4))break;n=++s}return t.line=s,t.tokens.push({type:"code",content:t.getLines(e,n,4+t.blkIndent,!0),block:!0,lines:[e,t.line],level:t.level}),!0}],["fences",function(t,e,i,s){var n,o,r,a,l,c=!1,h=t.bMarks[e]+t.tShift[e],u=t.eMarks[e];if(h+3>u||126!==(n=t.src.charCodeAt(h))&&96!==n||(l=h,(o=(h=t.skipChars(h,n))-l)<3)||(r=t.src.slice(h,u).trim()).indexOf("`")>=0)return!1;if(s)return!0;for(a=e;!(++a>=i||(h=l=t.bMarks[a]+t.tShift[a],u=t.eMarks[a],h<u&&t.tShift[a]<t.blkIndent));)if(!(t.src.charCodeAt(h)!==n||t.tShift[a]-t.blkIndent>=4||(h=t.skipChars(h,n),h-l<o||(h=t.skipSpaces(h),h<u)))){c=!0;break}return o=t.tShift[e],t.line=a+(c?1:0),t.tokens.push({type:"fence",params:r,content:t.getLines(e+1,a,o,!0),lines:[e,t.line],level:t.level}),!0},["paragraph","blockquote","list"]],["blockquote",function(t,e,i,s){var n,o,r,a,l,c,h,u,d,p,m,v=t.bMarks[e]+t.tShift[e],f=t.eMarks[e];if(v>f||62!==t.src.charCodeAt(v++)||t.level>=t.options.maxNesting)return!1;if(s)return!0;for(32===t.src.charCodeAt(v)&&v++,l=t.blkIndent,t.blkIndent=0,a=[t.bMarks[e]],t.bMarks[e]=v,o=(v=v<f?t.skipSpaces(v):v)>=f,r=[t.tShift[e]],t.tShift[e]=v-t.bMarks[e],u=t.parser.ruler.getRules("blockquote"),n=e+1;n<i&&!((v=t.bMarks[n]+t.tShift[n])>=(f=t.eMarks[n]));n++)if(62!==t.src.charCodeAt(v++)){if(o)break;for(m=!1,d=0,p=u.length;d<p;d++)if(u[d](t,n,i,!0)){m=!0;break}if(m)break;a.push(t.bMarks[n]),r.push(t.tShift[n]),t.tShift[n]=-1337}else 32===t.src.charCodeAt(v)&&v++,a.push(t.bMarks[n]),t.bMarks[n]=v,o=(v=v<f?t.skipSpaces(v):v)>=f,r.push(t.tShift[n]),t.tShift[n]=v-t.bMarks[n];for(c=t.parentType,t.parentType="blockquote",t.tokens.push({type:"blockquote_open",lines:h=[e,0],level:t.level++}),t.parser.tokenize(t,e,n),t.tokens.push({type:"blockquote_close",level:--t.level}),t.parentType=c,h[1]=t.line,d=0;d<r.length;d++)t.bMarks[d+e]=a[d],t.tShift[d+e]=r[d];return t.blkIndent=l,!0},["paragraph","blockquote","list"]],["hr",function(t,e,i,s){var n,o,r,a=t.bMarks[e],l=t.eMarks[e];if((a+=t.tShift[e])>l||42!==(n=t.src.charCodeAt(a++))&&45!==n&&95!==n)return!1;for(o=1;a<l;){if((r=t.src.charCodeAt(a++))!==n&&32!==r)return!1;r===n&&o++}return!(o<3)&&(s||(t.line=e+1,t.tokens.push({type:"hr",lines:[e,t.line],level:t.level})),!0)},["paragraph","blockquote","list"]],["list",function(t,e,i,s){var n,o,r,a,l,c,h,u,d,p,m,v,f,g,b,y,w,x,k,_,S,A=!0;if((u=Mt(t,e))>=0)v=!0;else{if(!((u=Tt(t,e))>=0))return!1;v=!1}if(t.level>=t.options.maxNesting)return!1;if(m=t.src.charCodeAt(u-1),s)return!0;for(g=t.tokens.length,v?(h=t.bMarks[e]+t.tShift[e],p=Number(t.src.substr(h,u-h-1)),t.tokens.push({type:"ordered_list_open",order:p,lines:y=[e,0],level:t.level++})):t.tokens.push({type:"bullet_list_open",lines:y=[e,0],level:t.level++}),n=e,b=!1,x=t.parser.ruler.getRules("list");n<i&&((d=(f=t.skipSpaces(u))>=t.eMarks[n]?1:f-u)>4&&(d=1),d<1&&(d=1),o=u-t.bMarks[n]+d,t.tokens.push({type:"list_item_open",lines:w=[e,0],level:t.level++}),a=t.blkIndent,l=t.tight,r=t.tShift[e],c=t.parentType,t.tShift[e]=f-t.bMarks[e],t.blkIndent=o,t.tight=!0,t.parentType="list",t.parser.tokenize(t,e,i,!0),(!t.tight||b)&&(A=!1),b=t.line-e>1&&t.isEmpty(t.line-1),t.blkIndent=a,t.tShift[e]=r,t.tight=l,t.parentType=c,t.tokens.push({type:"list_item_close",level:--t.level}),n=e=t.line,w[1]=n,f=t.bMarks[e],!(n>=i||t.isEmpty(n)||t.tShift[n]<t.blkIndent));){for(S=!1,k=0,_=x.length;k<_;k++)if(x[k](t,n,i,!0)){S=!0;break}if(S)break;if(v){if((u=Mt(t,n))<0)break}else if((u=Tt(t,n))<0)break;if(m!==t.src.charCodeAt(u-1))break}return t.tokens.push({type:v?"ordered_list_close":"bullet_list_close",level:--t.level}),y[1]=n,t.line=n,A&&function(t,e){var i,s,n=t.level+2;for(i=e+2,s=t.tokens.length-2;i<s;i++)t.tokens[i].level===n&&"paragraph_open"===t.tokens[i].type&&(t.tokens[i+2].tight=!0,t.tokens[i].tight=!0,i+=2)}(t,g),!0},["paragraph","blockquote"]],["footnote",function(t,e,i,s){var n,o,r,a,l,c=t.bMarks[e]+t.tShift[e],h=t.eMarks[e];if(c+4>h||91!==t.src.charCodeAt(c)||94!==t.src.charCodeAt(c+1)||t.level>=t.options.maxNesting)return!1;for(a=c+2;a<h;a++){if(32===t.src.charCodeAt(a))return!1;if(93===t.src.charCodeAt(a))break}return!(a===c+2||a+1>=h||58!==t.src.charCodeAt(++a))&&(s||(a++,t.env.footnotes||(t.env.footnotes={}),t.env.footnotes.refs||(t.env.footnotes.refs={}),l=t.src.slice(c+2,a-2),t.env.footnotes.refs[":"+l]=-1,t.tokens.push({type:"footnote_reference_open",label:l,level:t.level++}),n=t.bMarks[e],o=t.tShift[e],r=t.parentType,t.tShift[e]=t.skipSpaces(a)-a,t.bMarks[e]=a,t.blkIndent+=4,t.parentType="footnote",t.tShift[e]<t.blkIndent&&(t.tShift[e]+=t.blkIndent,t.bMarks[e]-=t.blkIndent),t.parser.tokenize(t,e,i,!0),t.parentType=r,t.blkIndent-=4,t.tShift[e]=o,t.bMarks[e]=n,t.tokens.push({type:"footnote_reference_close",level:--t.level})),!0)},["paragraph"]],["heading",function(t,e,i,s){var n,o,r,a=t.bMarks[e]+t.tShift[e],l=t.eMarks[e];if(a>=l||(35!==(n=t.src.charCodeAt(a))||a>=l))return!1;for(o=1,n=t.src.charCodeAt(++a);35===n&&a<l&&o<=6;)o++,n=t.src.charCodeAt(++a);return!(o>6||a<l&&32!==n)&&(s||(l=t.skipCharsBack(l,32,a),(r=t.skipCharsBack(l,35,a))>a&&32===t.src.charCodeAt(r-1)&&(l=r),t.line=e+1,t.tokens.push({type:"heading_open",hLevel:o,lines:[e,t.line],level:t.level}),a<l&&t.tokens.push({type:"inline",content:t.src.slice(a,l).trim(),level:t.level+1,lines:[e,t.line],children:[]}),t.tokens.push({type:"heading_close",hLevel:o,level:t.level})),!0)},["paragraph","blockquote"]],["lheading",function(t,e,i){var s,n,o,r=e+1;return!(r>=i||t.tShift[r]<t.blkIndent||t.tShift[r]-t.blkIndent>3||(n=t.bMarks[r]+t.tShift[r],o=t.eMarks[r],n>=o)||(s=t.src.charCodeAt(n),45!==s&&61!==s)||(n=t.skipChars(n,s),n=t.skipSpaces(n),n<o))&&(n=t.bMarks[e]+t.tShift[e],t.line=r+1,t.tokens.push({type:"heading_open",hLevel:61===s?1:2,lines:[e,t.line],level:t.level}),t.tokens.push({type:"inline",content:t.src.slice(n,t.eMarks[e]).trim(),level:t.level+1,lines:[e,t.line-1],children:[]}),t.tokens.push({type:"heading_close",hLevel:61===s?1:2,level:t.level}),!0)}],["htmlblock",function(t,e,i,s){var n,o,r,a=t.bMarks[e],l=t.eMarks[e],c=t.tShift[e];if(a+=c,!t.options.html||c>3||a+2>=l||60!==t.src.charCodeAt(a))return!1;if(33===(n=t.src.charCodeAt(a+1))||63===n){if(s)return!0}else{if(47!==n&&!function(t){var e=32|t;return e>=97&&e<=122}(n))return!1;if(47===n){if(!(o=t.src.slice(a,l).match(Ct)))return!1}else if(!(o=t.src.slice(a,l).match(jt)))return!1;if(!0!==Ot[o[1].toLowerCase()])return!1;if(s)return!0}for(r=e+1;r<t.lineMax&&!t.isEmpty(r);)r++;return t.line=r,t.tokens.push({type:"htmlblock",level:t.level,lines:[e,t.line],content:t.getLines(e,r,0,!0)}),!0},["paragraph","blockquote"]],["table",function(t,e,i,s){var n,o,r,a,l,c,h,u,d,p,m;if(e+2>i||(l=e+1,t.tShift[l]<t.blkIndent)||(r=t.bMarks[l]+t.tShift[l])>=t.eMarks[l]||124!==(n=t.src.charCodeAt(r))&&45!==n&&58!==n||(o=Et(t,e+1),!/^[-:| ]+$/.test(o))||(c=o.split("|"))<=2)return!1;for(u=[],a=0;a<c.length;a++){if(!(d=c[a].trim())){if(0===a||a===c.length-1)continue;return!1}if(!/^:?-+:?$/.test(d))return!1;58===d.charCodeAt(d.length-1)?u.push(58===d.charCodeAt(0)?"center":"right"):58===d.charCodeAt(0)?u.push("left"):u.push("")}if(-1===(o=Et(t,e).trim()).indexOf("|")||(c=o.replace(/^\||\|$/g,"").split("|"),u.length!==c.length))return!1;if(s)return!0;for(t.tokens.push({type:"table_open",lines:p=[e,0],level:t.level++}),t.tokens.push({type:"thead_open",lines:[e,e+1],level:t.level++}),t.tokens.push({type:"tr_open",lines:[e,e+1],level:t.level++}),a=0;a<c.length;a++)t.tokens.push({type:"th_open",align:u[a],lines:[e,e+1],level:t.level++}),t.tokens.push({type:"inline",content:c[a].trim(),lines:[e,e+1],level:t.level,children:[]}),t.tokens.push({type:"th_close",level:--t.level});for(t.tokens.push({type:"tr_close",level:--t.level}),t.tokens.push({type:"thead_close",level:--t.level}),t.tokens.push({type:"tbody_open",lines:m=[e+2,0],level:t.level++}),l=e+2;l<i&&!(t.tShift[l]<t.blkIndent||(o=Et(t,l).trim(),-1===o.indexOf("|")));l++){for(c=o.replace(/^\||\|$/g,"").split("|"),t.tokens.push({type:"tr_open",level:t.level++}),a=0;a<c.length;a++)t.tokens.push({type:"td_open",align:u[a],level:t.level++}),h=c[a].substring(124===c[a].charCodeAt(0)?1:0,124===c[a].charCodeAt(c[a].length-1)?c[a].length-1:c[a].length).trim(),t.tokens.push({type:"inline",content:h,level:t.level,children:[]}),t.tokens.push({type:"td_close",level:--t.level});t.tokens.push({type:"tr_close",level:--t.level})}return t.tokens.push({type:"tbody_close",level:--t.level}),t.tokens.push({type:"table_close",level:--t.level}),p[1]=m[1]=l,t.line=l,!0},["paragraph"]],["deflist",function(t,e,i,s){var n,o,r,a,l,c,h,u,d,p,m,v,f,g;if(s)return!(t.ddIndent<0)&&It(t,e)>=0;if(h=e+1,t.isEmpty(h)&&++h>i||t.tShift[h]<t.blkIndent||(n=It(t,h))<0||t.level>=t.options.maxNesting)return!1;c=t.tokens.length,t.tokens.push({type:"dl_open",lines:l=[e,0],level:t.level++}),r=e,o=h;t:for(;;){for(g=!0,f=!1,t.tokens.push({type:"dt_open",lines:[r,r],level:t.level++}),t.tokens.push({type:"inline",content:t.getLines(r,r+1,t.blkIndent,!1).trim(),level:t.level+1,lines:[r,r],children:[]}),t.tokens.push({type:"dt_close",level:--t.level});;){if(t.tokens.push({type:"dd_open",lines:a=[h,0],level:t.level++}),v=t.tight,d=t.ddIndent,u=t.blkIndent,m=t.tShift[o],p=t.parentType,t.blkIndent=t.ddIndent=t.tShift[o]+2,t.tShift[o]=n-t.bMarks[o],t.tight=!0,t.parentType="deflist",t.parser.tokenize(t,o,i,!0),(!t.tight||f)&&(g=!1),f=t.line-o>1&&t.isEmpty(t.line-1),t.tShift[o]=m,t.tight=v,t.parentType=p,t.blkIndent=u,t.ddIndent=d,t.tokens.push({type:"dd_close",level:--t.level}),a[1]=h=t.line,h>=i||t.tShift[h]<t.blkIndent)break t;if((n=It(t,h))<0)break;o=h}if(h>=i||(r=h,t.isEmpty(r))||t.tShift[r]<t.blkIndent||(o=r+1)>=i||(t.isEmpty(o)&&o++,o>=i)||t.tShift[o]<t.blkIndent||(n=It(t,o))<0)break}return t.tokens.push({type:"dl_close",level:--t.level}),l[1]=h,t.line=h,g&&function(t,e){var i,s,n=t.level+2;for(i=e+2,s=t.tokens.length-2;i<s;i++)t.tokens[i].level===n&&"paragraph_open"===t.tokens[i].type&&(t.tokens[i+2].tight=!0,t.tokens[i].tight=!0,i+=2)}(t,c),!0},["paragraph"]],["paragraph",function(t,e){var i,s,n,o,r,a,l=e+1;if(l<(i=t.lineMax)&&!t.isEmpty(l))for(a=t.parser.ruler.getRules("paragraph");l<i&&!t.isEmpty(l);l++)if(!(t.tShift[l]-t.blkIndent>3)){for(n=!1,o=0,r=a.length;o<r;o++)if(a[o](t,l,i,!0)){n=!0;break}if(n)break}return s=t.getLines(e,l,t.blkIndent,!1).trim(),t.line=l,s.length&&(t.tokens.push({type:"paragraph_open",tight:!1,lines:[e,t.line],level:t.level}),t.tokens.push({type:"inline",content:s,level:t.level+1,lines:[e,t.line],children:[]}),t.tokens.push({type:"paragraph_close",tight:!1,level:t.level})),!0}]];function Nt(){this.ruler=new st;for(var t=0;t<Pt.length;t++)this.ruler.push(Pt[t][0],Pt[t][1],{alt:(Pt[t][2]||[]).slice()})}Nt.prototype.tokenize=function(t,e,i){for(var s,n=this.ruler.getRules(""),o=n.length,r=e,a=!1;r<i&&(t.line=r=t.skipEmptyLines(r),!(r>=i||t.tShift[r]<t.blkIndent));){for(s=0;s<o&&!n[s](t,r,i,!1);s++);if(t.tight=!a,t.isEmpty(t.line-1)&&(a=!0),(r=t.line)<i&&t.isEmpty(r)){if(a=!0,++r<i&&"list"===t.parentType&&t.isEmpty(r))break;t.line=r}}};var Rt=/[\n\t]/g,qt=/\r[\n\u0085]|[\u2424\u2028\u0085]/g,Bt=/\u00a0/g;function Lt(t){switch(t){case 10:case 92:case 96:case 42:case 95:case 94:case 91:case 93:case 33:case 38:case 60:case 62:case 123:case 125:case 36:case 37:case 64:case 126:case 43:case 61:case 58:return!0;default:return!1}}Nt.prototype.parse=function(t,e,i,s){var n,o=0,r=0;if(!t)return[];(t=(t=t.replace(Bt," ")).replace(qt,"\n")).indexOf("\t")>=0&&(t=t.replace(Rt,(function(e,i){var s;return 10===t.charCodeAt(i)?(o=i+1,r=0,e):(s=" ".slice((i-o-r)%4),r=i-o+1,s)}))),n=new At(t,this,e,i,s),this.tokenize(n,n.line,n.lineMax)};for(var Ft=[],zt=0;zt<256;zt++)Ft.push(0);function Dt(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}function $t(t,e){var i,s,n,o=e,r=!0,a=!0,l=t.posMax,c=t.src.charCodeAt(e);for(i=e>0?t.src.charCodeAt(e-1):-1;o<l&&t.src.charCodeAt(o)===c;)o++;return o>=l&&(r=!1),(n=o-e)>=4?r=a=!1:((32===(s=o<l?t.src.charCodeAt(o):-1)||10===s)&&(r=!1),(32===i||10===i)&&(a=!1),95===c&&(Dt(i)&&(r=!1),Dt(s)&&(a=!1))),{can_open:r,can_close:a,delims:n}}"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach((function(t){Ft[t.charCodeAt(0)]=1}));var Jt=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Ut=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Vt=["coap","doi","javascript","aaa","aaas","about","acap","cap","cid","crid","data","dav","dict","dns","file","ftp","geo","go","gopher","h323","http","https","iax","icap","im","imap","info","ipp","iris","iris.beep","iris.xpc","iris.xpcs","iris.lwz","ldap","mailto","mid","msrp","msrps","mtqp","mupdate","news","nfs","ni","nih","nntp","opaquelocktoken","pop","pres","rtsp","service","session","shttp","sieve","sip","sips","sms","snmp","soap.beep","soap.beeps","tag","tel","telnet","tftp","thismessage","tn3270","tip","tv","urn","vemmi","ws","wss","xcon","xcon-userid","xmlrpc.beep","xmlrpc.beeps","xmpp","z39.50r","z39.50s","adiumxtra","afp","afs","aim","apt","attachment","aw","beshare","bitcoin","bolo","callto","chrome","chrome-extension","com-eventbrite-attendee","content","cvs","dlna-playsingle","dlna-playcontainer","dtn","dvb","ed2k","facetime","feed","finger","fish","gg","git","gizmoproject","gtalk","hcp","icon","ipn","irc","irc6","ircs","itms","jar","jms","keyparc","lastfm","ldaps","magnet","maps","market","message","mms","ms-help","msnim","mumble","mvn","notes","oid","palm","paparazzi","platform","proxy","psyc","query","res","resource","rmi","rsync","rtmp","secondlife","sftp","sgn","skype","smb","soldat","spotify","ssh","steam","svn","teamspeak","things","udp","unreal","ut2004","ventrilo","view-source","webcal","wtai","wyciwyg","xfire","xri","ymsgr"],Ht=/^<([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/,Kt=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;function Gt(t,e){return t=t.source,e=e||"",function i(s,n){return s?(n=n.source||n,t=t.replace(s,n),i):new RegExp(t,e)}}var Zt=Gt(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",/[^"'=<>`\x00-\x20]+/)("single_quoted",/'[^']*'/)("double_quoted",/"[^"]*"/)(),Wt=Gt(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",/[a-zA-Z_:][a-zA-Z0-9:._-]*/)("attr_value",Zt)(),Xt=Gt(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",Wt)(),Yt=Gt(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",Xt)("close_tag",/<\/[A-Za-z][A-Za-z0-9]*\s*>/)("comment",/<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->/)("processing",/<[?].*?[?]>/)("declaration",/<![A-Z]+\s+[^>]*>/)("cdata",/<!\[CDATA\[[\s\S]*?\]\]>/)();var Qt=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,te=/^&([a-z][a-z0-9]{1,31});/i;var ee=[["text",function(t,e){for(var i=t.pos;i<t.posMax&&!Lt(t.src.charCodeAt(i));)i++;return i!==t.pos&&(e||(t.pending+=t.src.slice(t.pos,i)),t.pos=i,!0)}],["newline",function(t,e){var i,s,n=t.pos;if(10!==t.src.charCodeAt(n))return!1;if(i=t.pending.length-1,s=t.posMax,!e)if(i>=0&&32===t.pending.charCodeAt(i))if(i>=1&&32===t.pending.charCodeAt(i-1)){for(var o=i-2;o>=0;o--)if(32!==t.pending.charCodeAt(o)){t.pending=t.pending.substring(0,o+1);break}t.push({type:"hardbreak",level:t.level})}else t.pending=t.pending.slice(0,-1),t.push({type:"softbreak",level:t.level});else t.push({type:"softbreak",level:t.level});for(n++;n<s&&32===t.src.charCodeAt(n);)n++;return t.pos=n,!0}],["escape",function(t,e){var i,s=t.pos,n=t.posMax;if(92!==t.src.charCodeAt(s))return!1;if(++s<n){if((i=t.src.charCodeAt(s))<256&&0!==Ft[i])return e||(t.pending+=t.src[s]),t.pos+=2,!0;if(10===i){for(e||t.push({type:"hardbreak",level:t.level}),s++;s<n&&32===t.src.charCodeAt(s);)s++;return t.pos=s,!0}}return e||(t.pending+="\\"),t.pos++,!0}],["backticks",function(t,e){var i,s,n,o,r,a=t.pos;if(96!==t.src.charCodeAt(a))return!1;for(i=a,a++,s=t.posMax;a<s&&96===t.src.charCodeAt(a);)a++;for(n=t.src.slice(i,a),o=r=a;-1!==(o=t.src.indexOf("`",r));){for(r=o+1;r<s&&96===t.src.charCodeAt(r);)r++;if(r-o===n.length)return e||t.push({type:"code",content:t.src.slice(a,o).replace(/[ \n]+/g," ").trim(),block:!1,level:t.level}),t.pos=r,!0}return e||(t.pending+=n),t.pos+=n.length,!0}],["del",function(t,e){var i,s,n,o,r,a=t.posMax,l=t.pos;if(126!==t.src.charCodeAt(l)||e||l+4>=a||126!==t.src.charCodeAt(l+1)||t.level>=t.options.maxNesting||(o=l>0?t.src.charCodeAt(l-1):-1,r=t.src.charCodeAt(l+2),126===o)||126===r||32===r||10===r)return!1;for(s=l+2;s<a&&126===t.src.charCodeAt(s);)s++;if(s>l+3)return t.pos+=s-l,e||(t.pending+=t.src.slice(l,s)),!0;for(t.pos=l+2,n=1;t.pos+1<a;){if(126===t.src.charCodeAt(t.pos)&&126===t.src.charCodeAt(t.pos+1)&&(o=t.src.charCodeAt(t.pos-1),126!==(r=t.pos+2<a?t.src.charCodeAt(t.pos+2):-1)&&126!==o&&(32!==o&&10!==o?n--:32!==r&&10!==r&&n++,n<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=l+2,e||(t.push({type:"del_open",level:t.level++}),t.parser.tokenize(t),t.push({type:"del_close",level:--t.level})),t.pos=t.posMax+2,t.posMax=a,!0):(t.pos=l,!1)}],["ins",function(t,e){var i,s,n,o,r,a=t.posMax,l=t.pos;if(43!==t.src.charCodeAt(l)||e||l+4>=a||43!==t.src.charCodeAt(l+1)||t.level>=t.options.maxNesting||(o=l>0?t.src.charCodeAt(l-1):-1,r=t.src.charCodeAt(l+2),43===o)||43===r||32===r||10===r)return!1;for(s=l+2;s<a&&43===t.src.charCodeAt(s);)s++;if(s!==l+2)return t.pos+=s-l,e||(t.pending+=t.src.slice(l,s)),!0;for(t.pos=l+2,n=1;t.pos+1<a;){if(43===t.src.charCodeAt(t.pos)&&43===t.src.charCodeAt(t.pos+1)&&(o=t.src.charCodeAt(t.pos-1),43!==(r=t.pos+2<a?t.src.charCodeAt(t.pos+2):-1)&&43!==o&&(32!==o&&10!==o?n--:32!==r&&10!==r&&n++,n<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=l+2,e||(t.push({type:"ins_open",level:t.level++}),t.parser.tokenize(t),t.push({type:"ins_close",level:--t.level})),t.pos=t.posMax+2,t.posMax=a,!0):(t.pos=l,!1)}],["mark",function(t,e){var i,s,n,o,r,a=t.posMax,l=t.pos;if(61!==t.src.charCodeAt(l)||e||l+4>=a||61!==t.src.charCodeAt(l+1)||t.level>=t.options.maxNesting||(o=l>0?t.src.charCodeAt(l-1):-1,r=t.src.charCodeAt(l+2),61===o)||61===r||32===r||10===r)return!1;for(s=l+2;s<a&&61===t.src.charCodeAt(s);)s++;if(s!==l+2)return t.pos+=s-l,e||(t.pending+=t.src.slice(l,s)),!0;for(t.pos=l+2,n=1;t.pos+1<a;){if(61===t.src.charCodeAt(t.pos)&&61===t.src.charCodeAt(t.pos+1)&&(o=t.src.charCodeAt(t.pos-1),61!==(r=t.pos+2<a?t.src.charCodeAt(t.pos+2):-1)&&61!==o&&(32!==o&&10!==o?n--:32!==r&&10!==r&&n++,n<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=l+2,e||(t.push({type:"mark_open",level:t.level++}),t.parser.tokenize(t),t.push({type:"mark_close",level:--t.level})),t.pos=t.posMax+2,t.posMax=a,!0):(t.pos=l,!1)}],["emphasis",function(t,e){var i,s,n,o,r,a,l,c=t.posMax,h=t.pos,u=t.src.charCodeAt(h);if(95!==u&&42!==u||e)return!1;if(i=(l=$t(t,h)).delims,!l.can_open)return t.pos+=i,e||(t.pending+=t.src.slice(h,t.pos)),!0;if(t.level>=t.options.maxNesting)return!1;for(t.pos=h+i,a=[i];t.pos<c;)if(t.src.charCodeAt(t.pos)!==u)t.parser.skipToken(t);else{if(s=(l=$t(t,t.pos)).delims,l.can_close){for(o=a.pop(),r=s;o!==r;){if(r<o){a.push(o-r);break}if(r-=o,0===a.length)break;t.pos+=o,o=a.pop()}if(0===a.length){i=o,n=!0;break}t.pos+=s;continue}l.can_open&&a.push(s),t.pos+=s}return n?(t.posMax=t.pos,t.pos=h+i,e||((2===i||3===i)&&t.push({type:"strong_open",level:t.level++}),(1===i||3===i)&&t.push({type:"em_open",level:t.level++}),t.parser.tokenize(t),(1===i||3===i)&&t.push({type:"em_close",level:--t.level}),(2===i||3===i)&&t.push({type:"strong_close",level:--t.level})),t.pos=t.posMax+i,t.posMax=c,!0):(t.pos=h,!1)}],["sub",function(t,e){var i,s,n=t.posMax,o=t.pos;if(126!==t.src.charCodeAt(o)||e||o+2>=n||t.level>=t.options.maxNesting)return!1;for(t.pos=o+1;t.pos<n;){if(126===t.src.charCodeAt(t.pos)){i=!0;break}t.parser.skipToken(t)}return!i||o+1===t.pos||(s=t.src.slice(o+1,t.pos)).match(/(^|[^\\])(\\\\)*\s/)?(t.pos=o,!1):(t.posMax=t.pos,t.pos=o+1,e||t.push({type:"sub",level:t.level,content:s.replace(Jt,"$1")}),t.pos=t.posMax+1,t.posMax=n,!0)}],["sup",function(t,e){var i,s,n=t.posMax,o=t.pos;if(94!==t.src.charCodeAt(o)||e||o+2>=n||t.level>=t.options.maxNesting)return!1;for(t.pos=o+1;t.pos<n;){if(94===t.src.charCodeAt(t.pos)){i=!0;break}t.parser.skipToken(t)}return!i||o+1===t.pos||(s=t.src.slice(o+1,t.pos)).match(/(^|[^\\])(\\\\)*\s/)?(t.pos=o,!1):(t.posMax=t.pos,t.pos=o+1,e||t.push({type:"sup",level:t.level,content:s.replace(Ut,"$1")}),t.pos=t.posMax+1,t.posMax=n,!0)}],["links",function(t,e){var i,s,n,o,r,a,l,c,h=!1,u=t.pos,d=t.posMax,p=t.pos,m=t.src.charCodeAt(p);if(33===m&&(h=!0,m=t.src.charCodeAt(++p)),91!==m||t.level>=t.options.maxNesting||(i=p+1,(s=ot(t,p))<0))return!1;if((a=s+1)<d&&40===t.src.charCodeAt(a)){for(a++;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);if(a>=d)return!1;for(p=a,lt(t,a)?(o=t.linkContent,a=t.pos):o="",p=a;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);if(a<d&&p!==a&&ct(t,a))for(r=t.linkContent,a=t.pos;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);else r="";if(a>=d||41!==t.src.charCodeAt(a))return t.pos=u,!1;a++}else{if(t.linkLevel>0)return!1;for(;a<d&&(32===(c=t.src.charCodeAt(a))||10===c);a++);if(a<d&&91===t.src.charCodeAt(a)&&(p=a+1,(a=ot(t,a))>=0?n=t.src.slice(p,a++):a=p-1),n||(typeof n>"u"&&(a=s+1),n=t.src.slice(i,s)),!(l=t.env.references[ht(n)]))return t.pos=u,!1;o=l.href,r=l.title}return e||(t.pos=i,t.posMax=s,h?t.push({type:"image",src:o,title:r,alt:t.src.substr(i,s-i),level:t.level}):(t.push({type:"link_open",href:o,title:r,level:t.level++}),t.linkLevel++,t.parser.tokenize(t),t.linkLevel--,t.push({type:"link_close",level:--t.level}))),t.pos=a,t.posMax=d,!0}],["footnote_inline",function(t,e){var i,s,n,o,r=t.posMax,a=t.pos;return!(a+2>=r||94!==t.src.charCodeAt(a)||91!==t.src.charCodeAt(a+1)||t.level>=t.options.maxNesting||(i=a+2,s=ot(t,a+1),s<0))&&(e||(t.env.footnotes||(t.env.footnotes={}),t.env.footnotes.list||(t.env.footnotes.list=[]),n=t.env.footnotes.list.length,t.pos=i,t.posMax=s,t.push({type:"footnote_ref",id:n,level:t.level}),t.linkLevel++,o=t.tokens.length,t.parser.tokenize(t),t.env.footnotes.list[n]={tokens:t.tokens.splice(o)},t.linkLevel--),t.pos=s+1,t.posMax=r,!0)}],["footnote_ref",function(t,e){var i,s,n,o,r=t.posMax,a=t.pos;if(a+3>r||!t.env.footnotes||!t.env.footnotes.refs||91!==t.src.charCodeAt(a)||94!==t.src.charCodeAt(a+1)||t.level>=t.options.maxNesting)return!1;for(s=a+2;s<r;s++){if(32===t.src.charCodeAt(s)||10===t.src.charCodeAt(s))return!1;if(93===t.src.charCodeAt(s))break}return!(s===a+2||s>=r||(s++,i=t.src.slice(a+2,s-1),typeof t.env.footnotes.refs[":"+i]>"u"))&&(e||(t.env.footnotes.list||(t.env.footnotes.list=[]),t.env.footnotes.refs[":"+i]<0?(n=t.env.footnotes.list.length,t.env.footnotes.list[n]={label:i,count:0},t.env.footnotes.refs[":"+i]=n):n=t.env.footnotes.refs[":"+i],o=t.env.footnotes.list[n].count,t.env.footnotes.list[n].count++,t.push({type:"footnote_ref",id:n,subId:o,level:t.level})),t.pos=s,t.posMax=r,!0)}],["autolink",function(t,e){var i,s,n,o,r,a=t.pos;return!(60!==t.src.charCodeAt(a)||(i=t.src.slice(a),i.indexOf(">")<0))&&((s=i.match(Kt))?!(Vt.indexOf(s[1].toLowerCase())<0||(o=s[0].slice(1,-1),r=at(o),!t.parser.validateLink(o)))&&(e||(t.push({type:"link_open",href:r,level:t.level}),t.push({type:"text",content:o,level:t.level+1}),t.push({type:"link_close",level:t.level})),t.pos+=s[0].length,!0):!!(n=i.match(Ht))&&(r=at("mailto:"+(o=n[0].slice(1,-1))),!!t.parser.validateLink(r)&&(e||(t.push({type:"link_open",href:r,level:t.level}),t.push({type:"text",content:o,level:t.level+1}),t.push({type:"link_close",level:t.level})),t.pos+=n[0].length,!0)))}],["htmltag",function(t,e){var i,s,n,o=t.pos;return!(!t.options.html||(n=t.posMax,60!==t.src.charCodeAt(o)||o+2>=n)||(i=t.src.charCodeAt(o+1),33!==i&&63!==i&&47!==i&&!function(t){var e=32|t;return e>=97&&e<=122}(i))||(s=t.src.slice(o).match(Yt),!s))&&(e||t.push({type:"htmltag",content:t.src.slice(o,o+s[0].length),level:t.level}),t.pos+=s[0].length,!0)}],["entity",function(t,e){var i,s,n=t.pos,o=t.posMax;if(38!==t.src.charCodeAt(n))return!1;if(n+1<o)if(35===t.src.charCodeAt(n+1)){if(s=t.src.slice(n).match(Qt))return e||(i="x"===s[1][0].toLowerCase()?parseInt(s[1].slice(1),16):parseInt(s[1],10),t.pending+=$(i)?J(i):J(65533)),t.pos+=s[0].length,!0}else if(s=t.src.slice(n).match(te)){var r=B(s[1]);if(s[1]!==r)return e||(t.pending+=r),t.pos+=s[0].length,!0}return e||(t.pending+="&"),t.pos++,!0}]];function ie(){this.ruler=new st;for(var t=0;t<ee.length;t++)this.ruler.push(ee[t][0],ee[t][1]);this.validateLink=se}function se(t){var e=t.trim().toLowerCase();return!(-1!==(e=K(e)).indexOf(":")&&-1!==["vbscript","javascript","file","data"].indexOf(e.split(":")[0]))}ie.prototype.skipToken=function(t){var e,i,s=this.ruler.getRules(""),n=s.length,o=t.pos;if((i=t.cacheGet(o))>0)t.pos=i;else{for(e=0;e<n;e++)if(s[e](t,!0))return void t.cacheSet(o,t.pos);t.pos++,t.cacheSet(o,t.pos)}},ie.prototype.tokenize=function(t){for(var e,i,s=this.ruler.getRules(""),n=s.length,o=t.posMax;t.pos<o;){for(i=0;i<n&&!(e=s[i](t,!1));i++);if(e){if(t.pos>=o)break}else t.pending+=t.src[t.pos++]}t.pending&&t.pushPending()},ie.prototype.parse=function(t,e,i,s){var n=new nt(t,this,e,i,s);this.tokenize(n)};var ne={default:{options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["block","inline","references","replacements","smartquotes","references","abbr2","footnote_tail"]},block:{rules:["blockquote","code","fences","footnote","heading","hr","htmlblock","lheading","list","paragraph","table"]},inline:{rules:["autolink","backticks","del","emphasis","entity","escape","footnote_ref","htmltag","links","newline","text"]}}},full:{options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{},block:{},inline:{}}},commonmark:{options:{html:!0,xhtmlOut:!0,breaks:!1,langPrefix:"language-",linkTarget:"",typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["block","inline","references","abbr2"]},block:{rules:["blockquote","code","fences","heading","hr","htmlblock","lheading","list","paragraph"]},inline:{rules:["autolink","backticks","emphasis","entity","escape","htmltag","links","newline","text"]}}}};function oe(t,e,i){this.src=e,this.env=i,this.options=t.options,this.tokens=[],this.inlineMode=!1,this.inline=t.inline,this.block=t.block,this.renderer=t.renderer,this.typographer=t.typographer}function re(t,e){"string"!=typeof t&&(e=t,t="default"),e&&null!=e.linkify&&console.warn("linkify option is removed. Use linkify plugin instead:\n\nimport Remarkable from 'remarkable';\nimport linkify from 'remarkable/linkify';\nnew Remarkable().use(linkify)\n"),this.inline=new ie,this.block=new Nt,this.core=new St,this.renderer=new it,this.ruler=new st,this.options={},this.configure(ne[t]),this.set(e||{})}re.prototype.set=function(t){F(this.options,t)},re.prototype.configure=function(t){var e=this;if(!t)throw new Error("Wrong `remarkable` preset, check name/content");t.options&&e.set(t.options),t.components&&Object.keys(t.components).forEach((function(i){t.components[i].rules&&e[i].ruler.enable(t.components[i].rules,!0)}))},re.prototype.use=function(t,e){return t(this,e),this},re.prototype.parse=function(t,e){var i=new oe(this,t,e);return this.core.process(i),i.tokens},re.prototype.render=function(t,e){return e=e||{},this.renderer.render(this.parse(t,e),this.options,e)},re.prototype.parseInline=function(t,e){var i=new oe(this,t,e);return i.inlineMode=!0,this.core.process(i),i.tokens},re.prototype.renderInline=function(t,e){return e=e||{},this.renderer.render(this.parseInline(t,e),this.options,e)};const ae=class t{static instantiate(e){if(e)return new re({...t.DEFAULT_PROPERTIES,...e});if(window.hljs){const t=window.hljs;return new re({highlight:function(e,i){if(i&&t.getLanguage(i))try{return t.highlight(e,{language:i}).value}catch{console.error("failed to setup the highlight dependency")}try{return t.highlightAuto(e).value}catch{console.error("failed to automatically highlight messages")}return""},html:!1,xhtmlOut:!1,breaks:!0,langPrefix:"language-",linkTarget:"_blank",typographer:!0})}return new re(t.DEFAULT_PROPERTIES)}static createNew(e){const i=t.instantiate(e);return i.inline.validateLink=()=>!0,i}};ae.DEFAULT_PROPERTIES={breaks:!0,linkTarget:"_blank"};let le=ae;class ce{static applyCustomStylesToElements(t,e,i){if(i&&(Object.assign(t.outerContainer.style,i.outerContainer),Object.assign(t.innerContainer.style,i.innerContainer),Object.assign(t.bubbleElement.style,i.bubble),e)){const e=t.bubbleElement.children[0],s="a"!==e.tagName.toLocaleLowerCase()?e:e.children[0];Object.assign(s.style,i.media)}}static applySideStyles(t,e,i,s){s&&(ce.applyCustomStylesToElements(t,i,s.shared),e===Se.USER_ROLE?ce.applyCustomStylesToElements(t,i,s.user):(ce.applyCustomStylesToElements(t,i,s.ai),ce.applyCustomStylesToElements(t,i,s[e])))}static isElementsStyles(t){return!!(t.outerContainer||t.innerContainer||t.bubble||t.media)}static applyCustomStyles(t,e,i,s,n){var o;n&&t.default!==n?ce.isElementsStyles(n)?(ce.applyCustomStylesToElements(e,s,null==(o=t.default)?void 0:o.shared),ce.applyCustomStylesToElements(e,s,n)):(ce.applySideStyles(e,i,s,t.default),ce.applySideStyles(e,i,s,n)):ce.applySideStyles(e,i,s,t.default)}static extractParticularSharedStyles(t,e){if(null==e||!e.shared)return;const i=e.shared,s={outerContainer:{},innerContainer:{},bubble:{},media:{}};return t.forEach((t=>{var e,n,o,r;s.outerContainer[t]=(null==(e=i.outerContainer)?void 0:e[t])||"",s.innerContainer[t]=(null==(n=i.innerContainer)?void 0:n[t])||"",s.bubble[t]=(null==(o=i.bubble)?void 0:o[t])||"",s.media[t]=(null==(r=i.media)?void 0:r[t])||""})),s}}class he{static onMessage(t,e,i){var s;const n=JSON.parse(JSON.stringify({message:e,isHistory:i,isInitial:i}));M.reAddFileRefToObject(e,n),null==(s=t.onMessage)||s.call(t,n),t.dispatchEvent(new CustomEvent("message",{detail:n})),O.fireOnNewMessage(t,n)}static onClearMessages(t){var e;null==(e=t.onClearMessages)||e.call(t),t.dispatchEvent(new CustomEvent("clear-messages"))}static onRender(t){var e;null==(e=t.onComponentRender)||e.call(t,t),t.dispatchEvent(new CustomEvent("render",{detail:t}))}static onError(t,e){var i;null==(i=t.onError)||i.call(t,e),t.dispatchEvent(new CustomEvent("error",{detail:e}))}}const ue=class t{static generateLoadingRingElement(){const t=document.createElement("div");return t.classList.add("loading-history"),t.appendChild(document.createElement("div")),t.appendChild(document.createElement("div")),t.appendChild(document.createElement("div")),t.appendChild(document.createElement("div")),t}static apply(t,e,i){A.setRing(e.bubbleElement,null==i?void 0:i.bubble),null!=i&&i.bubble&&delete(i=JSON.parse(JSON.stringify(i))).bubble,t.applyCustomStyles(e,"history",!1,i)}static addLoadHistoryMessage(e,i,s=!0){var n,o,r,a,l,c,h,u;e.bubbleElement.classList.add(t.CLASS);const d=s?t.FULL_VIEW_CLASS:t.SMALL_CLASS;e.outerContainer.classList.add(d);const p=s?null==(a=null==(r=null==(o=null==(n=i.messageStyles)?void 0:n.loading)?void 0:o.history)?void 0:r.full)?void 0:a.styles:null==(u=null==(h=null==(c=null==(l=i.messageStyles)?void 0:l.loading)?void 0:c.history)?void 0:h.small)?void 0:u.styles;t.apply(i,e,p),i.elementRef.prepend(e.outerContainer)}static createDefaultElements(e){const i=e.createMessageElements("",Se.AI_ROLE),{bubbleElement:s}=i,n=t.generateLoadingRingElement();return s.appendChild(n),i}static addMessage(e,i=!0){var s,n,o,r;const a=null==(r=null==(o=null==(n=null==(s=e.messageStyles)?void 0:s.loading)?void 0:n.history)?void 0:o.full)?void 0:r.html,l=a?R.createElements(e,a,Se.AI_ROLE,!0):t.createDefaultElements(e);return t.addLoadHistoryMessage(l,e,i),l}static tryChangeViewToSmall(e,i){var s,n,o,r,a,l,c,h;if(null!=i&&i.outerContainer.classList.contains(t.FULL_VIEW_CLASS)){i.outerContainer.classList.replace(t.FULL_VIEW_CLASS,t.SMALL_CLASS);const u=null==(r=null==(o=null==(n=null==(s=e.messageStyles)?void 0:s.loading)?void 0:n.history)?void 0:o.small)?void 0:r.styles;u&&t.apply(e,i,u);const d=null==(h=null==(c=null==(l=null==(a=e.messageStyles)?void 0:a.loading)?void 0:l.history)?void 0:c.small)?void 0:h.html;return d&&(i.bubbleElement.innerHTML=d),!0}return!1}static changeFullViewToSmall(e){const i=e.messageElementRefs[e.messageElementRefs.length-1];t.tryChangeViewToSmall(e,i)||t.tryChangeViewToSmall(e,e.messageElementRefs[0])}};ue.CLASS="loading-history-message",ue.FULL_VIEW_CLASS="loading-history-message-full-view",ue.SMALL_CLASS="loading-history-message-small";let de=ue;const pe=class t{static setFade(e,i){e.style.transitionDuration="number"==typeof i?`${i}ms`:`${t.DEFAULT_FADE_MS}ms`}static async fadeAnimation(e,i){e.style.opacity="0";const s="number"==typeof i?i:t.DEFAULT_FADE_MS;await new Promise((t=>{setTimeout((()=>t()),s)})),e.style.opacity="1"}};pe.DEFAULT_FADE_MS=500;let me=pe;const ve=class t{constructor(e){var i;this.messageElementRefs=[],this.htmlClassUtilities={},this.messageToElements=[],this.elementRef=t.createContainerElement(),this.messageStyles=O.processMessageStyles(e.messageStyles),this._remarkable=le.createNew(e.remarkable),this.avatars=e.avatars,this.names=e.names,this._onMessage=he.onMessage.bind(this,e),e.htmlClassUtilities&&(this.htmlClassUtilities=e.htmlClassUtilities),this.focusMode=e.focusMode,this.focusMode||(this._lastGroupMessagesElement=document.createElement("div")),"boolean"!=typeof this.focusMode&&null!=(i=this.focusMode)&&i.fade&&me.setFade(this.elementRef,this.focusMode.fade),setTimeout((()=>{this.submitUserMessage=e.submitUserMessage}))}static createContainerElement(){const t=document.createElement("div");return t.id="messages",t}addNewTextMessage(e,i,s,n=!1){if(null!=s&&s.status){const t=this.overwriteText(i,e,this.messageElementRefs);if(t)return t;s.status=!1}const o=n?this.createAndPrependNewMessageElement(e,i,n):this.createAndAppendNewMessageElement(e,i);return o.bubbleElement.classList.add(t.TEXT_BUBBLE_CLASS),this.applyCustomStyles(o,i,!1),Se.fillEmptyMessageElement(o.bubbleElement,e),o}overwriteText(e,i,s){const n=Se.overwriteMessage(this.messageToElements,s,i,e,"text",t.TEXT_BUBBLE_CLASS);return n&&this.renderText(n.bubbleElement,i),n}createAndAppendNewMessageElement(t,e){return this.focusMode?this.appendNewMessageElementFocusMode(t,e):this.createAndAppendNewMessageElementDefault(t,e)}appendNewMessageElementFocusMode(t,e){var i,s;const n=this.createNewMessageElement(t,e);if(this.appendOuterContainerElemet(n.outerContainer,e),"user"===e){const t="boolean"!=typeof this.focusMode&&(null==(i=this.focusMode)?void 0:i.isScroll);setTimeout((()=>x.scrollToBottom(this.elementRef,t)))}else null==(s=this.messageElementRefs[this.messageElementRefs.length-2])||s.outerContainer.scrollIntoView();return n}createNewGroupElementFocusMode(){var e;null==(e=this._lastGroupMessagesElement)||e.classList.remove(t.LAST_GROUP_MESSAGES_ACTIVE);const i=document.createElement("div");this._lastGroupMessagesElement&&i.classList.add(t.LAST_GROUP_MESSAGES_ACTIVE),this._lastGroupMessagesElement=i}createAndAppendNewMessageElementDefault(t,e){const i=this.createNewMessageElement(t,e);return this.appendOuterContainerElemet(i.outerContainer),setTimeout((()=>x.scrollToBottom(this.elementRef))),i}appendOuterContainerElemet(t,e){var i;this.focusMode&&("user"===e||!this._lastGroupMessagesElement)&&this.createNewGroupElementFocusMode(),null==(i=this._lastGroupMessagesElement)||i.appendChild(t),this.elementRef.appendChild(this._lastGroupMessagesElement)}createAndPrependNewMessageElement(e,i,s){var n;const o=this.createNewMessageElement(e,i,s);if(s&&null!=(n=this.elementRef.firstChild)&&n.classList.contains(t.INTRO_CLASS)){this.elementRef.firstChild.insertAdjacentElement("afterend",o.outerContainer);const t=this.messageElementRefs[0];this.messageElementRefs[0]=this.messageElementRefs[1],this.messageElementRefs[1]=t}else this.elementRef.insertBefore(o.outerContainer,this.elementRef.firstChild);return o}createMessageElementsOnOrientation(t,e,i){return i?this.createAndPrependNewMessageElement(t,e,!0):this.createNewMessageElement(t,e)}createNewMessageElement(e,i,s=!1){var n;null==(n=this._introPanel)||n.hide();const o=this.messageElementRefs[this.messageElementRefs.length-1];return de.changeFullViewToSmall(this),t.isTemporaryElement(o)&&(this.revealRoleElementsIfTempRemoved(o,i),this.removeLastMessage()),this.createMessageElements(e,i,s)}revealRoleElementsIfTempRemoved(t,e){if((this.avatars||this.names)&&I.isElementTemporary(t)){const i=this.messageElementRefs[this.messageElementRefs.length-2];i&&this.messageToElements.length>0&&!t.bubbleElement.classList.contains(Se.getRoleClass(e))&&Se.revealRoleElements(i.innerContainer,!!this.avatars,!!this.names)}}static isTemporaryElement(e){return t.isLoadingMessage(e)||I.isElementTemporary(e)}createElements(e,i){const s=t.createBaseElements(i),{outerContainer:n,innerContainer:o,bubbleElement:r}=s;return n.appendChild(o),this.addInnerContainerElements(r,e,i),s}createMessageElements(t,e,i=!1){const s=this.createElements(t,e);return Se.updateRefArr(this.messageElementRefs,s,i),Se.classifyRoleMessages(this.messageElementRefs,e),s}static createBaseElements(t){const e=document.createElement("div"),i=document.createElement("div");i.classList.add("inner-message-container"),e.appendChild(i),e.classList.add("outer-message-container"),e.classList.add(Se.buildRoleOuterContainerClass(t));const s=document.createElement("div");return s.classList.add("message-bubble"),i.appendChild(s),{outerContainer:e,innerContainer:i,bubbleElement:s}}addInnerContainerElements(t,e,i){const s=this.messageElementRefs[this.messageElementRefs.length-1];return Se.areOuterContainerClassRolesSame(i,s)&&!this.isLastMessageError()&&Se.hideRoleElements(s.innerContainer,!!this.avatars,!!this.names),t.classList.add("message-bubble",Se.getRoleClass(i),i===Se.USER_ROLE?"user-message-text":"ai-message-text"),this.renderText(t,e),Se.addRoleElements(t,i,this.avatars,this.names),{bubbleElement:t}}applyCustomStyles(t,e,i,s){t&&this.messageStyles&&ce.applyCustomStyles(this.messageStyles,t,e,i,s)}static createMessageContent(t){const{text:e,files:i,html:s,custom:n,_sessionId:o,role:r}=t,a={role:r||Se.AI_ROLE};return e&&(a.text=e),i&&(a.files=i),s&&(a.html=s),!e&&!i&&!s&&(a.text=""),n&&(a.custom=n),o&&(a._sessionId=o),a}removeMessage(t){t.outerContainer.remove();const e=this.messageElementRefs.findIndex((e=>e===t));this.messageElementRefs.splice(e,1)}removeLastMessage(){this.messageElementRefs[this.messageElementRefs.length-1].outerContainer.remove(),this.messageElementRefs.pop()}isLastMessageError(){var t;return null==(t=Se.getLastMessageBubbleElement(this.elementRef))?void 0:t.classList.contains(Se.ERROR_MESSAGE_TEXT_CLASS)}static isLoadingMessage(t){return null==t?void 0:t.bubbleElement.classList.contains(A.BUBBLE_CLASS)}sendClientUpdate(t,e=!1){var i;null==(i=this._onMessage)||i.call(this,t,e)}renderText(t,e){t.innerHTML=this._remarkable.render(e),0===t.innerText.trim().length&&(t.innerText=e)}refreshTextMessages(t){this._remarkable=le.createNew(t),this.messageToElements.forEach((t=>{t[1].text&&t[0].text&&this.renderText(t[1].text.bubbleElement,t[0].text)}))}};ve.TEXT_BUBBLE_CLASS="text-message",ve.INTRO_CLASS="deep-chat-intro",ve.LAST_GROUP_MESSAGES_ACTIVE="deep-chat-last-group-messages-active";let fe=ve;const ge="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='iso-8859-1'?%3e%3csvg%20fill='%23000000'%20version='1.1'%20id='Layer_1'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20viewBox='0%200%2032%2032'%20xml:space='preserve'%3e%3cpath%20d='M23,30.36H9c-2.404,0-4.36-1.956-4.36-4.36V15c0-2.404,1.956-4.36,4.36-4.36h3.659%20c0.167-1.566,1.415-2.813,2.981-2.981V5.333c-1.131-0.174-2-1.154-2-2.333c0-1.301,1.059-2.36,2.36-2.36%20c1.302,0,2.36,1.059,2.36,2.36c0,1.179-0.869,2.159-2,2.333V7.66c1.566,0.167,2.814,1.415,2.981,2.981H23%20c2.404,0,4.36,1.956,4.36,4.36v11C27.36,28.404,25.404,30.36,23,30.36z%20M9,11.36c-2.007,0-3.64,1.633-3.64,3.64v11%20c0,2.007,1.633,3.64,3.64,3.64h14c2.007,0,3.64-1.633,3.64-3.64V15c0-2.007-1.633-3.64-3.64-3.64H9z%20M13.384,10.64h5.231%20C18.439,9.354,17.334,8.36,16,8.36C14.667,8.36,13.561,9.354,13.384,10.64z%20M16,1.36c-0.904,0-1.64,0.736-1.64,1.64%20S15.096,4.64,16,4.64c0.904,0,1.64-0.736,1.64-1.64S16.904,1.36,16,1.36z%20M20,27.36h-8c-1.301,0-2.36-1.059-2.36-2.36%20s1.059-2.36,2.36-2.36h8c1.302,0,2.36,1.059,2.36,2.36S21.302,27.36,20,27.36z%20M12,23.36c-0.904,0-1.64,0.735-1.64,1.64%20s0.736,1.64,1.64,1.64h8c0.904,0,1.64-0.735,1.64-1.64s-0.735-1.64-1.64-1.64H12z%20M31,23.86h-2c-0.199,0-0.36-0.161-0.36-0.36V15%20c0-0.199,0.161-0.36,0.36-0.36h2c0.199,0,0.36,0.161,0.36,0.36v8.5C31.36,23.699,31.199,23.86,31,23.86z%20M29.36,23.14h1.279v-7.78%20H29.36V23.14z%20M3,23.86H1c-0.199,0-0.36-0.161-0.36-0.36V15c0-0.199,0.161-0.36,0.36-0.36h2c0.199,0,0.36,0.161,0.36,0.36v8.5%20C3.36,23.699,3.199,23.86,3,23.86z%20M1.36,23.14h1.28v-7.78H1.36V23.14z%20M20,20.36c-1.302,0-2.36-1.059-2.36-2.36%20s1.059-2.36,2.36-2.36s2.36,1.059,2.36,2.36C22.36,19.302,21.302,20.36,20,20.36z%20M20,16.36c-0.904,0-1.64,0.736-1.64,1.64%20s0.735,1.64,1.64,1.64s1.64-0.735,1.64-1.64S20.904,16.36,20,16.36z%20M12,20.36c-1.301,0-2.36-1.059-2.36-2.36s1.059-2.36,2.36-2.36%20s2.36,1.059,2.36,2.36C14.36,19.302,13.301,20.36,12,20.36z%20M12,16.36c-0.904,0-1.64,0.736-1.64,1.64s0.736,1.64,1.64,1.64%20s1.64-0.735,1.64-1.64S12.904,16.36,12,16.36z'/%3e%3crect%20style='fill:none;'%20width='32'%20height='32'/%3e%3c/svg%3e",be="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAMAAAC/MqoPAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAADNQTFRF////9vX18vLy/Pz86enp4+Li2tnZ1tbWzczM+fn57Ozs4N/f09LS0M/P5uXl7+/v3dzcwtncCAAAAAFiS0dEAIgFHUgAAAAJcEhZcwAAAEgAAABIAEbJaz4AAAZNSURBVHja7d3bdtsqEABQYABZSLH9/3+ZpnUsIcF5iOM6PfElNoMHMfPQdq3GmL0GkLhEUqLaUExnOtOZznSmM53pTGc605nOdKYznelMZzrTmV4LXSqllKyJDkob26xWq8Zae/iH0QoWTm9d1xur4WuypQJtTd+5dqn0VjcxzNO5/57mEBvdLo8Oron6aseWOjYOFkVvjQs3DmgyONMuht52EfztP+4hdu0i6LCO808/M8c1lE/fuPGej41uUzgdtoO/75N+2ELJ9I3b3//hPXbiMenm3pR/Jt4USgcLBIp4Bh10gqKVhvLo0klCxeSky96nKcj3siw6pJIL4XsoiQ7apyvMY/V3HHrSRioLopvEhSpTCn2TPEuwKYMOIX0tAxRBf/Hpa+lfSqBv9gi1FPsNfTrMAiVmIE/vJhz61FGnQxRIEYE4vfNYdN8Rp6MlHaHotHTn8ejekaZPAjEmyvQWdZFTtYTpXqCGJ0zvcek9Yfoel76nS0ffv1NMp1ca+pkgyfRCGind4L7OWWc605l+cxjsyhqy9AGbPpClc1/nvl5VX0c/3Alk6RU3+Am7shNZ+h6bvidLr7jBB+zKBrL0irOOudmIUDzTmf5gIP+iEuXtRuTVaEmY/oZLfyNMrzjryPc0gerMTdpVg0tvjJUU6bLPcGOoUv46SLL6Wi8yhLf06C7TUyekI0efRaaYqdFltkeNpPumRPSMDxgBYvSM035FrKAmH72hRW99PrpvSdEHkTEGUvSsK3yKVDkuJ92RohcZaehzzirPpOg+J92Tolfc4Cumx5xVXpGiZ34+ICX6W84qv5GiR5NPbiIpOv6BCoSvSkTX+eiaGP092zINvBOj4x8mSf9FqejvNo/cvpOji19ZbmviL0GPLsYMFzgzCor0+Bv/ePDvSJKOb9dJ5UlnbnEHiHgzv6cdTpJOWuc/u3FEucLDOL75xGtBiefrcwgoC9NDSH/jkH6pAuXmBqPQ9HSUPVdZBH1GGOrMXAQdYxcKZfxAoK+KKBKFLosoEoX+u4giUehz8jlcnAuhp78I46yDYNAd+QLR6K+pr+yvxdBTHyVDubQh0UfSxaHSd0lbvNkVRE87JGOtc+PQd2QLQ6fHhJkKsSh6yg13tO08JPprsgrrXWH0dJd2vH1MLPprot4eXoujpzrdhngiD40ek2y92lggPcnWa8qN1Yz0BFuvZhRl0uOfR0v4Ewuli/Bg4Qr3lArqGdndQ3UPO1EunXYwnelMZzrTmc50pjOd6UxnOtOZznSmM53pTGf6kuj6oedFKV0s3fX6sX1S3bsi6a4PD7+/YAqYeBw6pIB/4qEgOqxdSPbGiim4NRRCbzs3Jj0L4UfXtQXQVRfn5IdA/Bw7RZzurEV6EtdsLeGXkIPuA+K1UoVeA0l62zmN/LqfSSft9KkepmoRuvi3nd5uKNFB9zbbXEANqdr941XO0NJx2v2jdJenpf+/3bvn0ts16ph+sd6hX7dPo2+2cZzE02Ia43bzDHqr+2Evnhz74ZHU30ffbKOeng1/NPV30Ns1gYQnSP2P6e65Pfxc6h02XZqXQCjhJ6kPL6bFo4NrGvAU4UII4SE2P1vQuZkuOxckVfehisF1MjUddN/MZBN+kvq5uf0O/xa66gyNS9ktMWlz44rO1Z8C19i5FPdHzPamXn+F3hryPfxMr78+4F+kq22kO6Rf6fUQt+puuustyWv4rbG3l/duztFB96GYoe1cTBdXMr+nw9qVM6ZfxOvzezff0nXi/ZOndvrR6Zvpm0c3h6nhdb+5iS7tsIim/qXZD9+97/Jf+rpZ5BET1ayv0GUzLhEuhBBjIy/RdVPgndutIRt9nt7p5cKFEEJ3Z+jQFDZL+XnMDXxHB73gxn5s9Kc3d3/pFciFkN/QTSXHJpX5l66gDrkQoP6hL3xsPw39la4qOiV8tH78XeSbue6N9mvWa6J/ybpc1CT1Wnh5Qq9meP8IOKH3ddH7E/ri1iYux/SXDrXR4UiPdck/wUpU+FtPf6/orja6O9KL3l56LOvVxe5Ib2qjN0d6Vbex4ghWlU3bPqI90If66MNng680FNpbJijH6kCvaF3uMzQ3+IrpFerV4Y9dffQdN3im10ivbuImhD3Qq5u4HdZkua8znelMZ/pS4z9CPVKkxowNxgAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxNy0wMy0yN1QxNTo0NToxNSswMDowMN1xSg4AAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTctMDMtMjdUMTU6NDU6MTUrMDA6MDCsLPKyAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAABJRU5ErkJggg==",ye=class t{static errorFallback(t,e){const i=e.target;i.onerror=null,i.src=t}static hide(e){var i;(i=e.getElementsByClassName(t.CONTAINER_CLASS)[0].style).visibility||(i.visibility="hidden")}static reveal(e){e.getElementsByClassName(t.CONTAINER_CLASS)[0].style.visibility=""}static applyCustomStylesToElements(t,e,i){Object.assign(t.style,i.container),Object.assign(e.style,i.avatar)}static applyCustomStyles(e,i,s,n){var o,r,a,l;if(null!=(o=s.default)&&o.styles&&t.applyCustomStylesToElements(e,i,s.default.styles),n===Se.USER_ROLE)null!=(r=s.user)&&r.styles&&t.applyCustomStylesToElements(e,i,s.user.styles);else{null!=(a=s.ai)&&a.styles&&t.applyCustomStylesToElements(e,i,s.ai.styles);const o=null==(l=s[n])?void 0:l.styles;o&&t.applyCustomStylesToElements(e,i,o)}}static createAvatar(e,i){var s,n,o,r,a;const l=document.createElement("img");e===Se.USER_ROLE?(l.src=(null==(s=null==i?void 0:i.user)?void 0:s.src)||(null==(n=null==i?void 0:i.default)?void 0:n.src)||be,l.onerror=t.errorFallback.bind(this,be)):(l.src=(null==(o=null==i?void 0:i[e])?void 0:o.src)||(null==(r=null==i?void 0:i.ai)?void 0:r.src)||(null==(a=null==i?void 0:i.default)?void 0:a.src)||ge,l.onerror=t.errorFallback.bind(this,ge)),l.classList.add("avatar"),l.alt=`${e} avatar`;const c=document.createElement("div");return c.classList.add(t.CONTAINER_CLASS),c.appendChild(l),i&&t.applyCustomStyles(c,l,i,e),c}static getPosition(t,e){var i,s,n,o,r,a;let l=null==(s=null==(i=null==e?void 0:e[t])?void 0:i.styles)?void 0:s.position;return t!==Se.USER_ROLE&&(l??(l=null==(o=null==(n=null==e?void 0:e.ai)?void 0:n.styles)?void 0:o.position)),l??(l=null==(a=null==(r=null==e?void 0:e.default)?void 0:r.styles)?void 0:a.position),l??(l=t===Se.USER_ROLE?"right":"left"),l}static add(e,i,s){const n="boolean"==typeof s?void 0:s,o=t.createAvatar(i,n),r=t.getPosition(i,n);o.classList.add("left"===r?"left-item-position":"right-item-position"),e.insertAdjacentElement("left"===r?"beforebegin":"afterend",o)}};ye.CONTAINER_CLASS="avatar-container";let we=ye;const xe=class t{static hide(e){var i;(i=e.getElementsByClassName(t.NAME_CLASS)[0].style).visibility||(i.visibility="hidden")}static reveal(e){e.getElementsByClassName(t.NAME_CLASS)[0].style.visibility=""}static getPosition(t,e){var i,s,n;let o=null==(i=null==e?void 0:e[t])?void 0:i.position;return t!==Se.USER_ROLE&&(o??(o=null==(s=null==e?void 0:e.ai)?void 0:s.position)),o??(o=null==(n=null==e?void 0:e.default)?void 0:n.position),o??(o=t===Se.USER_ROLE?"right":"left"),o}static applyStyle(t,e,i){var s,n,o,r;Object.assign(t.style,null==(s=i.default)?void 0:s.style),e===Se.USER_ROLE?Object.assign(t.style,null==(n=i.user)?void 0:n.style):(Object.assign(t.style,null==(o=i.ai)?void 0:o.style),Object.assign(t.style,null==(r=i[e])?void 0:r.style))}static getNameText(t,e){var i,s,n,o,r,a;return t===Se.USER_ROLE?(null==(i=e.user)?void 0:i.text)||(null==(s=e.default)?void 0:s.text)||"User":t===Se.AI_ROLE?(null==(n=e.ai)?void 0:n.text)||(null==(o=e.default)?void 0:o.text)||"AI":(null==(r=e[t])?void 0:r.text)||(null==(a=e.default)?void 0:a.text)||t}static createName(e,i){const s=document.createElement("div");return s.classList.add(t.NAME_CLASS),s.textContent=t.getNameText(e,i),t.applyStyle(s,e,i),s}static add(e,i,s){const n="boolean"==typeof s?{}:s,o=t.createName(i,n),r=t.getPosition(i,n);o.classList.add("left"===r?"left-item-position":"right-item-position"),e.insertAdjacentElement("left"===r?"beforebegin":"afterend",o)}};xe.NAME_CLASS="name";let ke=xe;const _e=class t{static getLastElementsByClass(t,e,i){for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n.bubbleElement.classList.contains(e[0])&&!e.slice(1).find((t=>!n.bubbleElement.classList.contains(t)))){if(!i)return n;if(!i.find((t=>n.bubbleElement.classList.contains(t))))return n}}}static getLastMessage(t,e,i){for(let s=t.length-1;s>=0;s-=1)if(t[s][0].role===e){if(!i)return t[s][0];if(t[s][0][i])return t[s][0]}}static getLastTextToElement(t,e){for(let i=t.length-1;i>=0;i-=1)if(t[i][0]===e)return t[i]}static overwriteMessage(e,i,s,n,o,r){const a=t.getLastElementsByClass(i,[t.getRoleClass(n),r],[A.BUBBLE_CLASS]),l=t.getLastMessage(e,n,o);return l&&(l[o]=s),a}static getRoleClass(t){return`${t}-message`}static fillEmptyMessageElement(e,i){0===i.trim().length&&(e.classList.add(t.EMPTY_MESSAGE_CLASS),e.innerHTML='<div style="color:#00000000">.</div>')}static unfillEmptyMessageElement(e,i){e.classList.contains(t.EMPTY_MESSAGE_CLASS)&&i.trim().length>0&&e.replaceChildren()}static getLastMessageBubbleElement(e){var i,s,n;return Array.from((null==(n=null==(s=null==(i=t.getLastMessageElement(e))?void 0:i.children)?void 0:s[0])?void 0:n.children)||[]).find((t=>t.classList.contains("message-bubble")))}static getLastMessageElement(t){return t.children[t.children.length-1]}static addRoleElements(t,e,i,s){i&&we.add(t,e,i),s&&ke.add(t,e,s)}static hideRoleElements(t,e,i){e&&we.hide(t),i&&ke.hide(t)}static revealRoleElements(t,e,i){e&&we.reveal(t),i&&ke.reveal(t)}static updateRefArr(t,e,i){i?t.unshift(e):t.push(e)}static buildRoleOuterContainerClass(e){return`${t.OUTER_CONTAINER_CLASS_ROLE_PREFIX}${e}`}static addNewPositionClasses(e,i){e.outerContainer.classList.remove(t.POSITION_TOP_MESSAGE_CLASS,t.POSITION_MIDDLE_MESSAGE_CLASS,t.POSITION_BOTTOM_MESSAGE_CLASS),e.outerContainer.classList.add(...i)}static getNumberOfElements(t){let e=0;return void 0!==t.text&&(e+=1),void 0!==t.html&&(e+=1),t.files&&(e+=t.files.length),e}static filterdMessageElements(t,e){return t.filter((t=>t.bubbleElement.classList.contains(e)))}static findMessageElements(t,e){return t.find((t=>t.bubbleElement.classList.contains(e)))}static generateMessageBodyElements(e,i){const s={};return e.text&&(s.text=t.findMessageElements(i,fe.TEXT_BUBBLE_CLASS)),e.html&&(s.html=t.findMessageElements(i,R.HTML_BUBBLE_CLASS)),e.files&&(s.files=t.filterdMessageElements(i,M.FILE_BUBBLE_CLASS)),s}static generateMessageBody(e,i,s=!1){const n=t.getNumberOfElements(e),o=s?i.slice(0,n):i.slice(i.length-n);return t.generateMessageBodyElements(e,o)}static classifyRoleMessages(e,i){let s=i?t.buildRoleOuterContainerClass(i):void 0;for(let n=e.length-1;n>=0;n-=1){if(i||(s=Array.from(e[n].outerContainer.classList).find((e=>e.startsWith(t.OUTER_CONTAINER_CLASS_ROLE_PREFIX)))),!s)continue;const o=e[n],r=o.outerContainer.classList.contains(s),a=e[n-1],l=e[n+1],c=null==a?void 0:a.outerContainer.classList.contains(s),h=null==l?void 0:l.outerContainer.classList.contains(s);if(r)!c&&h?t.addNewPositionClasses(o,[t.POSITION_TOP_MESSAGE_CLASS]):c&&h?t.addNewPositionClasses(o,[t.POSITION_MIDDLE_MESSAGE_CLASS]):c&&!h?t.addNewPositionClasses(o,[t.POSITION_BOTTOM_MESSAGE_CLASS]):!c&&!h&&t.addNewPositionClasses(o,[t.POSITION_TOP_MESSAGE_CLASS,t.POSITION_BOTTOM_MESSAGE_CLASS]);else if(i)break}}static areOuterContainerClassRolesSame(e,i){return!!i&&Array.from(i.outerContainer.classList).find((e=>e.startsWith(t.OUTER_CONTAINER_CLASS_ROLE_PREFIX)))===t.buildRoleOuterContainerClass(e)}static resetAllRoleElements(e,i,s){if(!i&&!s)return;let n="";e.forEach(((o,r)=>{o.bubbleElement.classList.contains(t.ERROR_MESSAGE_TEXT_CLASS)||t.revealRoleElements(o.innerContainer,i,s);const a=Array.from(o.outerContainer.classList).find((e=>e.startsWith(t.OUTER_CONTAINER_CLASS_ROLE_PREFIX)));n===a&&t.hideRoleElements(e[r-1].innerContainer,i,s),n=a}))}};_e.AI_ROLE="ai",_e.USER_ROLE="user",_e.ERROR_MESSAGE_TEXT_CLASS="error-message-text",_e.OUTER_CONTAINER_CLASS_ROLE_PREFIX="deep-chat-outer-container-role-",_e.EMPTY_MESSAGE_CLASS="empty-message",_e.POSITION_TOP_MESSAGE_CLASS="deep-chat-top-message",_e.POSITION_MIDDLE_MESSAGE_CLASS="deep-chat-middle-message",_e.POSITION_BOTTOM_MESSAGE_CLASS="deep-chat-bottom-message";let Se=_e;const Ae=class t{constructor(t){this._fileAdded=!1,this._streamType="",this._hasStreamEnded=!1,this._messages=t}upsertStreamedMessage(t){var e;if(this._hasStreamEnded)return;if(void 0===(null==t?void 0:t.text)&&void 0===(null==t?void 0:t.html))return console.error(y.INVALID_STREAM_EVENT);const i=(null==t?void 0:t.text)||(null==t?void 0:t.html)||"",s=x.isScrollbarAtBottomOfElement(this._messages.elementRef),n=void 0!==(null==t?void 0:t.text)?"text":"html";if(this._elements||this._message){if(this._streamType!==n)return console.error(y.INVALID_STREAM_EVENT_MIX);this.updateBasedOnType(i,n,null==(e=this._elements)?void 0:e.bubbleElement,null==t?void 0:t.overwrite)}else this.setInitialState(n,i,null==t?void 0:t.role);!this._messages.focusMode&&s&&x.scrollToBottom(this._messages.elementRef)}setInitialState(e,i,s){this._streamType=e,s??(s=Se.AI_ROLE),this._elements="text"===e?this._messages.addNewTextMessage(i,s):R.add(this._messages,i,s,this._messages.messageElementRefs),this._elements&&(this._elements.bubbleElement.classList.add(t.MESSAGE_CLASS),this._activeMessageRole=s,this._message={role:this._activeMessageRole,[e]:i},this._messages.messageToElements.push([this._message,{[e]:this._elements}]))}updateBasedOnType(t,e,i,s=!1){Se.unfillEmptyMessageElement(i,t),("text"===e?this.updateText:this.updateHTML).bind(this)(t,i,s)}updateText(t,e,i){this._message&&(this._message.text=i?t:this._message.text+t,this._messages.renderText(e,this._message.text))}updateHTML(t,e,i){if(this._message)if(i)this._message.html=t,e.innerHTML=t;else{const i=document.createElement("span");i.innerHTML=t,e.appendChild(i),this._message.html=(null==e?void 0:e.innerHTML)||""}}finaliseStreamedMessage(){var e;if(!this._endStreamAfterOperation&&this._message&&(!this._fileAdded||this._elements)){if(!this._elements)throw Error(y.NO_VALID_STREAM_EVENTS_SENT);null!=(e=this._elements.bubbleElement)&&e.classList.contains(t.MESSAGE_CLASS)&&("text"===this._streamType?this._messages.textToSpeech&&_.speak(this._message.text||"",this._messages.textToSpeech):"html"===this._streamType&&this._elements&&P.apply(this._messages,this._elements.outerContainer),this._elements.bubbleElement.classList.remove(t.MESSAGE_CLASS),this._message&&this._messages.sendClientUpdate(fe.createMessageContent(this._message),!1),this._hasStreamEnded=!0)}}markFileAdded(){this._fileAdded=!0}newMessage(){this.finaliseStreamedMessage(),this._elements=void 0,delete this._message,this._fileAdded=!1,this._hasStreamEnded=!1,this._activeMessageRole=void 0}async endStreamAfterFileDownloaded(t,e){var i;this._endStreamAfterOperation=!0;const{text:s,files:n}=await e();s&&this.updateBasedOnType(s,"text",null==(i=this._elements)?void 0:i.bubbleElement,!0),this._endStreamAfterOperation=!1,this.finaliseStreamedMessage(),n&&t.addNewMessage({files:n})}};Ae.MESSAGE_CLASS="streamed-message";let Te=Ae;const Me=class t{static async tempRemoveContentHeader(e,i,s){if(null==e||!e.headers)throw new Error("Request settings have not been set up");const n=e.headers[t.CONTENT_TYPE];let o;delete e.headers[t.CONTENT_TYPE];try{o=await i(s)}catch(i){throw e.headers[t.CONTENT_TYPE]=n,i}return e.headers[t.CONTENT_TYPE]=n,o}static displayError(t,e,i="Service error, please try again."){if(console.error(e),"object"==typeof e)return e instanceof Error?t.addNewErrorMessage("service",e.message):Array.isArray(e)||"string"==typeof e.error?t.addNewErrorMessage("service",e):0===Object.keys(e).length?t.addNewErrorMessage("service",i):t.addNewErrorMessage("service",JSON.stringify(e));t.addNewErrorMessage("service",e)}static fetch(t,e,i,s){var n,o;const r={method:(null==(n=t.connectSettings)?void 0:n.method)||"POST",headers:e};return"GET"!==r.method&&(r.body=i?JSON.stringify(s):s),t.connectSettings.credentials&&(r.credentials=t.connectSettings.credentials),fetch((null==(o=t.connectSettings)?void 0:o.url)||t.url||"",r)}static processResponseByType(t){const e=t.headers.get("content-type");return null!=e&&e.includes("application/json")?t.json():null!=e&&e.includes("text/plain")||!e?t:t.blob()}static async processRequestInterceptor(t,e){var i;const s=await(null==(i=t.requestInterceptor)?void 0:i.call(t,e))||e,n=s,o=s;return{body:n.body,headers:n.headers,error:o.error}}static validateResponseFormat(t,e){if(!t)return!1;const i=Array.isArray(t)?t:[t];return e&&i.length>1?(console.error(y.INVALID_STREAM_ARRAY_RESPONSE),!1):!i.find((t=>"object"!=typeof t||!("string"==typeof t.error||"string"==typeof t.text||"string"==typeof t.html||Array.isArray(t.files))))}static onInterceptorError(t,e,i){t.addNewErrorMessage("service",e),null==i||i()}static async basicResponseProcessing(e,i,s={}){const{io:n,displayError:o=!0,useRI:r=!0}=s;if(null==n||!n.extractResultData)return i;const a=r?n.deepChat.responseInterceptor:void 0,l=await(null==a?void 0:a(i))||i,c=await n.extractResultData(l);if(c&&("object"==typeof c||Array.isArray(c)))return c;if(o){const s=y.INVALID_RESPONSE(i,"response",!!a,l);t.displayError(e,s)}}};Me.CONTENT_TYPE="Content-Type";let Oe=Me;function je(t){let e,i,s,n=!1;return function(o){void 0===e?(e=o,i=0,s=-1):e=function(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}(e,o);const r=e.length;let a=0;for(;i<r;){n&&(10===e[i]&&(a=++i),n=!1);let o=-1;for(;i<r&&-1===o;++i)switch(e[i]){case 58:-1===s&&(s=i-a);break;case 13:n=!0;case 10:o=i}if(-1===o)break;t(e.subarray(a,o),s),a=i,s=-1}a===r?e=void 0:0!==a&&(e=e.subarray(a),i-=a)}}const Ce="text/event-stream",Ee="last-event-id";function Ie(t,e){var{signal:i,headers:s,onopen:n,onmessage:o,onclose:r,onerror:a,openWhenHidden:l,fetch:c}=e,h=function(t,e){var i={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(i[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(i[s[n]]=t[s[n]])}return i}(e,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise(((e,u)=>{const d=Object.assign({},s);let p;function m(){p.abort(),document.hidden||w()}d.accept||(d.accept=Ce),l||document.addEventListener("visibilitychange",m);let v=1e3,f=0;function g(){document.removeEventListener("visibilitychange",m),window.clearTimeout(f),p.abort()}null==i||i.addEventListener("abort",(()=>{g(),e()}));const b=c??window.fetch,y=n??Pe;async function w(){var i;p=new AbortController;try{const i=await b(t,Object.assign(Object.assign({},h),{headers:d,signal:p.signal}));await y(i),await async function(t,e){const i=t.getReader();let s;for(;!(s=await i.read()).done;)e(s.value)}(i.body,je(function(t,e,i){let s={data:"",event:"",id:"",retry:void 0};const n=new TextDecoder;return function(o,r){if(0===o.length)null==i||i(s),s={data:"",event:"",id:"",retry:void 0};else if(r>0){const i=n.decode(o.subarray(0,r)),a=r+(32===o[r+1]?2:1),l=n.decode(o.subarray(a));switch(i){case"data":s.data=s.data?s.data+"\n"+l:l;break;case"event":s.event=l;break;case"id":t(s.id=l);break;case"retry":const i=parseInt(l,10);isNaN(i)||e(s.retry=i)}}}}((t=>{t?d[Ee]=t:delete d[Ee]}),(t=>{v=t}),o))),null==r||r(),g(),e()}catch(t){if(!p.signal.aborted)try{const e=null!==(i=null==a?void 0:a(t))&&void 0!==i?i:v;window.clearTimeout(f),f=window.setTimeout(w,e)}catch(t){g(),u(t)}}}w()}))}function Pe(t){const e=t.headers.get("content-type");if(null==e||!e.startsWith(Ce))throw new Error(`Expected content-type to be ${Ce}, Actual: ${e}`)}class Ne{static async request(t,e,i,s=!0,n=!1){var o,r,a,l,c,h;const u={body:e,headers:null==(o=t.connectSettings)?void 0:o.headers},{body:d,headers:p,error:m}=await Oe.processRequestInterceptor(t.deepChat,u),{onOpen:v,onClose:f,abortStream:g}=t.streamHandlers;if(m)return Oe.onInterceptorError(i,m,f);if(null!=(r=t.connectSettings)&&r.handler)return Le.stream(t,d,i);if((null==(a=t.connectSettings)?void 0:a.url)===qe.URL)return qe.requestStream(i,t);const b=new Te(i),y=Oe.fetch.bind(this,t,p,s);return Ie((null==(l=t.connectSettings)?void 0:l.url)||t.url||"",{method:(null==(c=t.connectSettings)?void 0:c.method)||"POST",headers:p,credentials:null==(h=t.connectSettings)?void 0:h.credentials,body:s?JSON.stringify(d):d,openWhenHidden:!0,async onopen(t){if(t.ok)return v();throw await Oe.processResponseByType(t)},async onmessage(e){var s,n,o;if(JSON.stringify(e.data)!==JSON.stringify("[DONE]")){let r;try{r=JSON.parse(e.data)}catch{r={}}const a=await(null==(n=(s=t.deepChat).responseInterceptor)?void 0:n.call(s,r))||r;null==(o=t.extractResultData)||o.call(t,a,y,d).then((e=>{t.asyncCallInProgress&&e&&""!==e.text?(Ne.simulate(i,t.streamHandlers,e),f(),t.asyncCallInProgress=!1):Ne.upsertWFiles(i,b.upsertStreamedMessage.bind(b),b,e)})).catch((t=>Oe.displayError(i,t)))}},onerror(t){throw f(),t},onclose(){if(!t.asyncCallInProgress)try{b.finaliseStreamedMessage(),f()}catch(t){if(!n)throw t}},signal:g.signal}).catch((e=>{var s;i.isLastMessageError()||null==(s=t.extractResultData)||s.call(t,e).then((()=>{Oe.displayError(i,e)})).catch((t=>{Oe.displayError(i,t)}))})),b}static async simulate(t,e,i,s){const n=e;if(!await Oe.basicResponseProcessing(t,i,{io:s,useRI:!1}))return e.onClose();if(Array.isArray(i)&&(i=i[0]),i.files){const e=await Oe.basicResponseProcessing(t,{files:i.files},{io:s});t.addNewMessage({sendUpdate:!1,ignoreText:!0,...e},!1)}if(i.text){e.onOpen();const o=i.text.split("");Ne.populateMessages(t,o,new Te(t),n,"text",0,s)}if(i.html){e.onOpen();let o=P.splitHTML(i.html);0===o.length&&(o=i.html.split("")),Ne.populateMessages(t,o,new Te(t),n,"html",0,s)}}static async populateMessages(t,e,i,s,n,o,r){const a=e[o];if(a){const l=await Oe.basicResponseProcessing(t,{[n]:a},{io:r});Ne.upsertWFiles(t,i.upsertStreamedMessage.bind(i),i,l);const c=setTimeout((()=>{Ne.populateMessages(t,e,i,s,n,o+1,r)}),s.simulationInterim||6);s.abortStream.abort=()=>{Ne.abort(c,i,s.onClose)}}else i.finaliseStreamedMessage(),s.onClose()}static isSimulation(t){return"object"==typeof t&&!!t.simulation}static isSimulatable(t,e){return Ne.isSimulation(t)&&e&&(e.text||e.html)}static abort(t,e,i){clearTimeout(t),e.finaliseStreamedMessage(),i()}static upsertWFiles(t,e,i,s){if(s&&Array.isArray(s)&&(s=s[0]),null!=s&&s.text||null!=s&&s.html){const t=e(s);i??(i=t||void 0)}null!=s&&s.files&&(t.addNewMessage({files:s.files}),null==i||i.markFileAdded())}}const Re=class t{static generateResponse(t){const e=t[t.length-1][0];if(e.files&&e.files.length>0){if(e.files.length>1)return"These are interesting files!";const t=e.files[0];return t.src&&t.src.startsWith("data:image/gif")?"That is a nice gif!":"image"===t.type?"That is a nice image!":"audio"===t.type?"I like the sound of that!":"That is an interesting file!"}if(e.text){if("?"===e.text.charAt(e.text.length-1))return"I'm sorry but I can't answer that question...";if(e.text.includes("updog"))return"What's updog?"}return"Hi there! This is a demo response!"}static getCustomResponse(t,e){return"function"==typeof t?t(e):t}static getResponse({customDemoResponse:e,messageToElements:i}){return e?t.getCustomResponse(e,i[i.length-1][0]):{text:t.generateResponse(i)}}static request(e,i){const s=t.getResponse(i);setTimeout((async()=>{const t=await Oe.basicResponseProcessing(i,s,{io:e});if(!t)return e.completionsHandlers.onFinish();const n=Array.isArray(t)?t:[t],o=n.find((t=>"string"==typeof t.error));o?(i.addNewErrorMessage("service",o.error),e.completionsHandlers.onFinish()):Ne.isSimulatable(e.stream,t)?Ne.simulate(i,e.streamHandlers,t):(n.forEach((t=>i.addNewMessage(t))),e.completionsHandlers.onFinish())}),400)}static requestStream(e,i){setTimeout((()=>{const s=t.getResponse(e);Ne.simulate(e,i.streamHandlers,s,i)}),400)}};Re.URL="deep-chat-demo";let qe=Re;class Be{static setup(t){t.permittedErrorPrefixes=["Connection error","Error in server message"],t.websocket="pending"}static isElementPresentInDOM(t){return t.getRootNode({composed:!0})instanceof Document}static createConnection(t,e){if(!Be.isElementPresentInDOM(t.deepChat))return;const i=t.connectSettings.websocket;if(i){if(t.connectSettings.handler)return Le.websocket(t,e);try{const s="boolean"!=typeof i?i:void 0,n=new WebSocket(t.connectSettings.url||"",s);t.websocket=n,t.websocket.onopen=()=>{var i,s;e.removeError(),t.websocket&&"object"==typeof t.websocket&&Be.assignListeners(t,n,e),null==(s=(i=t.deepChat)._validationHandler)||s.call(i)},t.websocket.onerror=i=>{console.error(i),Be.retryConnection(t,e)}}catch(i){console.error(i),Be.retryConnection(t,e)}}}static retryConnection(t,e){var i,s;null==(s=(i=t.deepChat)._validationHandler)||s.call(i),Be.isElementPresentInDOM(t.deepChat)&&(t.websocket="pending",e.isLastMessageError()||e.addNewErrorMessage("service","Connection error"),setTimeout((()=>{Be.createConnection(t,e)}),5e3))}static assignListeners(t,e,i){const s={};e.onmessage=async e=>{if(t.extractResultData)try{const n=JSON.parse(e.data),o=await Oe.basicResponseProcessing(i,n,{io:t,displayError:!1});if(!o)throw Error(y.INVALID_RESPONSE(n,"server",!!t.deepChat.responseInterceptor,o));if(Ne.isSimulation(t.stream)){const e=Be.stream.bind(this,t,i,s),r=s[n.role||Se.AI_ROLE];Ne.upsertWFiles(i,e,r,o)}else(Array.isArray(o)?o:[o]).forEach((t=>i.addNewMessage(t)))}catch(t){Oe.displayError(i,t,"Error in server message")}},e.onclose=()=>{console.error("Connection closed"),i.isLastMessageError()||i.addNewErrorMessage("service","Connection error"),t.stream&&t.streamHandlers.abortStream.abort(),Be.createConnection(t,i)}}static async sendWebsocket(t,e,i,s=!0){var n,o;if((null==(n=t.connectSettings)?void 0:n.url)===qe.URL)return qe.request(t,i);const r=t.websocket;if(!r||"pending"===r)return;const a={body:e,headers:null==(o=t.connectSettings)?void 0:o.headers},{body:l,error:c}=await Oe.processRequestInterceptor(t.deepChat,a);if(c)return i.addNewErrorMessage("service",c);if(!Be.isWebSocket(r))return r.newUserMessage.listener(l);const h=s?JSON.stringify(l):l;void 0===r.readyState||r.readyState!==r.OPEN?(console.error("Connection is not open"),i.isLastMessageError()||i.addNewErrorMessage("service","Connection error")):(r.send(JSON.stringify(h)),t.completionsHandlers.onFinish())}static canSendMessage(t){return!t||"pending"!==t&&(Be.isWebSocket(t)?void 0!==t.readyState&&t.readyState===t.OPEN:t.isOpen)}static isWebSocket(t){return void 0!==t.send}static stream(t,e,i,s){if(!s)return;const n=t.stream.simulation;if("string"==typeof n){const t=s.role||Se.AI_ROLE,o=i[t];s.text===n||s.html===n?(null==o||o.finaliseStreamedMessage(),delete i[t]):(i[t]??(i[t]=new Te(e)),i[t].upsertStreamedMessage(s))}else Ne.simulate(e,t.streamHandlers,s)}}class Le{static async request(t,e,i){var s,n;let o=!0;const r=Le.generateOptionalSignals();null==(n=(s=t.connectSettings).handler)||n.call(s,e,{...r,onResponse:async e=>{if(!o)return;o=!1;const s=await Oe.basicResponseProcessing(i,e,{io:t,displayError:!1});if(s){const e=Array.isArray(s)?s:[s],n=e.find((t=>"string"==typeof t.error));n?(console.error(n.error),i.addNewErrorMessage("service",n.error),t.completionsHandlers.onFinish()):Ne.isSimulatable(t.stream,s)?Ne.simulate(i,t.streamHandlers,s):(e.forEach((t=>i.addNewMessage(t))),t.completionsHandlers.onFinish())}else console.error(y.INVALID_RESPONSE(e,"server",!!t.deepChat.responseInterceptor,s)),i.addNewErrorMessage("service","Error in server message"),t.completionsHandlers.onFinish()}})}static attemptToFinaliseStream(t,e){try{const i=e.messageElementRefs[e.messageElementRefs.length-1];fe.isLoadingMessage(i)?e.removeLastMessage():t.finaliseStreamedMessage()}catch(t){console.error(t),e.addNewErrorMessage("service",t)}}static stream(t,e,i){var s,n;let o=!0,r=!1;const a=new Te(i);t.streamHandlers.abortStream.abort=()=>{Le.attemptToFinaliseStream(a,i),t.streamHandlers.onClose(),o=!1};const l=Le.generateOptionalSignals();null==(n=(s=t.connectSettings).handler)||n.call(s,e,{...l,onOpen:()=>{r||!o||(t.streamHandlers.onOpen(),r=!0)},onResponse:async e=>{if(!o)return;const s=await Oe.basicResponseProcessing(i,e,{io:t,displayError:!1});if(s)s.error?(Le.streamError(s.error,a,t,i),o=!1):Ne.upsertWFiles(i,a.upsertStreamedMessage.bind(a),a,s);else{const n=y.INVALID_RESPONSE(e,"server",!!t.deepChat.responseInterceptor,s);Le.streamError(n,a,t,i),o=!1}},onClose:()=>{o&&(Le.attemptToFinaliseStream(a,i),t.streamHandlers.onClose(),o=!1)},stopClicked:t.streamHandlers.stopClicked})}static streamError(t,e,i,s){console.error(t),e.finaliseStreamedMessage(),s.addNewErrorMessage("service",t),i.streamHandlers.onClose()}static websocket(t,e){var i,s;const n={isOpen:!1,newUserMessage:{listener:()=>{}},roleToStream:{}};t.websocket=n;const o=Le.generateOptionalSignals();null==(s=(i=t.connectSettings).handler)||s.call(i,void 0,{...o,onOpen:()=>{e.removeError(),n.isOpen=!0},onResponse:async i=>{if(!n.isOpen)return;const s=await Oe.basicResponseProcessing(e,i,{io:t,displayError:!1});if(s){const i=Array.isArray(s)?s:[s],o=i.find((t=>"string"==typeof t.error));if(o)console.error(o.error),e.isLastMessageError()||e.addNewErrorMessage("service",o.error);else if(Ne.isSimulation(t.stream)){const i=s,o=Be.stream.bind(this,t,e,n.roleToStream),r=n.roleToStream[i.role||Se.AI_ROLE];Ne.upsertWFiles(e,o,r,i)}else i.forEach((t=>e.addNewMessage(t)))}else console.error(y.INVALID_RESPONSE(i,"server",!!t.deepChat.responseInterceptor,s)),e.addNewErrorMessage("service","Error in server message")},onClose:()=>{n.isOpen=!1},newUserMessage:n.newUserMessage})}static generateOptionalSignals(){return{onClose:()=>{},onOpen:()=>{},stopClicked:{listener:()=>{}},newUserMessage:{listener:()=>{}}}}}class Fe{static async request(t,e,i,s=!0){var n,o,r;const a={body:e,headers:null==(n=t.connectSettings)?void 0:n.headers},{body:l,headers:c,error:h}=await Oe.processRequestInterceptor(t.deepChat,a),{onFinish:u}=t.completionsHandlers;if(h)return Oe.onInterceptorError(i,h,u);if(null!=(o=t.connectSettings)&&o.handler)return Le.request(t,l,i);if((null==(r=t.connectSettings)?void 0:r.url)===qe.URL)return qe.request(t,i);let d=!0;const p=Oe.fetch.bind(this,t,c,s);p(l).then((t=>(d=!!t.ok,t))).then((t=>Oe.processResponseByType(t))).then((async e=>{var s,n;if(!t.extractResultData)return;const o=await(null==(n=(s=t.deepChat).responseInterceptor)?void 0:n.call(s,e))||e,r=await t.extractResultData(o,p,l);if(!d)throw e;if(!r||"object"!=typeof r&&!Array.isArray(r))throw Error(y.INVALID_RESPONSE(e,"response",!!t.deepChat.responseInterceptor,o));r.makingAnotherRequest||(Ne.isSimulatable(t.stream,r)?Ne.simulate(i,t.streamHandlers,r):((Array.isArray(r)?r:[r]).forEach((t=>i.addNewMessage(t))),u()))})).catch((t=>{Oe.displayError(i,t),u()}))}static executePollRequest(t,e,i,s){const{onFinish:n}=t.completionsHandlers;fetch(e,i).then((t=>t.json())).then((async o=>{var r,a;if(!t.extractPollResultData)return;const l=await t.extractPollResultData(await(null==(a=(r=t.deepChat).responseInterceptor)?void 0:a.call(r,o))||o);l.timeoutMS?setTimeout((()=>{Fe.executePollRequest(t,e,i,s)}),l.timeoutMS):Ne.isSimulatable(t.stream,l)?Ne.simulate(s,t.streamHandlers,l):(s.addNewMessage(l),n())})).catch((t=>{Oe.displayError(s,t),n()}))}static async poll(t,e,i,s=!0){var n,o,r;const a={body:e,headers:null==(n=t.connectSettings)?void 0:n.headers},{body:l,headers:c,error:h}=await Oe.processRequestInterceptor(t.deepChat,a);if(h)return Oe.onInterceptorError(i,h);const u=(null==(o=t.connectSettings)?void 0:o.url)||t.url||"",d={method:(null==(r=t.connectSettings)?void 0:r.method)||"POST",body:s?JSON.stringify(l):l,headers:c};t.connectSettings.credentials&&(d.credentials=t.connectSettings.credentials),Fe.executePollRequest(t,u,d,i)}static verifyKey(t,e,i,s,n,o,r,a,l){if(""===t)return o(y.INVALID_KEY);r(),fetch(e,{method:s,headers:i,body:l||null}).then((t=>Oe.processResponseByType(t))).then((e=>{a(e,t,n,o)})).catch((t=>{o(y.CONNECTION_FAILED),console.error(t)}))}}const ze=class t{constructor(t,e,i){this._isLoading=!1,this._isPaginationComplete=!1,this._index=0,this._messages=e,i.fetchHistory&&this.fetchHistory(i.fetchHistory),t.loadHistory&&this.setupLoadHistoryOnScroll(t.loadHistory),this.setupInitialHistory(t)}async fetchHistory(e){const i=de.addMessage(this._messages),s=await e();this._messages.removeMessage(i),t.displayIntroMessages(this._messages.messageElementRefs),s.forEach((t=>this._messages.addAnyMessage(t,!0))),setTimeout((()=>x.scrollToBottom(this._messages.elementRef)),0)}processLoadedHistory(t){var e;const{messageElementRefs:i,messageToElements:s,elementRef:n}=this._messages,o=null==(e=i.find((t=>!t.outerContainer.classList.contains(fe.INTRO_CLASS))))?void 0:e.outerContainer,r=n.scrollTop;null==t||t.reverse().map((t=>{const e=this._messages.addAnyMessage({...t,sendUpdate:!0},!0,!0);if(e){const t=Se.generateMessageBody(e,i,!0);s.unshift([e,t])}return e})).filter((t=>!!t)).reverse().forEach((t=>this._messages.sendClientUpdate(t,!0))),o&&(n.scrollTop=r+o.offsetTop-40)}populateMessages(t,e){this._messages.removeMessage(t),this._isPaginationComplete=e.findIndex((t=>!t))<0;const i=e.filter((t=>!!t));this.processLoadedHistory(i);const{messageElementRefs:s,avatars:n,names:o}=this._messages;Se.resetAllRoleElements(s,!!n,!!o)}async setupLoadHistoryOnScroll(e){this._messages.elementRef.onscroll=async()=>{if(!this._isLoading&&!this._isPaginationComplete&&0===this._messages.elementRef.scrollTop){this._isLoading=!0;const i=de.addMessage(this._messages,!1);try{const t=await e(this._index++);this.populateMessages(i,t),this._isLoading=!1}catch(e){this._messages.removeMessage(i),this._isPaginationComplete=!0,this._messages.addNewErrorMessage("service",t.FAILED_ERROR_MESSAGE,!0),console.error(e)}}}}populateInitialHistory(t){t.forEach((t=>{O.processHistoryFile(t),this._messages.addAnyMessage(t,!0)}))}async loadInitialHistory(e){this._isLoading=!0;const i=de.addMessage(this._messages);try{const t=await e(this._index++),s=this._messages.elementRef.scrollTop;this.populateMessages(i,t),0===s&&setTimeout((()=>x.scrollToBottom(this._messages.elementRef)),0)}catch(e){this._messages.removeMessage(i),this._isPaginationComplete=!0,this._messages.addNewErrorMessage("service",t.FAILED_ERROR_MESSAGE,!0),console.error(e)}t.displayIntroMessages(this._messages.messageElementRefs),this._isLoading=!1}async setupInitialHistory(t){t.loadHistory&&this.loadInitialHistory(t.loadHistory);const e=t.history||O.processHistory(t);e&&(this.populateInitialHistory(e),this._index+=1)}static addErrorPrefix(e){e.permittedErrorPrefixes??(e.permittedErrorPrefixes=[]),e.permittedErrorPrefixes.push(t.FAILED_ERROR_MESSAGE)}static displayIntroMessages(t){for(let e=0;e<t.length;e+=1){const e=t[0];if(!e.outerContainer.classList.contains(fe.INTRO_CLASS))break;e.outerContainer.style.display=""}}};ze.FAILED_ERROR_MESSAGE="Failed to load history";let De=ze;class $e{static getCharacterLimitMessages(t,e){var i;if(-1===e)return t;let s=0,n=t.length-1;for(;n>=0;n-=1){const o=null==(i=t[n])?void 0:i.text;if(void 0!==o&&(s+=o.length,s>e)){t[n].text=o.substring(0,o.length-(s-e));break}}return t.slice(Math.max(n,0))}static getMaxMessages(t,e){return t.slice(Math.max(t.length-e,0))}static processMessages(t,e,i){return void 0!==e?e>0&&(t=$e.getMaxMessages(t,e)):t=[t[t.length-1]],t=JSON.parse(JSON.stringify(t)),void 0===i?t:$e.getCharacterLimitMessages(t,i)}}class Je{static parseConfig(t,e,i,s){var n;const o={files:e};if("object"==typeof s){O.processFileConfigConnect(s);const{files:e,connect:r,button:a}=s;e&&(e.infoModal&&(o.files.infoModal=e.infoModal,null!=(n=e.infoModal)&&n.textMarkDown&&(o.infoModalTextMarkUp=i.render(e.infoModal.textMarkDown))),e.acceptedFormats&&(o.files.acceptedFormats=e.acceptedFormats),e.maxNumberOfFiles&&(o.files.maxNumberOfFiles=e.maxNumberOfFiles)),o.button=a,r&&(r.headers||r.method||r.url||r.credentials||t.headers||t.method||t.url||t.credentials)&&(o.connect={url:(null==r?void 0:r.url)||t.url,method:(null==r?void 0:r.method)||t.method,headers:(null==r?void 0:r.headers)||t.headers,credentials:(null==r?void 0:r.credentials)||t.credentials})}return o}static processMixedFiles(t,e,i){if(i){const s={acceptedFormats:""};t.fileTypes.mixedFiles=Je.parseConfig(t.connectSettings,s,e,i)}}static processMicrophone(t,e,i,s){var n,o,r,a,l,c;const h={acceptedFormats:"audio/*",...(null==(n=t.fileTypes.audio)?void 0:n.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.recordAudio=Je.parseConfig(t.connectSettings,h,e,i),"object"==typeof i&&i.files&&((o=t.recordAudio).files??(o.files={}),t.recordAudio.files.format=null==(r=i.files)?void 0:r.format,t.recordAudio.files.maxDurationSeconds=null==(a=i.files)?void 0:a.maxDurationSeconds,null!=(l=t.fileTypes.audio)&&l.files&&((c=t.fileTypes.audio.files).maxNumberOfFiles??(c.maxNumberOfFiles=i.files.maxNumberOfFiles)))):s||(t.fileTypes.audio=Je.parseConfig(t.connectSettings,h,e,i)))}static processAudioConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"audio/*",...(null==s?void 0:s.files)||{}};t.fileTypes.audio=Je.parseConfig(t.connectSettings,n,e,i)}static processGifConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"image/gif",...(null==s?void 0:s.files)||{}};t.fileTypes.gifs=Je.parseConfig(t.connectSettings,n,e,i)}static processCamera(t,e,i,s){var n,o,r,a;const l={acceptedFormats:"image/*",...(null==(n=t.fileTypes.images)?void 0:n.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.camera=Je.parseConfig(t.connectSettings,l,e,i),"object"==typeof i&&(t.camera.modalContainerStyle=i.modalContainerStyle,i.files&&((o=t.camera).files??(o.files={}),t.camera.files.format=null==(r=i.files)?void 0:r.format,t.camera.files.dimensions=null==(a=i.files)?void 0:a.dimensions))):s||(t.fileTypes.images=Je.parseConfig(t.connectSettings,l,e,i)))}static processImagesConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"image/*",...(null==s?void 0:s.files)||{}};t.fileTypes.images=Je.parseConfig(t.connectSettings,n,e,i)}static populateDefaultFileIO(t,e){var i,s;t&&(t.files??(t.files={}),(i=t.files).acceptedFormats??(i.acceptedFormats=e),(s=t.files).maxNumberOfFiles??(s.maxNumberOfFiles=1))}static set(t,e,i){Je.populateDefaultFileIO(null==i?void 0:i.audio,".4a,.mp3,.webm,.mp4,.mpga,.wav,.mpeg,.m4a"),Je.populateDefaultFileIO(null==i?void 0:i.images,".png,.jpg");const s=le.createNew(t.remarkable);Je.processImagesConfig(e,s,t.images,null==i?void 0:i.images),Je.processCamera(e,s,t.camera,t.images),Je.processGifConfig(e,s,t.gifs,null==i?void 0:i.gifs),Je.processAudioConfig(e,s,t.audio,null==i?void 0:i.audio),Je.processMicrophone(e,s,t.microphone,t.audio),Je.processMixedFiles(e,s,t.mixedFiles)}}class Ue{constructor(t,e,i){var s,n,o,r,a;this.rawBody={},this.validateKeyProperty=!1,this.canSendMessage=Ue.canSendMessage,this.connectSettings={},this.fileTypes={},this.completionsHandlers={},this.streamHandlers={},this.deepChat=t,this.demo=i,Object.assign(this.rawBody,null==(s=t.connect)?void 0:s.additionalBodyProps),this.totalMessagesMaxCharLength=null==(n=null==t?void 0:t.requestBodyLimits)?void 0:n.totalMessagesMaxCharLength,this.maxMessages=null==(o=null==t?void 0:t.requestBodyLimits)?void 0:o.maxMessages,Je.set(t,this,e),t.connect&&(this.connectSettings=t.connect),this.demo&&((r=this.connectSettings).url??(r.url=qe.URL)),this.connectSettings.websocket&&Be.setup(this),this.stream=(null==(a=this.deepChat.connect)?void 0:a.stream)||O.checkForStream(this.deepChat),t.loadHistory&&De.addErrorPrefix(this)}static canSendMessage(t,e,i){return!!i||(!(!t||""===t.trim())||!!(e&&e.length>0))}verifyKey(t,e){}static createCustomFormDataBody(t,e,i){const s=new FormData;i.forEach((t=>s.append("files",t))),Object.keys(t).forEach((e=>s.append(e,String(t[e]))));let n=0;e.slice(0,e.length-1).forEach((t=>{s.append(`message${n+=1}`,JSON.stringify(t))}));const o=e[e.length-1];return o.text&&(delete o.files,s.append(`message${n+=1}`,JSON.stringify(o))),s}getServiceIOByType(t){if(t.type.startsWith("audio")&&this.fileTypes.audio)return this.fileTypes.audio;if(t.type.startsWith("image")){if(this.fileTypes.gifs&&t.type.endsWith("/gif"))return this.fileTypes.gifs;if(this.fileTypes.images)return this.fileTypes.images;if(this.camera)return this.camera}return this.fileTypes.mixedFiles}async request(t,e,i=!0){return this.stream&&!Ne.isSimulation(this.stream)?Ne.request(this,t,e,i):Fe.request(this,t,e,i)}async callAPIWithText(t,e){var i,s,n,o;const r={messages:e,...this.rawBody};let a=!1;null!=(i=this.connectSettings.headers)&&i["Content-Type"]||((s=this.connectSettings).headers??(s.headers={}),(n=this.connectSettings.headers)["Content-Type"]??(n["Content-Type"]="application/json"),a=!0),await this.request(r,t),a&&(null==(o=this.connectSettings.headers)||delete o["Content-Type"])}async callApiWithFiles(t,e,i){const s=Ue.createCustomFormDataBody(this.rawBody,e,i),n=this.connectSettings,o=this.getServiceIOByType(i[0]);this.connectSettings=(null==o?void 0:o.connect)||this.connectSettings,await this.request(s,t,!1),this.connectSettings=n}async callServiceAPI(t,e,i){i?this.callApiWithFiles(t,e,i):this.callAPIWithText(t,e)}async callAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=$e.processMessages(e.messageToElements.map((([t])=>t)),this.maxMessages,this.totalMessagesMaxCharLength);if(!this.connectSettings.websocket||this.connectSettings.handler&&this.connectSettings.url===qe.URL)this.callServiceAPI(e,i,t.files);else{const t={messages:i,...this.rawBody};Be.sendWebsocket(this,t,e,!1)}}async extractResultData(t){if(t.error)throw t.error;return t.result?O.handleResponseProperty(t):Oe.validateResponseFormat(t,!!this.stream)?t:void 0}isDirectConnection(){return!1}isWebModel(){return!1}isCustomView(){return!1}}class Ve extends Ue{constructor(t,e,i,s,n){var o;super(t,n),this.insertKeyPlaceholderText="API Key",this.keyHelpUrl="",Object.assign(this.rawBody,null==(o=t.connect)?void 0:o.additionalBodyProps),this.keyVerificationDetails=e,this.buildHeadersFunc=i,s&&this.setApiKeyProperties(s),this.connectSettings=this.buildConnectSettings(this.key||"",t.connect)}setApiKeyProperties(t){this.key=t.key,t.validateKeyProperty&&(this.validateKeyProperty=t.validateKeyProperty)}buildConnectSettings(t,e){const i=e??{};return i.headers??(i.headers={}),Object.assign(i.headers,this.buildHeadersFunc(t)),i}keyAuthenticated(t,e){this.connectSettings=this.buildConnectSettings(e,this.connectSettings),this.key=e,t()}verifyKey(t,e){const{url:i,method:s,handleVerificationResult:n,createHeaders:o,body:r}=this.keyVerificationDetails,a=(null==o?void 0:o(t))||this.buildHeadersFunc(t);Fe.verifyKey(t,i,a,s,this.keyAuthenticated.bind(this,e.onSuccess),e.onFail,e.onLoad,n,r)}isDirectConnection(){return!0}}class He{static waitForPropertiesToBeUpdatedBeforeRender(t){t._propUpdated_=!1,setTimeout((()=>{t._propUpdated_?He.waitForPropertiesToBeUpdatedBeforeRender(t):(t._waitingToRender_=!1,t.onRender())}))}static attemptRender(t){t._propUpdated_=!0,t._waitingToRender_||(t._waitingToRender_=!0,He.waitForPropertiesToBeUpdatedBeforeRender(t))}}const Ke=class t extends HTMLElement{constructor(){super(),this._waitingToRender_=!1,this._propUpdated_=!1,Object.keys(t._attributeToProperty_).forEach((e=>{const i=t._attributeToProperty_[e];this.constructPropertyAccessors(i),this.hasOwnProperty(e)||this.constructPropertyAccessors(i,e)}))}static get observedAttributes(){return Object.keys(t._attributes_)||[]}constructPropertyAccessors(t,e){let i;Object.defineProperty(this,e||t,{get:function(){return i},set:function(s){i=s,e?this[t]=s:He.attemptRender(this)}})}attributeChangedCallback(e,i,s){if(i===s)return;const n=t._attributes_[e](s);this[t._attributeToProperty_[e]]=n}onRender(){}};Ke._attributes_={},Ke._attributeToProperty_={};let Ge=Ke;class Ze{static createSVGElement(t){return(new DOMParser).parseFromString(t,"image/svg+xml").documentElement}}const We=class t{static changeVisibility(e,i,s,n){n.target.id===t.VISIBLE_ICON_ID?(i.style.display="none",s.style.display="block",e.type="password"):(i.style.display="block",s.style.display="none",e.type="text")}static createIconElement(t,e){const i=Ze.createSVGElement(t);return i.id=e,i.classList.add("visibility-icon"),i}static create(e){const i=document.createElement("div");i.id="visibility-icon-container";const s=t.createIconElement('<?xml version="1.0" standalone="no"?>\n<svg version="1.1"\n\txmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n\txmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0.9em" height="0.9em"\n\tviewBox="0 0 1200 1200" enable-background="new 0 0 1200 1200">\n\t\t<path id="path6686" inkscape:connector-curvature="0" d="M779.843,599.925c0,95.331-80.664,172.612-180.169,172.612\n\t\t\tc-99.504,0-180.168-77.281-180.168-172.612c0-95.332,80.664-172.612,180.168-172.612\n\t\t\tC699.179,427.312,779.843,504.594,779.843,599.925z M600,240.521c-103.025,0.457-209.814,25.538-310.904,73.557\n\t\t\tc-75.058,37.122-148.206,89.496-211.702,154.141C46.208,501.218,6.431,549,0,599.981c0.76,44.161,48.13,98.669,77.394,131.763\n\t\t\tc59.543,62.106,130.786,113.018,211.702,154.179c94.271,45.751,198.616,72.092,310.904,73.557\n\t\t\tc103.123-0.464,209.888-25.834,310.866-73.557c75.058-37.122,148.243-89.534,211.74-154.179\n\t\t\tc31.185-32.999,70.962-80.782,77.394-131.763c-0.76-44.161-48.13-98.671-77.394-131.764\n\t\t\tc-59.543-62.106-130.824-112.979-211.74-154.141C816.644,268.36,712.042,242.2,600,240.521z M599.924,329.769\n\t\t\tc156.119,0,282.675,120.994,282.675,270.251c0,149.256-126.556,270.25-282.675,270.25S317.249,749.275,317.249,600.02\n\t\t\tC317.249,450.763,443.805,329.769,599.924,329.769L599.924,329.769z"/>\n</svg>\n',t.VISIBLE_ICON_ID);s.style.display="none",i.appendChild(s);const n=t.createIconElement('<?xml version="1.0" standalone="no"?>\n<svg version="1.1"\n\txmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n\txmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0.9em" height="0.9em"\n\tviewBox="0 0 1200 1200" enable-background="new 0 0 1200 1200">\n\t\t<path d="\n\t\t\tM669.727,273.516c-22.891-2.476-46.15-3.895-69.727-4.248c-103.025,0.457-209.823,25.517-310.913,73.536\n\t\t\tc-75.058,37.122-148.173,89.529-211.67,154.174C46.232,529.978,6.431,577.76,0,628.74c0.76,44.162,48.153,98.67,77.417,131.764\n\t\t\tc59.543,62.106,130.754,113.013,211.67,154.174c2.75,1.335,5.51,2.654,8.276,3.955l-75.072,131.102l102.005,60.286l551.416-960.033\n\t\t\tl-98.186-60.008L669.727,273.516z M902.563,338.995l-74.927,129.857c34.47,44.782,54.932,100.006,54.932,159.888\n\t\t\tc0,149.257-126.522,270.264-282.642,270.264c-6.749,0-13.29-0.728-19.922-1.172l-49.585,85.84c22.868,2.449,45.99,4.233,69.58,4.541\n\t\t\tc103.123-0.463,209.861-25.812,310.84-73.535c75.058-37.122,148.246-89.529,211.743-154.174\n\t\t\tc31.186-32.999,70.985-80.782,77.417-131.764c-0.76-44.161-48.153-98.669-77.417-131.763\n\t\t\tc-59.543-62.106-130.827-113.013-211.743-154.175C908.108,341.478,905.312,340.287,902.563,338.995L902.563,338.995z\n\t\t\tM599.927,358.478c6.846,0,13.638,0.274,20.361,0.732l-58.081,100.561c-81.514,16.526-142.676,85.88-142.676,168.897\n\t\t\tc0,20.854,3.841,40.819,10.913,59.325c0.008,0.021-0.008,0.053,0,0.074l-58.228,100.854\n\t\t\tc-34.551-44.823-54.932-100.229-54.932-160.182C317.285,479.484,443.808,358.477,599.927,358.478L599.927,358.478z M768.896,570.513\n\t\t\tL638.013,797.271c81.076-16.837,141.797-85.875,141.797-168.603C779.81,608.194,775.724,588.729,768.896,570.513L768.896,570.513z"\n\t\t\t/>\n</svg>\n',"not-visible-icon");return i.appendChild(n),i.onclick=t.changeVisibility.bind(this,e,s,n),i}};We.VISIBLE_ICON_ID="visible-icon";let Xe=We;class Ye{static createCautionText(){const t=document.createElement("a");return t.classList.add("insert-key-input-help-text"),t.innerText="Please exercise CAUTION when inserting your API key outside of deepchat.dev or localhost!!",t}static createHelpLink(t){const e=document.createElement("a");return e.classList.add("insert-key-input-help-text"),e.href=t,e.innerText="Find more info here",e.target="_blank",e}static createFailText(){const t=document.createElement("div");return t.id="insert-key-input-invalid-text",t.style.display="none",t}static createHelpTextContainer(t,e=!0){const i=document.createElement("div");i.id="insert-key-help-text-container";const s=document.createElement("div");s.id="insert-key-help-text-contents";const n=Ye.createFailText();if(s.appendChild(n),t){const e=Ye.createHelpLink(t);s.appendChild(e)}if(!0===e){const t=Ye.createCautionText();s.appendChild(t)}return i.appendChild(s),{helpTextContainerElement:i,failTextElement:n}}static onFail(t,e,i,s){t.classList.replace("insert-key-input-valid","insert-key-input-invalid"),i.innerText=s,i.style.display="block",e.innerText="Start",t.classList.remove("loading")}static onLoad(t,e){t.classList.add("loading"),e.innerHTML='<div id="loading-key"></div>'}static verifyKey(t,e,i){const s=t.value.trim();i.verifyKey(s,e)}static addVerificationEvents(t,e,i,s,n){const o={onSuccess:s,onFail:Ye.onFail.bind(this,t,e,i),onLoad:Ye.onLoad.bind(this,t,e)},r=Ye.verifyKey.bind(this,t,o,n);e.onclick=r,t.onkeydown=e=>{!t.classList.contains("loading")&&e.key===c.ENTER&&r()}}static createStartButton(){const t=document.createElement("div");return t.id="start-button",t.innerText="Start",t}static onInputFocus(t){t.target.classList.replace("insert-key-input-invalid","insert-key-input-valid")}static createInput(t){const e=document.createElement("div");e.id="insert-key-input-container";const i=document.createElement("input");return i.id="insert-key-input",i.placeholder=t||"API Key",i.type="password",i.classList.add("insert-key-input-valid"),i.onfocus=Ye.onInputFocus,e.appendChild(i),e}static createContents(t,e){var i;const s=document.createElement("div");s.id="insert-key-contents";const n=Ye.createInput(e.insertKeyPlaceholderText),o=n.children[0],r=Xe.create(o);n.appendChild(r),s.appendChild(n);const a=Ye.createStartButton(),{helpTextContainerElement:l,failTextElement:c}=Ye.createHelpTextContainer(e.keyHelpUrl,null==(i=e.deepChat._insertKeyViewStyles)?void 0:i.displayCautionText);return s.appendChild(a),s.appendChild(l),Ye.addVerificationEvents(o,a,c,t,e),s}static createElements(t,e){const i=document.createElement("div");i.id="insert-key-view";const s=Ye.createContents(t,e);return i.appendChild(s),i}static render(t,e,i){const s=Ye.createElements(e,i);t.replaceChildren(s)}}const Qe=class t{static enableButtons(e,i,s=0){window.webLLM?(e&&(e.disabled=!1),i&&(i.disabled=!1)):s<4*si.MODULE_SEARCH_LIMIT_S&&setTimeout((()=>t.enableButtons(e,i,s+1)),250)}static setUpInitial(e,i,s,n){const o=(null==i?void 0:i.downloadClass)||t.DOWNLOAD_BUTTON_CLASS,r=(null==i?void 0:i.uploadClass)||t.UPLOAD_BUTTON_CLASS,a=(null==i?void 0:i.fileInputClass)||t.FILE_INPUT_CLASS;return setTimeout((()=>{const i=null==s?void 0:s.getElementsByClassName(o)[0],n=null==s?void 0:s.getElementsByClassName(a)[0],l=null==s?void 0:s.getElementsByClassName(r)[0];i&&(i.onclick=()=>e()),n&&(n.onchange=()=>{n.files&&n.files.length>0&&e(n.files)}),l&&(l.onclick=()=>n.click()),(i||l)&&t.enableButtons(i,l)})),(null==i?void 0:i.initialHtml)||`<div>\n Download or upload a web model that will run entirely on your browser: <br/> \n <button disabled class="${o} deep-chat-button deep-chat-web-model-button">Download</button>\n ${n?"":`<input type="file" class="${a}" hidden multiple />\n <button disabled class="${r} deep-chat-button deep-chat-web-model-button">Upload</button>`}\n </div>`}static exportFile(t){const e=document.createElement("a");for(let i=0;i<t.length/4;i+=1)setTimeout((()=>{const s=4*i;for(let i=s;i<Math.min(s+4,t.length);i+=1){const s=URL.createObjectURL(t[i]);e.href=s,e.download=t[i].name,document.body.appendChild(e),e.click(),URL.revokeObjectURL(s)}}),500*i)}static setUpAfterLoad(e,i,s,n){const o=(null==i?void 0:i.exportFilesClass)||t.EXPORT_BUTTON_CLASS;return setTimeout((()=>{const i=null==s?void 0:s.getElementsByClassName(o)[0];i&&(i.onclick=()=>t.exportFile(e))})),(null==i?void 0:i.afterLoadHtml)||`<div>\n Model loaded successfully and has been cached for future requests.\n ${n?"":`<br/> <button style="margin-top: 5px" class="${o} deep-chat-button">Export</button>`}\n </div>`}};Qe.DOWNLOAD_BUTTON_CLASS="deep-chat-download-button",Qe.UPLOAD_BUTTON_CLASS="deep-chat-upload-button",Qe.FILE_INPUT_CLASS="deep-chat-file-input",Qe.EXPORT_BUTTON_CLASS="deep-chat-export-button";let ti=Qe;const ei={model_list:[{model_url:"https://huggingface.co/mlc-ai/Llama-2-7b-chat-hf-q4f32_1-MLC/resolve/main/",local_id:"Llama-2-7b-chat-hf-q4f32_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-7b-chat-hf/Llama-2-7b-chat-hf-q4f32_1-ctx4k_cs1k-webgpu.wasm",vram_required_MB:9109.03,low_resource_required:!1},{model_url:"https://huggingface.co/mlc-ai/Llama-2-7b-chat-hf-q4f16_1-MLC/resolve/main/",local_id:"Llama-2-7b-chat-hf-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-7b-chat-hf/Llama-2-7b-chat-hf-q4f16_1-ctx4k_cs1k-webgpu.wasm",vram_required_MB:6749.02,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/Llama-2-7b-chat-hf-q4f16_1-MLC/resolve/main/",local_id:"Llama-2-7b-chat-hf-q4f16_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-7b-chat-hf/Llama-2-7b-chat-hf-q4f16_1-ctx1k-webgpu.wasm",vram_required_MB:4618.52,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/Llama-2-13b-chat-hf-q4f16_1-MLC/resolve/main/",local_id:"Llama-2-13b-chat-hf-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-13b-chat-hf/Llama-2-13b-chat-hf-q4f16_1-ctx4k_cs1k-webgpu.wasm",vram_required_MB:11814.09,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/Llama-2-70b-chat-hf-q4f16_1-MLC/resolve/main/",local_id:"Llama-2-70b-chat-hf-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Llama-2-70b-chat-hf/Llama-2-70b-chat-hf-q4f16_1-ctx4k_cs1k-webgpu.wasm",vram_required_MB:43729.05,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/RedPajama-INCITE-Chat-3B-v1-q4f16_1-MLC/resolve/main/",local_id:"RedPajama-INCITE-Chat-3B-v1-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/RedPajama-INCITE-Chat-3B-v1/RedPajama-INCITE-Chat-3B-v1-q4f16_1-ctx2k-webgpu.wasm",vram_required_MB:2972.09,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/RedPajama-INCITE-Chat-3B-v1-q4f32_1-MLC/resolve/main/",local_id:"RedPajama-INCITE-Chat-3B-v1-q4f32_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/RedPajama-INCITE-Chat-3B-v1/RedPajama-INCITE-Chat-3B-v1-q4f32_1-ctx2k-webgpu.wasm",vram_required_MB:3928.09,low_resource_required:!1},{model_url:"https://huggingface.co/mlc-ai/RedPajama-INCITE-Chat-3B-v1-q4f16_1-MLC/resolve/main/",local_id:"RedPajama-INCITE-Chat-3B-v1-q4f16_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/RedPajama-INCITE-Chat-3B-v1/RedPajama-INCITE-Chat-3B-v1-q4f16_1-ctx1k-webgpu.wasm",vram_required_MB:2041.09,low_resource_required:!0,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/RedPajama-INCITE-Chat-3B-v1-q4f32_1-MLC/resolve/main/",local_id:"RedPajama-INCITE-Chat-3B-v1-q4f32_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/RedPajama-INCITE-Chat-3B-v1/RedPajama-INCITE-Chat-3B-v1-q4f32_1-ctx1k-webgpu.wasm",vram_required_MB:2558.09,low_resource_required:!0},{model_url:"https://huggingface.co/mlc-ai/WizardMath-7B-V1.1-q4f16_1-MLC/resolve/main/",local_id:"WizardMath-7B-V1.1-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Mistral-7B-Instruct-v0.2/Mistral-7B-Instruct-v0.2-q4f16_1-sw4k_cs1k-webgpu.wasm",vram_required_MB:6079.02,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/Mistral-7B-Instruct-v0.2-q4f16_1-MLC/resolve/main/",local_id:"Mistral-7B-Instruct-v0.2-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Mistral-7B-Instruct-v0.2/Mistral-7B-Instruct-v0.2-q4f16_1-sw4k_cs1k-webgpu.wasm",vram_required_MB:6079.02,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/OpenHermes-2.5-Mistral-7B-q4f16_1-MLC/resolve/main/",local_id:"OpenHermes-2.5-Mistral-7B-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Mistral-7B-Instruct-v0.2/Mistral-7B-Instruct-v0.2-q4f16_1-sw4k_cs1k-webgpu.wasm",vram_required_MB:6079.02,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/NeuralHermes-2.5-Mistral-7B-q4f16_1-MLC/resolve/main/",local_id:"NeuralHermes-2.5-Mistral-7B-q4f16_1",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/Mistral-7B-Instruct-v0.2/Mistral-7B-Instruct-v0.2-q4f16_1-sw4k_cs1k-webgpu.wasm",vram_required_MB:6079.02,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/TinyLlama-1.1B-Chat-v0.4-q0f16-MLC/resolve/main/",local_id:"TinyLlama-1.1B-Chat-v0.4-q0f16",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/TinyLlama-1.1B-Chat-v0.4/TinyLlama-1.1B-Chat-v0.4-q0f16-ctx2k-webgpu.wasm",vram_required_MB:5063.52,low_resource_required:!1,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/TinyLlama-1.1B-Chat-v0.4-q0f32-MLC/resolve/main/",local_id:"TinyLlama-1.1B-Chat-v0.4-q0f32",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/TinyLlama-1.1B-Chat-v0.4/TinyLlama-1.1B-Chat-v0.4-q0f32-ctx2k-webgpu.wasm",vram_required_MB:5394.53,low_resource_required:!1},{model_url:"https://huggingface.co/mlc-ai/TinyLlama-1.1B-Chat-v0.4-q4f16_1-MLC/resolve/main/",local_id:"TinyLlama-1.1B-Chat-v0.4-q4f16_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/TinyLlama-1.1B-Chat-v0.4/TinyLlama-1.1B-Chat-v0.4-q4f16_1-ctx1k-webgpu.wasm",vram_required_MB:899.11,low_resource_required:!0,required_features:["shader-f16"]},{model_url:"https://huggingface.co/mlc-ai/TinyLlama-1.1B-Chat-v0.4-q4f32_1-MLC/resolve/main/",local_id:"TinyLlama-1.1B-Chat-v0.4-q4f32_1-1k",model_lib_url:"https://raw.githubusercontent.com/mlc-ai/binary-mlc-llm-libs/main/TinyLlama-1.1B-Chat-v0.4/TinyLlama-1.1B-Chat-v0.4-q4f32_1-ctx1k-webgpu.wasm",vram_required_MB:992.11,low_resource_required:!0}],use_web_worker:!0},ii=class t extends Ue{constructor(e){var i,s;super(e),this._isModelLoaded=!1,this._isModelLoading=!1,this._loadOnFirstMessage=!1,this._webModel={},this.permittedErrorPrefixes=[t.MULTIPLE_MODELS_ERROR,t.WEB_LLM_NOT_FOUND_ERROR,t.GENERIC_ERROR],this._conversationHistory=[],"object"==typeof e.webModel&&(this._webModel=e.webModel),null!=(i=this._webModel.load)&&i.clearCache&&t.clearAllCache(),this.findModelInWindow(e),this.canSendMessage=this.canSubmit.bind(this),this._chatEl=null==(s=e.shadowRoot)?void 0:s.children[0],e.history&&t.setUpHistory(this._conversationHistory,e.history)}setUpMessages(t){this._messages=t,this._removeIntro=()=>{t.removeIntroductoryMessage(),this._removeIntro=void 0}}static setUpHistory(t,e){e.forEach(((i,s)=>{if(i.role===Se.USER_ROLE&&i.text){const n=e[s+1];null!=n&&n.text&&n.role!==Se.USER_ROLE&&t.push([i.text,n.text])}}))}findModelInWindow(e,i=0){var s;window.webLLM?this.configureInit(this.shouldAddIntroMessage(e.introMessage)):i>t.MODULE_SEARCH_LIMIT_S?(null==(s=this._messages)||s.addNewErrorMessage("service",t.WEB_LLM_NOT_FOUND_ERROR),console.error("The deep-chat-web-llm module has not been attached to the window object. Please see the following guide:"),console.error("https://deepchat.dev/examples/externalModules")):setTimeout((()=>this.findModelInWindow(e,i+1)),1e3)}shouldAddIntroMessage(t){var e;return!t&&this._webModel&&!1!==(null==(e=this._webModel.introMessage)?void 0:e.displayed)}scrollToTop(t){var e;!1!==(null==(e=this._webModel.introMessage)?void 0:e.autoScroll)&&setTimeout((()=>{var t,e;null!=(t=this._messages)&&t.elementRef&&x.scrollToTop(null==(e=this._messages)?void 0:e.elementRef)}),t)}getIntroMessage(t){if(!this.shouldAddIntroMessage(t)||!this._chatEl)return;const e=ti.setUpInitial(this.init.bind(this),this._webModel.introMessage,this._chatEl,!!this._webModel.worker);return this.scrollToTop(1),{role:Se.AI_ROLE,html:e,sendUpdate:!1}}async configureInit(t){const{load:e}=this._webModel;if(e){if(e.onInit)return void this.init();if(e.onMessage)return void(this._loadOnFirstMessage=!0)}t||this.init()}async init(t){var e;null==(e=this._messages)||e.removeError();const i=this.attemptToCreateChat();i&&await this.loadModel(i,t)}attemptToCreateChat(){var e;if(t.chat)return null==(e=this._messages)||e.addNewErrorMessage("service",t.MULTIPLE_MODELS_ERROR),void console.error(t.MULTIPLE_MODELS_ERROR);if(this._isModelLoaded||this._isModelLoading)return;const{worker:i}=this._webModel;return ei.use_web_worker&&i?new window.webLLM.ChatWorkerClient(i):new window.webLLM.ChatModule}getConfig(){var e;let i=t.DEFAULT_MODEL;this._webModel.model&&(i=this._webModel.model);const s=JSON.parse(JSON.stringify(ei));if(this._webModel.urls){const t=s.model_list.find((t=>t.local_id=i));t&&(this._webModel.urls.model&&(t.model_url=this._webModel.urls.model),this._webModel.urls.wasm&&(t.model_lib_url=this._webModel.urls.wasm))}return null!=(e=this._webModel.load)&&e.skipCache&&(s.use_cache=!1),{model:i,appConfig:s}}async loadModel(e,i){var s,n,o,r,a,l,c;this.scrollToTop(),t.chat=e,this._isModelLoading=!0;let h=!1===(null==(s=this._webModel.introMessage)?void 0:s.displayed);let u;t.chat.setInitProgressCallback((t=>{var e;null==(e=this._messages)||e.addNewMessage({html:`<div>${t.text}</div>`,overwrite:!0,sendUpdate:!1}),h&&(setTimeout((()=>{var t;return x.scrollToBottom(null==(t=this._messages)?void 0:t.elementRef)})),h=!1)}));try{const{model:e,appConfig:s}=this.getConfig(),n={};this._webModel.instruction&&(n.conv_config={system:this._webModel.instruction}),this._conversationHistory.length>0&&(n.conversation_history=this._conversationHistory),u=await t.chat.reload(e,n,s,i)}catch(t){return this.unloadChat(t)}if(null==(o=(n=this.deepChat)._validationHandler)||o.call(n),null!=(r=this._webModel.introMessage)&&r.removeAfterLoad)!1===this._webModel.introMessage.displayed?null==(l=this._messages)||l.removeLastMessage():null==(c=this._removeIntro)||c.call(this);else{const t=ti.setUpAfterLoad(u,this._webModel.introMessage,this._chatEl,!!this._webModel.worker);null==(a=this._messages)||a.addNewMessage({html:t,overwrite:!0,sendUpdate:!1})}this._isModelLoaded=!0,this._isModelLoading=!1}async unloadChat(e){var i;null==(i=this._messages)||i.addNewErrorMessage("service",t.GENERIC_ERROR),console.error(e),this._isModelLoaded=!1,this._isModelLoading=!1,t.chat&&(await t.chat.unload(),t.chat=void 0)}async immediateResp(e,i,s){const n={text:await s.generate(i,void 0,0)},o=await t.processResponse(this.deepChat,e,n);o&&o.forEach((t=>e.addNewMessage(t))),this.completionsHandlers.onFinish()}async streamResp(e,i,s){this.streamHandlers.abortStream.abort=()=>{s.interruptGenerate()},this.streamHandlers.onOpen();const n=new Te(e);await s.generate(i,(async(i,s)=>{const o=await t.processResponse(this.deepChat,e,{text:s});o&&n.upsertStreamedMessage({text:o[0].text,overwrite:!0})})),n.finaliseStreamedMessage(),this.streamHandlers.onClose()}async generateRespByType(t,e,i,s){var n;try{i?await this.streamResp(t,e,s):await this.immediateResp(t,e,s)}catch(t){null==(n=this._messages)||n.addNewErrorMessage("service"),console.log(t)}}async generateResp(t,e,i){const s=e[e.length-1].text,{body:n,error:o}=await Oe.processRequestInterceptor(this.deepChat,{body:{text:s}}),r=!!this.stream;try{if(o)Oe.displayError(t,new Error(o)),(r?this.streamHandlers.onClose:this.completionsHandlers.onFinish)();else if(n&&n.text)this.generateRespByType(t,n.text,!!this.stream,i);else{const e=y.INVALID_MODEL_REQUEST({body:n},!1);console.error(e);const i=r?this.streamHandlers.onClose:this.completionsHandlers.onFinish;Oe.onInterceptorError(t,e,i)}}catch(t){this.unloadChat(t)}}async callServiceAPI(e,i){var s,n;if(!this._isModelLoaded){if(!this._loadOnFirstMessage)return;await this.init()}!t.chat||this._isModelLoading||(null!=(s=this._webModel.introMessage)&&s.removeAfterMessage&&(null==(n=this._removeIntro)||n.call(this)),e.addLoadingMessage(),this.generateResp(e,i,t.chat))}canSubmit(t){return!(null==t||!t.trim()||this._isModelLoading)&&(!!this._loadOnFirstMessage||!!this._isModelLoaded)}static async processResponse(t,e,i){var s,n;const o=await(null==(s=t.responseInterceptor)?void 0:s.call(t,i))||i;if(null!=(n=t.connect)&&n.stream&&Array.isArray(o)&&o.length>1)return void console.error(y.INVALID_STREAM_ARRAY_RESPONSE);const r=Array.isArray(o)?o:[o],a=r.find((t=>"string"==typeof t.error));if(a)Oe.displayError(e,new Error(a.error));else{if(!r.find((t=>!t||!t.text)))return r;{const s=y.INVALID_MODEL_RESPONSE(i,!!t.responseInterceptor,o);Oe.displayError(e,new Error(s))}}}isWebModel(){return!0}static clearAllCache(){t.clearCache("webllm/model"),t.clearCache("webllm/wasm")}static clearCache(t){caches.open(t).then((t=>{t.keys().then((e=>{e.forEach((e=>{t.delete(e)}))}))}))}};ii.GENERIC_ERROR="Error, please check the [troubleshooting](https://deepchat.dev/docs/webModel#troubleshooting) section of documentation for help.",ii.MULTIPLE_MODELS_ERROR="Cannot run multiple web models",ii.WEB_LLM_NOT_FOUND_ERROR="WebLLM module not found",ii.DEFAULT_MODEL="Llama-2-7b-chat-hf-q4f32_1",ii.MODULE_SEARCH_LIMIT_S=5;let si=ii;class ni{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,s){const n=t;Array.isArray(n.error)&&"Error in `parameters`: field required"===n.error[0]?i(e):s(y.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api-inference.huggingface.co/models/gpt2",method:"POST",handleVerificationResult:ni.handleVerificationResult}}}const oi=class t extends Ve{constructor(e,i,s,n,o,r){super(e,ni.buildKeyVerificationDetails(),ni.buildHeaders,o,r),this.insertKeyPlaceholderText="Hugging Face Token",this.keyHelpUrl="https://huggingface.co/settings/tokens",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Hugging Face</b></div>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>',this.permittedErrorPrefixes=["Authorization header"],this.url=`${t.URL_PREFIX}${s}`,this.textInputPlaceholderText=i,"object"==typeof n&&(n.model&&(this.url=`${t.URL_PREFIX}${n.model}`),n.options&&(this.rawBody.options=n.options),n.parameters&&(this.rawBody.parameters=n.parameters))}preprocessBody(t,e,i){const s=JSON.parse(JSON.stringify(t)),n=e[e.length-1].text;if(n)return s.options??(s.options={}),s.options.wait_for_model=!0,{inputs:n,...s}}async callServiceAPI(t,e,i){if(!this.connectSettings)throw new Error("Request settings have not been set up");const s=this.preprocessBody(this.rawBody,e,i);Fe.request(this,s,t)}};oi.URL_PREFIX="https://api-inference.huggingface.co/models/";let ri=oi;class ai extends ri{constructor(t,e,i,s,n,o){super(t,e,i,s,n,o),this.isTextInputDisabled=!0,this.canSendMessage=ai.canSendFile}static canSendFile(t,e){return!(null==e||!e[0])}preprocessBody(t,e,i){return i[0]}async callServiceAPI(t,e,i){if(!this.connectSettings)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");Fe.poll(this,i[0],t,!1)}}class li extends ai{constructor(t){var e,i,s;super(t,"Attach an audio file","ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.audioClassification,null==(s=t.directConnection)?void 0:s.huggingFace,{audio:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.label)||""}}}class ci extends ai{constructor(t){var e,i,s;super(t,"Attach an image file","google/vit-base-patch16-224",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.imageClassification,null==(s=t.directConnection)?void 0:s.huggingFace,{images:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.label)||""}}}const hi="data:image/png;base64,";class ui{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,s){t.message?s(y.INVALID_KEY):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.stability.ai/v1/engines/list",method:"GET",handleVerificationResult:ui.handleVerificationResult}}}class di extends Ve{constructor(t,e,i,s,n){super(t,e,i,s,n),this.insertKeyPlaceholderText="Stability AI API Key",this.keyHelpUrl="https://platform.stability.ai/docs/getting-started/authentication",this.permittedErrorPrefixes=["Incorrect","invalid_"]}}class pi extends di{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=null==i?void 0:i.stabilityAI;super(t,ui.buildKeyVerificationDetails(),ui.buildHeaders,s,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}),this.url="https://api.stability.ai/v1/generation/esrgan-v1-x2plus/image-to-image/upscale",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI</b></div>\n <div style="width: 100%; text-align: center; margin-left: -10px; margin-top: 5px"><b>Image to Image Upscale</b></div>\n <p>Upload an image to generate a new one with higher resolution.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageUpscale;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/image-to-image/upscale`),pi.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=pi.canSendFileMessage}static cleanConfig(t){delete t.engine_id}static canSendFileMessage(t,e){return!(null==e||!e[0])}createFormDataBody(t,e){const i=new FormData;return i.append("image",e),Object.keys(t).forEach((e=>{i.append(e,String(t[e]))})),i}async callServiceAPI(t,e,i){if(!this.connectSettings)throw new Error("Request settings have not been set up");if(!i)throw new Error("Image was not found");const s=this.createFormDataBody(this.rawBody,i[0]);Oe.tempRemoveContentHeader(this.connectSettings,Fe.request.bind(this,this,s,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${hi}${t.base64}`,type:"image"})))}}}class mi extends di{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=null==i?void 0:i.stabilityAI;super(t,ui.buildKeyVerificationDetails(),ui.buildHeaders,s,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.url="https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/image-to-image/masking",this._maskSource="MASK_IMAGE_WHITE",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI</b></div>\n <div style="width: 100%; text-align: center; margin-left: -10px; margin-top: 5px"><b>Image to Image Masking</b></div>\n <p>Upload an image, its mask image to create a new one based on the changes you have described for the mask area.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageMasking;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/image-to-image/masking`),void 0!==n.weight&&null!==n.weight&&(this._imageWeight=n.weight),void 0!==n.mask_source&&null!==n.mask_source&&(this._maskSource=n.mask_source),mi.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=mi.canSendFileTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendFileTextMessage(t,e){return!(null==e||!e[0]||!t||""===t.trim())}createFormDataBody(t,e,i,s){const n=new FormData;return n.append("init_image",e),n.append("mask_source",String(this._maskSource)),n.append("mask_image",i),s&&""!==s&&n.append("text_prompts[0][text]",s),void 0!==this._imageWeight&&null!==this._imageWeight&&n.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach((e=>{n.append(e,String(t[e]))})),void 0===n.get("weight")&&n.append("weight",String(1)),n}async callServiceAPI(t,e,i){var s,n;if(!this.connectSettings)throw new Error("Request settings have not been set up");if(!i||!i[0]||!i[1])throw new Error("Image was not found");const o=null==(n=null==(s=e[e.length-1])?void 0:s.text)?void 0:n.trim(),r=this.createFormDataBody(this.rawBody,i[0],i[1],o);Oe.tempRemoveContentHeader(this.connectSettings,Fe.request.bind(this,this,r,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${hi}${t.base64}`,type:"image"})))}}}class vi extends ai{constructor(t){var e,i,s;super(t,"Attach an audio file","facebook/wav2vec2-large-960h-lv60-self",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.audioSpeechRecognition,null==(s=t.directConnection)?void 0:s.huggingFace,{audio:{}})}async extractPollResultData(t){if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:t.text||""}}}class fi extends ri{constructor(t){var e,i,s;super(t,"Once upon a time","gpt2",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.textGeneration,null==(s=t.directConnection)?void 0:s.huggingFace)}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.generated_text)||""}}}class gi extends ri{constructor(t){var e,i,s;const n=null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.questionAnswer;super(t,"Ask a question","bert-large-uncased-whole-word-masking-finetuned-squad",n,null==(s=t.directConnection)?void 0:s.huggingFace),this.permittedErrorPrefixes=["Authorization header","Error in"],this.context=n.context}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return{inputs:{question:i,context:this.context,options:{wait_for_model:!0}}}}async extractResultData(t){if(t.error)throw t.error;return{text:t.answer||""}}}class bi extends ri{constructor(t){var e,i,s;super(t,"Insert text to summarize","facebook/bart-large-cnn",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.summarization,null==(s=t.directConnection)?void 0:s.huggingFace)}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.summary_text)||""}}}class yi extends ri{constructor(t){var e,i,s;super(t,"Ask me anything!","facebook/blenderbot-400M-distill",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.conversation,null==(s=t.directConnection)?void 0:s.huggingFace),this.maxMessages??(this.maxMessages=-1)}processMessages(t){const e=t.filter((t=>t.text)),i=e[e.length-1].text,s=e.slice(0,e.length-1);if(!i)return;return{past_user_inputs:s.filter((t=>"user"===t.role)).map((t=>t.text)),generated_responses:s.filter((t=>"ai"===t.role)).map((t=>t.text)),mostRecentMessageText:i}}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=this.processMessages(e);if(s)return i.options??(i.options={}),i.options.wait_for_model=!0,{inputs:{past_user_inputs:s.past_user_inputs,generated_responses:s.generated_responses,text:s.mostRecentMessageText},...i}}async extractResultData(t){if(t.error)throw t.error;return{text:t.generated_text||""}}}class wi extends di{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=i.stabilityAI;super(t,ui.buildKeyVerificationDetails(),ui.buildHeaders,s,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/image-to-image",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI: Image to Image</b></div>\n <p>Upload an image to create a new one with the changes you have described.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=i.stabilityAI)?void 0:e.imageToImage;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/text-to-image`),void 0!==n.weight&&null!==n.weight&&(this._imageWeight=n.weight),wi.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=wi.canSendFileTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendFileTextMessage(t,e){return!(null==e||!e[0]||!t||""===t.trim())}createFormDataBody(t,e,i){const s=new FormData;return s.append("init_image",e),i&&""!==i&&s.append("text_prompts[0][text]",i),void 0!==this._imageWeight&&null!==this._imageWeight&&s.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach((e=>{s.append(e,String(t[e]))})),void 0===s.get("weight")&&s.append("weight",String(1)),s}async callServiceAPI(t,e,i){var s,n;if(!this.connectSettings)throw new Error("Request settings have not been set up");if(!i)throw new Error("Image was not found");const o=null==(n=null==(s=e[e.length-1])?void 0:s.text)?void 0:n.trim(),r=this.createFormDataBody(this.rawBody,i[0],o);Oe.tempRemoveContentHeader(this.connectSettings,Fe.request.bind(this,this,r,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${hi}${t.base64}`,type:"image"})))}}}class xi extends ri{constructor(t){var e,i,s;super(t,"Insert text to translate","Helsinki-NLP/opus-tatoeba-en-ja",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.translation,null==(s=t.directConnection)?void 0:s.huggingFace)}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.translation_text)||""}}}class ki extends di{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=i.stabilityAI;super(t,ui.buildKeyVerificationDetails(),ui.buildHeaders,s),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/text-to-image",this.textInputPlaceholderText="Describe an image",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI: Text to Image</b></div>\n <p>Insert text to generate an image.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=i.stabilityAI)?void 0:e.textToImage;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/text-to-image`),void 0!==n.weight&&null!==n.weight&&(this._imageWeight=n.weight),ki.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=ki.canSendTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendTextMessage(t){return!(!t||""===t.trim())}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s={text:e};return this._imageWeight&&(s.weight=this._imageWeight),i.text_prompts=[s],i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e[e.length-1].text);Fe.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${hi}${t.base64}`,type:"image"})))}}}class _i extends ri{constructor(t){var e,i,s;super(t,"The goal of life is [MASK].","bert-base-uncased",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.fillMask,null==(s=t.directConnection)?void 0:s.huggingFace),this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Hugging Face</b></div>\n <p>Insert a sentence with the word [MASK] and the model will try to fill it for you. E.g. I want [MASK].</p>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>',this.permittedErrorPrefixes=["Authorization header","No mask_token"]}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.sequence)||""}}}const Si=class t{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,s){const n=t;n.error?"invalid_api_key"===n.error.code?s(y.INVALID_KEY):s(y.CONNECTION_FAILED):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.openai.com/v1/models",method:"GET",handleVerificationResult:t.handleVerificationResult}}static async directFetch(t,e,i,s=!0){t.connectSettings.method=i;const n=await Oe.fetch(t,t.connectSettings.headers,s,e).then((t=>Oe.processResponseByType(t)));if(n.error)throw n.error.message;return n}};Si.FUNCTION_TOOL_RESP_ERROR="Response object must either be {response: string}[] for each individual function or {text: string} for a direct response, see https://deepchat.dev/docs/directConnection/OpenAI#FunctionHandler.",Si.FUNCTION_TOOL_RESP_ARR_ERROR="Arrays are not accepted in handler responses";let Ai=Si;const Ti=class t{static async storeFiles(t,e,i,s){const n=t.connectSettings.headers;if(!n)return;t.url=s;const o=n[Oe.CONTENT_TYPE];delete n[Oe.CONTENT_TYPE];const r=i.map((async e=>{const i=new FormData;return i.append("purpose","assistants"),i.append("file",e),new Promise((e=>{e(Ai.directFetch(t,i,"POST",!1))}))}));try{const t=(await Promise.all(r)).map((t=>({id:t.id,name:t.filename})));return n[Oe.CONTENT_TYPE]=o,t}catch(i){throw n[Oe.CONTENT_TYPE]=o,Oe.displayError(e,i),t.completionsHandlers.onFinish(),i}}static getType(t,e){const{path:i}=t[e];return!i||i.endsWith("png")?"image":"any"}static async getFiles(e,i,s,n){const o=i.map((({fileId:t})=>(e.url=`${s}${t}${n}`,new Promise((t=>{t(Ai.directFetch(e,void 0,"GET",!1))}))))),r=(await Promise.all(o)).map(((e,s)=>new Promise((n=>{const o=new FileReader;o.readAsDataURL(e),o.onload=e=>{n({src:e.target.result,name:i[s].name,type:t.getType(i,s)})}}))));return await Promise.all(r)}static getFileName(t){const e=t.split("/");return e[e.length-1]}static async getFilesAndNewText(e,i,s,n,o){var r,a;let l;const{getFilesPrefix:c,getFilesPostfix:h}=s;return i.length>0&&(l=await t.getFiles(e,i,c,h),null!=(r=null==o?void 0:o.text)&&r.value&&l.forEach(((t,e)=>{var s;if(!t.src)return;const n=i[e].path;null!=(s=null==o?void 0:o.text)&&s.value&&n&&(o.text.value=o.text.value.replace(n,t.src))}))),null!=(a=null==o?void 0:o.text)&&a.value?{text:o.text.value,role:n}:{files:l,role:n}}static getFileDetails(e,i){var s;const n=[];return null!=(s=null==i?void 0:i.text)&&s.value&&e.content.forEach((e=>{var i,s;null==(s=null==(i=e.text)?void 0:i.annotations)||s.forEach((e=>{var i;e.text&&e.text.startsWith("sandbox:")&&null!=(i=e.file_path)&&i.file_id&&n.push({path:e.text,fileId:e.file_path.file_id,name:t.getFileName(e.text)})}))})),null!=i&&i.image_file&&n.push({fileId:i.image_file.file_id}),n}static async getFilesAndText(e,i,s,n){const o=t.getFileDetails(i,n);return await t.getFilesAndNewText(e,o,s,i.role,n)}static parseResult(t,e){let i=[];if(e)i=t.data;else for(let e=0;e<t.data.length;e+=1){const s=t.data[e];if("assistant"!==s.role)break;i.push(s)}return i.reverse()}static parseMessages(e,i,s){const n=[];return i.forEach((async i=>{i.content.filter((t=>!!t.text||!!t.image_file)).sort((t=>t.text?-1:t.image_file?1:0)).forEach((async o=>{n.push(t.getFilesAndText(e,i,s,o))}))})),Promise.all(n)}static async processStreamMessages(e,i,s){return t.parseMessages(e,[{content:i,role:"assistant"}],s)}static async processAPIMessages(e,i,s,n){const o=t.parseResult(i,s);return t.parseMessages(e,o,n)}};Ti.FILES_WITH_TEXT_ERROR="content with type `text` must have `text` values",Ti.FUNCTION_TOOL_RESP_ERROR="Response must contain an array of strings for each individual function/tool_call, see https://deepchat.dev/docs/directConnection/OpenAI/#assistant-functions.";let Mi=Ti;const Oi=class t extends Ve{constructor(t,e,i,s,n,o){if(super(t,s,n,o),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.url="",this.permittedErrorPrefixes=["Incorrect","Please send text",De.FAILED_ERROR_MESSAGE],this.shouldFetchHistory=!1,this.searchedForThreadId=!1,this.config={},this.newAssistantDetails={model:"gpt-4"},this.waitingForStreamResponse=!1,this.isSSEStream=!1,this.urlSegments=i,"object"==typeof e){this.config=e;const{new_assistant:t,thread_id:i,load_thread_history:s}=this.config;Object.assign(this.newAssistantDetails,t),i&&(this.sessionId=i),s&&(this.shouldFetchHistory=!0)}this.maxMessages=1,this.isSSEStream=!(!this.stream||"object"==typeof this.stream&&this.stream.simulation)}async fetchHistoryFunc(){setTimeout((()=>this.deepChat.disableSubmitButton()),2);try{const t=await this.getThreadMessages(this.sessionId,!0);return this.deepChat.disableSubmitButton(!1),t}catch{return[{error:"Failed to fetch history"}]}}static processImageMessage(t,e){const i=null==e?void 0:e.filter((t=>M.isImageFileExtension(t.name))).map((t=>({type:"image_file",image_file:{file_id:t.id}})));if(i&&i.length>0)return t.text&&t.text.length>0&&i.push({type:"text",text:t.text}),{content:i,role:"user"}}static processAttachmentsMessage(t,e,i){return{attachments:e.map((t=>({tools:[{type:i}],file_id:t.id}))),content:[{type:"text",text:t.text}],role:"user"}}processMessage(e,i){const s=this.totalMessagesMaxCharLength||-1,n=$e.getCharacterLimitMessages(e,s)[0];if(i&&i.length>0){let e=this.filesToolType;if("function"==typeof this.filesToolType){const t=this.filesToolType(i.map((({name:t})=>t)));"code_interpreter"===t||"file_search"===t||"images"===t?e=t:(console.error(`Tool type "${t}" is not valid`),console.error('Expected "code_interpreter" or "file_search" or "images". Going to default to "images"'))}if("file_search"===e)return t.processAttachmentsMessage(n,i,"file_search");if("code_interpreter"===e)return t.processAttachmentsMessage(n,i,"code_interpreter");if(i.find((({name:t})=>!M.isImageFileExtension(t))))console.error("The uploaded files contained a non-image file"),console.error('Make sure only images can be uploaded or define a "code_interpreter" or "file_search" value in the "files_tool_type" property'),console.warn('Make sure your existing assistant supports these "tools" or specify them in the "new_assistant" property');else{const e=t.processImageMessage(n,i);if(e)return e}}return{content:n.text||"",role:"user"}}createNewThreadMessages(t,e,i){const s=JSON.parse(JSON.stringify(t)),n=this.processMessage(e,i);return s.thread={messages:[n]},s}callService(t,e,i){if(this.messages=t,this.sessionId){this.url=`${this.urlSegments.threadsPrefix}/${this.sessionId}/messages${this.urlSegments.createMessagePostfix}`;const s=this.processMessage(e,i);Fe.request(this,s,t)}else{this.url=`${this.urlSegments.threadsPrefix}/runs${this.urlSegments.threadsPosfix}`;const s=this.createNewThreadMessages(this.rawBody,e,i);this.isSSEStream?this.createStreamRun(s):Fe.request(this,s,t)}}async callServiceAPI(t,e,i){var s;if(this.waitingForStreamResponse=!1,!this.connectSettings)throw new Error("Request settings have not been set up");(s=this.rawBody).assistant_id??(s.assistant_id=this.config.assistant_id||await this.createNewAssistant()),this.searchedForThreadId||this.searchPreviousMessagesForThreadId(t.messageToElements);const n=i?await Mi.storeFiles(this,t,i,this.urlSegments.storeFiles):void 0;this.connectSettings.method="POST",this.callService(t,e,n)}async createNewAssistant(){try{this.url=this.urlSegments.newAssistantUrl;const t=await Ai.directFetch(this,JSON.parse(JSON.stringify(this.newAssistantDetails)),"POST");return this.config.assistant_id=t.id,this.config.assistant_id}catch(t){console.error(t),console.error("Failed to create a new assistant")}}searchPreviousMessagesForThreadId(t){const e=t.find((([t])=>t._sessionId));e&&(this.sessionId=e[0]._sessionId),this.searchedForThreadId=!0}async extractResultData(t){var e;if(this.waitingForStreamResponse||this.isSSEStream&&this.sessionId)return await this.handleStream(t);if(t.error)throw t.error.message.startsWith(Mi.FILES_WITH_TEXT_ERROR)?Error("Please send text with your file(s)"):t.error.message;await this.assignThreadAndRun(t);const i=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs/${this.run_id}${this.urlSegments.threadsPosfix}`,s={method:"GET",headers:null==(e=this.connectSettings)?void 0:e.headers};return Fe.executePollRequest(this,i,s,this.messages),{makingAnotherRequest:!0}}async assignThreadAndRun(t){if(this.sessionId){this.url=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs${this.urlSegments.threadsPosfix}`;const t=await Ai.directFetch(this,JSON.parse(JSON.stringify(this.rawBody)),"POST");this.run_id=t.id}else this.sessionId=t.thread_id,this.run_id=t.id,this.messages&&this.messages.messageToElements.length>0&&(this.messages.messageToElements[this.messages.messageToElements.length-1][0]._sessionId=this.sessionId)}async getThreadMessages(t,e=!1){var i,s;this.url=`${this.urlSegments.threadsPrefix}/${t}/messages?${this.urlSegments.listMessagesPostfix}`;let n=await Ai.directFetch(this,{},"GET");return!e&&this.deepChat.responseInterceptor&&(n=await(null==(s=(i=this.deepChat).responseInterceptor)?void 0:s.call(i,n))),Mi.processAPIMessages(this,n,e,this.urlSegments)}async extractPollResultData(e){var i;const{status:s,required_action:n}=e;if("queued"===s||"in_progress"===s)return{timeoutMS:t.POLLING_TIMEOUT_MS};if("completed"===s&&this.messages){const t=await this.getThreadMessages(e.thread_id),{text:i,files:s}=t.shift();return setTimeout((()=>{t.forEach((t=>this.deepChat.addMessage(t)))})),{text:i,_sessionId:this.sessionId,files:s}}const o=null==(i=null==n?void 0:n.submit_tool_outputs)?void 0:i.tool_calls;if("requires_action"===s&&o)return await this.handleTools(o);throw Error(`Thread run status: ${s}`)}async handleTools(e){if(!this.functionHandler)throw Error("Please define the `function_handler` property inside the [openAI](https://deepchat.dev/docs/directConnection/openAI#Assistant) object.");const i=e.map((t=>({name:t.function.name,arguments:t.function.arguments}))),s=await this.functionHandler(i);if(!Array.isArray(s)||e.length!==s.length)throw Error(Mi.FUNCTION_TOOL_RESP_ERROR);const n=await Promise.all(s);if(n.find((t=>"string"!=typeof t)))throw Error(Mi.FUNCTION_TOOL_RESP_ERROR);const o=n.map(((t,i)=>({tool_call_id:e[i].id,output:t}))),r=`${this.urlSegments.threadsPrefix}/${this.sessionId}`,a=`/runs/${this.run_id}/submit_tool_outputs${this.urlSegments.threadsPosfix}`;return this.url=`${r}${a}`,this.isSSEStream?await this.createStreamRun({tool_outputs:o}):await Ai.directFetch(this,{tool_outputs:o},"POST"),{timeoutMS:t.POLLING_TIMEOUT_MS}}async handleStream(t){var e,i;const s=null==(i=null==(e=t.required_action)?void 0:e.submit_tool_outputs)?void 0:i.tool_calls;if("requires_action"===t.status&&s)return this.run_id=t.id,await this.handleTools(s);if(this.waitingForStreamResponse)return this.parseStreamResult(t);if(this.isSSEStream&&this.sessionId){this.url=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs${this.urlSegments.threadsPosfix}`;const t=JSON.parse(JSON.stringify(this.rawBody));this.createStreamRun(t)}return{makingAnotherRequest:!0}}async parseStreamResult(t){var e,i,s,n,o;if(t.content&&t.content.length>0&&this.messages){const s=t.content.find((t=>t.text));if(null!=(e=null==s?void 0:s.text)&&e.annotations&&s.text.annotations.length>0){const e=t.content.find((t=>!!t.text))||t.content[0],s=Mi.getFilesAndText.bind(this,this,{role:"assistant",content:t.content},this.urlSegments,e);return null==(i=this.messageStream)||i.endStreamAfterFileDownloaded(this.messages,s),{text:""}}}if(null!=(s=t.delta)&&s.content){if(t.delta.content.length>1){const e=t.delta.content.find((t=>t.text));if(null!=(n=null==e?void 0:e.text)&&n.annotations&&0===e.text.annotations.length){const e=await Mi.processStreamMessages(this,t.delta.content,this.urlSegments);return{text:e[0].text,files:e[1].files}}}return{text:null==(o=t.delta.content[0].text)?void 0:o.value}}return!this.sessionId&&t.thread_id&&(this.sessionId=t.thread_id),{makingAnotherRequest:!0}}async createStreamRun(t){t.stream=!0,this.waitingForStreamResponse=!0,this.messageStream=await Ne.request(this,t,this.messages,!0,!0)}};Oi.POLLING_TIMEOUT_MS=500;let ji=Oi;class Ci extends ji{constructor(t){var e,i,s,n,o;const r=JSON.parse(JSON.stringify(t.directConnection)),a=r.openAI,l=null==(e=r.openAI)?void 0:e.assistant;if(super(t,l,Ci.buildUrlSegments(l),Ai.buildKeyVerificationDetails(),Ai.buildHeaders,a),(i=this.connectSettings).headers??(i.headers={}),(s=this.connectSettings.headers)["OpenAI-Beta"]??(s["OpenAI-Beta"]="assistants=v2"),this.shouldFetchHistory&&this.sessionId&&(this.fetchHistory=this.fetchHistoryFunc.bind(this)),"object"==typeof l){const{function_handler:e,files_tool_type:i}=null==(o=null==(n=t.directConnection)?void 0:n.openAI)?void 0:o.assistant;e&&(this.functionHandler=e),i&&(this.filesToolType=i)}}static buildUrlSegments(t){const e="object"==typeof t&&t.custom_base_url||"https://api.openai.com/v1";return{threadsPrefix:`${e}/threads`,threadsPosfix:"",newAssistantUrl:`${e}/assistants`,createMessagePostfix:"",listMessagesPostfix:"order=desc",storeFiles:`${e}/files`,getFilesPrefix:`${e}/files/`,getFilesPostfix:"/content"}}}class Ei{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json",accept:"application/json"}}static handleVerificationResult(t,e,i,s){var n;null!=(n=t.message)&&n.includes("invalid request: prompt must be at least 1 token long")?i(e):s(y.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api.cohere.ai/v1/generate",method:"POST",handleVerificationResult:Ei.handleVerificationResult,body:JSON.stringify({prompt:""})}}}class Ii extends Ve{constructor(t,e,i,s,n){super(t,Ei.buildKeyVerificationDetails(),Ei.buildHeaders,n),this.insertKeyPlaceholderText="Cohere API Key",this.keyHelpUrl="https://dashboard.cohere.ai/api-keys",this.permittedErrorPrefixes=["invalid"],this.url=e,this.textInputPlaceholderText=i,s&&"object"==typeof s&&Object.assign(this.rawBody,s)}}class Pi extends Ii{constructor(t){var e,i,s;super(t,"https://api.cohere.ai/v1/generate","Once upon a time",null==(i=null==(e=t.directConnection)?void 0:e.cohere)?void 0:i.textGeneration,null==(s=t.directConnection)?void 0:s.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e[e.length-1].text;if(s)return{prompt:s,...i}}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Fe.request(this,i,t)}async extractResultData(t){var e;if(t.message)throw t.message;return{text:(null==(e=t.generations)?void 0:e[0].text)||""}}}const Ni=class{static buildHeaders(t){return{"api-key":t,"Content-Type":"application/json"}}static buildKeyVerificationDetails(t){return{url:`${t.endpoint}/openai/models?api-version=${t.version}`,method:"GET",handleVerificationResult:Ai.handleVerificationResult}}static validateURLDetails(t){const{endpoint:e,version:i,deploymentId:s}=t;return e&&i&&s}};Ni.URL_DETAILS_ERROR_MESSAGE="Please define the Azure URL Details. [More Information](https://deepchat.dev/docs/directConnection/Azure)";let Ri=Ni;const qi=class t extends ji{constructor(e){var i,s,n,o,r,a,l,c;const h=JSON.parse(JSON.stringify(e.directConnection)),u=h.azure,d=null==(i=h.azure)?void 0:i.openAI,p=(null==d?void 0:d.urlDetails)||{},m=`${null==(s=null==d?void 0:d.urlDetails)?void 0:s.endpoint}/openai/`,v=`?api-version=${null==(n=null==d?void 0:d.urlDetails)?void 0:n.version}`,f={threadsPrefix:`${m}${t.THREAD_RESOURCE}`,threadsPosfix:v,newAssistantUrl:`${m}${t.NEW_ASSISTANT_RESOURCE}${v}`,createMessagePostfix:v,listMessagesPostfix:`order=desc&api-version=${null==(o=null==d?void 0:d.urlDetails)?void 0:o.version}`,storeFiles:`${m}files${v}`,getFilesPrefix:`${m}files/`,getFilesPostfix:`/content${v}`};if(super(e,null==d?void 0:d.assistant,f,Ri.buildKeyVerificationDetails(p),Ri.buildHeaders,u),this.permittedErrorPrefixes=[Ri.URL_DETAILS_ERROR_MESSAGE],this.insertKeyPlaceholderText="Azure OpenAI API Key",this.keyHelpUrl="https://learn.microsoft.com/en-us/answers/questions/1193991/how-to-get-the-value-of-openai-api-key",this.isTextInputDisabled=!1,"object"==typeof(null==d?void 0:d.assistant)){const{function_handler:t,files_tool_type:i}=null==(l=null==(a=null==(r=e.directConnection)?void 0:r.azure)?void 0:a.openAI)?void 0:l.assistant;t&&(this.functionHandler=t),i&&(this.filesToolType=i)}Ri.validateURLDetails(p)?(c=this.connectSettings).headers??(c.headers={}):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout((()=>{e.addMessage({error:Ri.URL_DETAILS_ERROR_MESSAGE})})))}};qi.THREAD_RESOURCE="threads",qi.NEW_ASSISTANT_RESOURCE="assistants";let Bi=qi;class Li extends Ii{constructor(t){var e,i,s;super(t,"https://api.cohere.ai/v1/summarize","Insert text to summarize",null==(i=null==(e=t.directConnection)?void 0:e.cohere)?void 0:i.summarization,null==(s=t.directConnection)?void 0:s.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e[e.length-1].text;if(s)return{text:s,...i}}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Fe.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.summary||""}}}class Fi{static addAttributes(t){t.role="button",t.setAttribute("tabindex","0")}static addAriaBusy(t){t.setAttribute("aria-busy","true")}static removeAriaBusy(t){t.removeAttribute("aria-busy")}static addAriaDisabled(t){t.setAttribute("aria-disabled","true")}static removeAriaDisabled(t){t.removeAttribute("aria-disabled")}static removeAriaAttributes(t){Fi.removeAriaBusy(t),Fi.removeAriaDisabled(t)}}const zi='<?xml version="1.0" encoding="iso-8859-1"?>\n<svg height="1.4em" width="1.4em" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"\n\t viewBox="0 0 490.9 490.9" xml:space="preserve">\n\t<g>\n\t\t<g>\n\t\t\t<path d="M245.5,322.9c53,0,96.2-43.2,96.2-96.2V96.2c0-53-43.2-96.2-96.2-96.2s-96.2,43.2-96.2,96.2v130.5\n\t\t\t\tC149.3,279.8,192.5,322.9,245.5,322.9z M173.8,96.2c0-39.5,32.2-71.7,71.7-71.7s71.7,32.2,71.7,71.7v130.5\n\t\t\t\tc0,39.5-32.2,71.7-71.7,71.7s-71.7-32.2-71.7-71.7V96.2z"/>\n\t\t\t<path d="M94.4,214.5c-6.8,0-12.3,5.5-12.3,12.3c0,85.9,66.7,156.6,151.1,162.8v76.7h-63.9c-6.8,0-12.3,5.5-12.3,12.3\n\t\t\t\ts5.5,12.3,12.3,12.3h152.3c6.8,0,12.3-5.5,12.3-12.3s-5.5-12.3-12.3-12.3h-63.9v-76.7c84.4-6.3,151.1-76.9,151.1-162.8\n\t\t\t\tc0-6.8-5.5-12.3-12.3-12.3s-12.3,5.5-12.3,12.3c0,76.6-62.3,138.9-138.9,138.9s-138.9-62.3-138.9-138.9\n\t\t\t\tC106.6,220,101.2,214.5,94.4,214.5z"/>\n\t\t</g>\n\t</g>\n</svg>\n';class Di{static createTextElement(t){const e=document.createElement("div");return e.classList.add("text-button"),e.innerText=t,e}static createElement(t,e){return e?Di.createTextElement(t):Ze.createSVGElement(t)}static createCustomElement(t,e){var i,s,n,o;const r=null==e?void 0:e[t];return null!=(i=null==r?void 0:r.svg)&&i.content?Di.createElement(null==(s=null==r?void 0:r.svg)?void 0:s.content,!1):null!=(n=null==r?void 0:r.text)&&n.content?Di.createElement(null==(o=null==r?void 0:r.text)?void 0:o.content,!0):void 0}static processElement(t,e){null!=e&&e.classList.contains("text-button")||t.classList.add("input-button-svg")}static createSpecificStateElement(t,e,i){let s;return i&&(s=Di.createCustomElement(e,i)),Di.processElement(t,s),s}static createInnerElement(t,e,i,s,n=!1){var o,r;return(!n||null!=(r=null==(o=null==s?void 0:s[i])?void 0:o.svg)&&r.content)&&Di.createSpecificStateElement(t,i,s)||e}}class $i{static unsetAllCSS(t,e){var s,n;e.container&&i.unsetAllCSSMouseStates(t,e.container),null!=(s=e.svg)&&s.styles&&i.unsetAllCSSMouseStates(t.children[0],e.svg.styles),null!=(n=e.text)&&n.styles&&i.unsetAllCSSMouseStates(t.children[0],e.text.styles)}static unsetActionCSS(t,e){var s,n;e.container&&i.unsetActivityCSSMouseStates(t,e.container),null!=(s=e.svg)&&s.styles&&i.unsetActivityCSSMouseStates(t.children[0],e.svg.styles),null!=(n=e.text)&&n.styles&&i.unsetActivityCSSMouseStates(t.children[0],e.text.styles)}static setElementsCSS(t,e,i){var s,n,o,r,a;Object.assign(t.style,null==(s=e.container)?void 0:s[i]),Object.assign(t.children[0].style,null==(o=null==(n=e.svg)?void 0:n.styles)?void 0:o[i]),Object.assign(t.children[0].style,null==(a=null==(r=e.text)?void 0:r.styles)?void 0:a[i])}static setElementCssUpToState(t,e,i){$i.setElementsCSS(t,e,"default"),"default"!==i&&($i.setElementsCSS(t,e,"hover"),"hover"!==i&&$i.setElementsCSS(t,e,"click"))}}class Ji{constructor(t,e,i,s){this._mouseState={state:"default"},Fi.addAttributes(t),this.elementRef=t,this._customStyles=i,this.position=e,this.dropupText=s}buttonMouseLeave(t){this._mouseState.state="default",t&&($i.unsetAllCSS(this.elementRef,t),$i.setElementsCSS(this.elementRef,t,"default"))}buttonMouseEnter(t){this._mouseState.state="hover",t&&$i.setElementsCSS(this.elementRef,t,"hover")}buttonMouseUp(t){t&&$i.unsetActionCSS(this.elementRef,t),this.buttonMouseEnter(t)}buttonMouseDown(t){this._mouseState.state="click",t&&$i.setElementsCSS(this.elementRef,t,"click")}setEvents(t){this.elementRef.onmousedown=this.buttonMouseDown.bind(this,t),this.elementRef.onmouseup=this.buttonMouseUp.bind(this,t),this.elementRef.onmouseenter=this.buttonMouseEnter.bind(this,t),this.elementRef.onmouseleave=this.buttonMouseLeave.bind(this,t)}unsetCustomStateStyles(t){if(this._customStyles)for(let e=0;e<t.length;e+=1){const i=t[e],s=i&&this._customStyles[i];s&&$i.unsetActionCSS(this.elementRef,s)}}reapplyStateStyle(t,e){if(!this._customStyles)return;e&&this.unsetCustomStateStyles(e);const i=this._customStyles[t];i&&$i.setElementCssUpToState(this.elementRef,i,this._mouseState.state),this.setEvents(i)}}const Ui=class t extends Ji{constructor(t){super(document.createElement("div"),void 0,t),this.isActive=!1,this._innerElements=this.createInnerElements(this._customStyles),this.changeToDefault()}createInnerElements(e){var i,s;const n=Ze.createSVGElement((null==(s=null==(i=null==e?void 0:e.default)?void 0:i.svg)?void 0:s.content)||t.EMPTY_SVG);return{default:this.createInnerElement(n,"default",e),active:this.createInnerElement(n,"active",e),unavailable:this.createInnerElement(n,"unavailable",e)}}createInnerElement(t,e,i){return Di.createSpecificStateElement(this.elementRef,e,i)||t}changeToActive(){this.elementRef.replaceChildren(this._innerElements.active),this.reapplyStateStyle("active",["unavailable","default"]),this.isActive=!0}changeToDefault(){var t,e,i,s;this.elementRef.replaceChildren(this._innerElements.default),null!=(t=this._customStyles)&&t.active&&$i.unsetAllCSS(this.elementRef,null==(e=this._customStyles)?void 0:e.active),null!=(i=this._customStyles)&&i.unavailable&&$i.unsetAllCSS(this.elementRef,null==(s=this._customStyles)?void 0:s.unavailable),this.reapplyStateStyle("default",["active","unavailable"]),this.isActive=!1}changeToUnavailable(){var t,e,i,s;this.elementRef.replaceChildren(this._innerElements.unavailable),null!=(t=this._customStyles)&&t.active&&$i.unsetAllCSS(this.elementRef,null==(e=this._customStyles)?void 0:e.active),null!=(i=this._customStyles)&&i.default&&$i.unsetAllCSS(this.elementRef,null==(s=this._customStyles)?void 0:s.default),this.reapplyStateStyle("unavailable",["default","active"]),this.isActive=!1}};Ui.EMPTY_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"></svg>';let Vi=Ui;class Hi{static setPropertyValueIfDoesNotExist(t,e,i){const s=e[0];1===e.length?t[s]??(t[s]=i):(t[s]??(t[s]={}),e.shift(),Hi.setPropertyValueIfDoesNotExist(t[s],e,i))}static setPropertyValue(t,e,i){const s=e[0];1===e.length?t[s]=i:(t[s]??(t[s]={}),e.shift(),Hi.setPropertyValue(t[s],e,i))}static getObjectValue(t,e){const i=t[e[0]];return void 0===i||1===e.length?i:Hi.getObjectValue(i,e.slice(1))}static overwritePropertyObjectFromAnother(t,e,i){const s=Hi.getObjectValue(e,i);if(s){const e={...s,...Hi.getObjectValue(t,i)||{}};Hi.setPropertyValue(t,i,e)}}static isJson(t){try{return JSON.stringify(t),!0}catch{return!1}}static assignPropertyFromOneToAnother(t,e,i){e[t]??(e[t]={}),Object.assign(e[t],null==i?void 0:i[t])}}const Ki='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <title>play</title>\n <path d="M5.92 24.096q0 1.088 0.928 1.728 0.512 0.288 1.088 0.288 0.448 0 0.896-0.224l16.16-8.064q0.48-0.256 0.8-0.736t0.288-1.088-0.288-1.056-0.8-0.736l-16.16-8.064q-0.448-0.224-0.896-0.224-0.544 0-1.088 0.288-0.928 0.608-0.928 1.728v16.16z"></path>\n</svg>',Gi='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n<title>stop</title>\n<path d="M5.92 24.096q0 0.832 0.576 1.408t1.44 0.608h16.128q0.832 0 1.44-0.608t0.576-1.408v-16.16q0-0.832-0.576-1.44t-1.44-0.576h-16.128q-0.832 0-1.44 0.576t-0.576 1.44v16.16z"></path>\n</svg>',Zi=class t extends Ve{constructor(e){var i,s,n,o;const r=JSON.parse(JSON.stringify(e.directConnection)),a=t.getKey(e);super(e,Ai.buildKeyVerificationDetails(),Ai.buildHeaders,{key:a}),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this._muteButton=null,this._toggleButton=null,this._errorElement=null,this._loadingElement=null,this._pc=null,this._mediaStream=null,this._isMuted=!1;const l=null==(i=r.openAI)?void 0:i.realtime;if("object"==typeof l){this._avatarConfig=l.avatar,this._ephemeralKey=l.ephemeralKey,this._errorConfig=l.error,this._loadingConfig=l.loading,Object.assign(this.rawBody,l.config);const{function_handler:t}=(null==(n=null==(s=e.directConnection)?void 0:s.openAI)?void 0:n.realtime).config||{};t&&(this._functionHandler=t)}(o=this.rawBody).model??(o.model="gpt-4o-realtime-preview-2024-12-17"),this._avatarConfig=t.buildAvatarConfig(l),this._buttonsConfig=t.buildButtonsConfig(l),this._avatarEl=t.createAvatar(this._avatarConfig),this._containerEl=this.createContainer(),this._deepChat=e}static getKey(t){const e=t.directConnection.openAI;if(null!=e&&e.key)return e.key;const i=null==e?void 0:e.realtime;return"object"==typeof i&&(i.ephemeralKey||i.fetchEphemeralKey)?"placeholder":void 0}setUpView(t,e){t.style.display="none",e.appendChild(this._containerEl),this.setup()}async setup(){var t;const e=null==(t=this._deepChat.directConnection)?void 0:t.openAI;if(!e)return;const i=null==e?void 0:e.realtime;if("object"!=typeof i||!i.autoStart&&!i.autoFetchEphemeralKey)return;const s=this.key||e.key;(i.fetchEphemeralKey||s)&&i.autoStart&&(this.changeToUnavailable(),this.displayLoading()),this.fetchEphemeralKey(i.autoStart)}async fetchEphemeralKey(t){var e;const i=null==(e=this._deepChat.directConnection)?void 0:e.openAI,s="object"==typeof(null==i?void 0:i.realtime)?null==i?void 0:i.realtime.fetchEphemeralKey:void 0,n=null==i?void 0:i.realtime,o=this.key||i.key;if("object"==typeof n){if(!this._ephemeralKey)try{if(s){const t=s();t.then&&(this._retrievingEphemeralKey=t),this._ephemeralKey=await t}else o&&(this._retrievingEphemeralKey=this.getEphemeralKey(o),this._ephemeralKey=await this._retrievingEphemeralKey)}catch(t){this.displayFailedToRetrieveEphemeralKey(t)}this._ephemeralKey&&(t?this.init(this._ephemeralKey):this.changeToAvailable())}else if(o)try{this._retrievingEphemeralKey=this.getEphemeralKey(o),this._ephemeralKey=await this._retrievingEphemeralKey,t&&this.init(this._ephemeralKey)}catch(t){this.displayFailedToRetrieveEphemeralKey(t)}}async getEphemeralKey(t){return(await(await fetch("https://api.openai.com/v1/realtime/sessions",{method:"POST",body:JSON.stringify(this.rawBody),headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}})).json()).client_secret.value}static buildAvatarConfig(t){const e="object"==typeof t&&t.avatar?JSON.parse(JSON.stringify(t.avatar)):{};return e.maxScale=e.maxScale&&e.maxScale>=1?e.maxScale:2.5,e}static buildButtonsConfig(t){var e,i,s,n,o,r,a,l,c,h,u,d;const p="object"==typeof t&&t.buttons?JSON.parse(JSON.stringify(t.buttons)):{};return null!=(s=null==(i=null==(e=p.microphone)?void 0:e.default)?void 0:i.text)&&s.content||(p.microphone??(p.microphone={}),(n=p.microphone).default??(n.default={}),(o=p.microphone.default).svg??(o.svg={}),p.microphone.default.svg.content=zi),null!=(l=null==(a=null==(r=p.toggle)?void 0:r.default)?void 0:a.text)&&l.content||(p.toggle??(p.toggle={}),(c=p.toggle).default??(c.default={}),(h=p.toggle.default).svg??(h.svg={}),p.toggle.default.svg.content=Ki,(u=p.toggle).active??(u.active={}),(d=p.toggle.active).svg??(d.svg={}),p.toggle.active.svg.content=Gi),p}createContainer(){const t=document.createElement("div");return t.id="deep-chat-openai-realtime-container",t.appendChild(this.createAvatarContainer()),t.appendChild(this.createButtonsContainer()),t.appendChild(this.createError()),t}createAvatarContainer(){var t,e;const i=document.createElement("div");return i.id="deep-chat-openai-realtime-avatar-container",Object.assign(i.style,null==(e=null==(t=this._avatarConfig)?void 0:t.styles)?void 0:e.container),i.appendChild(this._avatarEl),i}static createAvatar(t){var e;const i=document.createElement("img");return i.id="deep-chat-openai-realtime-avatar",Object.assign(i.style,null==(e=null==t?void 0:t.styles)?void 0:e.avatar),i.src=(null==t?void 0:t.src)||be,i}createButtonsContainer(){var e;const i=document.createElement("div");i.id="deep-chat-openai-realtime-buttons-container",Object.assign(i.style,null==(e=this._buttonsConfig)?void 0:e.container),this._muteButton=this.createMuteButton();const s=t.createButtonContainer(this._muteButton.elementRef);this._toggleButton=this.createToggleButton();const n=t.createButtonContainer(this._toggleButton.elementRef);return i.appendChild(s),i.appendChild(n),i.appendChild(this.createLoading()),i}static createButtonContainer(t){const e=document.createElement("div");return e.classList.add("deep-chat-openai-realtime-button-container"),e.appendChild(t),e}createMuteButton(){var e;const i=new Vi(null==(e=this._buttonsConfig)?void 0:e.microphone);return i.elementRef.classList.replace("input-button-svg","deep-chat-openai-realtime-button"),i.elementRef.classList.add(t.BUTTON_DEFAULT,"deep-chat-openai-realtime-mute"),i.elementRef.onclick=()=>{i.isActive?(this.toggleMute(!0),i.elementRef.classList.replace(t.MUTE_ACTIVE,t.BUTTON_DEFAULT),i.changeToDefault(),this._isMuted=!1):(this.toggleMute(!1),i.elementRef.classList.replace(t.BUTTON_DEFAULT,t.MUTE_ACTIVE),Fi.removeAriaAttributes(i.elementRef),i.changeToActive(),this._isMuted=!0)},i}toggleMute(t){var e;null==(e=this._mediaStream)||e.getAudioTracks().forEach((e=>e.enabled=t))}createToggleButton(){var e;const i=new Vi(null==(e=this._buttonsConfig)?void 0:e.toggle);return i.elementRef.classList.replace("input-button-svg","deep-chat-openai-realtime-button"),i.elementRef.classList.add(t.BUTTON_DEFAULT,"deep-chat-openai-realtime-toggle"),i.elementRef.onclick=async()=>{var t;if(i.isActive)i.changeToDefault(),this.stop();else try{if(this._ephemeralKey)this.displayLoading(),await this.init(this._ephemeralKey);else if(this._retrievingEphemeralKey){this.displayLoading();const e=await this._retrievingEphemeralKey;null!=(t=this._toggleButton)&&t.isActive&&await this.init(e)}else this.displayLoading(),await this.fetchEphemeralKey(!0)}catch(t){console.error("Failed to start conversation:",t),this.displayError("Error"),this.hideLoading()}},i}async init(t){const e=new RTCPeerConnection;this._pc=e;const i=document.createElement("audio");i.autoplay=!0;const s=new AudioContext,n=s.createAnalyser();n.fftSize=256;const o=new Uint8Array(n.frequencyBinCount);this._pc.ontrack=async t=>{if(t.streams[0]){i.srcObject=t.streams[0];const e=s.createMediaStreamSource(t.streams[0]);"suspended"===s.state&&await s.resume(),e.connect(n),this.monitorFrequencies(n,o)}else console.error("No streams found in the ontrack event."),this.displayError("Error")},await navigator.mediaDevices.getUserMedia({audio:!0}).then((t=>{var i;e===this._pc&&(this._mediaStream=t,null==(i=this._pc)||i.addTrack(this._mediaStream.getTracks()[0]),this._isMuted&&this.toggleMute(!1))})).catch((t=>{console.error("Error accessing microphone:",t),this.displayError("Error")}));const r=this._pc.createDataChannel("oai-events");r.addEventListener("message",(async t=>{var e;const i=JSON.parse(t.data);if("session.created"===i.type)this.removeUnavailable(),this._toggleButton&&(Fi.removeAriaAttributes(this._toggleButton.elementRef),this._toggleButton.changeToActive()),this.hideLoading();else if("response.done"===i.type){const i=null==(e=JSON.parse(t.data).response.output)?void 0:e[0];if("function_call"===(null==i?void 0:i.type)){const{name:t,call_id:e}=i;try{await this.handleTool(t,i.arguments,e,r)}catch(t){this.stopOnError(t)}}}else"error"===i.type?this.stopOnError(i.error.message):"invalid_request_error"===i.type?this.stopOnError(i.message):i.type}));try{const i=await this._pc.createOffer();if(e!==this._pc||(await this._pc.setLocalDescription(i),e!==this._pc))return;const s=await fetch("https://api.openai.com/v1/realtime",{method:"POST",body:i.sdp,headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/sdp"}});if(e!==this._pc)return;const n={type:"answer",sdp:await s.text()};if(e!==this._pc||(await this._pc.setRemoteDescription(n),e!==this._pc))return}catch(t){console.error(t),this.displayError("Error")}}monitorFrequencies(t,e){const i=()=>{var s;t.getByteFrequencyData(e);const n=1+e.reduce(((t,e)=>t+e),0)/(255*e.length)*100/100*((null==(s=this._avatarConfig)?void 0:s.maxScale)-1);this._avatarEl.style.transform=`scale(${n})`,requestAnimationFrame(i)};i()}stopOnError(t){this.stop(),console.error(t),this.displayError("Error")}stop(){var t;null==(t=this._mediaStream)||t.getTracks().forEach((t=>t.stop())),this._mediaStream=null,this._pc&&(this._pc.close(),this._pc=null)}changeToUnavailable(){this._muteButton&&t.changeButtonToUnavailable(this._muteButton),this._toggleButton&&t.changeButtonToUnavailable(this._toggleButton)}static changeButtonToUnavailable(e){e.elementRef.classList.add(t.UNAVAILABLE),Fi.removeAriaBusy(e.elementRef),Fi.addAriaDisabled(e.elementRef),e.changeToUnavailable()}changeToAvailable(){this._muteButton&&t.changeButtonToAvailable(this._muteButton),this._toggleButton&&t.changeButtonToAvailable(this._toggleButton)}static changeButtonToAvailable(e){t.removeButtonUnavailable(e),e.changeToDefault()}removeUnavailable(){this._muteButton&&t.removeButtonUnavailable(this._muteButton),this._toggleButton&&t.removeButtonUnavailable(this._toggleButton)}static removeButtonUnavailable(e){Fi.removeAriaDisabled(e.elementRef),e.elementRef.classList.remove(t.UNAVAILABLE)}createError(){var t;const e=document.createElement("div");return e.id="deep-chat-openai-realtime-error",Object.assign(e.style,null==(t=this._errorConfig)?void 0:t.style),this._errorElement=e,e}displayFailedToRetrieveEphemeralKey(t){console.error("Failed to retrieve ephemeral key"),console.error(t),this.displayError("Error")}displayError(t){var e;this._errorElement&&(this._errorElement.style.display="block",this._errorElement.textContent=(null==(e=this._errorConfig)?void 0:e.text)||t,this.changeToUnavailable())}createLoading(){var t,e;const i=document.createElement("div");return i.id="deep-chat-openai-realtime-loading",this._loadingElement=i,null!=(t=this._loadingConfig)&&t.html&&(this._loadingElement.innerHTML=this._loadingConfig.html),Object.assign(i.style,null==(e=this._loadingConfig)?void 0:e.style),i.style.display="none",i}displayLoading(){var e,i,s;this._toggleButton&&(this._toggleButton.changeToActive(),this._toggleButton.elementRef.classList.add(t.BUTTON_LOADING),Fi.removeAriaDisabled(this._toggleButton.elementRef),Fi.addAriaBusy(this._toggleButton.elementRef)),("boolean"!=typeof(null==(e=this._loadingConfig)?void 0:e.display)||this._loadingConfig.display)&&this._loadingElement&&(this._loadingElement.style.display="block",null!=(i=this._loadingConfig)&&i.html||(this._loadingElement.textContent=(null==(s=this._loadingConfig)?void 0:s.text)||"Loading"))}hideLoading(){this._toggleButton&&(this._toggleButton.elementRef.classList.remove(t.BUTTON_LOADING),Fi.removeAriaBusy(this._toggleButton.elementRef)),this._loadingElement&&(this._loadingElement.style.display="none")}async handleTool(t,e,i,s){if(!this._functionHandler)throw Error("Please define the `function_handler` property inside the [openAI](https://deepchat.dev/docs/directConnection/openAI#Realtime) object.");const n=await this._functionHandler({name:t,arguments:e});if("object"!=typeof n||!Hi.isJson(n))throw Error('The `function_handler` response must be a JSON object, e.g. {response: "My response"}');if("generate_horoscope"===t){const t=JSON.stringify({type:"conversation.item.create",item:{type:"function_call_output",call_id:i,output:JSON.stringify(n)}});s.send(t);const e={type:"response.create"};s.send(JSON.stringify(e))}}isCustomView(){return!0}};Zi.BUTTON_DEFAULT="deep-chat-openai-realtime-button-default",Zi.BUTTON_LOADING="deep-chat-openai-realtime-button-loading",Zi.MUTE_ACTIVE="deep-chat-openai-realtime-mute-active",Zi.UNAVAILABLE="deep-chat-openai-realtime-button-unavailable";let Wi=Zi;const Xi=class t extends Ve{constructor(e){var i,s,n;const o=JSON.parse(JSON.stringify(e.directConnection)),r=null==o?void 0:o.openAI;super(e,Ai.buildKeyVerificationDetails(),Ai.buildHeaders,r),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/audio/speech",this.permittedErrorPrefixes=["Invalid"],this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI : Text To Speech</b></div>\n <p>Generate an audio file based on your text input.</p>\n <p>Click <a href="https://platform.openai.com/docs/guides/text-to-speech">here</a> for more information.</p>';const a=null==(i=null==o?void 0:o.openAI)?void 0:i.textToSpeech;"object"==typeof a&&Object.assign(this.rawBody,a),(s=this.rawBody).model??(s.model=t.DEFAULT_MODEL),(n=this.rawBody).voice??(n.voice=t.DEFAULT_VOIDE),this.textInputPlaceholderText="Insert text to generate audio",this.rawBody.response_format="mp3"}preprocessBody(t,e){var i,s;const n=JSON.parse(JSON.stringify(t)),o=null==(s=null==(i=e[e.length-1])?void 0:i.text)?void 0:s.trim();return o&&""!==o&&(n.input=o),n}async callServiceAPI(t,e){var i;if(null==(i=this.connectSettings)||!i.headers)throw new Error("Request settings have not been set up");this.url=this.connectSettings.url||this.url;const s=this.preprocessBody(this.rawBody,e);Fe.request(this,s,t)}async extractResultData(t){if(t instanceof Blob)return new Promise((e=>{const i=new FileReader;i.readAsDataURL(t),i.onload=t=>{e({files:[{src:t.target.result,type:"audio"}]})}}));if(t.error)throw t.error.message;return{error:"error"}}};Xi.DEFAULT_MODEL="tts-1",Xi.DEFAULT_VOIDE="alloy";let Yi=Xi;const Qi=class t extends Ve{constructor(e){var i,s;const n=JSON.parse(JSON.stringify(e.directConnection)),o=null==n?void 0:n.openAI;super(e,Ai.buildKeyVerificationDetails(),Ai.buildHeaders,o,{audio:{}}),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI : Speech To Text</b></div>\n <p><b>Upload an audio file</b> to transcribe it into text. You can optionally provide text to guide the audio\n processing.\n <p>Click <a href="https://platform.openai.com/docs/guides/speech-to-text">here</a> for more info.</p>',this.url="",this.permittedErrorPrefixes=["Invalid"],this.textInputPlaceholderText="Upload an audio file",this._service_url=t.AUDIO_TRANSCRIPTIONS_URL;const r=null==(i=null==n?void 0:n.openAI)?void 0:i.audio;"object"==typeof r&&(this.processConfig(r),t.cleanConfig(r),Object.assign(this.rawBody,r)),(s=this.rawBody).model??(s.model=t.DEFAULT_MODEL),this.rawBody.response_format="json",this.canSendMessage=t.canSendFileMessage}static canSendFileMessage(t,e){return!(null==e||!e[0])}processConfig(e){null!=e&&e.type&&"translation"===e.type&&(this._service_url=t.AUDIO_TRANSLATIONS_URL,delete e.language)}static cleanConfig(t){delete t.type}static createFormDataBody(t,e){const i=new FormData;return i.append("file",e),Object.keys(t).forEach((e=>{i.append(e,String(t[e]))})),i}preprocessBody(t,e){var i,s;const n=JSON.parse(JSON.stringify(t)),o=null==(s=null==(i=e[e.length-1])?void 0:i.text)?void 0:s.trim();return o&&""!==o&&(n.prompt=o),n}async callServiceAPI(e,i,s){var n;if(null==(n=this.connectSettings)||!n.headers)throw new Error("Request settings have not been set up");if(null==s||!s[0])throw new Error("No file was added");this.url=this.connectSettings.url||this._service_url;const o=this.preprocessBody(this.rawBody,i),r=t.createFormDataBody(o,s[0]);Oe.tempRemoveContentHeader(this.connectSettings,Fe.request.bind(this,this,r,e),!1)}async extractResultData(t){if(t.error)throw t.error.message;return{text:t.text}}};Qi.AUDIO_TRANSCRIPTIONS_URL="https://api.openai.com/v1/audio/transcriptions",Qi.AUDIO_TRANSLATIONS_URL="https://api.openai.com/v1/audio/translations",Qi.DEFAULT_MODEL="whisper-1";let ts=Qi;class es{static buildTextToSpeechHeaders(t,e){return{"Ocp-Apim-Subscription-Key":e,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":t}}static buildSpeechToTextHeaders(t){return{"Ocp-Apim-Subscription-Key":t,Accept:"application/json"}}static handleSpeechVerificationResult(t,e,i,s){t.error?s(y.INVALID_KEY):i(e)}static buildSpeechKeyVerificationDetails(t){return{url:`https://${t}.api.cognitive.microsoft.com/sts/v1.0/issuetoken`,method:"POST",createHeaders:t=>({"Ocp-Apim-Subscription-Key":`${t}`}),handleVerificationResult:es.handleSpeechVerificationResult}}static buildSummarizationHeader(t){return{"Ocp-Apim-Subscription-Key":t,"Content-Type":"application/json"}}static handleLanguageVerificationResult(t,e,i,s){var n;"401"===(null==(n=t.error)?void 0:n.code)?s(y.INVALID_KEY):i(e)}static buildLanguageKeyVerificationDetails(t){return{url:`${t}/language/analyze-text/jobs?api-version=2022-10-01-preview`,method:"POST",createHeaders:t=>({"Ocp-Apim-Subscription-Key":`${t}`}),handleVerificationResult:es.handleLanguageVerificationResult}}static handleTranslationVerificationResult(t,e,i,s){t.json().then((t=>{Array.isArray(t)||401e3!==t.error.code?i(e):s(y.INVALID_KEY)}))}static buildTranslationKeyVerificationDetails(t){return{url:"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es",method:"POST",createHeaders:e=>es.buildTranslationHeaders(t,e),handleVerificationResult:es.handleTranslationVerificationResult}}static buildTranslationHeaders(t,e){const i={"Ocp-Apim-Subscription-Key":e,"Content-Type":"application/json"};return t&&(i["Ocp-Apim-Subscription-Region"]=t),i}}class is extends Ve{constructor(t,e,i,s,n){super(t,es.buildLanguageKeyVerificationDetails(i),e,s,n),this.insertKeyPlaceholderText="Azure Language Subscription Key",this.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",this.permittedErrorPrefixes=["Access"]}}const ss=class t extends is{constructor(e){var i,s,n,o;const r=null==(s=null==(i=e.directConnection)?void 0:i.azure)?void 0:s.summarization,a=null==(n=e.directConnection)?void 0:n.azure;super(e,es.buildSummarizationHeader,r.endpoint,a),this.permittedErrorPrefixes=[t.ENDPOINT_ERROR_MESSAGE],this.url="",this.textInputPlaceholderText="Insert text to summarize",this.isTextInputDisabled=!1,r.endpoint?((o=this.rawBody).language??(o.language="en"),Object.assign(this.rawBody,r),this.url=`${r.endpoint}/language/analyze-text/jobs?api-version=2022-10-01-preview`):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout((()=>{e.addMessage({error:t.ENDPOINT_ERROR_MESSAGE})})))}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return{analysisInput:{documents:[{id:"1",language:t.language,text:i}]},tasks:[{kind:"ExtractiveSummarization"}]}}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Fe.request(this,i,t),this.messages=t}async extractResultData(t){var e;if(t.error)throw t.error.message;if(this.messages&&this.completionsHandlers){const i=t.headers.get("operation-location"),s={method:"GET",headers:null==(e=this.connectSettings)?void 0:e.headers};Fe.executePollRequest(this,i,s,this.messages)}return{makingAnotherRequest:!0}}async extractPollResultData(t){if(t.error)throw t.error;if("running"===t.status)return{timeoutMS:2e3};if(t.errors.length>0)throw t.errors[0];if(t.tasks.items[0].results.errors.length>0)throw t.tasks.items[0].results.errors[0];let e="";for(const i of t.tasks.items[0].results.documents[0].sentences)e+=i.text;return{text:e||""}}};ss.ENDPOINT_ERROR_MESSAGE="Please define the azure endpoint. [More Information](https://deepchat.dev/docs/directConnection/Azure#Summarization)";let ns=ss;class os{static async poll(t,e){const i={authorization:t,"content-type":"application/json"},s=`https://api.assemblyai.com/v2/transcript/${(await(await fetch("https://api.assemblyai.com/v2/transcript",{method:"POST",body:JSON.stringify({audio_url:e}),headers:i})).json()).id}`;let n;for(;!n;){const t=await(await fetch(s,{headers:i})).json();if("completed"===t.status)n=t;else{if("error"===t.status)throw new Error(`Transcription failed: ${t.error}`);await new Promise((t=>setTimeout(t,3e3)))}}return n}static buildHeaders(t){return{Authorization:t,"Content-Type":"application/octet-stream"}}static handleVerificationResult(t,e,i,s){const n=t;n.error?"invalid_api_key"===n.error.code?s(y.INVALID_KEY):s(y.CONNECTION_FAILED):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.assemblyai.com/v2/upload",method:"POST",handleVerificationResult:os.handleVerificationResult}}}class rs extends Ve{constructor(t){var e;const i=null==(e=t.directConnection)?void 0:e.assemblyAI;super(t,os.buildKeyVerificationDetails(),os.buildHeaders,i,{audio:{}}),this.insertKeyPlaceholderText="AssemblyAI API Key",this.keyHelpUrl="https://www.assemblyai.com/app/account",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>AssemblyAI Audio</b></div>\n <p><b>Upload an audio file</b> to transcribe it into text.\n <p>\n Click <a href="https://www.assemblyai.com/docs/Guides/transcribing_an_audio_file#get-started">here</a> for more info.\n </p>',this.url="https://api.assemblyai.com/v2/upload",this.isTextInputDisabled=!0,this.textInputPlaceholderText="Upload an audio file",this.permittedErrorPrefixes=["Authentication","Invalid"],this.canSendMessage=rs.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])}async callServiceAPI(t,e,i){var s;if(null==(s=this.connectSettings)||!s.headers)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");Fe.request(this,i[0],t,!1)}async extractResultData(t){var e,i;if(t.error)throw t.error;const s=null==(i=null==(e=this.connectSettings)?void 0:e.headers)?void 0:i.Authorization;return{text:(await os.poll(s,t.upload_url)).text}}}class as extends Ve{constructor(t,e,i,s,n){super(t,es.buildSpeechKeyVerificationDetails(i),e,s,n),this.insertKeyPlaceholderText="Azure Speech Subscription Key",this.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal"}}const ls=class t extends as{constructor(e){var i,s,n,o,r,a;const l=null==(s=null==(i=e.directConnection)?void 0:i.azure)?void 0:s.textToSpeech,c=null==(n=e.directConnection)?void 0:n.azure;super(e,es.buildTextToSpeechHeaders.bind({},(null==l?void 0:l.outputFormat)||"audio-16khz-128kbitrate-mono-mp3"),l.region,c),this.permittedErrorPrefixes=[t.REGION_ERROR_MESSAGE],this.introPanelMarkUp=`\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Azure Text To Speech</b></div>\n <p>Insert text to synthesize it to audio.\n <p>\n Click <a href="${t.HELP_LINK}">here</a> for more info.\n </p>`,this.isTextInputDisabled=!1,this.url="",l.region?(Object.assign(this.rawBody,l),(o=this.rawBody).lang??(o.lang="en-US"),(r=this.rawBody).name??(r.name="en-US-JennyNeural"),(a=this.rawBody).gender??(a.gender="Female"),this.url=`https://${l.region}.tts.speech.microsoft.com/cognitiveservices/v1`):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout((()=>{e.addMessage({error:t.REGION_ERROR_MESSAGE})})))}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return`<speak version='1.0' xml:lang='${t.lang}'>\n <voice xml:lang='${t.lang}' xml:gender='${t.gender}' name='${t.name}'>\n ${i}\n </voice>\n </speak>`}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Fe.request(this,i,t,!1)}async extractResultData(t){return new Promise((e=>{const i=new FileReader;i.readAsDataURL(t),i.onload=t=>{e({files:[{src:t.target.result,type:"audio"}]})}}))}};ls.HELP_LINK="https://learn.microsoft.com/en-GB/azure/cognitive-services/speech-service/get-started-text-to-speech?tabs=windows%2Cterminal&pivots=programming-language-rest",ls.REGION_ERROR_MESSAGE="Please define a region config property. [More Information](https://deepchat.dev/docs/directConnection/Azure#TextToSpeech)";let cs=ls;const hs=class t extends as{constructor(e){var i,s,n;const o=null==(s=null==(i=e.directConnection)?void 0:i.azure)?void 0:s.speechToText,r=null==(n=e.directConnection)?void 0:n.azure;if(super(e,es.buildSpeechToTextHeaders,o.region,r,{audio:{files:{acceptedFormats:".wav,.ogg"}}}),this.permittedErrorPrefixes=[t.REGION_ERROR_MESSAGE],this.introPanelMarkUp=`\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Azure Speech To Text</b></div>\n <p><b>Upload a .wav or .ogg audio file</b> to transcribe it into text.\n <p>\n Click <a href="${t.HELP_LINK}">here</a> for more info.\n </p>`,this.url="",this.isTextInputDisabled=!0,this.textInputPlaceholderText="Upload an audio file",o.region){this.canSendMessage=t.canFileSendMessage;const e=o.lang||"en-US";this.url=`https://${o.region}.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=${e}&format=detailed`,this.recordAudio=void 0}else this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout((()=>{e.addMessage({error:t.REGION_ERROR_MESSAGE})}))}static canFileSendMessage(t,e){return!(null==e||!e[0])}async callServiceAPI(t,e,i){var s,n;if(null==(s=this.connectSettings)||!s.headers)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");null!=(n=this.connectSettings)&&n.headers&&(this.connectSettings.headers["Content-Type"]=i[0].name.toLocaleLowerCase().endsWith(".wav")?"audio/wav; codecs=audio/pcm; samplerate=16000":"audio/ogg; codecs=opus"),Fe.request(this,i[0],t,!1)}async extractResultData(t){if(t.error)throw t.error;return{text:t.DisplayText||""}}};hs.HELP_LINK="https://learn.microsoft.com/en-GB/azure/cognitive-services/speech-service/get-started-text-to-speech?tabs=windows%2Cterminal&pivots=programming-language-rest",hs.REGION_ERROR_MESSAGE="Please define a region config property. [More Information](https://deepchat.dev/docs/directConnection/Azure#SpeechToText)";let us=hs;class ds extends Ve{constructor(t){var e,i,s;const n=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.translation,o=null==(s=t.directConnection)?void 0:s.azure;super(t,es.buildTranslationKeyVerificationDetails(n.region),es.buildTranslationHeaders.bind({},null==n?void 0:n.region),o),this.insertKeyPlaceholderText="Azure Translate Subscription Key",this.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",this.url="",this.url=`https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=${n.language||"es"}`}preprocessBody(t){const e=t[t.length-1].text;if(e)return[{Text:e}]}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(e);Fe.request(this,i,t)}async extractResultData(t){var e;if(Array.isArray(t))return{text:(null==(e=t[0].translations)?void 0:e[0].text)||""};throw t.error}}class ps extends Ve{constructor(t,e,i,s,n){var o,r,a,l,c;const h=JSON.parse(JSON.stringify(t.directConnection));super(t,e||Ai.buildKeyVerificationDetails(),i||Ai.buildHeaders,s||h.openAI),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/chat/completions",this.permittedErrorPrefixes=["Incorrect"],this.asyncCallInProgress=!1,this._systemMessage=ps.generateSystemMessage("You are a helpful assistant.");const u=n||(null==(o=h.openAI)?void 0:o.chat);if("object"==typeof u){u.system_prompt&&(this._systemMessage=ps.generateSystemMessage(u.system_prompt));const e=null==(l=null==(a=null==(r=t.directConnection)?void 0:r.openAI)?void 0:a.chat)?void 0:l.function_handler;e&&(this._functionHandler=e),this.cleanConfig(u),Object.assign(this.rawBody,u)}this.maxMessages??(this.maxMessages=-1),(c=this.rawBody).model??(c.model="gpt-4o")}static generateSystemMessage(t){return{role:"system",content:t}}cleanConfig(t){delete t.system_prompt,delete t.function_handler}static getContent(t){if(t.files&&t.files.length>0){const e=t.files.map((t=>({type:"image_url",image_url:{url:t.src}})));return t.text&&t.text.trim().length>0&&e.unshift({type:"text",text:t.text}),e}return t.text}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=$e.getCharacterLimitMessages(e,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.content.length:-1).map((t=>({content:ps.getContent(t),role:t.role===Se.USER_ROLE?"user":"assistant"})));return e.find((t=>t.files&&t.files.length>0))&&(i.max_tokens??(i.max_tokens=300)),i.messages=[this._systemMessage,...s],i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e),s=this.stream;s&&("object"!=typeof s||!s.simulation)||i.stream?(i.stream=!0,Ne.request(this,i,t)):Fe.request(this,i,t)}async extractResultData(t,e,i){var s,n,o,r;if(t.error)throw t.error.message;return null!=(n=null==(s=t.choices)?void 0:s[0])&&n.delta?this.extractStreamResult(t.choices[0],e,i):null!=(r=null==(o=t.choices)?void 0:o[0])&&r.message?t.choices[0].message.tool_calls?this.handleTools(t.choices[0].message,e,i):{text:t.choices[0].message.content}:{text:""}}async extractStreamResult(t,e,i){const{delta:s,finish_reason:n}=t;if("tool_calls"===n){this.asyncCallInProgress=!0;const t={tool_calls:this._streamToolCalls};return this._streamToolCalls=void 0,this.handleTools(t,e,i)}return null!=s&&s.tool_calls&&(this._streamToolCalls?s.tool_calls.forEach(((t,e)=>{this._streamToolCalls&&(this._streamToolCalls[e].function.arguments+=t.function.arguments)})):this._streamToolCalls=s.tool_calls),{text:(null==s?void 0:s.content)||""}}async handleTools(t,e,i){var s,n,o,r,a;if(!(t.tool_calls&&e&&i&&this._functionHandler))throw Error("Please define the `function_handler` property inside the [openAI](https://deepchat.dev/docs/directConnection/openAI#Chat) object.");const l=JSON.parse(JSON.stringify(i)),c=t.tool_calls.map((t=>({name:t.function.name,arguments:t.function.arguments}))),h=await(null==(s=this._functionHandler)?void 0:s.call(this,c));if(!Array.isArray(h)){if(h.text){const t={text:h.text},e=await(null==(o=(n=this.deepChat).responseInterceptor)?void 0:o.call(n,t))||t;if(Array.isArray(e))throw Error(Ai.FUNCTION_TOOL_RESP_ARR_ERROR);return e}throw Error(Ai.FUNCTION_TOOL_RESP_ERROR)}const u=await Promise.all(h);if(l.messages.push({tool_calls:t.tool_calls,role:"assistant",content:null}),!u.find((({response:t})=>"string"!=typeof t))&&c.length===u.length){u.forEach(((e,i)=>{var s;const n=null==(s=t.tool_calls)?void 0:s[i];null==l||l.messages.push({role:"tool",tool_call_id:null==n?void 0:n.id,name:null==n?void 0:n.function.name,content:e.response})})),delete l.tools,delete l.tool_choice,delete l.stream;try{let t=await(null==e?void 0:e(l).then((t=>Oe.processResponseByType(t))));if(t=await(null==(a=(r=this.deepChat).responseInterceptor)?void 0:a.call(r,t))||t,t.error)throw t.error.message;return{text:t.choices[0].message.content||""}}catch(t){throw this.asyncCallInProgress=!1,t}}throw Error(Ai.FUNCTION_TOOL_RESP_ERROR)}}class ms extends ps{constructor(t){var e,i,s,n,o,r,a;const l=JSON.parse(JSON.stringify(t.directConnection)),c=l.azure,h=(null==(i=null==(e=l.azure)?void 0:e.openAI)?void 0:i.urlDetails)||{},u=null==(n=null==(s=l.azure)?void 0:s.openAI)?void 0:n.chat;if(super(t,Ri.buildKeyVerificationDetails(h),Ri.buildHeaders,c,u),this.permittedErrorPrefixes=[Ri.URL_DETAILS_ERROR_MESSAGE],this.isTextInputDisabled=!1,"object"==typeof u){const{function_handler:e}=null==(a=null==(r=null==(o=t.directConnection)?void 0:o.azure)?void 0:r.openAI)?void 0:a.chat;e&&(this._functionHandler=e)}Ri.validateURLDetails(h)?this.url=ms.buildURL(h):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout((()=>{t.addMessage({error:Ri.URL_DETAILS_ERROR_MESSAGE})})))}static buildURL(t){const{endpoint:e,deploymentId:i,version:s}=t;return`${e}/openai/deployments/${i}/completions?api-version=${s}`}}const vs=class t extends Ve{constructor(e){var i;const{directConnection:s}=e,n=null==s?void 0:s.openAI;super(e,Ai.buildKeyVerificationDetails(),Ai.buildHeaders,n,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI DALL·E</b></div>\n <p><b>Insert text</b> to generate an image.</p>\n <p><b>Upload 1</b> PNG image to generate its variation and optionally insert text to specify the change.</p>\n <p><b>Upload 2</b> PNG images where the second is a copy of the first with a transparent area where the edit should\n take place and text to specify the edit.</p>\n <p>Click <a href="https://platform.openai.com/docs/guides/images/introduction">here</a> for more info.</p>',this.url="",this.permittedErrorPrefixes=["Incorrect","Invalid input image"];const o=null==(i=null==s?void 0:s.openAI)?void 0:i.images;if(this.camera){const t="object"==typeof o&&o.size?Number.parseInt(o.size):1024;this.camera.files={dimensions:{width:t,height:t}}}"object"==typeof o&&Object.assign(this.rawBody,o),this.canSendMessage=t.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])||!(!t||""===t.trim())}static createFormDataBody(t,e,i){const s=new FormData;return s.append("image",e),i&&s.append("mask",i),Object.keys(t).forEach((e=>{s.append(e,String(t[e]))})),s}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t));return e&&""!==e&&(i.prompt=e),i}callApiWithImage(e,i,s){var n,o;let r;const a=null==(o=null==(n=i[i.length-1])?void 0:n.text)?void 0:o.trim();if(s[1]||a&&""!==a){this.url=t.IMAGE_EDIT_URL;const e=this.preprocessBody(this.rawBody,a);r=t.createFormDataBody(e,s[0],s[1])}else this.url=t.IMAGE_VARIATIONS_URL,r=t.createFormDataBody(this.rawBody,s[0]);Oe.tempRemoveContentHeader(this.connectSettings,Fe.request.bind(this,this,r,e),!1)}async callServiceAPI(e,i,s){var n;if(null==(n=this.connectSettings)||!n.headers)throw new Error("Request settings have not been set up");if(null!=s&&s[0])this.callApiWithImage(e,i,s);else{if(!this.connectSettings)throw new Error("Request settings have not been set up");this.url=t.IMAGE_GENERATION_URL;const s=this.preprocessBody(this.rawBody,i[i.length-1].text);Fe.request(this,s,e)}}async extractResultData(t){if(t.error)throw t.error.message;return{files:t.data.map((t=>t.url?{src:t.url,type:"image"}:{src:`${hi}${t.b64_json}`,type:"image"}))}}};vs.IMAGE_GENERATION_URL="https://api.openai.com/v1/images/generations",vs.IMAGE_VARIATIONS_URL="https://api.openai.com/v1/images/variations",vs.IMAGE_EDIT_URL="https://api.openai.com/v1/images/edits";let fs=vs;class gs extends Ii{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=null==(e=i.cohere)?void 0:e.chat;super(t,"https://api.cohere.ai/v1/chat","Ask me anything!",s,i.cohere),"object"==typeof s&&Object.assign(this.rawBody,s),this.maxMessages??(this.maxMessages=-1)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e.filter((t=>t.text));return i.query=s[s.length-1].text,i.chat_history=s.slice(0,s.length-1).map((t=>({text:t.text,user_name:"ai"===t.role?"CHATBOT":"USER"}))),i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Fe.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.text}}}class bs{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json",accept:"application/json"}}static handleVerificationResult(t,e,i,s){var n;null!=(n=t.message)&&n.includes("invalid request: prompt must be at least 1 token long")?i(e):s(y.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api.mistral.ai/v1/models",method:"GET",handleVerificationResult:bs.handleVerificationResult}}}class ys extends Ve{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)).mistral;super(t,bs.buildKeyVerificationDetails(),bs.buildHeaders,i),this.insertKeyPlaceholderText="Mistral API Key",this.keyHelpUrl="https://console.mistral.ai/api-keys/",this.url="https://api.mistral.ai/v1/chat/completions",this.permittedErrorPrefixes=["invalid"],i&&(this.cleanConfig(i),Object.assign(this.rawBody,i)),this.maxMessages??(this.maxMessages=-1),(e=this.rawBody).model??(e.model="open-mistral-7b")}cleanConfig(t){delete t.key}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e.filter((t=>t.text));return i.messages=s.slice(0,s.length-1).map((t=>({text:t.text,user_name:"ai"===t.role?"system":"user"}))),i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Fe.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.text}}}class ws{static create(t){const{directConnection:e,connect:i,demo:s,webModel:n}=t;if(n)return new si(t);if(e){if(e.openAI)return e.openAI.images?new fs(t):e.openAI.speechToText?new ts(t):e.openAI.textToSpeech?new Yi(t):e.openAI.assistant?new Ci(t):e.openAI.realtime?new Wi(t):new ps(t);if(e.assemblyAI)return new rs(t);if(e.cohere)return e.cohere.textGeneration?new Pi(t):e.cohere.summarization?new Li(t):new gs(t);if(e.huggingFace)return e.huggingFace.textGeneration?new fi(t):e.huggingFace.summarization?new bi(t):e.huggingFace.translation?new xi(t):e.huggingFace.fillMask?new _i(t):e.huggingFace.questionAnswer?new gi(t):e.huggingFace.audioSpeechRecognition?new vi(t):e.huggingFace.audioClassification?new li(t):e.huggingFace.imageClassification?new ci(t):new yi(t);if(e.azure){if(e.azure.openAI){if(e.azure.openAI.chat)return new ms(t);if(e.azure.openAI.assistant)return new Bi(t)}if(e.azure.speechToText)return new us(t);if(e.azure.textToSpeech)return new cs(t);if(e.azure.summarization)return new ns(t);if(e.azure.translation)return new ds(t)}if(e.stabilityAI)return e.stabilityAI.imageToImage?new wi(t):e.stabilityAI.imageToImageUpscale?new pi(t):e.stabilityAI.imageToImageMasking?new mi(t):new ki(t);if(e.mistral)return new ys(t)}return i&&Object.keys(i).length>0&&!s?new Ue(t):new Ue(t,void 0,s||!0)}}const xs=class{};xs.attibutes={string:t=>t,number:t=>parseFloat(t),boolean:t=>"true"===t,object:t=>JSON.parse(t),array:t=>JSON.parse(t),function:t=>new Function(`return ${t}`)()};let ks=xs;function _s(t){return function(e,i){Object.defineProperty(e,i,{});const s=e.constructor,n=i.toLocaleLowerCase();s._attributes_[n]=ks.attibutes[t],s._attributeToProperty_[n]=i}}class Ss{constructor(t,e,i){this._isDisplayed=!1,t?(this._elementRef=this.createIntroPanelWithChild(t,i),this._isDisplayed=!0):e&&(this._elementRef=this.createInternalIntroPanel(e,i),this._isDisplayed=!0)}static createIntroPanel(t){const e=document.createElement("div");return e.classList.add("intro-panel"),Object.assign(e.style,t),e}createIntroPanelWithChild(t,e){const i=Ss.createIntroPanel(e);return"none"===t.style.display&&(t.style.display="block"),i.appendChild(t),i}createInternalIntroPanel(t,e){const i=Ss.createIntroPanel(e);return i.id="internal-intro-panel",i.innerHTML=t,i}hide(){this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="none",this._isDisplayed=!1)}display(){!this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="",this._isDisplayed=!0)}}const As=class t{static createImage(t,e,i){const s=new Image;return s.src=t.src,i&&M.scrollDownOnImageLoad(s.src,e),M.processContent("image",s,s.src,t.name)}static createImageMessage(e,i,s,n){const o=t.createImage(i,e.elementRef,!n&&!e.focusMode),r=e.createNewMessageElement("",s);return r.bubbleElement.appendChild(o),r.bubbleElement.classList.add(t.IMAGE_BUBBLE_CLASS),{type:"image",elements:r}}static createAudioElement(t,e){const i=document.createElement("audio");return i.src=t.src,i.classList.add("audio-player"),i.controls=!0,l.IS_SAFARI&&(i.classList.add("audio-player-safari"),i.classList.add(e===Se.USER_ROLE?"audio-player-safari-right":"audio-player-safari-left")),i}static createNewAudioMessage(e,i,s,n){const o=t.createAudioElement(i,s),r=e.createMessageElementsOnOrientation("",s,n);return r.bubbleElement.appendChild(o),r.bubbleElement.classList.add(t.AUDIO_BUBBLE_CLASS),{type:"audio",elements:r}}static createAnyFile(t){const e=document.createElement("div");e.classList.add("any-file-message-contents");const i=document.createElement("div");i.classList.add("any-file-message-icon-container");const s=Ze.createSVGElement('<?xml version="1.0" encoding="iso-8859-1"?>\n<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" \n\t viewBox="50 30 420 450" xml:space="preserve">\n<g filter="brightness(0) saturate(100%) invert(16%) sepia(0%) saturate(1942%) hue-rotate(215deg) brightness(99%) contrast(93%)">\n\t<g>\n\t\t<path d="M447.933,103.629c-0.034-3.076-1.224-6.09-3.485-8.352L352.683,3.511c-0.004-0.004-0.007-0.005-0.011-0.008\n\t\t\tC350.505,1.338,347.511,0,344.206,0H89.278C75.361,0,64.04,11.32,64.04,25.237v461.525c0,13.916,11.32,25.237,25.237,25.237\n\t\t\th333.444c13.916,0,25.237-11.32,25.237-25.237V103.753C447.96,103.709,447.937,103.672,447.933,103.629z M356.194,40.931\n\t\t\tl50.834,50.834h-49.572c-0.695,0-1.262-0.567-1.262-1.262V40.931z M423.983,486.763c0,0.695-0.566,1.261-1.261,1.261H89.278\n\t\t\tc-0.695,0-1.261-0.566-1.261-1.261V25.237c0-0.695,0.566-1.261,1.261-1.261h242.94v66.527c0,13.916,11.322,25.239,25.239,25.239\n\t\t\th66.527V486.763z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,164.014H149.912c-6.62,0-11.988,5.367-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,169.381,368.707,164.014,362.088,164.014z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,236.353H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,241.721,368.707,236.353,362.088,236.353z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,308.691H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C374.076,314.06,368.707,308.691,362.088,308.691z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M256,381.031H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988H256\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C267.988,386.398,262.62,381.031,256,381.031z"/>\n\t</g>\n</g>\n</svg>');s.classList.add("any-file-message-icon"),i.appendChild(s);const n=document.createElement("div");return n.classList.add("any-file-message-text"),n.textContent=t.name||M.DEFAULT_FILE_NAME,e.appendChild(i),e.appendChild(n),M.processContent("any",e,t.src,n.textContent)}static createNewAnyFileMessage(e,i,s,n){const o=e.createMessageElementsOnOrientation("",s,n),r=t.createAnyFile(i);return o.bubbleElement.classList.add(t.ANY_FILE_BUBBLE_CLASS),o.bubbleElement.appendChild(r),{type:"file",elements:o}}static createMessages(e,i,s,n=!1){return i.map((i=>(i.ref&&(i=M.removeFileRef(i)),M.isAudioFile(i)?t.createNewAudioMessage(e,i,s,n):M.isImageFile(i)?t.createImageMessage(e,i,s,n):t.createNewAnyFileMessage(e,i,s,n))))}static addMessages(e,i,s,n){t.createMessages(e,i,s,n).forEach((({type:t,elements:i})=>{M.addMessage(e,i,t,s,n)}))}};As.IMAGE_BUBBLE_CLASS="image-message",As.AUDIO_BUBBLE_CLASS="audio-message",As.ANY_FILE_BUBBLE_CLASS="any-file-message";let Ts=As;class Ms{static removeElements(t,e){if(!e)return;const i=t.findIndex((t=>t===e));t.splice(i,1),null==e||e.outerContainer.remove()}static removeFilesMessages(t,e){var i;null==(i=e[1].files)||i.forEach((e=>{Ms.removeElements(t.messageElementRefs,e)})),delete e[0].files,delete e[1].files}static removeTextHTMLMessage(t,e,i){const s=e[1][i];Ms.removeElements(t.messageElementRefs,s),delete e[0][i],delete e[1][i]}static updateHTMLMessage(t,e,i){var s,n,o;if(e[1].html)R.overwriteElements(t,i,e[1].html);else{const r=R.create(t,i,e[0].role),a=(null==(n=e[1].files)?void 0:n[(null==(s=e[1].files)?void 0:s.length)-1])||e[1].text,{nextSibling:l}=a.outerContainer;null==(o=null==l?void 0:l.parentElement)||o.insertBefore(r.outerContainer,l),t.messageElementRefs.splice(t.messageElementRefs.length-1,1);const c=t.messageElementRefs.findIndex((t=>t===a));t.messageElementRefs.splice(c+1,0,r),e[1].html=r}e[0].html=i}static updateFileMessages(t,e,i){var s,n;const o=e[0].role,r=Ts.createMessages(t,i,o),a=e[1].html,l=(null==(n=e[1].files)?void 0:n[(null==(s=e[1].files)?void 0:s.length)-1])||e[1].text,c=a||l;let h=t.messageElementRefs.findIndex((t=>t===c));l&&(h+=1);const u=(null==a?void 0:a.outerContainer)||(null==l?void 0:l.outerContainer.nextSibling);r.forEach((({type:e,elements:i},s)=>{var n;M.setElementProps(t,i,e,o),null==(n=u.parentElement)||n.insertBefore(i.outerContainer,u),t.messageElementRefs.splice(t.messageElementRefs.length-1,1),t.messageElementRefs.splice(h+s,0,i)})),Ms.removeFilesMessages(t,e),e[1].files=r.map((({elements:t})=>t)),e[0].files=i}static updateTextMessage(t,e,i){var s,n;if(e[1].text)t.renderText(e[1].text.bubbleElement,i);else{const o=t.createElements(i,e[0].role),r=(null==(s=e[1].files)?void 0:s[0])||e[1].html;null==(n=r.outerContainer.parentElement)||n.insertBefore(o.outerContainer,r.outerContainer);const a=t.messageElementRefs.findIndex((t=>t===r));t.messageElementRefs.splice(a,0,o),e[1].text=o}e[0].text=i}static isElementActive(t){var e,i;return js.isActiveElement(null==(e=t.text)?void 0:e.bubbleElement.classList)||js.isActiveElement(null==(i=t.html)?void 0:i.bubbleElement.classList)}static update(t,e,i){const s=t.messageToElements[i];if(s){if(Ms.isElementActive(s[1]))return console.error("Cannot update a message that is being streamed");e.text&&Ms.updateTextMessage(t,s,e.text),e.files?Ms.updateFileMessages(t,s,e.files):Ms.removeFilesMessages(t,s),e.html&&Ms.updateHTMLMessage(t,s,e.html),!e.text&&s[1].text&&Ms.removeTextHTMLMessage(t,s,"text"),!e.html&&s[1].html&&Ms.removeTextHTMLMessage(t,s,"html");const{messageElementRefs:i,avatars:n,names:o}=t;Se.classifyRoleMessages(i),Se.resetAllRoleElements(i,!!n,!!o)}else console.error("Message index not found. Please use the `getMessages` method to find the correct index")}}class Os{static getText(t,e){var i;if(!(t.directConnection||t.connect||t.webModel||t.demo))return"Connect to any API using the [connect](https://deepchat.dev/docs/connect#connect-1) property or a popular service via [directConnection](https://deepchat.dev/docs/directConnection/#directConnection).\n Host AI entirely on your browser via a [webModel](https://deepchat.dev/docs/webModel).\n To get started checkout the [Start](https://deepchat.dev/start) page and live code [examples](https://deepchat.dev/examples/frameworks).\n To remove this message set the [demo](https://deepchat.dev/docs/demo#demo) property to true.";if(t.directConnection){if(!e.isDirectConnection())return"Please define a valid service inside\n the [directConnection](https://deepchat.dev/docs/directConnection/#directConnection) object.";const s=null==(i=t.directConnection.openAI)?void 0:i.chat;if("object"==typeof s&&s.tools&&!s.function_handler)return"Please define the `function_handler` property inside the openAI [chat](https://deepchat.dev/docs/directConnection/openAI#Chat) object."}else if(t.connect&&!t.connect.url&&!t.connect.handler)return"Please define a `url` or a `handler` property inside the [connect](https://deepchat.dev/docs/connect#connect-1) object.";return null}}class js extends fe{constructor(t,e,i){var s,n;super(t);const{permittedErrorPrefixes:o,introPanelMarkUp:r,demo:a}=e;this._errorMessageOverrides=null==(s=t.errorMessages)?void 0:s.overrides,this._onClearMessages=he.onClearMessages.bind(this,t),this._onError=he.onError.bind(this,t),this._isLoadingMessageAllowed=js.getDefaultDisplayLoadingMessage(t,e),"object"==typeof t.displayLoadingBubble&&t.displayLoadingBubble.toggle&&(t.displayLoadingBubble.toggle=this.setLoadingToggle.bind(this)),this._permittedErrorPrefixes=o,this.addSetupMessageIfNeeded(t,e)||this.populateIntroPanel(i,r,t.introPanelStyle),a&&this.prepareDemo(O.processDemo(a),t.loadHistory),this.addIntroductoryMessages(t,e),new De(t,this,e),this._displayServiceErrorMessages=null==(n=t.errorMessages)?void 0:n.displayServiceErrorMessages,t.getMessages=()=>JSON.parse(JSON.stringify(this.messageToElements.map((([t])=>t)))),t.clearMessages=this.clearMessages.bind(this,e),t.refreshMessages=this.refreshTextMessages.bind(this,t.remarkable),t.scrollToBottom=x.scrollToBottom.bind(this,this.elementRef),t.addMessage=(t,e)=>{this.addAnyMessage({...t,sendUpdate:!!e},!e)},t.updateMessage=(t,e)=>Ms.update(this,t,e),e.isWebModel()&&e.setUpMessages(this),t.textToSpeech&&_.processConfig(t.textToSpeech,(t=>{this.textToSpeech=t}))}static getDefaultDisplayLoadingMessage(t,e){return e.websocket?!!t.displayLoadingBubble:("object"==typeof t.displayLoadingBubble||t.displayLoadingBubble)??!0}setLoadingToggle(){const t=this.messageElementRefs[this.messageElementRefs.length-1];fe.isLoadingMessage(t)?this.removeLastMessage():this.addLoadingMessage(!0)}prepareDemo(t,e){var i;if("object"==typeof t){if(!e&&t.displayLoading){const{history:e}=t.displayLoading;null!=e&&e.small&&de.addMessage(this,!1),null!=e&&e.full&&de.addMessage(this)}t.displayErrors&&(t.displayErrors.default&&this.addNewErrorMessage("",""),t.displayErrors.service&&this.addNewErrorMessage("service",""),t.displayErrors.speechToText&&this.addNewErrorMessage("speechToText","")),null!=(i=t.displayLoading)&&i.message&&this.addLoadingMessage(),t.response&&(this.customDemoResponse=t.response)}}addSetupMessageIfNeeded(t,e){const i=Os.getText(t,e);if(i){const t=this.createAndAppendNewMessageElement(i,Se.AI_ROLE);this.applyCustomStyles(t,Se.AI_ROLE,!1)}return!!i}addIntroductoryMessages(t,e){null!=t&&t.shadowRoot&&(this._introMessage=t.introMessage);let i=this._introMessage;null!=e&&e.isWebModel()&&(i??(i=e.getIntroMessage(i)));const s=!(null!=t&&t.history||!(null!=t&&t.loadHistory||null!=e&&e.fetchHistory));i&&(Array.isArray(i)?i.forEach(((t,e)=>{if(0!==e){const t=this.messageElementRefs[this.messageElementRefs.length-1].innerContainer;Se.hideRoleElements(t,!!this.avatars,!!this.names)}this.addIntroductoryMessage(t,s)})):this.addIntroductoryMessage(i,s))}addIntroductoryMessage(t,e){var i;let s;return null!=t&&t.text?s=this.createAndAppendNewMessageElement(t.text,Se.AI_ROLE):null!=t&&t.html&&(s=R.add(this,t.html,Se.AI_ROLE,this.messageElementRefs)),s&&(this.applyCustomStyles(s,Se.AI_ROLE,!1,null==(i=this.messageStyles)?void 0:i.intro),s.outerContainer.classList.add(fe.INTRO_CLASS),e&&(s.outerContainer.style.display="none")),s}removeIntroductoryMessage(){const t=this.messageElementRefs[0];t.outerContainer.classList.contains(fe.INTRO_CLASS)&&(t.outerContainer.remove(),this.messageElementRefs.shift())}addAnyMessage(t,e=!1,i=!1){return t.error?this.addNewErrorMessage("service",t.error,i):this.addNewMessage(t,e,i)}tryAddTextMessage(t,e,i,s=!1,n=!1){!i.ignoreText&&void 0!==t.text&&null!==i.text&&(this.addNewTextMessage(t.text,t.role,e,n),!s&&this.textToSpeech&&t.role!==Se.USER_ROLE&&_.speak(t.text,this.textToSpeech))}tryAddFileMessages(t,e=!1){t.files&&Array.isArray(t.files)&&Ts.addMessages(this,t.files,t.role,e)}tryAddHTMLMessage(t,e,i=!1){if(void 0!==t.html&&null!==t.html){const s=R.add(this,t.html,t.role,this.messageElementRefs,e,i);I.isElementTemporary(s)&&delete t.html}}addNewMessage(t,e=!1,i=!1){const s=js.createMessageContent(t),n={status:t.overwrite};return i?(this.tryAddHTMLMessage(s,n,i),this.tryAddFileMessages(s,i),this.tryAddTextMessage(s,n,t,e,i)):(this.tryAddTextMessage(s,n,t,e,i),this.tryAddFileMessages(s,i),this.tryAddHTMLMessage(s,n,i)),this.isValidMessageContent(s)&&!i&&this.updateStateOnMessage(s,t.overwrite,t.sendUpdate,e),s}isValidMessageContent(t){return t.text||t.html||t.files&&t.files.length>0}updateStateOnMessage(t,e,i=!0,s=!1){if(!e){const e=Se.generateMessageBody(t,this.messageElementRefs);this.messageToElements.push([t,e])}i&&this.sendClientUpdate(t,s)}removeMessageOnError(){const t=this.messageElementRefs[this.messageElementRefs.length-1],e=null==t?void 0:t.bubbleElement;(null!=e&&e.classList.contains(Te.MESSAGE_CLASS)&&""===e.textContent||js.isTemporaryElement(t))&&this.removeLastMessage()}addNewErrorMessage(t,e,i=!1){var s,n,o,r,a;this.removeMessageOnError();const l=this.getPermittedMessage(e)||(null==(s=this._errorMessageOverrides)?void 0:s[t])||(null==(n=this._errorMessageOverrides)?void 0:n.default)||"Error, please try again.",c=this.createMessageElementsOnOrientation(l,"error",i);Se.hideRoleElements(c.innerContainer,!!this.avatars,!!this.names);const{bubbleElement:h,outerContainer:u}=c;h.classList.add(Se.ERROR_MESSAGE_TEXT_CLASS),this.renderText(h,l);const d=ce.extractParticularSharedStyles(["fontSize","fontFamily"],null==(o=this.messageStyles)?void 0:o.default);ce.applyCustomStylesToElements(c,!1,d),ce.applyCustomStylesToElements(c,!1,null==(r=this.messageStyles)?void 0:r.error),i||this.appendOuterContainerElemet(u),this.textToSpeech&&_.speak(l,this.textToSpeech),null==(a=this._onError)||a.call(this,l)}static checkPermittedErrorPrefixes(t,e){for(let i=0;i<t.length;i+=1)if(e.startsWith(t[i]))return e}static extractErrorMessages(t){return Array.isArray(t)?t:t instanceof Error?[t.message]:"string"==typeof t?[t]:"object"==typeof t&&t.error?[t.error]:[]}getPermittedMessage(t){if(t){const e=js.extractErrorMessages(t);for(let t=0;t<e.length;t+=1){const i=e[t];if("string"==typeof i){if(this._displayServiceErrorMessages)return i;if(this._permittedErrorPrefixes){const t=js.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,i);if(t)return t}}}}}removeError(){this.isLastMessageError()&&Se.getLastMessageElement(this.elementRef).remove()}addDefaultLoadingMessage(){const t=this.createMessageElements("",Se.AI_ROLE),{bubbleElement:e}=t;t.bubbleElement.classList.add(A.DOTS_CONTAINER_CLASS);const i=document.createElement("div");return i.classList.add("loading-message-dots"),e.appendChild(i),A.setDots(e,this.messageStyles),t}addLoadingMessage(t=!1){var e,i,s,n,o,r;const a=this.messageElementRefs[this.messageElementRefs.length-1];if(fe.isLoadingMessage(a)||!t&&!this._isLoadingMessageAllowed)return;const l=null==(s=null==(i=null==(e=this.messageStyles)?void 0:e.loading)?void 0:i.message)?void 0:s.html,c=l?R.createElements(this,l,Se.AI_ROLE,!1):this.addDefaultLoadingMessage();this.appendOuterContainerElemet(c.outerContainer),c.bubbleElement.classList.add(A.BUBBLE_CLASS),this.applyCustomStyles(c,Se.AI_ROLE,!1,null==(r=null==(o=null==(n=this.messageStyles)?void 0:n.loading)?void 0:o.message)?void 0:r.styles),this.focusMode||x.scrollToBottom(this.elementRef)}populateIntroPanel(t,e,i){(t||e)&&(this._introPanel=new Ss(t,e,i),this._introPanel._elementRef&&(P.apply(this,this._introPanel._elementRef),this.elementRef.appendChild(this._introPanel._elementRef)))}async addMultipleFiles(t){return Promise.all((t||[]).map((t=>new Promise((e=>{if(t.type&&"any"!==t.type){const i=new FileReader;i.readAsDataURL(t.file),i.onload=()=>{e({src:i.result,type:t.type,ref:t.file})}}else{const i=t.file.name||M.DEFAULT_FILE_NAME;e({name:i,type:"any",ref:t.file})}})))))}static isActiveElement(t){return!!t&&(t.contains(A.BUBBLE_CLASS)||t.contains(de.CLASS)||t.contains(Te.MESSAGE_CLASS))}clearMessages(t,e){var i,s;const n=[];this.messageElementRefs.forEach((t=>{js.isActiveElement(t.bubbleElement.classList)?n.push(t):t.outerContainer.remove()})),Array.from(this.elementRef.children).forEach((t=>{var e;const i=null==(e=t.children[0])?void 0:e.children[0];null!=i&&i.classList.contains(Se.ERROR_MESSAGE_TEXT_CLASS)&&t.remove()})),this.messageElementRefs=n;const o=this.messageToElements.filter((t=>t[1].text&&js.isActiveElement(t[1].text.bubbleElement.classList)||t[1].html&&js.isActiveElement(t[1].html.bubbleElement.classList)));this.messageToElements.splice(0,this.messageToElements.length,...o),!1!==e&&(null!=(i=this._introPanel)&&i._elementRef&&this._introPanel.display(),this.addIntroductoryMessages()),null==(s=this._onClearMessages)||s.call(this),delete t.sessionId}}const Cs=class t{static adjustInputPadding(t,e){e["inside-left"].length>0&&t.classList.add("text-input-inner-left-adjustment"),e["inside-right"].length>0&&t.classList.add("text-input-inner-right-adjustment")}static adjustForOutsideButton(e,i,s){0===s["outside-right"].length&&s["outside-left"].length>0?(e[0].classList.add(t.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS)):0===s["outside-left"].length&&s["outside-right"].length>0&&(e[3].classList.add(t.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS))}static adjustOutsideSubmit(e,i,s){if(!(s["inside-left"].length>0||s["inside-right"].length>0)){if(0===s["outside-right"].length&&s["outside-left"].length>0)return e[0].classList.add(t.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),s["outside-left"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")));if(0===s["outside-left"].length&&s["outside-right"].length>0)return e[3].classList.add(t.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),s["outside-right"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")))}}static set(e,i,s,n){!!t.adjustOutsideSubmit(i,s,n)||t.adjustForOutsideButton(i,s,n),t.adjustInputPadding(e,n)}};Cs.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS="text-input-container-left-adjustment",Cs.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS="text-input-container-right-adjustment",Cs.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS="text-input-container-left-small-adjustment",Cs.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS="text-input-container-right-small-adjustment";let Es=Cs;class Is{static create(){return Array.from({length:4}).map(((t,e)=>{const i=document.createElement("div");return i.classList.add("input-button-container"),(0===e||3===e)&&i.classList.add("outer-button-container"),(1===e||2===e)&&i.classList.add("inner-button-container"),i}))}static add(t,e){t.insertBefore(e[1],t.firstChild),t.insertBefore(e[0],t.firstChild),t.appendChild(e[2]),t.appendChild(e[3])}static getContainerIndex(t){return"outside-left"===t?0:"inside-left"===t?1:"inside-right"===t?2:3}static addButton(t,e,i){e.classList.add(i);const s=Is.getContainerIndex(i);t[s].appendChild(e),3===s&&e.classList.add("outside-right")}}const Ps=["camera","gifs","images","audio","mixedFiles","submit","microphone"],Ns='<?xml version="1.0" standalone="no"?>\n<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">\n<svg xmlns="http://www.w3.org/2000/svg" stroke="currentColor" fill="none" stroke-width="1" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round">\n <line x1="22" y1="2" x2="11" y2="14"></line>\n <polygon points="22 2 15 22 11 14 2 10 22 2"></polygon>\n</svg>\n';class Rs{static applyCustomStylesToDefault(t,e){var i,s;for(const n of Object.keys(t)){(i=t[n]).item??(i.item={});for(const i of["default","hover","click"])Hi.assignPropertyFromOneToAnother(i,t[n].item,null==(s=e[n])?void 0:s.item);Hi.assignPropertyFromOneToAnother("iconContainer",t[n],e[n]),Hi.assignPropertyFromOneToAnother("text",t[n],e[n])}}static createDropupStyles(t={}){return Rs.applyCustomStylesToDefault({default:{item:{}},active:{item:{}},disabled:{}},t),t}}const qs=class t{static addItemEvents(t,e,i,s){j.add(e,s),e.addEventListener("click",(()=>{i.click()})),e.addEventListener("mouseenter",(e=>{t.highlightedItem=e.target})),e.addEventListener("mouseleave",(()=>{t.highlightedItem=void 0}))}static createItemText(t,e){const i=document.createElement("div");return Object.assign(i.style,e),i.classList.add("dropup-menu-item-text"),i.textContent=t||"File",i}static createItemIcon(t,e){const i=document.createElement("div");return Object.assign(i.style,e),i.classList.add("dropup-menu-item-icon"),i.appendChild(t.children[0]),i}static populateItem(e,i,s,n){const o=e.children[0];o.classList.contains("text-button")?i.appendChild(t.createItemText(o.textContent,null==n?void 0:n.text)):(i.appendChild(t.createItemIcon(e,null==n?void 0:n.iconContainer)),i.appendChild(t.createItemText(s,null==n?void 0:n.text)))}static createItem(e,s,n){var o;const{elementRef:r,dropupText:a}=s,l=document.createElement("div");if(Object.assign(l.style,null==(o=null==n?void 0:n.item)?void 0:o.default),t.populateItem(r,l,a,n),l.classList.add(t.MENU_ITEM_CLASS),r.classList.contains(Fs.BUTTON_CLASS))s.setDropupItem(l);else{const s=i.processStateful((null==n?void 0:n.item)||{});t.addItemEvents(e,l,r,s)}return l}};qs.MENU_ITEM_CLASS="dropup-menu-item",qs.DISABLED_ITEM_CLASS="dropup-menu-item-disabled",qs.ACTIVE_ITEM_CLASS="dropup-menu-item-active";let Bs=qs;const Ls=class t extends Ji{constructor(e,i){var s,n;const o=(null==(s=null==e?void 0:e.dropupItem)?void 0:s.text)||`Custom ${i}`;super(t.createButtonElement(),null==e?void 0:e.position,null==e?void 0:e.styles,o),this._state="default",this._innerElements=this.createInnerElements(this._customStyles),this._onClick=e.onClick,this._dropupStyles=Rs.createDropupStyles(null==(n=e.dropupItem)?void 0:n.styles),this.setSetState(e),this.addClickListener(),this.changeState(e.initialState,!0)}static createButtonElement(){const e=document.createElement("div");return e.classList.add("input-button"),e.classList.add(t.BUTTON_CLASS),e}createInnerElements(t){var e,i,s,n;const o=Ze.createSVGElement(Ns);o.id="submit-icon";const r=null!=(i=null==(e=null==t?void 0:t.default)?void 0:e.svg)&&i.content?Ze.createSVGElement(null==(n=null==(s=null==t?void 0:t.default)?void 0:s.svg)?void 0:n.content):o;return{default:this.createInnerElement(r,"default",t),active:this.createInnerElement(r,"active",t),disabled:this.createInnerElement(r,"disabled",t)}}createInnerElement(t,e,i){return Di.createSpecificStateElement(this.elementRef,e,i)||t}setSetState(t){t.setState={setDefault:()=>{this.changeToDefault()},setActive:()=>{this.changeToActive()},setDisabled:()=>{this.changeToDisabled()}}}addClickListener(){this.elementRef.addEventListener("click",(()=>{var t;const e=null==(t=this._onClick)?void 0:t.call(this,this._state);("default"===e||"active"===e||"disabled"===e)&&this.changeState(e)}))}changeState(t,e){"disabled"===t?this.changeToDisabled(e):"active"===t?this.changeToActive(e):this.changeToDefault(e)}assignDropupItemStyle(t){var e;this.elementRef.parentElement&&this._originalElementRef&&(this.elementRef=P.replaceElementWithNewClone(this.elementRef,this._originalElementRef)),Object.assign(this.elementRef.style,null==(e=null==t?void 0:t.item)?void 0:e.default);const s=i.processStateful((null==t?void 0:t.item)||{});j.add(this.elementRef,s),this.addClickListener();const n=this.elementRef.children[0];n.classList.contains("text-button")||Object.assign(n.style,null==t?void 0:t.iconContainer)}changeToDefault(t){var e,i,s,n;!t&&"default"===this._state||(this.elementRef.classList.contains(Bs.MENU_ITEM_CLASS)?(this.assignDropupItemStyle(this._dropupStyles.default),this.elementRef.classList.remove(Bs.DISABLED_ITEM_CLASS),this.elementRef.classList.remove(Bs.ACTIVE_ITEM_CLASS)):(this.elementRef.replaceChildren(this._innerElements.default),null!=(e=this._customStyles)&&e.active&&$i.unsetAllCSS(this.elementRef,null==(i=this._customStyles)?void 0:i.active),null!=(s=this._customStyles)&&s.disabled&&$i.unsetAllCSS(this.elementRef,null==(n=this._customStyles)?void 0:n.disabled),this.reapplyStateStyle("default",["active","disabled"])),Fi.removeAriaDisabled(this.elementRef),this._state="default")}changeToActive(t){!t&&"active"===this._state||(this.elementRef.classList.contains(Bs.MENU_ITEM_CLASS)?(this.assignDropupItemStyle(this._dropupStyles.active),this.elementRef.classList.remove(Bs.DISABLED_ITEM_CLASS),this.elementRef.classList.add(Bs.ACTIVE_ITEM_CLASS)):(this.elementRef.replaceChildren(this._innerElements.active),this.reapplyStateStyle("active",["disabled","default"])),Fi.removeAriaDisabled(this.elementRef),this._state="active")}changeToDisabled(t){var e,i,s,n;!t&&"disabled"===this._state||(this.elementRef.classList.contains(Bs.MENU_ITEM_CLASS)?(this.assignDropupItemStyle(this._dropupStyles.disabled),this.elementRef.classList.remove(Bs.ACTIVE_ITEM_CLASS),this.elementRef.classList.add(Bs.DISABLED_ITEM_CLASS)):(this.elementRef.replaceChildren(this._innerElements.disabled),null!=(e=this._customStyles)&&e.active&&$i.unsetAllCSS(this.elementRef,null==(i=this._customStyles)?void 0:i.active),null!=(s=this._customStyles)&&s.default&&$i.unsetAllCSS(this.elementRef,null==(n=this._customStyles)?void 0:n.default),this.reapplyStateStyle("disabled",["default","active"])),Fi.addAriaDisabled(this.elementRef),this._state="disabled")}setDropupItem(t){this.elementRef=t,this._originalElementRef=t.cloneNode(!0),this.changeState(this._state,!0)}};Ls.INDICATOR_PREFIX="custom",Ls.BUTTON_CLASS="custom-button";let Fs=Ls;class zs{static focusItemWhenOnEdge(t,e){const i=e?t.children[0]:t.children[t.children.length-1];zs.focusSiblingItem(i,t,e,!0)}static focusSiblingItem(t,e,i,s=!1){const n=s?t:t[i?"nextSibling":"previousSibling"];n?(t.dispatchEvent(new MouseEvent("mouseleave")),n.dispatchEvent(new MouseEvent("mouseenter"))):(t.dispatchEvent(new MouseEvent("mouseleave")),zs.focusItemWhenOnEdge(e,i))}}class Ds{constructor(t,e){var i;this._isOpen=!0,this._styles=e,this.elementRef=Ds.createElement(null==(i=this._styles)?void 0:i.container),this.close(),setTimeout((()=>this.addWindowEvents(t)))}static createElement(t){const e=document.createElement("div");return e.id="dropup-menu",Object.assign(e.style,t),e}open(){this.elementRef.style.display="block",this._isOpen=!0}close(){this._isOpen&&(this.elementRef.style.display="none",this._isOpen=!1)}toggle(){this._isOpen?this.close():this.open()}addItem(t){const e=Bs.createItem(this,t,this._styles);this.elementRef.appendChild(e)}addWindowEvents(t){this.clickEvent=this.windowClick.bind(this,t),window.addEventListener("click",this.clickEvent),this.keyDownEvent=this.windowKeyDown.bind(this,t),window.addEventListener("keydown",this.keyDownEvent)}windowClick(t,e){var i;!t.isConnected&&this.clickEvent?window.removeEventListener("click",this.clickEvent):t.parentElement!==(null==(i=e.target.shadowRoot)?void 0:i.children[0])&&this.close()}windowKeyDown(t,e){var i,s,n;!t.isConnected&&this.keyDownEvent?window.removeEventListener("keydown",this.keyDownEvent):this._isOpen&&(e.key===c.ESCAPE?(this.close(),null==(i=this.highlightedItem)||i.dispatchEvent(new MouseEvent("mouseleave"))):e.key===c.ENTER?(null==(s=this.highlightedItem)||s.click(),null==(n=this.highlightedItem)||n.dispatchEvent(new MouseEvent("mouseleave"))):e.key===c.ARROW_DOWN?zs.focusSiblingItem(this.highlightedItem||this.elementRef.children[this.elementRef.children.length-1],this.elementRef,!0):e.key===c.ARROW_UP&&zs.focusSiblingItem(this.highlightedItem||this.elementRef.children[0],this.elementRef,!1))}}const $s=class t extends Ji{constructor(e,i){var s;super(t.createButtonElement(),void 0,{styles:null==(s=null==i?void 0:i.button)?void 0:s.styles});const n=this.createInnerElements(this._customStyles);this._menu=new Ds(e,null==i?void 0:i.menu),this.addClickEvent(),this.buttonContainer=t.createButtonContainer(),this.elementRef.appendChild(n.styles),this.buttonContainer.appendChild(this.elementRef),this.elementRef.classList.add(t.BUTTON_ICON_CLASS,"upload-file-button"),this.elementRef.children[0].id="dropup-icon",this.buttonContainer.appendChild(this._menu.elementRef),this.reapplyStateStyle("styles"),this.addContainerEvents(e)}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}createInnerElements(e){return{styles:this.createInnerElement(t.createSVGIconElement(),"styles",e)}}createInnerElement(t,e,i){return Di.createSpecificStateElement(this.elementRef,e,i)||t}static createSVGIconElement(){return Ze.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <path d="M16 0c-8.836 0-16 7.163-16 16s7.163 16 16 16c8.837 0 16-7.163 16-16s-7.163-16-16-16zM16 30.032c-7.72 0-14-6.312-14-14.032s6.28-14 14-14 14 6.28 14 14-6.28 14.032-14 14.032zM23 15h-6v-6c0-0.552-0.448-1-1-1s-1 0.448-1 1v6h-6c-0.552 0-1 0.448-1 1s0.448 1 1 1h6v6c0 0.552 0.448 1 1 1s1-0.448 1-1v-6h6c0.552 0 1-0.448 1-1s-0.448-1-1-1z"></path>\n</svg>')}addClickEvent(){this.elementRef.onclick=this._menu.toggle.bind(this._menu)}static createButtonContainer(){const t=document.createElement("div");return t.id="dropup-container",t}addItem(t){this._menu.addItem(t)}addContainerEvents(e){e.addEventListener("click",(e=>{const i=e.target.classList;!i.contains(t.BUTTON_ICON_CLASS)&&!i.contains(Bs.DISABLED_ITEM_CLASS)&&this._menu.close()}))}static getPosition(t,e){var i,s;return null!=(i=null==e?void 0:e.button)&&i.position?null==(s=null==e?void 0:e.button)?void 0:s.position:t["outside-left"].length>0&&0===t["outside-right"].length?"outside-right":"outside-left"}};$s.BUTTON_ICON_CLASS="dropup-icon";let Js=$s;class Us{static addToDropup(t,e,i,s){const n=new Js(i,s);Ps.forEach((t=>{const i=e["dropup-menu"].findIndex((e=>e.buttonType===t)),s=e["dropup-menu"][i];s&&(n.addItem(s.button),e["dropup-menu"].splice(i,1))})),e["dropup-menu"].forEach((({button:t})=>n.addItem(t)));const o=Js.getPosition(e,s);Is.addButton(t,n.buttonContainer,o),e[o].push({})}static addToSideContainer(t,e){["inside-left","inside-right","outside-left","outside-right"].forEach((i=>{const s=i;e[s].forEach((e=>{Is.addButton(t,e.button.elementRef,s)}))}))}static setPosition(t,e,i){const s={...t[e],buttonType:e};i.push(s),delete t[e]}static createPositionsToButtonsObj(){return{"dropup-menu":[],"outside-left":[],"inside-left":[],"inside-right":[],"outside-right":[]}}static generatePositionToButtons(t){const e=Us.createPositionsToButtonsObj();Object.keys(t).forEach((i=>{var s;const n=null==(s=t[i])?void 0:s.button.position;n&&Us.setPosition(t,i,e[n])})),0===e["inside-right"].length&&t.submit&&Us.setPosition(t,"submit",e["inside-right"]),0===e["outside-right"].length&&(t.submit?Us.setPosition(t,"submit",e["outside-right"]):t.microphone?Us.setPosition(t,"microphone",e["outside-right"]):t.camera?Us.setPosition(t,"camera",e["outside-right"]):t[`${Fs.INDICATOR_PREFIX}1`]&&Us.setPosition(t,`${Fs.INDICATOR_PREFIX}1`,e["outside-right"])),t.submit&&Us.setPosition(t,"submit",0===e["outside-left"].length?e["outside-left"]:e["inside-right"]),t.microphone&&Us.setPosition(t,"microphone",0===e["outside-left"].length?e["outside-left"]:e["inside-right"]);const i=Object.keys(t);return i.length>1||e["dropup-menu"].length>0?(Ps.forEach((i=>{t[i]&&e["dropup-menu"].push({...t[i],buttonType:i})})),i.forEach((i=>{const s=i;s.startsWith(Fs.INDICATOR_PREFIX)&&t[s]&&e["dropup-menu"].push({...t[s],customType:s})}))):1===i.length&&Us.setPosition(t,i[0],0===e["outside-right"].length?e["outside-right"]:e["outside-left"]),e}static addButtons(t,e,i,s){const n=Us.generatePositionToButtons(e);return Us.addToSideContainer(t,n),n["dropup-menu"].length>0&&Us.addToDropup(t,n,i,s),n}}const Vs={images:{id:"upload-images-icon",svgString:'<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">\n <path d="M20,15.2928932 L20,5.5 C20,4.67157288 19.3284271,4 18.5,4 L5.5,4 C4.67157288,4 4,4.67157288 4,5.5 L4,12.2928932 L7.14644661,9.14644661 C7.34170876,8.95118446 7.65829124,8.95118446 7.85355339,9.14644661 L13.5,14.7928932 L16.1464466,12.1464466 C16.3417088,11.9511845 16.6582912,11.9511845 16.8535534,12.1464466 L20,15.2928932 Z M20,16.7071068 L16.5,13.2071068 L13.8535534,15.8535534 C13.6582912,16.0488155 13.3417088,16.0488155 13.1464466,15.8535534 L7.5,10.2071068 L4,13.7071068 L4,18.5 C4,19.3284271 4.67157288,20 5.5,20 L18.5,20 C19.3284271,20 20,19.3284271 20,18.5 L20,16.7071068 Z M3,5.5 C3,4.11928813 4.11928813,3 5.5,3 L18.5,3 C19.8807119,3 21,4.11928813 21,5.5 L21,18.5 C21,19.8807119 19.8807119,21 18.5,21 L5.5,21 C4.11928813,21 3,19.8807119 3,18.5 L3,5.5 Z M15,6 L17,6 C17.5522847,6 18,6.44771525 18,7 L18,9 C18,9.55228475 17.5522847,10 17,10 L15,10 C14.4477153,10 14,9.55228475 14,9 L14,7 C14,6.44771525 14.4477153,6 15,6 Z M15,7 L15,9 L17,9 L17,7 L15,7 Z"/>\n</svg>\n',dropupText:"Image"},gifs:{id:"upload-gifs-icon",svgString:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 5.9266752 5.6408391" height="21.31971" width="22.4">\n <g>\n <path d="m 5.2564627,1.548212 c -3.1136005,-0.4796804 -1.5568006,-0.2398402 0,0 z M 2.0001198,2.0922063 c 0.1556781,0 0.2657489,0.020893 0.3917849,0.080366 0.081154,0.038347 0.1153492,0.134065 0.076377,0.2138602 -0.038973,0.07979 -0.1363527,0.1134129 -0.2175069,0.075091 -0.078199,-0.036919 -0.1407455,-0.048792 -0.250655,-0.048792 -0.2260486,0 -0.3921482,0.2042182 -0.3921482,0.4801409 0,0.2761822 0.1663188,0.4810688 0.3921482,0.4810688 0.1117901,0 0.2064255,-0.046133 0.255659,-0.1284198 l 0.00162,-0.00389 V 3.0534032 l -0.098011,1.75e-4 c -0.081844,0 -0.1495979,-0.059305 -0.1612403,-0.1365887 l -0.00175,-0.023683 c 0,-0.08047 0.060311,-0.1470874 0.1389194,-0.1585331 l 0.024085,-0.00195 h 0.2612303 c 0.081842,0 0.149598,0.059305 0.1612404,0.1365891 l 0.00175,0.023683 -3.398e-4,0.3968809 v 0 l -0.00168,0.014211 v 0 l -0.00553,0.023034 v 0 l -0.00532,0.014145 c -0.098178,0.22826 -0.3236506,0.3528713 -0.5706303,0.3528713 -0.4240855,0 -0.7181621,-0.3622714 -0.7181621,-0.8016063 0,-0.4391857 0.2940275,-0.8006848 0.7181621,-0.8006848 z m 1.2034759,0.031275 c 0.081843,0 0.1495977,0.059305 0.1612403,0.1365891 l 0.00175,0.023683 v 1.2211775 c 0,0.088516 -0.07298,0.1602721 -0.1630073,0.1602721 -0.081841,0 -0.1495972,-0.059305 -0.1612397,-0.1365892 L 3.040589,3.5049308 V 2.2837527 c 0,-0.088516 0.07298,-0.1602721 0.1630067,-0.1602714 z m 0.7813442,0 0.5209469,0.00195 c 0.090025,3.048e-4 0.1627543,0.072306 0.1624458,0.1608234 -2.809e-4,0.08047 -0.06083,0.1468798 -0.1394772,0.158066 l -0.024092,0.00195 -0.3575326,-0.0013 v 0.4497782 l 0.2928918,2.27e-4 c 0.081842,0 0.1495979,0.059305 0.1612403,0.136589 l 0.00175,0.023683 c 0,0.080469 -0.06031,0.1470871 -0.1389193,0.1585393 l -0.024092,0.00195 -0.2928919,-2.336e-4 1.563e-4,0.2860316 c 0,0.080471 -0.06031,0.1470873 -0.1389193,0.1585395 l -0.024085,0.00195 c -0.081843,0 -0.1495979,-0.059305 -0.1612403,-0.1365826 l -0.00175,-0.023691 V 2.2841354 c 2.798e-4,-0.08047 0.060829,-0.1468797 0.1394758,-0.1580594 z"/>\n <path d="m 5.0894191,1.0943261 c 0,-0.21918999 -0.177687,-0.39686999 -0.396876,-0.39686999 h -3.43959 c -0.2191879,0 -0.391262,0.1777519 -0.3968759,0.39686999 l -0.027082,3.4379266 c 0.040152,0.2939927 0.4235456,0.409415 0.4235456,0.409415 l 3.4785583,-0.00851 c 0,0 0.3008506,-0.1402998 0.3236271,-0.4201576 0.042911,-0.5272495 0.034693,-1.6106146 0.034693,-3.4186761 z m -4.49792494,0 c 0,-0.36530999 0.29614504,-0.66145999 0.66145894,-0.66145999 h 3.43959 c 0.365314,0 0.66146,0.29615 0.66146,0.66145999 v 3.43959 c 0,0.36532 -0.296146,0.66146 -0.66146,0.66146 h -3.43959 c -0.3653139,0 -0.66145894,-0.29614 -0.66145894,-0.66146 z"/>\n </g>\n</svg>\n',dropupText:"GIF"},audio:{id:"upload-audio-icon",svgString:'<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="-49.49 -49.49 593.87 593.87" stroke-width="3.95908" transform="rotate(0)">\n <g stroke-width="0"></g>\n <g stroke-linecap="round" stroke-linejoin="round" stroke-width="0.98977"></g>\n <g>\n <g>\n <g>\n <path d="M163.205,76.413v293.301c-3.434-3.058-7.241-5.867-11.486-8.339c-21.38-12.452-49.663-15.298-77.567-7.846 c-49.038,13.096-80.904,54.519-71.038,92.337c4.019,15.404,14.188,28.221,29.404,37.087c13.553,7.894,29.87,11.933,47.115,11.933 c9.962,0,20.231-1.356,30.447-4.087c42.74-11.406,72.411-44.344,72.807-77.654h0.011v-0.162c0.002-0.166,0-0.331,0-0.496V187.072 l290.971-67.3v178.082c-3.433-3.055-7.238-5.863-11.481-8.334c-21.385-12.452-49.654-15.308-77.567-7.846 c-49.038,13.087-80.904,54.519-71.038,92.356c4.019,15.385,14.183,28.212,29.404,37.067c13.548,7.894,29.875,11.933,47.115,11.933 c9.962,0,20.231-1.356,30.452-4.087c42.74-11.413,72.411-44.346,72.804-77.654h0.004v-0.065c0.003-0.236,0.001-0.469,0-0.704V0 L163.205,76.413z M104.999,471.779c-22.543,6.038-45.942,3.846-62.572-5.846c-10.587-6.163-17.591-14.817-20.255-25.038 c-7.144-27.375,18.452-58.029,57.062-68.346c8.409-2.25,16.938-3.346,25.188-3.346c13.87,0,26.962,3.115,37.389,9.192 c10.587,6.163,17.591,14.817,20.255,25.029c0.809,3.102,1.142,6.248,1.139,9.4v0.321h0.014 C162.99,437.714,139.082,462.678,104.999,471.779z M182.898,166.853V92.067l290.971-67.298v74.784L182.898,166.853z M415.677,399.923c-22.558,6.038-45.942,3.837-62.587-5.846c-10.587-6.163-17.587-14.817-20.25-25.019 c-7.144-27.385,18.452-58.058,57.058-68.365c8.414-2.25,16.942-3.346,25.192-3.346c13.875,0,26.962,3.115,37.385,9.192 c10.596,6.163,17.596,14.817,20.26,25.029v0.01c0.796,3.05,1.124,6.144,1.135,9.244v0.468h0.02 C473.668,365.851,449.763,390.814,415.677,399.923z">\n </path>\n </g>\n </g>\n </g>\n</svg>',dropupText:"Audio"},mixedFiles:{id:"upload-mixed-files-icon",svgString:'<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n<title>file</title>\n<path d="M20 10.9696L11.9628 18.5497C10.9782 19.4783 9.64274 20 8.25028 20C6.85782 20 5.52239 19.4783 4.53777 18.5497C3.55315 17.6211 3 16.3616 3 15.0483C3 13.7351 3.55315 12.4756 4.53777 11.547L12.575 3.96687C13.2314 3.34779 14.1217 3 15.05 3C15.9783 3 16.8686 3.34779 17.525 3.96687C18.1814 4.58595 18.5502 5.4256 18.5502 6.30111C18.5502 7.17662 18.1814 8.01628 17.525 8.63535L9.47904 16.2154C9.15083 16.525 8.70569 16.6989 8.24154 16.6989C7.77738 16.6989 7.33224 16.525 7.00403 16.2154C6.67583 15.9059 6.49144 15.4861 6.49144 15.0483C6.49144 14.6106 6.67583 14.1907 7.00403 13.8812L14.429 6.88674" stroke="#000000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>',dropupText:"File"}};class Hs extends Ji{constructor(t){"dropup-menu"===(null==t?void 0:t.position)&&(t.position="outside-right"),super(Hs.createMicrophoneElement(),null==t?void 0:t.position,t),this.isActive=!1,this._innerElements=this.createInnerElements(this._customStyles),this.changeToDefault()}createInnerElements(t){const e=Hs.createSVGIconElement();return{default:this.createInnerElement(e,"default",t),active:this.createInnerElement(e,"active",t),unsupported:this.createInnerElement(e,"unsupported",t),commandMode:this.createInnerElement(e,"commandMode",t)}}createInnerElement(t,e,i){return Di.createSpecificStateElement(this.elementRef,e,i)||t}static createMicrophoneElement(){const t=document.createElement("div");return t.id="microphone-button",t.classList.add("input-button"),t}static createSVGIconElement(){const t=Ze.createSVGElement(zi);return t.id="microphone-icon",t}changeToActive(){this.elementRef.replaceChildren(this._innerElements.active),this.toggleIconFilter("active"),this.reapplyStateStyle("active",["default","commandMode"]),this.isActive=!0}changeToDefault(){this.elementRef.replaceChildren(this._innerElements.default),this.toggleIconFilter("default"),this.reapplyStateStyle("default",["active","commandMode"]),this.isActive=!1}changeToCommandMode(){this.elementRef.replaceChildren(this._innerElements.unsupported),this.toggleIconFilter("command"),this.reapplyStateStyle("commandMode",["active"])}changeToUnsupported(){this.elementRef.replaceChildren(this._innerElements.unsupported),this.elementRef.classList.add("unsupported-microphone"),this.reapplyStateStyle("unsupported",["active"])}toggleIconFilter(t){const e=this.elementRef.children[0];if("svg"===e.tagName.toLocaleLowerCase())switch(t){case"default":e.classList.remove("active-microphone-icon","command-microphone-icon"),e.classList.add("default-microphone-icon");break;case"active":e.classList.remove("default-microphone-icon","command-microphone-icon"),e.classList.add("active-microphone-icon");break;case"command":e.classList.remove("active-microphone-icon","default-microphone-icon"),e.classList.add("command-microphone-icon")}}}function Ks(t){return t&&t.h&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Gs,Zs,Ws,Xs={},Ys={},Qs={},tn={},en={};function sn(){if(Gs)return en;Gs=1,Object.defineProperty(en,"h",{value:!0}),en.Text=void 0;class t{static capitalize(e){return e.replace(t.FIRST_CHAR_REGEX,(t=>t.toUpperCase()))}static lineBreak(e){return e.replace(t.DOUBLE_LINE,"<p></p>").replace(t.ONE_LINE,"<br>")}static isCharDefined(t){return void 0!==t&&" "!==t&&" "!==t&&"\n"!==t&&""!==t}static breakupIntoWordsArr(t){return t.split(/(\W+)/)}}return en.Text=t,t.FIRST_CHAR_REGEX=/\S/,t.DOUBLE_LINE=/\n\n/g,t.ONE_LINE=/\n/g,en}function nn(){if(Zs)return tn;Zs=1,Object.defineProperty(tn,"h",{value:!0}),tn.Translate=void 0;const t=sn();return tn.Translate=class{static translate(e,i){const s=t.Text.breakupIntoWordsArr(e);for(let t=0;t<s.length;t+=1)i[s[t]]&&(s[t]=i[s[t]]);return s.join("")}},tn}var on,rn={};function an(){if(on)return rn;on=1,Object.defineProperty(rn,"h",{value:!0}),rn.Browser=void 0;class t{}return rn.Browser=t,t.IS_SAFARI=()=>(void 0===t._IS_SAFARI&&(t._IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),t._IS_SAFARI),rn}var ln,cn={},hn={};var un,dn={};var pn,mn={},vn={};function fn(){if(pn)return vn;pn=1,Object.defineProperty(vn,"h",{value:!0}),vn.AutoScroll=void 0;class t{static changeStateIfNeeded(t,e){e&&!t.isCursorAtEnd&&(t.endPadding="",t.scrollingSpan.innerHTML="&nbsp;")}static scrollGeneric(t,e){t.isCursorAtEnd?e.scrollTop=e.scrollHeight:t.scrollingSpan.scrollIntoView({block:"nearest"})}static scrollSafariPrimitiveToEnd(t){t.scrollLeft=t.scrollWidth,t.scrollTop=t.scrollHeight}static isElementOverflown(t){return t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth}static isRequired(e,i){return e&&t.isElementOverflown(i)}}return vn.AutoScroll=t,vn}var gn,bn={};function yn(){if(gn)return bn;gn=1,Object.defineProperty(bn,"h",{value:!0}),bn.Elements=void 0;return bn.Elements=class{static isPrimitiveElement(t){return"INPUT"===t.tagName||"TEXTAREA"===t.tagName}static createInterimSpan(){const t=document.createElement("span");return t.style.color="grey",t.style.pointerEvents="none",t}static createGenericSpan(){const t=document.createElement("span");return t.style.pointerEvents="none",t}static appendSpans(t,e){if(t.spansPopulated=!0,t.insertInCursorLocation&&document.activeElement===e){const e=window.getSelection();if(null!=e&&e.focusNode){const i=e.getRangeAt(0);return i.insertNode(t.scrollingSpan),i.insertNode(t.interimSpan),i.insertNode(t.finalSpan),i.collapse(!1),e.removeAllRanges(),void e.addRange(i)}}e.appendChild(t.finalSpan),e.appendChild(t.interimSpan),e.appendChild(t.scrollingSpan)}static applyCustomColors(t,e){e.interim&&(t.interimSpan.style.color=e.interim),e.final&&(t.finalSpan.style.color=e.final)}static isInsideShadowDOM(t){return t.getRootNode()instanceof ShadowRoot}},bn}var wn,xn,kn={};function _n(){if(wn)return kn;wn=1,Object.defineProperty(kn,"h",{value:!0}),kn.Cursor=void 0;class t{static setOffsetForGeneric(e,i,s=0){let n=0;for(let o=0;o<e.childNodes.length;o+=1){const r=e.childNodes[o];if(r.childNodes.length>0){const e=t.setOffsetForGeneric(r,i,s);if(-1===e)return-1;s+=e}else if(null!==r.textContent){if(s+r.textContent.length>i){const t=document.createRange();t.setStart(r,i-s),t.collapse(!0);const n=window.getSelection();return null==n||n.removeAllRanges(),null==n||n.addRange(t),e.focus(),-1}s+=r.textContent.length,n+=r.textContent.length}}return n}static focusEndOfGeneric(t){const e=document.createRange();e.selectNodeContents(t),e.collapse(!1);const i=window.getSelection();i&&(i.removeAllRanges(),i.addRange(e))}static setOffsetForSafariGeneric(e,i){const s=window.getSelection();if(s){const n=t.getGenericElementCursorOffset(e,s,!0);t.setOffsetForGeneric(e,n+i)}}static setOffsetForPrimitive(t,e,i){i&&t.blur(),t.setSelectionRange(e,e),t.focus()}static getGenericElementCursorOffset(t,e,i){let s=0;if(e.rangeCount>0){const n=e.getRangeAt(0),o=n.cloneRange();o.selectNodeContents(t),i?o.setEnd(n.startContainer,n.startOffset):o.setEnd(n.endContainer,n.endOffset),s=o.toString().length}return s}}return kn.Cursor=t,kn}function Sn(){if(xn)return mn;xn=1,Object.defineProperty(mn,"h",{value:!0}),mn.CommandUtils=void 0;const t=fn(),e=yn(),i=an(),s=_n(),n=sn();class o{static processCommand(t,e){return(!e||!e.caseSensitive)&&(t=t.toLowerCase()),!1===(null==e?void 0:e.substrings)?n.Text.breakupIntoWordsArr(t):t}static process(t){var e;return!0===(null===(e=t.settings)||void 0===e?void 0:e.caseSensitive)?t:Object.keys(t).reduce(((e,i)=>{const s=t[i];return e[i]="string"==typeof s?o.processCommand(s,t.settings):s,e}),{})}static toggleCommandModeOn(t){var e;t.isWaitingForCommand=!0,null===(e=t.onCommandModeTrigger)||void 0===e||e.call(t,!0)}static toggleCommandModeOff(t){var e;t.isWaitingForCommand&&(null===(e=t.onCommandModeTrigger)||void 0===e||e.call(t,!1),t.isWaitingForCommand=!1)}static setText(n,r,a,l){o.toggleCommandModeOff(n),e.Elements.isPrimitiveElement(l)?(l.value=a,n.isTargetInShadow||s.Cursor.setOffsetForPrimitive(l,a.length,!0),i.Browser.IS_SAFARI()&&n.autoScroll&&t.AutoScroll.scrollSafariPrimitiveToEnd(l)):(l.textContent=a,n.isTargetInShadow||s.Cursor.focusEndOfGeneric(l),setTimeout((()=>t.AutoScroll.scrollGeneric(n,l)))),n.resetRecording(r)}static checkIfMatchesSubstring(t,e){return e.includes(t)}static checkIfMatchesWord(t,e,i){const s=t;for(let t=i.length-1;t>=0;t-=1){let e=t,n=s.length-1;for(;i[e]===s[n]&&n>=0;)e-=1,n-=1;if(n<0)return!0}return!1}static execCommand(t,e,i,s,r){var a,l,c;const h=t.commands;if(!h||!s||!i)return;const u=!0===(null===(a=h.settings)||void 0===a?void 0:a.caseSensitive)?e:e.toLowerCase(),d=n.Text.breakupIntoWordsArr(u),p=!1===(null===(l=h.settings)||void 0===l?void 0:l.substrings)?o.checkIfMatchesWord:o.checkIfMatchesSubstring;if(h.commandMode&&p(h.commandMode,u,d))return t.setInterimColorToFinal(),setTimeout((()=>o.toggleCommandModeOn(t))),{doNotProcessTranscription:!1};if(!h.commandMode||t.isWaitingForCommand){if(h.stop&&p(h.stop,u,d))return o.toggleCommandModeOff(t),setTimeout((()=>t.stop())),{doNotProcessTranscription:!1};if(h.pause&&p(h.pause,u,d))return o.toggleCommandModeOff(t),t.setInterimColorToFinal(),setTimeout((()=>{var e;t.isPaused=!0,null===(e=t.onPauseTrigger)||void 0===e||e.call(t,!0)})),{doNotProcessTranscription:!1};if(h.resume&&p(h.resume,u,d))return t.isPaused=!1,null===(c=t.onPauseTrigger)||void 0===c||c.call(t,!1),o.toggleCommandModeOff(t),t.resetRecording(i),{doNotProcessTranscription:!0};if(h.reset&&p(h.reset,u,d))return void 0!==r&&o.setText(t,i,r,s),{doNotProcessTranscription:!0};if(h.removeAllText&&p(h.removeAllText,u,d))return o.setText(t,i,"",s),{doNotProcessTranscription:!0}}}}return mn.CommandUtils=o,mn}var An,Tn={};var Mn,On,jn,Cn={};function En(){if(On)return cn;On=1,Object.defineProperty(cn,"h",{value:!0}),cn.Speech=void 0;const t=function(){if(ln)return hn;ln=1,Object.defineProperty(hn,"h",{value:!0}),hn.EventListeners=void 0;class t{static getElementIfFocusedOnAvailable(t,e){return Array.isArray(t)?t.find((t=>e===t)):e===t?t:void 0}static keyDownWindow(e){e.element&&t.getElementIfFocusedOnAvailable(e.element,document.activeElement)&&(null!==t.KEY_DOWN_TIMEOUT&&clearTimeout(t.KEY_DOWN_TIMEOUT),t.KEY_DOWN_TIMEOUT=setTimeout((()=>{t.KEY_DOWN_TIMEOUT=null,this.resetRecording(e)}),500))}static mouseDownWindow(e,i){this.mouseDownElement=t.getElementIfFocusedOnAvailable(e,i.target)}static mouseUpWindow(t){this.mouseDownElement&&this.resetRecording(t),this.mouseDownElement=void 0}static add(e,i){const s=void 0===(null==i?void 0:i.insertInCursorLocation)||(null==i?void 0:i.insertInCursorLocation);null!=i&&i.element&&s&&(e.mouseDownEvent=t.mouseDownWindow.bind(e,i.element),document.addEventListener("mousedown",e.mouseDownEvent),e.mouseUpEvent=t.mouseUpWindow.bind(e,i),document.addEventListener("mouseup",e.mouseUpEvent),e.keyDownEvent=t.keyDownWindow.bind(e,i),document.addEventListener("keydown",e.keyDownEvent))}static remove(t){document.removeEventListener("mousedown",t.mouseDownEvent),document.removeEventListener("mouseup",t.mouseUpEvent),document.removeEventListener("keydown",t.keyDownEvent)}}return hn.EventListeners=t,t.KEY_DOWN_TIMEOUT=null,hn}(),e=(un||(un=1,Object.defineProperty(dn,"h",{value:!0}),dn.PreResultUtils=void 0,dn.PreResultUtils=class{static process(t,e,i,s,n){const o=null==s?void 0:s(e,i);return!!o&&(setTimeout((()=>{o.restart?t.resetRecording(n):o.stop&&t.stop()})),(o.stop||o.restart)&&o.removeNewText)}}),dn),i=Sn(),s=fn(),n=function(){if(An)return Tn;An=1,Object.defineProperty(Tn,"h",{value:!0}),Tn.Highlight=void 0;const t=yn(),e=_n();class i{static setStateForPrimitive(t,e){let i,s;null!==e.selectionStart&&(i=e.selectionStart),null!==e.selectionEnd&&(s=e.selectionEnd),t.isHighlighted=i!==s}static setStateForGeneric(t,i){const s=window.getSelection();if(null!=s&&s.focusNode){const n=e.Cursor.getGenericElementCursorOffset(i,s,!0),o=e.Cursor.getGenericElementCursorOffset(i,s,!1);t.isHighlighted=n!==o}}static setState(e,s){document.activeElement===s&&(t.Elements.isPrimitiveElement(s)?i.setStateForPrimitive(e,s):i.setStateForGeneric(e,s))}static removeForGeneric(t,i){const s=window.getSelection();if(s){const n=e.Cursor.getGenericElementCursorOffset(i,s,!0);s.deleteFromDocument(),e.Cursor.setOffsetForGeneric(i,n),t.isHighlighted=!1}}static removeForPrimitive(t,i){const s=i.selectionStart,n=i.selectionEnd,o=i.value;if(s&&n){const r=o.substring(0,s)+o.substring(n);i.value=r,e.Cursor.setOffsetForPrimitive(i,s,t.autoScroll)}t.isHighlighted=!1}}return Tn.Highlight=i,Tn}(),o=yn(),r=function(){if(Mn)return Cn;Mn=1,Object.defineProperty(Cn,"h",{value:!0}),Cn.Padding=void 0;const t=yn(),e=_n(),i=sn();class s{static setStateForPrimitiveElement(t,e){if(document.activeElement===e&&null!==e.selectionStart){const s=e.selectionStart,n=e.value[s-1],o=null===e.selectionEnd?s:e.selectionEnd,r=e.value[o];return i.Text.isCharDefined(n)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),i.Text.isCharDefined(r)&&(t.endPadding=" ",t.numberOfSpacesAfterNewText=1),void(t.isCursorAtEnd=e.value.length===o)}const s=e.value[e.value.length-1];i.Text.isCharDefined(s)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),t.isCursorAtEnd=!0}static setStateForGenericElement(t,s){var n,o,r;if(document.activeElement===s){const a=window.getSelection();if(null!=a&&a.focusNode){const l=e.Cursor.getGenericElementCursorOffset(s,a,!0),c=null===(n=s.textContent)||void 0===n?void 0:n[l-1],h=e.Cursor.getGenericElementCursorOffset(s,a,!1),u=null===(o=s.textContent)||void 0===o?void 0:o[h];return i.Text.isCharDefined(c)&&(t.startPadding=" "),i.Text.isCharDefined(u)&&(t.endPadding=" "),void(t.isCursorAtEnd=(null===(r=s.textContent)||void 0===r?void 0:r.length)===h)}}const a=s.innerText.charAt(s.innerText.length-1);i.Text.isCharDefined(a)&&(t.startPadding=" "),t.isCursorAtEnd=!0}static setState(e,i){t.Elements.isPrimitiveElement(i)?s.setStateForPrimitiveElement(e,i):s.setStateForGenericElement(e,i)}static adjustStateAfterRecodingPrimitiveElement(t,e){t.primitiveTextRecorded=!0,t.insertInCursorLocation&&document.activeElement===e&&(null!==e.selectionEnd&&(t.endPadding=t.endPadding+e.value.slice(e.selectionEnd)),null!==e.selectionStart)?t.startPadding=e.value.slice(0,e.selectionStart)+t.startPadding:t.startPadding=e.value+t.startPadding}static adjustSateForNoTextPrimitiveElement(t){1===t.numberOfSpacesBeforeNewText&&(t.startPadding=t.startPadding.substring(0,t.startPadding.length-1),t.numberOfSpacesBeforeNewText=0),1===t.numberOfSpacesAfterNewText&&(t.endPadding=t.endPadding.substring(1),t.numberOfSpacesAfterNewText=0)}}return Cn.Padding=s,Cn}(),a=an(),l=_n(),c=sn();return cn.Speech=class{constructor(){this.finalTranscript="",this.interimSpan=o.Elements.createInterimSpan(),this.finalSpan=o.Elements.createGenericSpan(),this.scrollingSpan=o.Elements.createGenericSpan(),this.isCursorAtEnd=!1,this.spansPopulated=!1,this.startPadding="",this.endPadding="",this.numberOfSpacesBeforeNewText=0,this.numberOfSpacesAfterNewText=0,this.isHighlighted=!1,this.primitiveTextRecorded=!1,this.recognizing=!1,this._displayInterimResults=!0,this.insertInCursorLocation=!0,this.autoScroll=!0,this.isRestarting=!1,this.isPaused=!1,this.isWaitingForCommand=!1,this.isTargetInShadow=!1,this.cannotBeStopped=!1,this.resetState()}prepareBeforeStart(e){var s,n;if(null!=e&&e.element)if(t.EventListeners.add(this,e),Array.isArray(e.element)){const t=e.element.find((t=>t===document.activeElement))||e.element[0];if(!t)return;this.prepare(t)}else this.prepare(e.element);void 0!==(null==e?void 0:e.displayInterimResults)&&(this._displayInterimResults=e.displayInterimResults),null!=e&&e.textColor&&(this._finalTextColor=null===(s=null==e?void 0:e.textColor)||void 0===s?void 0:s.final,o.Elements.applyCustomColors(this,e.textColor)),void 0!==(null==e?void 0:e.insertInCursorLocation)&&(this.insertInCursorLocation=e.insertInCursorLocation),void 0!==(null==e?void 0:e.autoScroll)&&(this.autoScroll=e.autoScroll),this._onResult=null==e?void 0:e.onResult,this._onPreResult=null==e?void 0:e.onPreResult,this._onStart=null==e?void 0:e.onStart,this._onStop=null==e?void 0:e.onStop,this._onError=null==e?void 0:e.onError,this.onCommandModeTrigger=null==e?void 0:e.onCommandModeTrigger,this.onPauseTrigger=null==e?void 0:e.onPauseTrigger,this._options=e,null!==(n=this._options)&&void 0!==n&&n.commands&&(this.commands=i.CommandUtils.process(this._options.commands))}prepare(t){r.Padding.setState(this,t),n.Highlight.setState(this,t),this.isTargetInShadow=o.Elements.isInsideShadowDOM(t),o.Elements.isPrimitiveElement(t)?(this._primitiveElement=t,this._originalText=this._primitiveElement.value):(this._genericElement=t,this._originalText=this._genericElement.textContent)}resetRecording(t){this.isRestarting=!0,this.stop(!0),this.resetState(!0),this.start(t,!0)}updateElements(t,s,n){var o;const r=c.Text.capitalize(s);if(this.finalTranscript===r&&""===t)return;e.PreResultUtils.process(this,n,""===t,this._onPreResult,this._options)&&(t="",n="");const a=this.commands&&i.CommandUtils.execCommand(this,n,this._options,this._primitiveElement||this._genericElement,this._originalText);if(a){if(a.doNotProcessTranscription)return;t="",n=""}if(this.isPaused||this.isWaitingForCommand)return;null===(o=this._onResult)||void 0===o||o.call(this,n,""===t),this.finalTranscript=r,this._displayInterimResults||(t="");const l=""===this.finalTranscript&&""===t;this._primitiveElement?this.updatePrimitiveElement(this._primitiveElement,t,l):this._genericElement&&this.updateGenericElement(this._genericElement,t,l)}updatePrimitiveElement(t,e,i){this.isHighlighted&&n.Highlight.removeForPrimitive(this,t),this.primitiveTextRecorded||r.Padding.adjustStateAfterRecodingPrimitiveElement(this,t),i&&r.Padding.adjustSateForNoTextPrimitiveElement(this);const o=this.startPadding+this.finalTranscript+e;if(t.value=o+this.endPadding,!this.isTargetInShadow){const e=o.length+this.numberOfSpacesAfterNewText;l.Cursor.setOffsetForPrimitive(t,e,this.autoScroll)}this.autoScroll&&a.Browser.IS_SAFARI()&&this.isCursorAtEnd&&s.AutoScroll.scrollSafariPrimitiveToEnd(t)}updateGenericElement(t,e,i){this.isHighlighted&&n.Highlight.removeForGeneric(this,t),this.spansPopulated||o.Elements.appendSpans(this,t);const r=(i?"":this.startPadding)+c.Text.lineBreak(this.finalTranscript);this.finalSpan.innerHTML=r;const h=s.AutoScroll.isRequired(this.autoScroll,t);s.AutoScroll.changeStateIfNeeded(this,h);const u=c.Text.lineBreak(e)+(i?"":this.endPadding);this.interimSpan.innerHTML=u,a.Browser.IS_SAFARI()&&this.insertInCursorLocation&&l.Cursor.setOffsetForSafariGeneric(t,r.length+u.length),h&&s.AutoScroll.scrollGeneric(this,t),i&&(this.scrollingSpan.innerHTML="")}finalise(e){this._genericElement&&(e?(this.finalSpan=o.Elements.createGenericSpan(),this.setInterimColorToFinal(),this.interimSpan=o.Elements.createInterimSpan(),this.scrollingSpan=o.Elements.createGenericSpan()):this._genericElement.textContent=this._genericElement.textContent,this.spansPopulated=!1),t.EventListeners.remove(this)}setInterimColorToFinal(){this.interimSpan.style.color=this._finalTextColor||"black"}resetState(t){this._primitiveElement=void 0,this._genericElement=void 0,this.finalTranscript="",this.finalSpan.innerHTML="",this.interimSpan.innerHTML="",this.scrollingSpan.innerHTML="",this.startPadding="",this.endPadding="",this.isHighlighted=!1,this.primitiveTextRecorded=!1,this.numberOfSpacesBeforeNewText=0,this.numberOfSpacesAfterNewText=0,t||(this.stopTimeout=void 0)}setStateOnStart(){var t;this.recognizing=!0,this.isRestarting?this.isRestarting=!1:null===(t=this._onStart)||void 0===t||t.call(this)}setStateOnStop(){var t;this.recognizing=!1,this.isRestarting||null===(t=this._onStop)||void 0===t||t.call(this)}setStateOnError(t){var e;null===(e=this._onError)||void 0===e||e.call(this,t),this.recognizing=!1}},cn}function In(){if(jn)return Ys;jn=1,Object.defineProperty(Ys,"h",{value:!0}),Ys.WebSpeech=void 0;const t=function(){if(Ws)return Qs;Ws=1,Object.defineProperty(Qs,"h",{value:!0}),Qs.WebSpeechTranscript=void 0;const t=nn();return Qs.WebSpeechTranscript=class{static extract(e,i,s){let n="";for(let o=e.resultIndex;o<e.results.length;++o){let r=e.results[o][0].transcript;s&&(r=t.Translate.translate(r,s)),e.results[o].isFinal?i+=r:n+=r}return{interimTranscript:n,finalTranscript:i,newText:n||i}}static extractSafari(e,i,s){let n="";for(let i=e.resultIndex;i<e.results.length;++i){let o=e.results[i][0].transcript;s&&(o=t.Translate.translate(o,s)),n+=o}return{interimTranscript:"",finalTranscript:n,newText:n}}},Qs}(),e=an(),i=En();class s extends i.Speech{constructor(){super()}start(i){var s;void 0===this._extractText&&(this._extractText=e.Browser.IS_SAFARI()?t.WebSpeechTranscript.extractSafari:t.WebSpeechTranscript.extract),this.validate()&&(this.prepareBeforeStart(i),this.instantiateService(i),null===(s=this._service)||void 0===s||s.start(),this._translations=null==i?void 0:i.translations)}validate(){return!!s.getAPI()||(this.error("Speech Recognition is unsupported"),!1)}instantiateService(t){var e,i;const n=s.getAPI();this._service=new n,this._service.continuous=!0,this._service.interimResults=null===(e=null==t?void 0:t.displayInterimResults)||void 0===e||e,this._service.lang=(null===(i=null==t?void 0:t.language)||void 0===i?void 0:i.trim())||"en-US",this.setEvents()}setEvents(){this._service&&(this._service.onstart=()=>{this.setStateOnStart()},this._service.onerror=t=>{e.Browser.IS_SAFARI()&&"Another request is started"===t.message||"aborted"===t.error&&this.isRestarting||"no-speech"!==t.error&&this.error(t.message||t.error)},this._service.onaudioend=()=>{this.setStateOnStop()},this._service.onend=()=>{this._stopping=!1},this._service.onresult=t=>{if(typeof t.results>"u"&&this._service)this._service.onend=null,this._service.stop();else if(this._extractText&&!this._stopping){const{interimTranscript:e,finalTranscript:i,newText:s}=this._extractText(t,this.finalTranscript,this._translations);this.updateElements(e,i,s)}})}stop(t){var e;this._stopping=!0,null===(e=this._service)||void 0===e||e.stop(),this.finalise(t)}static getAPI(){return window.webkitSpeechRecognition||window.SpeechRecognition}error(t){console.error(t),this.setStateOnError(t),this.stop()}}return Ys.WebSpeech=s,Ys}var Pn,Nn={};var Rn,qn={},Bn={};var Ln,Fn,zn={},Dn={};function $n(){if(Fn)return zn;Fn=1,Object.defineProperty(zn,"h",{value:!0}),zn.AzureSpeechConfig=void 0;const t=(Ln||(Ln=1,Object.defineProperty(Dn,"h",{value:!0}),Dn.README_URL=void 0,Dn.README_URL="https://github.com/OvidijusParsiunas/speech-to-element"),Dn);class e{static validateOptions(e,i){return i?i.subscriptionKey||i.token||i.retrieveToken?!!i.region||(e(`Please define a 'region' property - more info: ${t.README_URL}`),!1):(e(`Please define a 'subscriptionKey', 'token' or 'retrieveToken' property - more info: ${t.README_URL}`),!1):(e(`Please provide subscription details - more info: ${t.README_URL}`),!1)}static async getNewSpeechConfig(t,e){if(e.region)return e.subscriptionKey?t.fromSubscription(e.subscriptionKey.trim(),e.region.trim()):e.token?t.fromAuthorizationToken(e.token.trim(),e.region.trim()):e.retrieveToken?e.retrieveToken().then((i=>e.region?t.fromAuthorizationToken((null==i?void 0:i.trim())||"",e.region.trim()):null)).catch((t=>(console.error(t),null))):null}static process(t,e){e.endpointId&&(t.endpointId=e.endpointId.trim()),e.language&&(t.speechRecognitionLanguage=e.language.trim())}static async get(t,i){const s=await e.getNewSpeechConfig(t,i);return s&&e.process(s,i),s}}return zn.AzureSpeechConfig=e,zn}var Jn,Un={};var Vn,Hn={};var Kn,Gn,Zn,Wn={};function Xn(){if(Gn)return qn;Gn=1,Object.defineProperty(qn,"h",{value:!0}),qn.Azure=void 0;const t=(Rn||(Rn=1,Object.defineProperty(Bn,"h",{value:!0}),Bn.PreventConnectionStop=void 0,Bn.PreventConnectionStop=class{static applyPrevention(t){clearTimeout(t._manualConnectionStopPrevention),t.cannotBeStopped=!0,t._manualConnectionStopPrevention=setTimeout((()=>{t.cannotBeStopped=!1}),800)}static clearPrevention(t){clearTimeout(t._manualConnectionStopPrevention),t.cannotBeStopped=!1}}),Bn),e=$n(),i=function(){if(Jn)return Un;Jn=1,Object.defineProperty(Un,"h",{value:!0}),Un.StopTimeout=void 0;class t{static set(t){t.stopTimeout=setTimeout((()=>t.stop()),t.stopTimeoutMS)}static reset(e,i){e.stopTimeoutMS=i||t.DEFAULT_MS,t.stop(e),t.set(e)}static stop(t){t.stopTimeout&&clearTimeout(t.stopTimeout)}}return Un.StopTimeout=t,t.DEFAULT_MS=2e4,Un}(),s=(Vn||(Vn=1,Object.defineProperty(Hn,"h",{value:!0}),Hn.AzureAudioConfig=void 0,Hn.AzureAudioConfig=class{static get(t,e){return e?t.fromMicrophoneInput(e):t.fromDefaultMicrophoneInput()}}),Hn),n=function(){if(Kn)return Wn;Kn=1,Object.defineProperty(Wn,"h",{value:!0}),Wn.AzureTranscript=void 0;const t=nn();return Wn.AzureTranscript=class{static extract(e,i,s,n){return n&&(e=t.Translate.translate(e,n)),s?{interimTranscript:"",finalTranscript:i+e,newText:e}:{interimTranscript:e,finalTranscript:i,newText:e}}},Wn}(),o=En();class r extends o.Speech{constructor(){super(...arguments),this._newTextPadding=""}start(e,s){this._newTextPadding="",void 0===this.stopTimeout&&i.StopTimeout.reset(this,null==e?void 0:e.stopAfterSilenceMs),this.prepareBeforeStart(e),this.startAsync(e),s||t.PreventConnectionStop.applyPrevention(this)}async startAsync(t){var e;this.validate(t)&&(await this.instantiateService(t),this._translations=null==t?void 0:t.translations,null===(e=this._service)||void 0===e||e.startContinuousRecognitionAsync((()=>{}),this.error))}validate(t){return r.getAPI()?e.AzureSpeechConfig.validateOptions(this.error.bind(this),t):(this.moduleNotFound(),!1)}async instantiateService(t){const i=r.getAPI(),n=s.AzureAudioConfig.get(i.AudioConfig,t.deviceId),o=await e.AzureSpeechConfig.get(i.SpeechConfig,t);if(o){let e;if(t.autoLanguage&&t.autoLanguage.languages.length>0){const{type:s,languages:r}=t.autoLanguage,a=r.slice(0,"Continuous"===s?10:4),l=i.AutoDetectSourceLanguageConfig.fromLanguages(a);"Continuous"===s&&(l.mode=1),e=i.SpeechRecognizer.FromConfig(o,l,n)}else e=new i.SpeechRecognizer(o,n);this.setEvents(e),this._service=e,t.retrieveToken&&this.retrieveTokenInterval(t.retrieveToken)}else this.error("Unable to contact Azure server")}setEvents(t){t.recognizing=this.onRecognizing.bind(this),t.recognized=this.onRecognized.bind(this),t.sessionStarted=this.onSessionStarted.bind(this),t.canceled=this.onCanceled.bind(this),t.sessionStopped=this.onSessionStopped.bind(this)}onRecognizing(t,e){if(this._stopping)return;const{interimTranscript:s,finalTranscript:o,newText:r}=n.AzureTranscript.extract(this._newTextPadding+e.result.text,this.finalTranscript,!1,this._translations);i.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(s,o,r)}onRecognized(t,e){const s=e.result;switch(s.reason){case window.SpeechSDK.ResultReason.Canceled:break;case window.SpeechSDK.ResultReason.RecognizedSpeech:if(s.text&&!this._stopping){const{interimTranscript:t,finalTranscript:e,newText:o}=n.AzureTranscript.extract(this._newTextPadding+s.text,this.finalTranscript,!0,this._translations);i.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(t,e,o),""!==e&&(this._newTextPadding=" ")}}}onCanceled(t,e){e.reason===window.SpeechSDK.CancellationReason.Error&&this.error(e.errorDetails)}onSessionStarted(){t.PreventConnectionStop.clearPrevention(this),this.setStateOnStart()}onSessionStopped(){this._retrieveTokenInterval||clearInterval(this._retrieveTokenInterval),this._stopping=!1,this.setStateOnStop()}retrieveTokenInterval(t){this._retrieveTokenInterval=setInterval((()=>{null==t||t().then((t=>{this._service&&(this._service.authorizationToken=(null==t?void 0:t.trim())||"")})).catch((t=>{this.error(t)}))}),1e4)}stop(t){var e;!t&&this._retrieveTokenInterval&&clearInterval(this._retrieveTokenInterval),this._stopping=!0,null===(e=this._service)||void 0===e||e.stopContinuousRecognitionAsync(),i.StopTimeout.stop(this),this.finalise(t)}static getAPI(){return window.SpeechSDK}moduleNotFound(){console.error("speech recognition module not found:"),console.error("please install the 'microsoft-cognitiveservices-speech-sdk' npm package or add a script tag: <script src=\"https://aka.ms/csspeech/jsbrowserpackageraw\"><\/script>"),this.setStateOnError("speech recognition module not found")}error(t){this._retrieveTokenInterval&&clearInterval(this._retrieveTokenInterval),console.error(t),this.setStateOnError(t),this.stop()}}return qn.Azure=r,qn}const Yn=Ks(function(){if(Zn)return Xs;Zn=1,Object.defineProperty(Xs,"h",{value:!0});const t=In(),e=Sn(),i=function(){if(Pn)return Nn;Pn=1,Object.defineProperty(Nn,"h",{value:!0}),Nn.GlobalState=void 0;class t{static doubleClickDetector(){return!!t.doubleClickPending||(t.doubleClickPending=!0,setTimeout((()=>{t.doubleClickPending=!1}),300),!1)}}return Nn.GlobalState=t,t.doubleClickPending=!1,Nn}(),s=Xn();class n{static toggle(t,e){var s,o;const r=t.toLocaleLowerCase().trim();null!==(s=i.GlobalState.service)&&void 0!==s&&s.recognizing?this.stop():"webspeech"===r?n.startWebSpeech(e):"azure"===r?n.startAzure(e):(console.error("service not found - must be either 'webspeech' or 'azure'"),null===(o=null==e?void 0:e.onError)||void 0===o||o.call(e,"service not found - must be either 'webspeech' or 'azure'"))}static startWebSpeech(e){n.stop()||(i.GlobalState.service=new t.WebSpeech,i.GlobalState.service.start(e))}static isWebSpeechSupported(){return!!t.WebSpeech.getAPI()}static startAzure(t){var e;n.stop()||null!==(e=i.GlobalState.service)&&void 0!==e&&e.cannotBeStopped||(i.GlobalState.service=new s.Azure,i.GlobalState.service.start(t))}static stop(){var t;return!!i.GlobalState.doubleClickDetector()||(!(null===(t=i.GlobalState.service)||void 0===t)&&t.recognizing&&i.GlobalState.service.stop(),!1)}static endCommandMode(){i.GlobalState.service&&e.CommandUtils.toggleCommandModeOff(i.GlobalState.service)}}return Xs.default=n,Xs}());class Qn{constructor(t,e){this.silenceMS=2e3,this.stop=!0,"boolean"==typeof e&&!1===e&&(this.stop=!1),"number"==typeof t&&(this.silenceMS=t)}setSilenceTimeout(t,e){this._silenceTimeout=setTimeout((()=>{var i;null==(i=t.submit)||i.call(t),Yn.stop(),this.stop||setTimeout(e,eo.MICROPHONE_RESET_TIMEOUT_MS)}),this.silenceMS)}clearSilenceTimeout(){this._silenceTimeout&&clearTimeout(this._silenceTimeout)}resetSilenceTimeout(t,e){this.clearSilenceTimeout(),this.setSilenceTimeout(t,e)}onPause(t,e,i){t?this.resetSilenceTimeout(e,i):this.clearSilenceTimeout()}}const to=class t extends Hs{constructor(t,e,i){const s="object"==typeof t.speechToText?t.speechToText:{};super(null==s?void 0:s.button);const{serviceName:n,processedConfig:o}=this.processConfiguration(e,t.speechToText);if(this._addErrorMessage=i,"webspeech"!==n||Yn.isWebSpeechSupported()){const i=!t.textInput||!t.textInput.disabled;this.elementRef.onclick=this.buttonClick.bind(this,e,i,n,o)}else this.changeToUnsupported();setTimeout((()=>{this._validationHandler=t._validationHandler}))}processConfiguration(e,i){var s;const n="object"==typeof i?i:{},o="object"==typeof n.webSpeech?n.webSpeech:{},r=n.azure||{},a={displayInterimResults:n.displayInterimResults??void 0,textColor:n.textColor??void 0,translations:n.translations??void 0,commands:n.commands??void 0,events:n.events??void 0,...o,...r},l=null==(s=n.commands)?void 0:s.submit;return l&&(a.onPreResult=t=>t.toLowerCase().includes(l)?(setTimeout((()=>{var t;return null==(t=e.submit)?void 0:t.call(e)})),Yn.endCommandMode(),{restart:!0,removeNewText:!0}):null),n.submitAfterSilence&&(this._silenceSubmit=new Qn(n.submitAfterSilence,n.stopAfterSubmit)),{serviceName:t.getServiceName(n),processedConfig:a}}static getServiceName(t){return t.azure?"azure":"webspeech"}buttonClick(t,e,i,s){const n=null==s?void 0:s.events;t.removePlaceholderStyle(),Yn.toggle(i,{insertInCursorLocation:!1,element:e?t.inputElementRef:void 0,onError:()=>{var t;this.onError(),null==(t=this._silenceSubmit)||t.clearSilenceTimeout()},onStart:()=>{var t;this.changeToActive(),null==(t=null==n?void 0:n.onStart)||t.call(n)},onStop:()=>{var t,e,i;null==(t=this._validationHandler)||t.call(this),null==(e=this._silenceSubmit)||e.clearSilenceTimeout(),this.changeToDefault(),null==(i=null==n?void 0:n.onStop)||i.call(n)},onPauseTrigger:e=>{var i,s;null==(i=this._silenceSubmit)||i.onPause(e,t,this.elementRef.onclick),null==(s=null==n?void 0:n.onPauseTrigger)||s.call(n,e)},onPreResult:(t,e)=>{var i;null==(i=null==n?void 0:n.onPreResult)||i.call(n,t,e)},onResult:(e,i)=>{var s,o,r;i&&(null==(s=this._validationHandler)||s.call(this)),null==(o=this._silenceSubmit)||o.resetSilenceTimeout(t,this.elementRef.onclick),null==(r=null==n?void 0:n.onResult)||r.call(n,e,i)},onCommandModeTrigger:t=>{var e;this.onCommandModeTrigger(t),null==(e=null==n?void 0:n.onCommandModeTrigger)||e.call(n,t)},...s})}onCommandModeTrigger(t){t?this.changeToCommandMode():this.changeToActive()}onError(){this._addErrorMessage("speechToText","speech input error")}static toggleSpeechAfterSubmit(e,i=!0){e.click(),i||setTimeout((()=>e.click()),t.MICROPHONE_RESET_TIMEOUT_MS)}};to.MICROPHONE_RESET_TIMEOUT_MS=300;let eo=to;class io{constructor(t,e,i,s){this._attachments=[],this._fileCountLimit=99,this._acceptedFormat="",e.maxNumberOfFiles&&(this._fileCountLimit=e.maxNumberOfFiles),this._toggleContainerDisplay=i,this._fileAttachmentsContainerRef=s,e.acceptedFormats&&(this._acceptedFormat=e.acceptedFormats),setTimeout((()=>{this._validationHandler=t._validationHandler}))}attemptAddFile(t,e){return!!io.isFileTypeValid(t,this._acceptedFormat)&&(this.addAttachmentBasedOnType(t,e,!0),!0)}static isFileTypeValid(t,e){if(""===e)return!0;const i=e.split(",");for(let e=0;e<i.length;e++){const s=i[e].trim();if(t.type===s)return!0;if(s.startsWith(".")){const e=s.slice(1);if(t.name.endsWith(e))return!0}else{if(t.name.endsWith(s))return!0;if(s.endsWith("/*")&&t.type.startsWith(s.slice(0,-2)))return!0}}return!1}static getTypeFromBlob(t){const{type:e}=t;return e.startsWith("image")?"image":e.startsWith("audio")?"audio":"any"}addAttachmentBasedOnType(t,e,i){const s=io.getTypeFromBlob(t);if("image"===s){const s=io.createImageAttachment(e);this.addFileAttachment(t,"image",s,i)}else if("audio"===s){const s=no.createAudioAttachment(e);this.addFileAttachment(t,"audio",s,i)}else{const e=io.createAnyFileAttachment(t.name);this.addFileAttachment(t,"any",e,i)}}static createImageAttachment(t){const e=new Image;return e.src=t,e.classList.add("image-attachment"),e}static createAnyFileAttachment(t){const e=document.createElement("div");e.classList.add("border-bound-attachment"),l.IS_SAFARI&&e.classList.add("border-bound-attachment-safari");const i=document.createElement("div");i.classList.add("any-file-attachment-text");const s=document.createElement("div");return s.classList.add("file-attachment-text-container"),s.appendChild(i),i.textContent=t,e.appendChild(s),e}addFileAttachment(t,e,i,s){var n;const o=io.createContainer(i);if(this._attachments.length>=this._fileCountLimit){const t=this._attachments[this._attachments.length-1].removeButton;null==t||t.click();const e=this._fileAttachmentsContainerRef.children;this._fileAttachmentsContainerRef.insertBefore(o,e[0])}else this._fileAttachmentsContainerRef.appendChild(o);const r={file:t,attachmentContainerElement:o,fileType:e};return s&&(r.removeButton=this.createRemoveAttachmentButton(r),o.appendChild(r.removeButton)),this._toggleContainerDisplay(!0),this._attachments.push(r),this._fileAttachmentsContainerRef.scrollTop=this._fileAttachmentsContainerRef.scrollHeight,null==(n=this._validationHandler)||n.call(this),r}static createContainer(t){const e=document.createElement("div");return e.classList.add("file-attachment"),e.appendChild(t),e}createRemoveAttachmentButton(t){const e=document.createElement("div");e.classList.add("remove-file-attachment-button"),e.onclick=this.removeAttachment.bind(this,t);const i=document.createElement("div");return i.classList.add("x-icon"),i.innerText="×",e.appendChild(i),e}removeAttachment(t){var e;const i=this._attachments.findIndex((e=>e===t)),s=this._attachments[i].attachmentContainerElement;this._attachments.splice(i,1),no.stopAttachmentPlayback(s),s.remove(),this._toggleContainerDisplay(!1),null==(e=this._validationHandler)||e.call(this)}getFiles(){return Array.from(this._attachments).map((t=>({file:t.file,type:t.fileType})))}removeAllAttachments(){this._attachments.forEach((t=>{setTimeout((()=>{var e;return null==(e=t.removeButton)?void 0:e.click()}))}))}}const so=class t extends io{constructor(t,e,i,s){super(t,e,i,s)}static createAudioContainer(){const t=document.createElement("div");return t.classList.add("border-bound-attachment","audio-attachment-icon-container"),l.IS_SAFARI&&t.classList.add("border-bound-attachment-safari"),t}static addAudioElements(t,e){const i=t.parentElement?x.cloneElement(t):t,s=document.createElement("audio");s.src=e;const n=Ze.createSVGElement(Ki);n.classList.add("attachment-icon","play-icon");const o=Ze.createSVGElement(Gi);o.classList.add("attachment-icon","stop-icon"),i.replaceChildren(n),s.onplay=()=>{i.replaceChildren(o)},s.onpause=()=>{i.replaceChildren(n),s.currentTime=0},s.onended=()=>{i.replaceChildren(n)},i.onclick=()=>{s.paused?s.play():s.pause()}}static createAudioAttachment(e){const i=t.createAudioContainer();return t.addAudioElements(i,e),i}createTimer(e,i){let s=0;const n=void 0!==i&&i<t.TIMER_LIMIT_S?i:t.TIMER_LIMIT_S;return setInterval((()=>{var t;s+=1,s===n&&(null==(t=this.stopPlaceholderCallback)||t.call(this),this.clearTimer()),600===s&&e.classList.add("audio-placeholder-text-4-digits");const i=Math.floor(s/60),o=(s%60).toString().padStart(2,"0");e.textContent=`${i}:${o}`}),1e3)}createPlaceholderAudioAttachment(e){const i=t.createAudioContainer(),s=document.createElement("div");s.classList.add("audio-placeholder-text-3-digits");const n=document.createElement("div");n.classList.add("file-attachment-text-container","audio-placeholder-text-3-digits-container"),n.appendChild(s);const o=Ze.createSVGElement(Gi);return o.classList.add("attachment-icon","stop-icon","not-removable-attachment-icon"),s.textContent="0:00",this._activePlaceholderTimer=this.createTimer(s,e),i.appendChild(n),this.addPlaceholderAudioAttachmentEvents(i,o,n),i}addPlaceholderAudioAttachmentEvents(t,e,i){t.addEventListener("mouseenter",(()=>t.replaceChildren(e)));t.addEventListener("mouseleave",(()=>t.replaceChildren(i)));t.addEventListener("click",(()=>{var t;return null==(t=this.stopPlaceholderCallback)?void 0:t.call(this)}))}addPlaceholderAttachment(t,e){const i=this.createPlaceholderAudioAttachment(e);this._activePlaceholderAttachment=this.addFileAttachment(new File([],""),"audio",i,!1),this.stopPlaceholderCallback=t}completePlaceholderAttachment(e,i){const s=this._activePlaceholderAttachment;s&&(s.file=e,t.addAudioElements(s.attachmentContainerElement.children[0],i),s.removeButton=this.createRemoveAttachmentButton(s),s.attachmentContainerElement.appendChild(s.removeButton),this._activePlaceholderAttachment=void 0,this.clearTimer())}removePlaceholderAttachment(){this._activePlaceholderAttachment&&(this.removeAttachment(this._activePlaceholderAttachment),this._activePlaceholderAttachment=void 0,this.clearTimer())}clearTimer(){void 0!==this._activePlaceholderTimer&&(clearInterval(this._activePlaceholderTimer),this._activePlaceholderTimer=void 0,this.stopPlaceholderCallback=void 0)}static stopAttachmentPlayback(t){var e,i,s;null!=(s=null==(i=null==(e=t.children[0])?void 0:e.children)?void 0:i[0])&&s.classList.contains("stop-icon")&&t.children[0].click()}};so.TIMER_LIMIT_S=5999;let no=so;class oo{static create(t,e,i,s,n){return"audio"===n?new no(t,e,i,s):new io(t,e,i,s)}}class ro{constructor(t,e,i){this._fileAttachmentsTypes=[],this.elementRef=this.createAttachmentContainer();const s="object"==typeof i&&!!i.displayFileAttachmentContainer;this.toggleContainerDisplay(s),t.appendChild(this.elementRef),e&&Object.assign(this.elementRef.style,e)}addType(t,e,i){const s=oo.create(t,e,this.toggleContainerDisplay.bind(this),this.elementRef,i);return this._fileAttachmentsTypes.push(s),s}createAttachmentContainer(){const t=document.createElement("div");return t.id="file-attachment-container",t}toggleContainerDisplay(t){t?this.elementRef.style.display="block":0===this.elementRef.children.length&&(this.elementRef.style.display="none")}getAllFileData(){const t=this._fileAttachmentsTypes.map((t=>t.getFiles())).flat();return t.length>0?t:void 0}async completePlaceholders(){await Promise.all(this._fileAttachmentsTypes.map((async t=>{var e;return null==(e=t.stopPlaceholderCallback)?void 0:e.call(t)})))}static addFilesToType(t,e){t.forEach((t=>{const i=new FileReader;i.readAsDataURL(t),i.onload=i=>{for(let s=0;s<e.length&&!e[s].attemptAddFile(t,i.target.result);s+=1);}}))}addFilesToAnyType(t){ro.addFilesToType(t,this._fileAttachmentsTypes)}removeAllFiles(){this._fileAttachmentsTypes.forEach((t=>t.removeAllAttachments())),this.elementRef.replaceChildren(),this.toggleContainerDisplay(!1)}getNumberOfTypes(){return this._fileAttachmentsTypes.length}}const ao=class t{constructor(e,i,s){this._isOpen=!1,this._contentRef=t.createModalContent(i,null==s?void 0:s.backgroundColor),this._buttonPanel=t.createButtonPanel(null==s?void 0:s.backgroundColor),this._elementRef=t.createContainer(this._contentRef,s),this._elementRef.appendChild(this._buttonPanel),e.appendChild(this._elementRef),this._backgroundPanelRef=t.createDarkBackgroundPanel(),e.appendChild(this._backgroundPanelRef),this.addWindowEvents(e)}isOpen(){return this._isOpen}static createContainer(t,e){const i=document.createElement("div");return i.classList.add("modal"),i.appendChild(t),e&&delete e.backgroundColor,Object.assign(i.style,e),i}static createModalContent(t,e){const i=document.createElement("div");return i.classList.add(...t),e&&(i.style.backgroundColor=e),document.createElement("div").appendChild(i),i}static createButtonPanel(t){const e=document.createElement("div");return e.classList.add("modal-button-panel"),t&&(e.style.backgroundColor=t),e}static createDarkBackgroundPanel(){const t=document.createElement("div");return t.id="modal-background-panel",t}addButtons(...t){t.forEach((t=>{Fi.addAttributes(t),this._buttonPanel.appendChild(t)}))}static createTextButton(t){const e=document.createElement("div");return e.classList.add("modal-button"),e.textContent=t,e}static createSVGButton(t){const e=document.createElement("div");e.classList.add("modal-button","modal-svg-button");const i=Ze.createSVGElement(t);return i.classList.add("modal-svg-button-icon"),e.appendChild(i),e}close(){this._elementRef.classList.remove("show-modal"),this._elementRef.classList.add("hide-modal"),this._backgroundPanelRef.classList.remove("show-modal-background"),this._backgroundPanelRef.classList.add("hide-modal-background"),this._isOpen=!1,setTimeout((()=>{this._elementRef.style.display="none",this._backgroundPanelRef.style.display="none"}),t.MODAL_CLOSE_TIMEOUT_MS)}displayModalElements(){this._elementRef.style.display="flex",this._elementRef.classList.remove("hide-modal"),this._elementRef.classList.add("show-modal"),this._backgroundPanelRef.style.display="block",this._backgroundPanelRef.classList.remove("hide-modal-background"),this._backgroundPanelRef.classList.add("show-modal-background"),this._isOpen=!0}openTextModal(t){this._contentRef.innerHTML=t,this.displayModalElements()}addCloseButton(e,i,s){const n=i?t.createSVGButton(e):t.createTextButton(e);return this.addButtons(n),n.onclick=()=>{this.close(),setTimeout((()=>{null==s||s()}),140)},n}static createTextModalFunc(e,i,s){var n;if("object"==typeof i&&null!=(n=i.files)&&n.infoModal){const n=new t(e,["modal-content"],i.files.infoModal.containerStyle);return n.addCloseButton("OK",!1,s),n.openTextModal.bind(n,i.infoModalTextMarkUp||"")}}addWindowEvents(t){this.keyDownEvent=this.windowKeyDown.bind(this,t),window.addEventListener("keydown",this.keyDownEvent)}windowKeyDown(t,e){var i,s;!t.isConnected&&this.keyDownEvent?window.removeEventListener("keydown",this.keyDownEvent):this._isOpen&&(e.key===c.ESCAPE?(this.close(),null==(i=this.extensionCloseCallback)||i.call(this)):e.key===c.ENTER&&(this.close(),null==(s=this.extensionCloseCallback)||s.call(this)))}};ao.MODAL_CLOSE_TIMEOUT_MS=190;let lo=ao;class co extends Ji{constructor(t,e,i,s,n,o){var r,a,l,c,h,u,d,p,m;const v=null==(r=null==i?void 0:i.button)?void 0:r.position,f=(null==(c=null==(l=null==(a=null==i?void 0:i.button)?void 0:a.styles)?void 0:l.text)?void 0:c.content)||o;super(co.createButtonElement(),v,i.button,f);const g="dropup-menu"===v,b=this.createInnerElements(s,n,this._customStyles,g);this._inputElement=co.createInputElement(null==(h=null==i?void 0:i.files)?void 0:h.acceptedFormats),this.addClickEvent(t,i),this.elementRef.replaceChildren(b.styles),this.reapplyStateStyle("styles"),this._fileAttachmentsType=e,this._openModalOnce=!1===(null==(d=null==(u=i.files)?void 0:u.infoModal)?void 0:d.openModalOnce)||null==(m=null==(p=i.files)?void 0:p.infoModal)?void 0:m.openModalOnce}createInnerElements(t,e,i,s=!1){const n=co.createSVGIconElement(t,e);return{styles:Di.createInnerElement(this.elementRef,n,"styles",i,s)}}triggerImportPrompt(t){t.onchange=this.import.bind(this,t),t.click()}import(t){ro.addFilesToType(Array.from(t.files||[]),[this._fileAttachmentsType]),t.value=""}static createInputElement(t){const e=document.createElement("input");return e.type="file",e.accept=t||"",e.hidden=!0,e.multiple=!0,e}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button","upload-file-button"),t}static createSVGIconElement(t,e){const i=Ze.createSVGElement(e);return i.id=t,i}addClickEvent(t,e){const i=this.triggerImportPrompt.bind(this,this._inputElement),s=lo.createTextModalFunc(t,e,i);this.elementRef.onclick=this.click.bind(this,s)}click(t){!t||void 0!==this._openModalOnce&&!0!==this._openModalOnce?this.triggerImportPrompt(this._inputElement):(t(),!0===this._openModalOnce&&(this._openModalOnce=!1))}}class ho{static create(t,e,i){const s=ho.createElement(i);ho.addEvents(s,t,e),t.appendChild(s)}static createElement(t){const e=document.createElement("div");return e.id="drag-and-drop","object"==typeof t&&Object.assign(e.style,t),e}static addEvents(t,e,i){e.ondragenter=e=>{e.preventDefault(),ho.display(t)},t.ondragleave=e=>{e.preventDefault(),ho.hide(t)},t.ondragover=t=>{t.preventDefault()},t.ondrop=e=>{e.preventDefault(),ho.uploadFile(i,e),ho.hide(t)}}static uploadFile(t,e){var i;const s=null==(i=e.dataTransfer)?void 0:i.files;s&&t.addFilesToAnyType(Array.from(s))}static display(t){t.style.display="block"}static hide(t){t.style.display="none"}static isEnabled(t,e){return(void 0===e||!1!==e)&&(!!e||t.getNumberOfTypes()>0)}}class uo{static validate(t,e,i,s,n){const o=t(i,s,n);return o?e.changeToSubmitIcon():e.changeToDisabledIcon(),o}static async useValidationFunc(t,e,i,s){const n=e.isTextInputEmpty()?"":e.inputElementRef.textContent;await i.completePlaceholders();const o=i.getAllFileData(),r=null==o?void 0:o.map((t=>t.file));return uo.validate(t,s,n,r)}static async useValidationFuncProgrammatic(t,e,i){var s;const n=null==(s=e.files)?void 0:s.map((t=>t.file));return uo.validate(t,i,e.text,n,!0)}static validateWebsocket(t,e){const{websocket:i,connectSettings:s}=t;return!(i&&s.url!==qe.URL&&!Be.canSendMessage(i))||(e.changeToDisabledIcon(),!1)}static attach(t,e,i,s,n){const o=t.validateInput||O.processValidateInput(t);t._validationHandler=async t=>{if(n.status.loadingActive||n.status.requestInProgress||!0===e.isSubmitProgrammaticallyDisabled||!uo.validateWebsocket(e,n))return!1;const r=o||e.canSendMessage;return r?t?uo.useValidationFuncProgrammatic(r,t,n):uo.useValidationFunc(r,i,s,n):null}}}class po{static getFileName(t,e){const i=new Date;return`${t}-${String(i.getHours()).padStart(2,"0")}-${String(i.getMinutes()).padStart(2,"0")}-${String(i.getSeconds()).padStart(2,"0")}.${e}`}}class mo extends Hs{constructor(t,e){var i,s;super(e.button),this._waitingForBrowserApproval=!1,this._audioType=t,this._extension=(null==(i=e.files)?void 0:i.format)||"mp3",this._maxDurationSeconds=null==(s=e.files)?void 0:s.maxDurationSeconds,this.elementRef.onclick=this.buttonClick.bind(this)}buttonClick(){this._waitingForBrowserApproval||(this.isActive?this.stop():(this._waitingForBrowserApproval=!0,this.record()))}stop(){return new Promise((t=>{var e,i;this.changeToDefault(),null==(e=this._mediaRecorder)||e.stop(),null==(i=this._mediaStream)||i.getTracks().forEach((t=>t.stop())),setTimeout((()=>{t()}),10)}))}record(){navigator.mediaDevices.getUserMedia({audio:!0}).then((t=>{this.changeToActive(),this._mediaRecorder=new MediaRecorder(t),this._audioType.addPlaceholderAttachment(this.stop.bind(this),this._maxDurationSeconds),this._mediaStream=t,this._mediaRecorder.addEventListener("dataavailable",(t=>{this.createFile(t)})),this._mediaRecorder.start()})).catch((t=>{console.error(t),this.stop()})).finally((()=>{this._waitingForBrowserApproval=!1}))}createFile(t){const e=new Blob([t.data],{type:`audio/${this._extension}`}),i=po.getFileName(this._newFilePrefix||"audio",this._extension),s=new File([e],i,{type:e.type}),n=new FileReader;n.readAsDataURL(s),n.onload=t=>{this._audioType.completePlaceholderAttachment(s,t.target.result)}}}class vo{static resetSubmit(t,e){e?t.unsetCustomStateStyles(["loading","submit"]):t.unsetCustomStateStyles(["stop","loading","submit"]),t.reapplyStateStyle("submit")}static overwriteDefaultStyleWithSubmit(t,e){if(!t.submit)return;const i=JSON.parse(JSON.stringify(t[e]||{}));Hi.overwritePropertyObjectFromAnother(i,t.submit,["container","default"]),Hi.overwritePropertyObjectFromAnother(i,t.submit,["text","styles","default"]),Hi.overwritePropertyObjectFromAnother(i,t.submit,["svg","styles","default"]),t[e]=i}static setUpDisabledButton(t){Hi.setPropertyValueIfDoesNotExist(t,["submit","container","default","backgroundColor"],""),Hi.setPropertyValueIfDoesNotExist(t,["disabled","container","default","backgroundColor"],"unset"),Hi.setPropertyValueIfDoesNotExist(t.submit,["svg","styles","default","filter"],""),Hi.setPropertyValueIfDoesNotExist(t.disabled,["svg","styles","default","filter"],"brightness(0) saturate(100%) invert(70%) sepia(0%) saturate(5564%) hue-rotate(207deg) brightness(100%) contrast(97%)"),vo.overwriteDefaultStyleWithSubmit(t,"disabled")}static process(t){const e=JSON.parse(JSON.stringify(t||{}));return vo.overwriteDefaultStyleWithSubmit(e,"loading"),vo.overwriteDefaultStyleWithSubmit(e,"stop"),null!=t&&t.alwaysEnabled||vo.setUpDisabledButton(e),e}}const fo=class t extends Ji{constructor(e,i,s,n,o,r){const a=vo.process(e.submitButtonStyles);super(t.createButtonContainerElement(),null==a?void 0:a.position,a),this._isSVGLoadingIconOverriden=!1,this.status={requestInProgress:!1,loadingActive:!1},this._messages=s,this._textInput=i,this._fileAttachments=o,this._innerElements=this.createInnerElements(),this._abortStream=new AbortController,this._stopClicked={listener:()=>{}},this._serviceIO=n,this._alwaysEnabled=!(null==a||!a.alwaysEnabled),e.disableSubmitButton=this.disableSubmitButton.bind(this,n),this.attemptOverwriteLoadingStyle(e),r.microphone&&this.setUpSpeechToText(r.microphone.button,e.speechToText),setTimeout((()=>{var t;this._validationHandler=e._validationHandler,this.assignHandlers(this._validationHandler),null==(t=this._validationHandler)||t.call(this)}))}createInnerElements(){const{submit:e,loading:i,stop:s}=this.createCustomElements(),n=e||t.createSubmitIconElement();return{submit:n,loading:i||t.createLoadingIconElement(),stop:s||t.createStopIconElement(),disabled:this.createDisabledIconElement(n)}}createCustomElements(){const t=Di.createSpecificStateElement(this.elementRef,"submit",this._customStyles),e={loading:void 0,stop:void 0};return Object.keys(e).forEach((t=>{const i=t,s=Di.createCustomElement(i,this._customStyles);s&&(e[i]=s)})),e.submit=t,e}static createButtonContainerElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSubmitIconElement(){const t=Ze.createSVGElement(Ns);return t.id="submit-icon",t}static createLoadingIconElement(){const t=document.createElement("div");return t.classList.add("loading-submit-button"),t}static createStopIconElement(){const t=document.createElement("div");return t.id="stop-icon",t}createDisabledIconElement(t){return Di.createCustomElement("disabled",this._customStyles)||t.cloneNode(!0)}attemptOverwriteLoadingStyle(t){var e,i,s,n,o,r,a,l,c;if(!(null!=(i=null==(e=this._customStyles)?void 0:e.submit)&&i.svg||null!=(o=null==(n=null==(s=this._customStyles)?void 0:s.loading)?void 0:n.svg)&&o.content||null!=(l=null==(a=null==(r=this._customStyles)?void 0:r.loading)?void 0:a.text)&&l.content||void 0!==t.displayLoadingBubble&&!0!==t.displayLoadingBubble)){const e=document.createElement("style");e.textContent="\n .loading-button > * {\n filter: brightness(0) saturate(100%) invert(72%) sepia(0%) saturate(3044%) hue-rotate(322deg) brightness(100%)\n contrast(96%) !important;\n }",null==(c=t.shadowRoot)||c.appendChild(e),this._isSVGLoadingIconOverriden=!0}}assignHandlers(t){this._serviceIO.completionsHandlers={onFinish:this.resetSubmit.bind(this,t)},this._serviceIO.streamHandlers={onOpen:this.changeToStopIcon.bind(this),onClose:this.resetSubmit.bind(this,t),abortStream:this._abortStream,stopClicked:this._stopClicked};const{stream:e}=this._serviceIO;"object"==typeof e&&"number"==typeof e.simulation&&(this._serviceIO.streamHandlers.simulationInterim=e.simulation)}setUpSpeechToText(t,e){this._microphoneButton=t,this._stopSTTAfterSubmit="object"==typeof e&&e.stopAfterSubmit}resetSubmit(t){this.status.requestInProgress=!1,this.status.loadingActive=!1,t()}async submitFromInput(){await this._fileAttachments.completePlaceholders();const t=this._fileAttachments.getAllFileData();if(this._textInput.isTextInputEmpty())this.attemptSubmit({text:"",files:t});else{const e=this._textInput.inputElementRef.innerText.trim();this.attemptSubmit({text:e,files:t})}}async programmaticSubmit(t){"string"==typeof t&&(t=O.processSubmitUserMessage(t));const e={text:t.text};t.files&&(e.files=Array.from(t.files).map((t=>({file:t,type:io.getTypeFromBlob(t)})))),setTimeout((()=>this.attemptSubmit(e,!0)))}async attemptSubmit(t,e=!1){var i,s,n,o;if(!1===await(null==(i=this._validationHandler)?void 0:i.call(this,e?t:void 0)))return;this.changeToLoadingIcon(),this._textInput.clear(),"boolean"!=typeof this._messages.focusMode&&null!=(s=this._messages.focusMode)&&s.fade&&await me.fadeAnimation(this._messages.elementRef,this._messages.focusMode.fade),await this.addNewMessage(t),this._serviceIO.isWebModel()||this._messages.addLoadingMessage();const r=null==(n=t.files)?void 0:n.map((t=>t.file)),a={text:""===t.text?void 0:t.text,files:r};await this._serviceIO.callAPI(a,this._messages),null==(o=this._fileAttachments)||o.removeAllFiles()}async addNewMessage({text:t,files:e}){const i={role:Se.USER_ROLE};t&&(i.text=t),e&&(i.files=await this._messages.addMultipleFiles(e)),this._serviceIO.sessionId&&(i._sessionId=this._serviceIO.sessionId),Object.keys(i).length>0&&this._messages.addNewMessage(i)}stopStream(){var t;this._abortStream.abort(),null==(t=this._stopClicked)||t.listener(),this._validationHandler&&this.resetSubmit(this._validationHandler)}changeToStopIcon(){this._serviceIO.websocket||(this.elementRef.classList.remove(t.LOADING_CLASS,t.DISABLED_CLASS,t.SUBMIT_CLASS),Fi.removeAriaAttributes(this.elementRef),this.elementRef.replaceChildren(this._innerElements.stop),this.reapplyStateStyle("stop",["loading","submit"]),this.elementRef.onclick=this.stopStream.bind(this),this.status.loadingActive=!1)}changeToLoadingIcon(){this._serviceIO.websocket||(this._isSVGLoadingIconOverriden||this.elementRef.replaceChildren(this._innerElements.loading),this.elementRef.classList.remove(t.SUBMIT_CLASS,t.DISABLED_CLASS),Fi.removeAriaDisabled(this.elementRef),this.elementRef.classList.add(t.LOADING_CLASS),Fi.addAriaBusy(this.elementRef),this.reapplyStateStyle("loading",["submit"]),this.elementRef.onclick=()=>{},this.status.requestInProgress=!0,this.status.loadingActive=!0)}changeToSubmitIcon(){this.elementRef.classList.contains(t.SUBMIT_CLASS)||(this.elementRef.classList.remove(t.LOADING_CLASS,t.DISABLED_CLASS),Fi.removeAriaAttributes(this.elementRef),this.elementRef.classList.add(t.SUBMIT_CLASS),this.elementRef.replaceChildren(this._innerElements.submit),vo.resetSubmit(this,this.status.loadingActive),this.elementRef.onclick=()=>{var t;this.submitFromInput(),null!=(t=this._microphoneButton)&&t.isActive&&eo.toggleSpeechAfterSubmit(this._microphoneButton.elementRef,!!this._stopSTTAfterSubmit)})}changeToDisabledIcon(e=!1){this._alwaysEnabled&&!e?this.changeToSubmitIcon():this.elementRef.classList.contains(t.DISABLED_CLASS)||(this.elementRef.classList.remove(t.LOADING_CLASS,t.SUBMIT_CLASS),Fi.removeAriaBusy(this.elementRef),this.elementRef.classList.add(t.DISABLED_CLASS),Fi.addAriaDisabled(this.elementRef),this.elementRef.replaceChildren(this._innerElements.disabled),this.reapplyStateStyle("disabled",["submit"]),this.elementRef.onclick=()=>{})}disableSubmitButton(t,e){var i;t.isSubmitProgrammaticallyDisabled=!1!==e,!this.status.requestInProgress&&!this.status.loadingActive&&(!1===e?null==(i=this._validationHandler)||i.call(this):this.changeToDisabledIcon(!0))}};fo.SUBMIT_CLASS="submit-button",fo.LOADING_CLASS="loading-button",fo.DISABLED_CLASS="disabled-button";let go=fo;class bo extends lo{constructor(t,e,i,s){super(t,["modal-content","modal-camera-content"],i),this._stopped=!1,this._format="image/png",this._canvas=document.createElement("canvas"),this._canvas.classList.add("camera-modal-canvas");const{captureButton:n,submitButton:o}=this.addButtonsAndTheirEvents(e);this._captureButton=n,this._submitButton=o,this._captureIcon=this._captureButton.children[0],this._refreshIcon=Ze.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">\n <path d="M27.1 14.313V5.396L24.158 8.34c-2.33-2.325-5.033-3.503-8.11-3.503C9.902 4.837 4.901 9.847 4.899 16c.001 6.152 5.003 11.158 11.15 11.16 4.276 0 9.369-2.227 10.836-8.478l.028-.122h-3.23l-.022.068c-1.078 3.242-4.138 5.421-7.613 5.421a8 8 0 0 1-5.691-2.359A7.993 7.993 0 0 1 8 16.001c0-4.438 3.611-8.049 8.05-8.049 2.069 0 3.638.58 5.924 2.573l-3.792 3.789H27.1z"/>\n</svg>\n'),this._refreshIcon.classList.add("modal-svg-button-icon","modal-svg-refresh-icon"),"jpeg"===(null==s?void 0:s.format)&&(this._format="image/jpeg"),null!=s&&s.dimensions&&(this._dimensions=s.dimensions),this._contentRef.appendChild(this._canvas),this.extensionCloseCallback=this.stop}addButtonsAndTheirEvents(t){const e=lo.createSVGButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <title>capture</title>\n <path d="M0 16q0 3.264 1.28 6.208t3.392 5.12 5.12 3.424 6.208 1.248 6.208-1.248 5.12-3.424 3.392-5.12 1.28-6.208-1.28-6.208-3.392-5.12-5.088-3.392-6.24-1.28q-3.264 0-6.208 1.28t-5.12 3.392-3.392 5.12-1.28 6.208zM4 16q0-3.264 1.6-6.016t4.384-4.352 6.016-1.632 6.016 1.632 4.384 4.352 1.6 6.016-1.6 6.048-4.384 4.352-6.016 1.6-6.016-1.6-4.384-4.352-1.6-6.048z"></path>\n</svg>\n');e.classList.add("modal-svg-camera-button"),e.children[0].classList.add("modal-svg-camera-icon");const i=this.addCloseButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="M195.2 195.2a64 64 0 0 1 90.496 0L512 421.504 738.304 195.2a64 64 0 0 1 90.496 90.496L602.496 512 828.8 738.304a64 64 0 0 1-90.496 90.496L512 602.496 285.696 828.8a64 64 0 0 1-90.496-90.496L421.504 512 195.2 285.696a64 64 0 0 1 0-90.496z"/>\n</svg>',!0);i.classList.add("modal-svg-close-button"),i.children[0].classList.add("modal-svg-close-icon");const s=lo.createSVGButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M4.89163 13.2687L9.16582 17.5427L18.7085 8" stroke="#000000" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>');return s.classList.add("modal-svg-submit-button"),this.addButtons(e,s),this.addButtonEvents(e,i,s,t),{captureButton:e,submitButton:s}}addButtonEvents(t,e,i,s){t.onclick=()=>{this.capture()},e.addEventListener("click",this.stop.bind(this)),i.onclick=()=>{const t=this.getFile();t&&ro.addFilesToType([t],[s]),this.stop(),this.close()}}stop(){this._mediaStream&&this._mediaStream.getTracks().forEach((t=>t.stop())),this._stopped=!0,setTimeout((()=>{this._captureButton.replaceChildren(this._captureIcon),this._captureButton.classList.replace("modal-svg-refresh-button","modal-svg-camera-button");const t=this._canvas.getContext("2d");null==t||t.clearRect(0,0,this._canvas.width,this._canvas.height)}),lo.MODAL_CLOSE_TIMEOUT_MS)}start(){this._dataURL=void 0,this._submitButton.classList.add("modal-svg-submit-disabled"),this._stopped=!1,navigator.mediaDevices.getUserMedia({video:this._dimensions||!0}).then((t=>{if(this._mediaStream=t,!this.isOpen())return this.stop();const e=document.createElement("video");e.srcObject=t,e.play(),requestAnimationFrame(this.updateCanvas.bind(this,e,this._canvas))})).catch((t=>{console.error(t),this.stop(),this.close()}))}capture(){this._dataURL?(this._captureButton.replaceChildren(this._captureIcon),this._captureButton.classList.replace("modal-svg-refresh-button","modal-svg-camera-button"),this._submitButton.classList.add("modal-svg-submit-disabled"),this._dataURL=void 0):(this._captureButton.replaceChildren(this._refreshIcon),this._captureButton.classList.replace("modal-svg-camera-button","modal-svg-refresh-button"),this._submitButton.classList.remove("modal-svg-submit-disabled"),this._dataURL=this._canvas.toDataURL())}getFile(){if(this._dataURL){const t=atob(this._dataURL.split(",")[1]),e=new Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);const i=new Uint8Array(e),s=new Blob([i],{type:this._format}),n="image/jpeg"===this._format?"jpeg":"png",o=po.getFileName(this._newFilePrefix||"photo",n);return new File([s],o,{type:s.type})}}updateCanvas(t,e){if(!this._stopped){if(!this._dataURL){e.width=t.videoWidth,e.height=t.videoHeight;const i=e.getContext("2d");null==i||i.drawImage(t,0,0,e.width,e.height)}requestAnimationFrame(this.updateCanvas.bind(this,t,e))}}openCameraModal(t){this.displayModalElements(),t.start()}static createCameraModalFunc(t,e,i,s){const n=new bo(t,e,i,s);return n.openCameraModal.bind(n,n)}}class yo extends Ji{constructor(t,e,i){var s,n,o,r;const a=null==(s=null==i?void 0:i.button)?void 0:s.position,l=(null==(r=null==(o=null==(n=null==i?void 0:i.button)?void 0:n.styles)?void 0:o.text)?void 0:r.content)||"Photo";super(yo.createButtonElement(),a,(null==i?void 0:i.button)||{},l);const c=this.createInnerElements(this._customStyles,"dropup-menu"===a);i&&this.addClickEvent(t,e,i.modalContainerStyle,i.files),this.elementRef.classList.add("upload-file-button"),this.elementRef.appendChild(c.styles),this.reapplyStateStyle("styles")}createInnerElements(t,e=!1){return{styles:Di.createInnerElement(this.elementRef,yo.createSVGIconElement(),"styles",t,e)}}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSVGIconElement(){const t=Ze.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <path d="M29 7h-4.599l-2.401-4h-12l-2.4 4h-4.6c-1 0-3 1-3 2.969v16.031c0 1.657 1.5 3 2.792 3h26.271c1.313 0 2.938-1.406 2.938-2.968v-16.032c0-1-1-3-3-3zM30 26.032c0 0.395-0.639 0.947-0.937 0.969h-26.265c-0.232-0.019-0.797-0.47-0.797-1v-16.031c0-0.634 0.851-0.953 1-0.969h5.732l2.4-4h9.802l1.785 3.030 0.55 0.97h5.731c0.705 0 0.99 0.921 1 1v16.032zM16 10c-3.866 0-7 3.134-7 7s3.134 7 7 7 7-3.134 7-7-3.134-7-7-7zM16 22c-2.757 0-5-2.243-5-5s2.243-5 5-5 5 2.243 5 5-2.243 5-5 5z"></path>\n</svg>');return t.id="camera-icon",t}addClickEvent(t,e,i,s){const n=bo.createCameraModalFunc(t,e,i,s);this.elementRef.onclick=n}}class wo{constructor(t,e,i,s){var n;this.elementRef=wo.createPanelElement(t.inputAreaStyle);const o={},r=this.createFileUploadComponents(t,i,s,o),a=new m(t,i,r);t.speechToText&&!o.microphone&&(o.microphone={button:new eo(t,a,e.addNewErrorMessage.bind(e))});const l=new go(t,a,e,i,r,o);a.submit=l.submitFromInput.bind(l),uo.attach(t,i,a,r,l),t.submitUserMessage=l.programmaticSubmit.bind(l),o.submit={button:l},null==(n=t.customButtons)||n.forEach(((t,e)=>{o[`${Fs.INDICATOR_PREFIX}${e+1}`]={button:new Fs(t,e)}})),wo.addElements(this.elementRef,a,o,s,r,t.dropupStyles)}static createPanelElement(t){const e=document.createElement("div");return e.id="input",Object.assign(e.style,t),e}createFileUploadComponents(t,e,i,s){var n,o,r,a;const l=new ro(this.elementRef,t.attachmentContainerStyle,e.demo);if(wo.createUploadButtons(t,e.fileTypes||{},l,i,s),null!=(n=e.camera)&&n.files){const n=(null==(o=s.images)?void 0:o.fileType)||l.addType(t,e.camera.files,"images");s.camera={button:new yo(i,n,e.camera)}}if(null!=(r=e.recordAudio)&&r.files){const i=(null==(a=s.audio)?void 0:a.fileType)||l.addType(t,e.recordAudio.files,"audio");s.microphone={button:new mo(i,e.recordAudio)}}return ho.isEnabled(l,t.dragAndDrop)&&ho.create(i,l,t.dragAndDrop),l}static createUploadButtons(t,e,i,s,n){Object.keys(e).forEach((o=>{const r=o,a=e[r];if(a.files){const e=i.addType(t,a.files,r),{id:o,svgString:l,dropupText:c}=Vs[r],h=new co(s,e,a,o,l,c);n[r]={button:h,fileType:e}}}))}static addElements(t,e,i,s,n,o){x.addElements(t,e.elementRef);const r=Is.create(),a=Us.addButtons(r,i,s,o);Es.set(e.inputElementRef,r,n.elementRef,a),Is.add(t,r)}}class xo{static createElements(t,e,i){const s=document.createElement("div");s.id="chat-view";const n=new js(t,e,i);e.websocket&&Be.createConnection(e,n);const o=new wo(t,n,e,s);return x.addElements(s,n.elementRef,o.elementRef),s}static render(t,e,i,s){const n=xo.createElements(t,i,s);e.replaceChildren(n),i.isCustomView()&&i.setUpView(n,e)}}var ko=Object.defineProperty,_o=(t,e,i,s)=>{for(var n,o=void 0,r=t.length-1;r>=0;r--)(n=t[r])&&(o=n(e,i,o)||o);return o&&ko(e,i,o),o};class So extends Ge{constructor(){super(),this.getMessages=()=>[],this.submitUserMessage=()=>console.warn("submitUserMessage failed - please wait for chat view to render before calling this property."),this.addMessage=()=>console.warn("addMessage failed - please wait for chat view to render before calling this property."),this.updateMessage=()=>{},this.clearMessages=()=>{},this.focusInput=()=>v.focusFromParentElement(this._elementRef),this.refreshMessages=()=>{},this.scrollToBottom=()=>{},this.disableSubmitButton=()=>{},this.setPlaceholderText=()=>{},this._hasBeenRendered=!1,this._auxiliaryStyleApplied=!1,this._elementRef=document.createElement("div"),this._elementRef.id="container",this.attachShadow({mode:"open"}).appendChild(this._elementRef),r.apply('#validate-property-key-view{height:100%;position:relative;display:flex;justify-content:center;align-items:center;padding:8px}#loading-validate-key-property{display:inline-block;width:50px;height:50px}#loading-validate-key-property:after{content:" ";display:block;width:38px;height:38px;margin:1px;border-radius:50%;border:5px solid #5fb2ff;border-color:#5fb2ff transparent #5fb2ff transparent;animation:loading-spinner 1.4s linear infinite}#deep-chat-openai-realtime-container{height:100%;width:100%}#deep-chat-openai-realtime-avatar-container{height:60%;width:100%;display:flex;justify-content:center;align-items:center}#deep-chat-openai-realtime-avatar{border-radius:50%;height:110px;border:1px solid rgb(215,215,215);padding:8px;-webkit-user-select:none;user-select:none;margin-top:20px}#deep-chat-openai-realtime-buttons-container{height:40%;display:flex;position:relative}.deep-chat-openai-realtime-button-container{height:100%;width:50%;display:flex;justify-content:center;align-items:center}.deep-chat-openai-realtime-button{width:70px;height:70px;border-radius:50%;display:flex;justify-content:center;align-items:center;cursor:pointer}.deep-chat-openai-realtime-button-default{background-color:#e3e3e3}.deep-chat-openai-realtime-button-default:hover{background-color:#d4d4d4}.deep-chat-openai-realtime-button-default:active{background-color:#c5c5c5}.deep-chat-openai-realtime-button-loading{opacity:.7;pointer-events:none}.deep-chat-openai-realtime-mute-active{background-color:#ffe7e7}.deep-chat-openai-realtime-mute-active:hover{background-color:#ffdede}.deep-chat-openai-realtime-mute-active:active{background-color:#ffd2d2}.deep-chat-openai-realtime-mute>*{height:30px;width:30px}.deep-chat-openai-realtime-mute-active>*{filter:brightness(0) saturate(100%) invert(35%) sepia(60%) saturate(1360%) hue-rotate(325deg) brightness(95%) contrast(92%)}.deep-chat-openai-realtime-toggle>*{height:32px;width:32px;padding-left:3px;filter:brightness(0) saturate(100%) invert(22%) sepia(0%) saturate(4537%) hue-rotate(208deg) brightness(105%) contrast(91%)}.deep-chat-openai-realtime-button-unavailable{opacity:.45;pointer-events:none}#deep-chat-openai-realtime-error{color:red;position:absolute;top:calc(50% + 40px);left:50%;transform:translate(-50%,-50%);font-size:17px}#deep-chat-openai-realtime-loading{position:absolute;font-size:15px;top:50%;left:50%;transform:translate(-50%,-50%)}#insert-key-view{height:100%;position:relative}#insert-key-contents{text-align:center;position:absolute;top:44%;left:50%;transform:translate(-50%,-50%);width:82%;display:flex;max-width:700px}#insert-key-title{margin-bottom:15px}#insert-key-input-container{margin-right:2.7em;width:calc(100% - 80px)}#insert-key-input{padding:.3em 1.7em .3em .3em;border-width:1px;border-style:solid;border-radius:3px;width:100%;font-size:inherit}.insert-key-input-valid{border-color:gray}.insert-key-input-invalid{border-color:red}#visibility-icon-container{position:relative;float:right;cursor:pointer;-webkit-user-select:none;user-select:none}.visibility-icon{filter:brightness(0) saturate(100%) invert(63%) sepia(1%) saturate(9%) hue-rotate(43deg) brightness(98%) contrast(92%);position:absolute;right:-1.7em;top:-1.43em}#visible-icon{top:-1.4em}.visibility-icon:hover{filter:unset}.visibility-icon>*{pointer-events:none}#start-button{border:1px solid grey;color:#454545;border-radius:4px;width:3em;display:flex;justify-content:center;align-items:center;cursor:pointer;padding:.28em .3em;-webkit-user-select:none;user-select:none;background-color:#fff}#start-button:hover{background-color:#f2f2f2}#start-button:active{background-color:#d2d2d2}#insert-key-help-text-container{width:100%;position:absolute;margin-top:32px;margin-bottom:20px}#insert-key-help-text-contents{width:100%;position:absolute}#insert-key-input-invalid-text{display:block;margin-top:1em;margin-bottom:.5em;color:red}.insert-key-input-help-text{display:block;margin-top:16px}#loading-key{display:inline-block;width:16px;height:16px}#loading-key:after{content:" ";display:block;width:11px;height:11px;margin:1px;border-radius:50%;border:2px solid #0084ff;border-color:#0084ff transparent #0084ff transparent;animation:loading-spinner 1.2s linear infinite}#error-view{color:red;font-size:1.2em;line-height:1.3em;margin-top:-5px;text-align:center;height:100%;display:flex;justify-content:center;align-items:center;padding-left:8px;padding-right:8px}@keyframes loading-spinner{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.intro-panel{position:absolute;display:flex;justify-content:center;right:0;bottom:0;left:0;margin:auto;height:fit-content;top:-2.5em}#internal-intro-panel{width:250px;height:min-content;display:block;border-radius:5px;overflow:auto;border:1px solid rgb(203,203,203);padding:10px;max-height:calc(100% - 6.8em)}#internal-intro-panel>p{margin-block-start:.8em;margin-block-end:.8em}pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}/*!\n Theme: a11y-dark\n Author: @ericwbailey\n Maintainer: @ericwbailey\n\n Based on the Tomorrow Night Eighties theme: https://github.com/isagalaev/highlight.js/blob/master/src/styles/tomorrow-night-eighties.css\n*/.hljs{background:#2b2b2b;color:#f8f8f2}.hljs-comment,.hljs-quote{color:#d4d0ab}.hljs-deletion,.hljs-name,.hljs-regexp,.hljs-selector-class,.hljs-selector-id,.hljs-tag,.hljs-template-variable,.hljs-variable{color:#ffa07a}.hljs-built_in,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-type{color:#f5ab35}.hljs-attribute{color:gold}.hljs-addition,.hljs-bullet,.hljs-string,.hljs-symbol{color:#abe338}.hljs-section,.hljs-title{color:#00e0e0}.hljs-keyword,.hljs-selector-tag{color:#dcc6e0}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}@media screen and (-ms-high-contrast: active){.hljs-addition,.hljs-attribute,.hljs-built_in,.hljs-bullet,.hljs-comment,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-quote,.hljs-string,.hljs-symbol,.hljs-type{color:highlight}.hljs-keyword,.hljs-selector-tag{font-weight:700}}#messages{overflow:auto}.outer-message-container:last-child{margin-bottom:5px}.inner-message-container{display:flex;margin-left:auto;margin-right:auto;width:calc(97.5% - 24px);max-width:100%}.message-bubble{margin-top:10px;word-wrap:break-word;width:fit-content;max-width:60%;border-radius:10px;padding:.42em .55em;height:fit-content;line-height:1.26em}.user-message-text{color:#fff;background-color:#0084ff;margin-right:0;margin-left:auto}.ai-message-text{color:#000;background-color:#e4e6eb;margin-left:0;margin-right:auto}.deep-chat-last-group-messages-active{height:100%}.loading-history-message-full-view{position:absolute;height:70%;width:100%;display:flex;align-items:center}.loading-history-message-small{height:20px;margin-bottom:30px}.loading-history-message-small>div>div{scale:.6}.loading-history-message{margin-top:0;width:100%;max-width:100%;display:flex;justify-content:center;background-color:unset}.loading-history{width:70px}.loading-history div{position:absolute;width:var(--loading-history-width);height:var(--loading-history-height);margin:var(--loading-history-margin);border:var(--loading-history-border);border-radius:50%;animation:loading-spinner 1.2s cubic-bezier(.5,0,.5,1) infinite;border-color:var(--loading-history-color) transparent transparent transparent}.loading-history div:nth-child(1){animation-delay:-.45s}.loading-history div:nth-child(2){animation-delay:-.3s}.loading-history div:nth-child(3){animation-delay:-.15s}.html-message{max-width:unset}.error-message-text{margin:14px auto 10px;background-color:#f4c0c0;color:#474747;text-align:center;max-width:95%}.deep-chat-loading-message-dots-container{width:1em;padding:.6em .75em .6em 1.3em}.loading-message-dots{position:relative;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite linear alternate;animation-delay:.5s}.loading-message-dots:before,.loading-message-dots:after{content:"";display:inline-block;position:absolute;top:0}.loading-message-dots:before{left:-.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite alternate;animation-delay:0s}.loading-message-dots:after{left:.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite alternate;animation-delay:1s}@keyframes loading-message-dots{0%{background-color:var(--loading-message-color)}50%,to{background-color:var(--loading-message-color-fade)}}.message-bubble>p:first-child{margin-top:0}.message-bubble>p:last-child{margin-bottom:0}pre{overflow:auto;display:block;word-break:break-all;word-wrap:break-word;border-radius:7px;background:#2b2b2b;color:#f8f8f2;margin-top:.8em;margin-bottom:.8em;padding:.6em;font-size:.9em;line-height:1.5em}.image-message{padding:0;display:flex;background-color:#ddd}.image-message>*,.image-message>*>*{width:100%;border-radius:8px;display:flex}.audio-message{width:60%;max-width:300px;height:2.2em;max-height:54px;padding:0;background-color:unset}.audio-player{width:100%;height:100%}.audio-player-safari{height:fit-content;width:40px}.audio-player-safari-left{float:left}.audio-player-safari-right{float:right}.any-file-message{padding:1px}.any-file-message-contents{display:flex}.any-file-message-icon-container{width:1.3em;min-width:1.3em;position:relative;border-radius:4px;margin-left:6px;margin-right:2px}.any-file-message-icon{background-color:#fff;border-radius:4px;position:absolute;width:1em;height:1.25em;padding:1px;margin-top:auto;margin-bottom:auto;top:0;bottom:0}.any-file-message-text{padding-top:5px;overflow-wrap:anywhere;padding-bottom:5px;padding-right:7px}.message-bubble>a{color:inherit}.left-item-position{margin-right:10px}.right-item-position{margin-left:10px}.avatar{padding-top:5px;width:1.5em;height:1.5em;border-radius:1px}.avatar-container{margin-top:9px}.name{margin-top:16px;font-size:15px}#drag-and-drop{position:absolute;display:none;z-index:10;height:calc(100% - 10px);width:calc(100% - 10px);background-color:#70c6ff4d;border:5px dashed #6dafff}#file-attachment-container{position:absolute;height:3.6em;width:calc(80% - 4px);top:-2.5em;border-radius:5px;overflow:auto;text-align:left;background-color:#d7d7d73b;padding-left:4px}.file-attachment{width:2.85em;height:2.85em;display:inline-flex;margin-right:.6em;margin-bottom:.44em;margin-top:4px;position:relative;background-color:#fff;border-radius:5px}.image-attachment{width:100%;height:100%;object-fit:cover;border-radius:5px}.border-bound-attachment{width:calc(100% - 2px);height:calc(100% - 2px);border:1px solid #c3c3c3;border-radius:5px;overflow:hidden}.border-bound-attachment-safari{width:calc(100% - 1px);height:calc(100% - 1px)}.audio-attachment-icon-container{cursor:pointer}.audio-attachment-icon-container:hover{background-color:#f8f8f8}.attachment-icon{left:0;right:0;bottom:0;top:2px;margin:auto;position:absolute;width:25px;-webkit-user-select:none;user-select:none}.not-removable-attachment-icon{top:0;right:0;bottom:0;left:0}.play-icon{filter:brightness(0) saturate(100%) invert(17%) sepia(0%) saturate(1392%) hue-rotate(67deg) brightness(98%) contrast(97%)}.stop-icon{filter:brightness(0) saturate(100%) invert(29%) sepia(90%) saturate(1228%) hue-rotate(198deg) brightness(93%) contrast(98%)}.audio-placeholder-text-3-digits{padding-left:.26rem}.audio-placeholder-text-4-digits{padding-left:.1rem}.any-file-attachment{padding:2px 0}.file-attachment-text-container{position:absolute;width:inherit;display:flex;align-items:center;height:100%;top:-1px}.audio-placeholder-text-3-digits-container{padding-top:1px;cursor:default}.any-file-attachment-text{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;padding-left:.13em;margin-left:auto;margin-right:auto}.remove-file-attachment-button{height:1.25em;width:1.25em;border:1px solid #cfcfcf;border-radius:25px;background-color:#fff;top:-4px;right:-5px;position:absolute;display:flex;justify-content:center;cursor:pointer;-webkit-user-select:none;user-select:none}.remove-file-attachment-button:hover{background-color:#e4e4e4}.remove-file-attachment-button:active{background-color:#d7d7d7}.x-icon{color:#4e4e4e;top:-.075em;position:relative;font-size:1.05em}.modal{display:none;flex-direction:column;align-items:center;justify-content:center;position:absolute;width:80%;max-width:420px;max-height:80%;margin:auto;top:0;right:0;bottom:0;left:0;z-index:2}.modal-content{border-top:1px solid rgb(217,217,217);border-left:1px solid rgb(217,217,217);border-right:1px solid rgb(217,217,217);border-top-left-radius:inherit;border-top-right-radius:inherit;background-color:#fff;overflow-y:auto;height:fit-content;max-height:calc(100% - 3.3em);width:100%}.modal-content>p{margin-left:1em;margin-right:1em}.modal-content>ul{margin-right:1em}.modal-button-panel{height:3.3em;border:1px solid;border-color:rgb(223,223,223) rgb(217,217,217) rgb(217,217,217);border-bottom-left-radius:inherit;border-bottom-right-radius:inherit;background-color:#fff;text-align:center;justify-content:center;display:flex;width:100%}.modal-button{min-width:2.5em;text-align:center;color:#fff;border-radius:5px;padding:.4em .4em .3em;height:1.25em;background-color:#3279b2;top:0;bottom:0;cursor:pointer;-webkit-user-select:none;user-select:none;margin:auto .31em}.modal-button:hover{background-color:#276da7}.modal-button:active{background-color:#1b5687}.modal-svg-button{padding:0 0 2px;width:2em;height:1.8em}.modal-svg-button-icon{width:100%;height:100%;filter:brightness(0) saturate(100%) invert(100%) sepia(15%) saturate(4%) hue-rotate(346deg) brightness(101%) contrast(102%)}#modal-background-panel{position:absolute;width:100%;height:100%;background-color:#00000042;z-index:1;display:none}.show-modal-background{animation:fadeInBackground .3s ease-in-out}@keyframes fadeInBackground{0%{opacity:0}to{opacity:1}}.show-modal{animation:fadeInModal .3s ease-in-out}@keyframes fadeInModal{0%{opacity:0;scale:.95}to{opacity:1;scale:1}}.hide-modal-background{animation:fadeOutBackground .2s ease-in-out}@keyframes fadeOutBackground{0%{opacity:1}to{opacity:0}}.hide-modal{animation:fadeOutModal .2s ease-in-out}@keyframes fadeOutModal{0%{opacity:1;scale:1}to{opacity:0;scale:.95}}.modal-camera-content{overflow:hidden;text-align:center;border:unset;height:100%;background-color:#2a2a2a;display:flex;justify-content:center}.camera-modal-canvas{max-width:100%;max-height:100%;margin-top:auto;margin-bottom:auto}.modal-svg-submit-button{background-color:green}.modal-svg-submit-button:hover{background-color:#007500}.modal-svg-submit-button:active{background-color:#006500}.modal-svg-submit-disabled{pointer-events:none;background-color:#747474}.modal-svg-close-button{height:1.56em;padding-top:.37em;padding-bottom:0;background-color:#c13e3e}.modal-svg-close-button:hover{background-color:#b43434}.modal-svg-close-button:active{background-color:#972929}.modal-svg-close-icon{width:80%;height:80%}.modal-svg-camera-button{height:1.6em;padding-top:.38em;padding-bottom:0}.modal-svg-camera-icon{height:76%}.modal-svg-refresh-icon{height:105%}.modal-svg-refresh-button{height:1.66em;padding-top:.11em;padding-bottom:.21em}.input-button-container{position:relative;z-index:1}.inside-right{position:absolute;right:calc(10% + .35em);bottom:.85em}.inside-left{position:absolute;left:calc(10% + .35em);bottom:.85em}.outside-left{position:absolute;right:calc(11px - .55em);bottom:.88em}.outside-right{position:absolute;left:calc(11px - .55em);bottom:.88em}#upload-images-icon{position:absolute;pointer-events:none;width:1.45em;height:1.45em;left:.11em;bottom:.08em;filter:brightness(0) saturate(100%) invert(43%) sepia(0%) saturate(740%) hue-rotate(77deg) brightness(99%) contrast(92%)}#upload-gifs-icon{position:absolute;pointer-events:none;width:1.5em;height:1.48em;left:.07em;bottom:.08em;filter:brightness(0) saturate(100%) invert(49%) sepia(0%) saturate(2586%) hue-rotate(12deg) brightness(93%) contrast(90%)}#upload-audio-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.17em;bottom:.2em;filter:brightness(0) saturate(100%) invert(15%) sepia(0%) saturate(337%) hue-rotate(125deg) brightness(91%) contrast(94%);transform:scaleX(.95)}#camera-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.23em;bottom:.2em;filter:brightness(0) saturate(100%) invert(52%) sepia(0%) saturate(161%) hue-rotate(164deg) brightness(91%) contrast(92%);transform:scaleX(.95)}#upload-mixed-files-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.2em;filter:brightness(0) saturate(100%) invert(53%) sepia(0%) saturate(36%) hue-rotate(74deg) brightness(98%) contrast(93%);transform:scaleX(.95)}#interim-text{color:gray}#microphone-button{padding-top:.5px}.outer-button-container>#microphone-button{padding-bottom:1px}#microphone-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.25em}.default-microphone-icon{filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%)}.active-microphone-icon{filter:brightness(0) saturate(100%) invert(10%) sepia(97%) saturate(7495%) hue-rotate(0deg) brightness(101%) contrast(107%);border-radius:10px}.command-microphone-icon{filter:brightness(0) saturate(100%) invert(42%) sepia(96%) saturate(1067%) hue-rotate(77deg) brightness(99%) contrast(102%)}.unsupported-microphone{display:none}#submit-icon{height:100%;filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%);width:1.21em}#stop-icon{background-color:#acacac;position:absolute;width:.95em;height:.95em;left:.35em;bottom:.35em;border-radius:2px}.submit-button-enlarged{scale:1.1;margin-right:.3em;margin-left:.3em}.loading-submit-button{position:relative;left:calc(-9990px + .275em);width:.22em;height:.22em;border-radius:5px;background-color:#848484;color:#848484;box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484;animation:loading-submit-button 1.5s infinite linear;bottom:-.75em}@keyframes loading-submit-button{0%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}16.667%{box-shadow:9990px -6px #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}33.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}50%{box-shadow:9990px 0 #848484,calc(9990px + .44em) -6px 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}66.667%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}83.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) -6px 0 0 #848484}to{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}}.input-button{border-radius:4px;cursor:pointer;margin-bottom:.2em;-webkit-user-select:none;user-select:none}.input-button-svg{width:1.65em;height:1.65em}.input-button:hover,.input-button:focus-visible{background-color:#9c9c9c2e}.input-button:active{background-color:#9c9c9c5e}.input-button:active:not(:hover){background-color:transparent}.loading-button{cursor:auto}.loading-button:hover{background-color:unset}.text-button{filter:unset!important;display:flex;justify-content:center;align-items:center;margin-left:4px;margin-right:4px;height:1.6em}#text-input-container{background-color:#fff;width:80%;display:flex;border:1px solid #0000001a;border-radius:5px;margin-top:.8em;margin-bottom:.8em;box-shadow:#959da533 0 1px 12px;overflow-y:auto;max-height:200px;position:relative}.text-input-container-left-adjustment{margin-left:1.5em}.text-input-container-right-adjustment{margin-right:1.5em}.text-input-container-left-small-adjustment{margin-left:1.1em}.text-input-container-left-small-adjustment>.outside-left{right:calc(14px - .55em)}.text-input-container-right-small-adjustment{margin-right:1.1em}.text-input-container-right-small-adjustment>.outside-right{left:calc(14px - .55em)}#text-input{text-align:left;outline:none;word-wrap:break-word;line-break:auto}.text-input-styling{padding:.4em .5em;overflow:overlay;width:100%}.text-input-inner-left-adjustment{padding-left:2.2em}.text-input-inner-right-adjustment{padding-right:2em}.text-input-disabled{pointer-events:none;-webkit-user-select:none;user-select:none}[contenteditable]:empty:before{content:attr(deep-chat-placeholder-text);pointer-events:none}[contenteditable][textcolor]:empty:before{color:gray}.outside-right>#dropup-menu,.inside-right>#dropup-menu{right:0}#dropup-icon{position:absolute;pointer-events:none;width:1.16em;height:1.2em;left:.265em;bottom:.43em;filter:brightness(0) saturate(100%) invert(54%) sepia(0%) saturate(724%) hue-rotate(6deg) brightness(92%) contrast(90%)}#dropup-menu{background-color:#fff;position:absolute;transform:translateY(-100%);border-radius:5px;z-index:1;top:-.49em;box-shadow:#0003 -1px 2px 10px,#0000001a 0 2px 4px;cursor:pointer;-webkit-user-select:none;user-select:none}.dropup-menu-item{height:1.4em;padding:.28em .84em .28em .35em;display:flex;position:relative}.dropup-menu-item:hover,.dropup-menu-item:focus-visible{background-color:#f3f3f3}.dropup-menu-item:active{background-color:#ebebeb}.dropup-menu-item:active:not(:hover){background-color:transparent}.dropup-menu-item:first-child{padding-top:.49em;border-top-left-radius:inherit;border-top-right-radius:inherit}.dropup-menu-item:last-child{padding-bottom:.45em;border-bottom-left-radius:inherit;border-bottom-right-radius:inherit}.dropup-menu-item-icon{width:1.39em;position:relative;margin-right:.56em}.dropup-menu-item-icon>svg{bottom:0!important;top:0!important;margin-bottom:auto;margin-top:auto}.dropup-menu-item-text{margin-top:.08em;width:max-content}.dropup-menu-item-active{background-color:#edf7ff;color:#0285ff}.dropup-menu-item-active:hover,.dropup-menu-item-active:focus-visible{background-color:#def0ff}.dropup-menu-item-active:active{background-color:#d2eaff}.dropup-menu-item-active>.dropup-menu-item-icon{filter:brightness(0) saturate(100%) invert(32%) sepia(34%) saturate(4196%) hue-rotate(196deg) brightness(107%) contrast(104%)}.dropup-menu-item-disabled{color:#aeaeae;cursor:auto}.dropup-menu-item-disabled>div{pointer-events:none}.dropup-menu-item-disabled:hover,.dropup-menu-item-disabled:focus-visible{background-color:transparent}.dropup-menu-item-disabled:active{background-color:transparent}.dropup-menu-item-disabled>.dropup-menu-item-icon{filter:brightness(0) saturate(100%) invert(67%) sepia(0%) saturate(818%) hue-rotate(28deg) brightness(102%) contrast(100%)}#input{width:100%;display:inline-flex;text-align:center;margin-left:auto;margin-right:auto;margin-top:auto;position:relative;justify-content:center}#chat-view{height:100%;display:grid;grid-template-columns:100%}::-webkit-scrollbar{width:9px;height:9px}::-webkit-scrollbar-thumb{background-color:#d0d0d0;border-radius:5px}::-webkit-scrollbar-track{background-color:#f2f2f2}.deep-chat-web-model-button{margin-top:10px;margin-bottom:5px;margin-left:1px}:host{all:initial;display:table-cell}#container{height:inherit;width:inherit;overflow:hidden}',this.shadowRoot),setTimeout((()=>{this._hasBeenRendered||this.onRender()}),20)}changeToChatView(){this._activeService&&(this._activeService.validateKeyProperty=!1),this.onRender()}onRender(){n.attemptAppendStyleSheetToHead(this.style),O.processConnect(this),(!this._activeService||this._activeService.demo)&&(this._activeService=ws.create(this)),this.auxiliaryStyle&&!this._auxiliaryStyleApplied&&(r.apply(this.auxiliaryStyle,this.shadowRoot),this._auxiliaryStyleApplied=!0),r.applyDefaultStyleToComponent(this.style,this.chatStyle),O.checkForContainerStyles(this,this._elementRef),this._activeService.key&&this._activeService.validateKeyProperty?e.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):this._activeService instanceof Ve&&!this._activeService.key?this._activeService instanceof Ve&&Ye.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):(this._childElement??(this._childElement=this.children[0]),xo.render(this,this._elementRef,this._activeService,this._childElement)),this._hasBeenRendered||he.onRender(this),this._hasBeenRendered=!0}disconnectedCallback(){si.chat=void 0}}_o([_s("object")],So.prototype,"connect"),_o([_s("object")],So.prototype,"directConnection"),_o([_s("object")],So.prototype,"webModel"),_o([_s("object")],So.prototype,"requestBodyLimits"),_o([_s("function")],So.prototype,"requestInterceptor"),_o([_s("function")],So.prototype,"responseInterceptor"),_o([_s("function")],So.prototype,"validateInput"),_o([_s("function")],So.prototype,"loadHistory"),_o([_s("object")],So.prototype,"chatStyle"),_o([_s("object")],So.prototype,"attachmentContainerStyle"),_o([_s("object")],So.prototype,"dropupStyles"),_o([_s("object")],So.prototype,"inputAreaStyle"),_o([_s("object")],So.prototype,"textInput"),_o([_s("object")],So.prototype,"submitButtonStyles"),_o([_s("object")],So.prototype,"customButtons"),_o([_s("string")],So.prototype,"auxiliaryStyle"),_o([_s("array")],So.prototype,"history"),_o([_s("object")],So.prototype,"introMessage"),_o([_s("object")],So.prototype,"avatars"),_o([_s("object")],So.prototype,"names"),_o([_s("object")],So.prototype,"displayLoadingBubble"),_o([_s("object")],So.prototype,"errorMessages"),_o([_s("object")],So.prototype,"messageStyles"),_o([_s("object")],So.prototype,"textToSpeech"),_o([_s("object")],So.prototype,"speechToText"),_o([_s("object")],So.prototype,"images"),_o([_s("object")],So.prototype,"gifs"),_o([_s("object")],So.prototype,"camera"),_o([_s("object")],So.prototype,"audio"),_o([_s("object")],So.prototype,"microphone"),_o([_s("object")],So.prototype,"mixedFiles"),_o([_s("object")],So.prototype,"dragAndDrop"),_o([_s("object")],So.prototype,"introPanelStyle"),_o([_s("object")],So.prototype,"htmlClassUtilities"),_o([_s("object")],So.prototype,"remarkable"),_o([_s("object")],So.prototype,"focusMode"),_o([_s("function")],So.prototype,"onMessage"),_o([_s("function")],So.prototype,"onClearMessages"),_o([_s("function")],So.prototype,"onComponentRender"),_o([_s("function")],So.prototype,"onError"),_o([_s("object")],So.prototype,"demo"),_o([_s("object")],So.prototype,"_insertKeyViewStyles"),customElements.define("deep-chat",So);export{So as DeepChat};