deep-chat-dev 9.0.359 → 9.0.361

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
- const t="classList",e="style",s=(t="div")=>document.createElement(t);class i{static render(t,e){const i=s();i.id="error-view",i.innerText=e,t.replaceChildren(i)}}class n{static onLoad(t){t.innerHTML='<div id="loading-validate-key-property"></div>'}static createElements(){const t=s();return t.id="validate-property-key-view",t}static render(t,e,s){const o=n.createElements(),r={onSuccess:e,onFail:i.render.bind(this,t,"Your 'key' has failed authentication"),onLoad:n.onLoad.bind(this,o)};s.key&&s.verifyKey(s.key,r),t.replaceChildren(o)}}const o="service",r="text",a="html",l="error",c="https://deepchat.dev/docs/",h="ai",u="user",d="assistant",p="error-message-text",m="deep-chat-outer-container-role-",v="empty-message",f="deep-chat-top-message",g="deep-chat-middle-message",b="deep-chat-bottom-message",y="src",w="type",x="file",k="files",_="image",M="images",C="camera",A="gifs",T="audio",S="microphone",j="mixedFiles",E="any",I="file-message",$="start",O="messages",P="role",B="string",R=t=>JSON.stringify(t),F=t=>JSON.parse(R(t));function L(t){return t.charAt(0).toUpperCase()+t.slice(1)}function q(t,e,s,i){const n=`\n${L(e)} message: ${R(t)} \n`,o=s?`${L(e)} message after interceptor: ${function(t){return t&&R(t)}(i)} \n`:"";return n+o}const z=function(t,e,s,i){return`${q(t,e,s,i)}Make sure the ${e} message is using the Response format: ${c}connect/#Response \nYou can also augment it using the responseInterceptor property: ${c}interceptors#responseInterceptor`},D=function(t,e){const s="request";return`${q(t,s,e)}Make sure the ${s} message is using the {body: {text: string}} format, e.g: {body: {text: "Model Response"}}`},N=function(t,e,s){const i="response";return`${q(t,i,e,s)}Make sure the ${i} message is using the {text: string} format, e.g: {text: "Model Response"}`},U=function(t){return`${t} failed - please wait for chat view to render before calling this property.`},H="Invalid API Key",V="Failed to connect",W="Request settings have not been set up",G="No file was added",Z="Image was not found",K="Multi-response arrays are not supported for streaming",J=`Make sure the events are using {text: string} or {html: string} format.\nYou can also augment them using the responseInterceptor property: ${c}interceptors#responseInterceptor`,X=`No valid stream events were sent.\n${J}`,Q="Please define a `function_handler` property inside the service config.",Y="Function tool response must be an array or contain a text property",tt="Failed to fetch history",et="inside-start",st="inside-end",it="outside-start",nt="outside-end",ot="dropup-menu",rt="default",at="hover",lt="click",ct="active",ht="disabled",ut="svg",dt="unavailable",pt="styles",mt="mouseenter",vt="mouseleave",ft="submit",gt="loading",bt="stop";class yt{static unsetStyle(t,s){const i=Object.keys(s).reduce((t,e)=>(t[e]="",t),{});Object.assign(t[e],i)}static unsetActivityCSSMouseStates(t,e){e[lt]&&yt.unsetStyle(t,e[lt]),e[at]&&yt.unsetStyle(t,e[at])}static unsetAllCSSMouseStates(t,e){yt.unsetActivityCSSMouseStates(t,e),e[rt]&&yt.unsetStyle(t,e[rt])}static processStateful(t){const e=t[rt]||{},s=Object.assign(F(e),null==t?void 0:t[at]),i=Object.assign(F(s),null==t?void 0:t[lt]);return{[rt]:e,[at]:s,[lt]:i}}static mergeStatefulStyles(t){const e={[rt]:{},[at]:{},[lt]:{}};return t.forEach(t=>{e[rt]=Object.assign(e[rt],t[rt]),e[at]=Object.assign(e[at],t[at]),e[lt]=Object.assign(e[lt],t[lt])}),e}static overwriteDefaultWithAlreadyApplied(t,s){Object.keys(t[rt]||[]).forEach(i=>{var n;const o=i;s[e][o]&&null!=(n=t[rt])&&n[o]&&(t[rt][i]=s[e][o])})}static applyToStyleIfNotDefined(t,e){for(const s in e){const i=e[s];""===t[s]&&i&&(t[s]=i)}}}const wt=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=s("link");e.rel="stylesheet",e.href=t.FONT_URL,i.appendChild(e)}}};wt.FONT_URL="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap",wt.DEFAULT_FONT_FAMILY="'Inter', sans-serif, Avenir, Helvetica, Arial";let xt=wt;const kt=class t{static apply(e,s){if(s)try{t.applyStyleSheet(e,s)}catch{t.addStyleElement(e,s)}}static applyStyleSheet(t,e){const s=new CSSStyleSheet;s.replaceSync(t),e.adoptedStyleSheets.push(s)}static addStyleElement(t,e){const i=s("style");i.innerHTML=t,e.appendChild(i)}static applyDefaultStyleToComponent(e,s){s&&yt.applyToStyleIfNotDefined(e,s),yt.applyToStyleIfNotDefined(e,t.DEFAULT_COMPONENT_STYLE)}};kt.DEFAULT_COMPONENT_STYLE={height:"350px",width:"320px",borderTop:"1px solid #cacaca",borderRight:"1px solid #cacaca",borderLeft:"1px solid #cacaca",borderBottom:"1px solid #cacaca",fontFamily:xt.DEFAULT_FONT_FAMILY,fontSize:"0.9rem",backgroundColor:"white",position:"relative",overflow:"hidden"};let _t=kt;const Mt=class i{static buildElement(){const e=s();e[t].add("tooltip");const i=s("span");return i[t].add("tooltip-text"),e.appendChild(i),e}static tryCreateConfig(t,s){if(s)return"boolean"==typeof s?{[r]:t}:{[r]:s[r]||t,timeout:s.timeout||0,style:s[e]}}static traverseParentUntilContainer(t){let e=t;for(;e.parentElement;)e=e.parentElement;return e}static setPosition(t,s){const n=s.getRootNode().host.getBoundingClientRect(),o=t.getBoundingClientRect(),r=s.getBoundingClientRect().width/2,a=o.left+o.width/2;s[e].left=a-r-n.left+"px",s[e].top=o.top-36-n.top+"px";const l=s.getBoundingClientRect();l.left<n.left?s[e].left=`${i.OVERFLOW_NEW_POSITION_PX}px`:l.right>n.right&&(s[e].left=n.width-l.width-i.OVERFLOW_NEW_POSITION_PX+"px")}static display(t,s,n){return n||(n=i.traverseParentUntilContainer(t).nextSibling),s[r]&&(n.children[0].textContent=s[r]),{timeout:setTimeout(()=>{n[e].visibility="visible",i.setPosition(t,n),s[e]&&Object.assign(n[e],s[e])},s.timeout||0),element:n}}static hide(t,s){clearTimeout(t.timeout),t.element[e].visibility="hidden",s[e]&&yt.unsetStyle(t.element,s[e]),t.element[e].left="",t.element[e].top=""}};Mt.OVERFLOW_NEW_POSITION_PX=4;let Ct=Mt;const At=class{};At.IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),At.IS_CHROMIUM=window.chrome,At.IS_MOBILE=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent);let Tt=At;var St=(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))(St||{});const jt=class t{static add(e,s,i,n){void 0!==i&&e.addEventListener("keydown",t.onKeyDown.bind(this,i)),e.oninput=t.onInput.bind(this,i,n),e.addEventListener("paste",t=>{var e;t.preventDefault(),null!=(e=t.clipboardData)&&e[k].length&&s.addFilesToAnyType(Array.from(t.clipboardData[k]))})}static onKeyDown(e,s){const i=s.target.textContent;i&&i.length>=e&&!t.PERMITTED_KEYS.has(s.key)&&!t.isKeyCombinationPermitted(s)&&s.preventDefault()}static isKeyCombinationPermitted(t){return"a"===t.key&&(t.ctrlKey||t.metaKey)}static onInput(t,e,s){const i=s.target,n=i.textContent||"";void 0!==t&&n.length>t&&(i.textContent=n.substring(0,t),Pt.focusEndOfInput(i)),null==e||e()}};jt.PERMITTED_KEYS=new Set([St.BACKSPACE,St.DELETE,St.ARROW_RIGHT,St.ARROW_LEFT,St.ARROW_DOWN,St.ARROW_UP,St.META,St.CONTROL,St.ENTER]);let Et=jt;class It{static sanitizePastedTextContent(t){var e,s;t.preventDefault();const i=null==(e=t.clipboardData)?void 0:e.getData("text/plain");i&&(null==(s=document.execCommand)||s.call(document,"insertText",!1,i))}}const $t=class i{constructor(t,e,s,n){var o,a,l,c;this._isComposing=!1;const h=i.processConfig(e,t.textInput);this.elementRef=i.createContainerElement(null==(o=null==h?void 0:h[pt])?void 0:o.container),this._config=h,this.inputElementRef=this.createInputElement(null==(a=t.defaultInput)?void 0:a[r],n),i.addFilesToAnyType(s,null==(l=t.defaultInput)?void 0:l[k]),this.elementRef.appendChild(this.inputElementRef),t.setPlaceholderText=this.setPlaceholderText.bind(this),t.setPlaceholderText((null==(c=this._config.placeholder)?void 0:c[r])||"Ask me anything!"),this._browserStorage=n,setTimeout(()=>{Et.add(this.inputElementRef,s,this._config.characterLimit,t._validationHandler),this._onInput=e.onInput})}static processConfig(t,e){var s;return e??(e={}),e[ht]??(e[ht]=t.isTextInputDisabled),e.placeholder??(e.placeholder={}),(s=e.placeholder)[r]??(s[r]=t.textInputPlaceholderText),e}static createContainerElement(t){const i=s();return i.id="text-input-container",Object.assign(i[e],t),i}static preventAutomaticScrollUpOnNewLine(t){let e;t.addEventListener("keydown",()=>{e=window.scrollY}),t.addEventListener("input",()=>{e!==window.scrollY&&window.scrollTo({top:e})})}clear(){var s,i,n;const o=window.scrollY;this.inputElementRef[t].contains(`text-input-${ht}`)||(Object.assign(this.inputElementRef[e],null==(s=this._config.placeholder)?void 0:s[e]),this.inputElementRef.textContent="",Pt.focusEndOfInput(this.inputElementRef),null==(i=this._onInput)||i.call(this,!1),null==(n=this._browserStorage)||n.addInputText("")),Tt.IS_CHROMIUM&&window.scrollTo({top:o})}createInputElement(n,o){var a,l,c,h;const u=s();return u.id=i.TEXT_INPUT_ID,u[t].add("text-input-styling"),u[P]="textbox","string"==typeof n?u.innerText=n:null!=o&&o.trackInputText&&(u.innerText=o.get().inputText||""),Tt.IS_MOBILE&&u.setAttribute("tabindex","0"),Tt.IS_CHROMIUM&&i.preventAutomaticScrollUpOnNewLine(u),"boolean"==typeof this._config[ht]&&!0===this._config[ht]?(u.contentEditable="false",u[t].add(`text-input-${ht}`),u.setAttribute(`aria-${ht}`,"true")):(u.contentEditable="true",u.removeAttribute(`aria-${ht}`),this.addEventListeners(u)),Object.assign(u[e],null==(a=this._config[pt])?void 0:a[r]),Object.assign(u[e],null==(l=this._config.placeholder)?void 0:l[e]),null!=(h=null==(c=this._config.placeholder)?void 0:c[e])&&h.color||u.setAttribute("textcolor",""),u}static addFilesToAnyType(t,e){e&&t.addFilesToAnyType(Array.from(e).map(t=>t))}removePlaceholderStyle(){var s,i,n,o;!this.inputElementRef[t].contains(`text-input-${ht}`)&&null!=(s=this._config.placeholder)&&s[e]&&(yt.unsetStyle(this.inputElementRef,null==(i=this._config.placeholder)?void 0:i[e]),Object.assign(this.inputElementRef[e],null==(o=null==(n=this._config)?void 0:n[pt])?void 0:o[r]))}addEventListeners(t){var s,i;null!=(s=this._config[pt])&&s.focus&&(t.onfocus=()=>{var t;return Object.assign(this.elementRef[e],null==(t=this._config[pt])?void 0:t.focus)},t.onblur=this.onBlur.bind(this,this._config[pt].focus,null==(i=this._config[pt])?void 0:i.container)),t.addEventListener("keydown",this.onKeydown.bind(this)),t.addEventListener("input",this.onInput.bind(this)),t.addEventListener("paste",It.sanitizePastedTextContent),t.addEventListener("compositionstart",()=>this._isComposing=!0),t.addEventListener("compositionend",()=>this._isComposing=!1)}onBlur(t,s){yt.unsetStyle(this.elementRef,t),s&&Object.assign(this.elementRef[e],s)}onKeydown(t){var e;t.key===St.ENTER&&!Tt.IS_MOBILE&&!this._isComposing&&!t.ctrlKey&&!t.shiftKey&&(t.preventDefault(),null==(e=this.submit)||e.call(this))}onInput(){var t,s;this.isTextInputEmpty()?Object.assign(this.inputElementRef[e],null==(t=this._config.placeholder)?void 0:t[e]):this.removePlaceholderStyle(),null==(s=this._onInput)||s.call(this,!0)}setPlaceholderText(t){this.inputElementRef.setAttribute("deep-chat-placeholder-text",t),this.inputElementRef.setAttribute("aria-label",t)}isTextInputEmpty(){return""===this.inputElementRef.textContent}};$t.TEXT_INPUT_ID="text-input";let Ot=$t;class Pt{static focusEndOfInput(t){const e=document.createRange();e.selectNodeContents(t),e.collapse(!1);const s=window.getSelection();null==s||s.removeAllRanges(),null==s||s.addRange(e),(Tt.IS_MOBILE||Tt.IS_SAFARI)&&t.focus()}static focusFromParentElement(t){const e=t.querySelector(`#${Ot.TEXT_INPUT_ID}`);e&&Pt.focusEndOfInput(e)}}const Bt="Authentication",Rt="Authorization",Ft="authorization",Lt="Unauthorized",qt="Authorization header",zt="Invalid",Dt="Incorrect",Nt="authentication_error",Ut="invalid_request_error",Ht="Content-Type",Vt="content-type",Wt="application/json",Gt="object",Zt="completed",Kt="Bearer ",Jt="GET",Xt="POST",Qt="Upload an audio file",Yt="function_call",te="input_audio",ee="image_url",se="system",ie=class t{static addElements(t,...e){e.forEach(e=>t.appendChild(e))}static isScrollbarAtBottomOfElement(e,s=t.CODE_SNIPPET_GENERATION_JUMP){const i=e.scrollHeight,n=e.clientHeight;return e.scrollTop>=i-n-s}static cloneElement(t){const e=t.cloneNode(!0);return t.parentNode.replaceChild(e,t),e}static scrollToBottom(t,e=!1,s){t.scrollButton&&t.scrollButton.hiddenElements.size>0&&t.scrollButton.clearHidden(),s?t.elementRef.scrollTo({left:0,top:s.offsetTop}):e?t.elementRef.scrollTo({left:0,top:t.elementRef.scrollHeight,behavior:"smooth"}):t.elementRef.scrollTop=t.elementRef.scrollHeight}static scrollToTop(t){t.scrollTop=0}static isVisibleInParent(t,e){const s=t.getBoundingClientRect(),i=e.getBoundingClientRect();return s.bottom>i.top&&s.top<i.bottom}static waitForScrollEnd(t,e){let s=-1,i=0;const n=()=>{const o=t.scrollTop;if(o===s){if(i++,i>2)return void e()}else i=0,s=o;requestAnimationFrame(n)};requestAnimationFrame(n)}static assignButtonEvents(t,e){t.onclick=e,t.onkeydown=t=>{t.key===St.ENTER&&setTimeout(e)}}};ie.CODE_SNIPPET_GENERATION_JUMP=1;let ne=ie;const oe=class t{static speak(t,e){if(!e.audio&&window.SpeechSynthesisUtterance){const s=new SpeechSynthesisUtterance(t);Object.assign(s,e),speechSynthesis.speak(s)}}static processConfig(e,s){const i={};setTimeout(()=>{if("object"==typeof e&&(e.audio&&(i.audio=e.audio),e.lang&&(i.lang=e.lang),e.pitch&&(i.pitch=e.pitch),e.rate&&(i.rate=e.rate),e.volume&&(i.volume=e.volume),e.voiceName)){const t=window.speechSynthesis.getVoices().find(t=>{var s;return t.name.toLocaleLowerCase()===(null==(s=e.voiceName)?void 0:s.toLocaleLowerCase())});t&&(i.voice=t)}s(i)},t.LOAD_VOICES_MS)}};oe.LOAD_VOICES_MS=200;let re=oe;const ae=class t{static colorToHex(t){const i=s();return i[e].color=t,document.body.appendChild(i),`#${window.getComputedStyle(i).color.match(/\d+/g).map(t=>parseInt(t).toString(16).padStart(2,"0")).join("")}`}static setDots(s,i){var n,o;if(null!=(o=null==(n=null==i?void 0:i[pt])?void 0:n.bubble)&&o.color){const n=t.colorToHex(i[pt].bubble.color);s[e].setProperty("--loading-message-color",n),s[e].setProperty("--loading-message-color-fade",`${n}33`)}else s[e].setProperty("--loading-message-color","#848484"),s[e].setProperty("--loading-message-color-fade","#55555533")}static setRing(s,i){const{color:n,width:o,height:r,margin:a,border:l}=i||{};if(n){const i=t.colorToHex(n);s[e].setProperty("--loading-history-color",i)}else s[e].setProperty("--loading-history-color","#dbdbdb");s[e].setProperty("--loading-history-height",r||"57px"),s[e].setProperty("--loading-history-width",o||"57px"),s[e].setProperty("--loading-history-margin",a||"7px"),s[e].setProperty("--loading-history-border",l||"6px solid")}};ae.BUBBLE_CLASS="deep-chat-loading-message-bubble",ae.DOTS_CONTAINER_CLASS="deep-chat-loading-message-dots-container";let le=ae;class ce{static checkForContainerStyles(t,s){const i=t.containerStyle;i&&(Object.assign(s[e],i),console[l](`The containerStyle property${ue}1.3.14.`),console[l](`${de}the style property instead: ${c}styles#style`))}static handleResponseProperty(t){return console[l](`The {result: ....} response object type${ue}1.3.0.`),console[l](`${de}the new response object: ${c}connect#Response`),t.result}static processHistory(t){const e=t.initialMessages;if(e)return console[l](`The initialMessages property${ue}2.0.0.`),console[l](`${de}the history property instead: ${c}messages/#history`),e}static processHistoryFile(t){const e=t[x];e&&(console[l](`The file property in MessageContent${ue}1.3.17.`),console[l](`${de}the files array property: ${c}messages/#MessageContent`),t[k]=[e])}static processValidateInput(t){const e=t.validateMessageBeforeSending;if(e)return console[l](`The validateMessageBeforeSending property${ue}1.3.24.`),console[l](`${de}validateInput: ${c}interceptors#validateInput`),e}static processSubmitUserMessage(t){return console[l](`The submitUserMessage(text: string) argument string type${ue}1.4.4.`),console[l](`${de}the new argument type: ${c}methods#submitUserMessage`),{[r]:t}}static flagHTMLUpdateClass(e){var s;null!=(s=e.children[0])&&s[t].contains("deep-chat-update-message")&&(console[l](`The "deep-chat-update-message" html class${ue}1.4.4.`),console[l](`${de}using {..., overwrite: true} object: ${c}connect#Response`))}static processConnect(t){const e=t;e.request&&(e.connect?Object.assign(e.connect,e.request):e.connect=e.request,console[l](`The request property${ue}2.0.0.`),console[l](`${pe}connect object: ${c}connect#connect-1`))}static checkForStream(t){const e=t.stream;if(e)return console[l](`The stream property${ve}the connect object in version 2.0.0.`),console[l](`${pe}connect object: ${c}connect#connect-1`),e}static fireOnNewMessage(t,e){var s;const i=t;i.onNewMessage&&(console[l](`The onNewMessage event${ue}2.0.0.`),console[l](`${pe}onMessage event: ${c}events#onMessage`),null==(s=i.onNewMessage)||s.call(i,e)),t.dispatchEvent(new CustomEvent("new-message",{detail:e}))}static processFileConfigConnect(t){const e=t;e.request&&(console[l](`The request property in file configuration${ue}2.0.0.`),console[l](`Please use the connect property instead: ${c}files`),e.connect||(e.connect=e.request))}static processMessageStyles(t){if(!t)return;const e=F(t),s=e.loading;return s&&(s.outerContainer||s.innerContainer||s.bubble||s.media)&&(console[l](`The loading message styles are defined using LoadingMessageStyles interface${he}2.1.0.`),console[l](`Check it out here: ${c}messages/styles#LoadingMessageStyles`),e.loading={message:{styles:s}}),e}static processDemo(t){return"boolean"==typeof t||t.displayLoadingBubble&&(console[l](`The demo displayLoadingBubble property${ue}2.1.0.`),console[l](`Please use displayLoading instead: ${c}modes#demo`),t.displayLoading={message:!0}),t}static processCohere(t){const e=t,s=`${pe}official documentation: ${c}directConnection/Cohere`;return e.chat&&(console[l](`Cohere chat property${ue}2.2.3.`),console[l](s),delete e.chat),e.textGeneration?(console[l](`Cohere textGeneration${me}2.2.3.`),console[l](s),delete e.textGeneration,!1):!e.summarization||(console[l](`Cohere summarization${me}2.2.3.`),console[l](s),delete e.summarization,!1)}static processStreamHTMLWrappers(t){if(!t||typeof t!==Gt)return;const e=t.htmlWrappers;return e?(console[l](`The htmlWrappers property${ve}Deep Chat's base${he}2.3.0.`),console[l](`Check it out here: ${c}messages/HTML#htmlWrappers`),e):void 0}static processFocusMode(t){return!t||"boolean"==typeof t||t.scroll&&(console[l](`The scroll property in focusMode has been changed to smoothScroll${he}2.3.0.`),console[l](`Check it out here: ${c}modes#focusMode`),t.smoothScroll=!0),t}static processPosition(t){if(!t)return t;const e=`Position names have been updated${he}2.3.1.`;return"inside-left"===t?(console[l](e),et):"inside-right"===t?(console[l](e),st):"outside-left"===t?(console[l](e),it):"outside-right"===t?(console[l](e),nt):t}static processBrowserStorage(t){const e=t.get();e&&Array.isArray(e)&&t.addMessages(e)}}const he=" since version ",ue=` is deprecated ${he}`,de="Please change to using ",pe="Please see the ",me=` is not supported ${he}`,ve=" has been moved to ";class fe{static mouseUp(t,s){yt.unsetAllCSSMouseStates(t,s),Object.assign(t[e],s[rt]),Object.assign(t[e],s[at])}static mouseDown(t,s){Object.assign(t[e],s[lt])}static mouseLeave(t,s){yt.unsetAllCSSMouseStates(t,s),Object.assign(t[e],s[rt])}static mouseEnter(t,s){Object.assign(t[e],s[at])}static add(t,e){t.addEventListener(mt,fe.mouseEnter.bind(this,t,e)),t.addEventListener(vt,fe.mouseLeave.bind(this,t,e)),t.addEventListener("mousedown",fe.mouseDown.bind(this,t,e)),t.addEventListener("mouseup",fe.mouseUp.bind(this,t,e))}}const ge={"deep-chat-button":{styles:{[rt]:{backgroundColor:"white",padding:"5px",paddingLeft:"7px",paddingRight:"7px",border:"1px solid #c2c2c2",borderRadius:"6px",cursor:"pointer"},[at]:{backgroundColor:"#fafafa"},[lt]:{backgroundColor:"#f1f1f1"}}}},be=Object.keys(ge);class ye{static applySuggestionEvent(t,e){setTimeout(()=>{e.addEventListener(lt,()=>{var s,i;null==(i=t.submitUserMessage)||i.call(t,{[r]:(null==(s=e.textContent)?void 0:s.trim())||""})})})}static isElementTemporary(e){var s;return!!e&&(null==(s=e.bubbleElement.children[0])?void 0:s[t].contains("deep-chat-temporary-message"))}static doesElementContainDeepChatClass(e){return be.find(s=>e[t].contains(s))}static applyEvents(t,e){const s=ge[e].events;Object.keys(s||[]).forEach(e=>{t.addEventListener(e,null==s?void 0:s[e])})}static getProcessedStyles(e,s,i){const n=Array.from(s[t]).reduce((t,s)=>{var i;const n=null==(i=e[s])?void 0:i[pt];return n&&e[s][pt]&&t.push(n),t},[]),o=ge[i][pt];if(o){const t=F(o);t[rt]&&yt.overwriteDefaultWithAlreadyApplied(t,s),n.unshift(t)}const r=yt.mergeStatefulStyles(n);return yt.processStateful(r)}static applyDeepChatUtilities(t,e,s){be.forEach(t=>{const i=s.getElementsByClassName(t);Array.from(i||[]).forEach(s=>{const i=ye.getProcessedStyles(e,s,t);we.applyStylesToElement(s,i),ye.applyEvents(s,t)})});const i=s.getElementsByClassName("deep-chat-suggestion-button");Array.from(i).forEach(e=>ye.applySuggestionEvent(t,e))}}class we{static applyStylesToElement(t,s){const i=yt.processStateful(s);fe.add(t,i),Object.assign(t[e],i[rt])}static applyEventsToElement(t,e){Object.keys(e).forEach(s=>{const i=e[s];i&&t.addEventListener(s,i)})}static applyClassUtilitiesToElement(t,e){const{events:s,styles:i}=e;s&&we.applyEventsToElement(t,s),i&&!ye.doesElementContainDeepChatClass(t)&&we.applyStylesToElement(t,i)}static applyCustomClassUtilities(t,e){Object.keys(t).forEach(s=>{const i=e.getElementsByClassName(s);Array.from(i).forEach(e=>{t[s]&&we.applyClassUtilitiesToElement(e,t[s])})})}static apply(t,e){ye.applyDeepChatUtilities(t,t.htmlClassUtilities,e),we.applyCustomClassUtilities(t.htmlClassUtilities,e)}static traverseNodes(t,e){t.nodeType===Node.ELEMENT_NODE&&e.push(t.outerHTML),t.childNodes.forEach(t=>{we.traverseNodes(t,e)})}static splitHTML(t){const e=(new DOMParser).parseFromString(t,"text/html"),s=[];return e.body.childNodes.forEach(t=>{we.traverseNodes(t,s)}),s}static isTemporaryBasedOnHTML(t){const e=s();return e.innerHTML=t,ye.isElementTemporary({outerContainer:e,bubbleElement:e,innerContainer:e})}static replaceElementWithNewClone(t,e){var s;const i=(e||t).cloneNode(!0);return null==(s=t.parentNode)||s.replaceChild(i,t),i}static tryAddWrapper(t,e,s,i){if(e&&i){const e=(null==s?void 0:s[i])||(null==s?void 0:s[rt]);if(e)return t.innerHTML=e,{contentEl:we.getTargetWrapper(t),wrapper:!0}}return{contentEl:t,wrapper:!1}}static getTargetWrapper(t){return t.getElementsByClassName("html-wrapper")[0]||t}}const xe=class e{static createElements(s,i,n,o,r=!1){const a=s.createMessageElementsOnOrientation("",n,o,r);a.bubbleElement[t].add(e.HTML_BUBBLE_CLASS);const{contentEl:l}=we.tryAddWrapper(a.bubbleElement,i,s._customWrappers,n);return l.innerHTML=i,a}static overwriteElements(t,e,s){s.bubbleElement.innerHTML=e,we.apply(t,s.outerContainer),ce.flagHTMLUpdateClass(s.bubbleElement)}static overwrite(t,s,i,n){const{messageToElements:o}=t,r=pi.overwriteMessage(o,n,s,i,a,e.HTML_BUBBLE_CLASS);return r&&e.overwriteElements(t,s,r),r}static create(t,s,i,n=!1){var o;const r=e.createElements(t,s,i,n);return pi.fillEmptyMessageElement(r.bubbleElement,s),we.apply(t,r.outerContainer),ce.flagHTMLUpdateClass(r.bubbleElement),t.applyCustomStyles(r,i,!1,null==(o=t.messageStyles)?void 0:o[a]),r}static add(t,s,i,n,o=!1){if(null!=n&&n.status){const e=this.overwrite(t,s,i,t.messageElementRefs);if(e)return e;n.status=!1}if(o&&t.messageElementRefs.length>0&&we.isTemporaryBasedOnHTML(s))return;const r=e.create(t,s,i,o);return o||t.appendOuterContainerElemet(r.outerContainer),r}};xe.HTML_BUBBLE_CLASS="html-message";let ke=xe;class _e{static katex(t,e,s){const i=(s||{}).delimiter||"$";if(1!==i.length)throw new Error("invalid delimiter");e.inline.ruler.push("katex",(t,e)=>{const s=t.pos,n=t.posMax;let o=s;if(t[y].charAt(o)!==i)return!1;for(++o;o<n&&t[y].charAt(o)===i;)++o;const r=t[y].slice(s,o);if(r.length>2)return!1;const a=o;let l=0;for(;o<n;){const s=t[y].charAt(o);if("{"!==s||0!==o&&"\\"===t[y].charAt(o-1)){if("}"!==s||0!==o&&"\\"===t[y].charAt(o-1)){if(s===i&&0===l){const s=o;let l=o+1;for(;l<n&&t[y].charAt(l)===i;)++l;if(l-s===r.length){if(!e){const e=t[y].slice(a,s).replace(/[ \n]+/g," ").trim();t.push({type:"katex",content:e,block:r.length>1,level:t.level})}return t.pos=l,!0}}}else if(l-=1,l<0)return!1}else l+=1;o+=1}return e||(t.pending+=r),t.pos+=r.length,!0},s),e.block.ruler.push("katex",(t,e,s)=>{let n=!1,o=t.bMarks[e]+t.tShift[e],r=t.eMarks[e];if(o+1>r)return!1;const a=t[y].charAt(o);if(a!==i)return!1;let l=o;o=t.skipChars(o,a);let c=o-l;if(2!==c)return!1;let h=e;for(;++h,!(h>=s||(o=l=t.bMarks[h]+t.tShift[h],r=t.eMarks[h],o<r&&t.tShift[h]<t.blkIndent));)if(!(t[y].charAt(o)!==i||t.tShift[h]-t.blkIndent>=4||(o=t.skipChars(o,a),o-l<c||(o=t.skipSpaces(o),o<r)))){n=!0;break}c=t.tShift[e],t.line=h+(n?1:0);const u=t.getLines(e+1,h,c,!0).replace(/[ \n]+/g," ").trim();return t.tokens.push({type:"katex",params:null,content:u,lines:[e,t.line],level:t.level,block:!0}),!0},s),e.renderer.rules.katex=(e,s)=>((e,s)=>{var i;return(null==(i=window.katex)?void 0:i.renderToString(e,{displayMode:s,throwOnError:!1,output:"mathml",...t}))||""})(e[s].content,e[s].block),e.renderer.rules.katex.delimiter=i}}var Me;function Ce(t){return(Me=Me||document.createElement("textarea")).innerHTML="&"+t+";",Me.value}var Ae=Object.prototype.hasOwnProperty;function Te(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(s){t[s]=e[s]})}}),t}var Se=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function je(t){return t.indexOf("\\")<0?t:t.replace(Se,"$1")}function Ee(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 Ie(t){if(t>65535){var e=55296+((t-=65536)>>10),s=56320+(1023&t);return String.fromCharCode(e,s)}return String.fromCharCode(t)}var $e=/&([a-z#][a-z0-9]{1,31});/gi,Oe=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;function Pe(t,e){var s=0,i=Ce(e);return e!==i?i:35===e.charCodeAt(0)&&Oe.test(e)&&Ee(s="x"===e[1].toLowerCase()?parseInt(e.slice(2),16):parseInt(e.slice(1),10))?Ie(s):t}function Be(t){return t.indexOf("&")<0?t:t.replace($e,Pe)}var Re=/[&<>"]/,Fe=/[&<>"]/g,Le={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function qe(t){return Le[t]}function ze(t){return Re.test(t)?t.replace(Fe,qe):t}var De={};function Ne(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?Ne(t,e+2):e}De.blockquote_open=function(){return"<blockquote>\n"},De.blockquote_close=function(t,e){return"</blockquote>"+Ue(t,e)},De.code=function(t,e){return t[e].block?"<pre><code>"+ze(t[e].content)+"</code></pre>"+Ue(t,e):"<code>"+ze(t[e].content)+"</code>"},De.fence=function(t,e,s,i,n){var o,r,a=t[e],l="",c=s.langPrefix;if(a.params){if(r=(o=a.params.split(/\s+/g)).join(" "),function(t,e){return!!t&&Ae.call(t,e)}(n.rules.fence_custom,o[0]))return n.rules.fence_custom[o[0]](t,e,s,i,n);l=' class="'+c+ze(Be(je(r)))+'"'}return"<pre><code"+l+">"+(s.highlight&&s.highlight.apply(s.highlight,[a.content].concat(o))||ze(a.content))+"</code></pre>"+Ue(t,e)},De.fence_custom={},De.heading_open=function(t,e){return"<h"+t[e].hLevel+">"},De.heading_close=function(t,e){return"</h"+t[e].hLevel+">\n"},De.hr=function(t,e,s){return(s.xhtmlOut?"<hr />":"<hr>")+Ue(t,e)},De.bullet_list_open=function(){return"<ul>\n"},De.bullet_list_close=function(t,e){return"</ul>"+Ue(t,e)},De.list_item_open=function(){return"<li>"},De.list_item_close=function(){return"</li>\n"},De.ordered_list_open=function(t,e){var s=t[e];return"<ol"+(s.order>1?' start="'+s.order+'"':"")+">\n"},De.ordered_list_close=function(t,e){return"</ol>"+Ue(t,e)},De.paragraph_open=function(t,e){return t[e].tight?"":"<p>"},De.paragraph_close=function(t,e){var s=!(t[e].tight&&e&&"inline"===t[e-1].type&&!t[e-1].content);return(t[e].tight?"":"</p>")+(s?Ue(t,e):"")},De.link_open=function(t,e,s){var i=t[e].title?' title="'+ze(Be(t[e].title))+'"':"",n=s.linkTarget?' target="'+s.linkTarget+'"':"";return'<a href="'+ze(t[e].href)+'"'+i+n+">"},De.link_close=function(){return"</a>"},De.image=function(t,e,s){var i=' src="'+ze(t[e].src)+'"',n=t[e].title?' title="'+ze(Be(t[e].title))+'"':"";return"<img"+i+(' alt="'+(t[e].alt?ze(Be(je(t[e].alt))):"")+'"')+n+(s.xhtmlOut?" /":"")+">"},De.table_open=function(){return"<table>\n"},De.table_close=function(){return"</table>\n"},De.thead_open=function(){return"<thead>\n"},De.thead_close=function(){return"</thead>\n"},De.tbody_open=function(){return"<tbody>\n"},De.tbody_close=function(){return"</tbody>\n"},De.tr_open=function(){return"<tr>"},De.tr_close=function(){return"</tr>\n"},De.th_open=function(t,e){var s=t[e];return"<th"+(s.align?' style="text-align:'+s.align+'"':"")+">"},De.th_close=function(){return"</th>"},De.td_open=function(t,e){var s=t[e];return"<td"+(s.align?' style="text-align:'+s.align+'"':"")+">"},De.td_close=function(){return"</td>"},De.strong_open=function(){return"<strong>"},De.strong_close=function(){return"</strong>"},De.em_open=function(){return"<em>"},De.em_close=function(){return"</em>"},De.del_open=function(){return"<del>"},De.del_close=function(){return"</del>"},De.ins_open=function(){return"<ins>"},De.ins_close=function(){return"</ins>"},De.mark_open=function(){return"<mark>"},De.mark_close=function(){return"</mark>"},De.sub=function(t,e){return"<sub>"+ze(t[e].content)+"</sub>"},De.sup=function(t,e){return"<sup>"+ze(t[e].content)+"</sup>"},De.hardbreak=function(t,e,s){return s.xhtmlOut?"<br />\n":"<br>\n"},De.softbreak=function(t,e,s){return s.breaks?s.xhtmlOut?"<br />\n":"<br>\n":"\n"},De.text=function(t,e){return ze(t[e].content)},De.htmlblock=function(t,e){return t[e].content},De.htmltag=function(t,e){return t[e].content},De.abbr_open=function(t,e){return'<abbr title="'+ze(Be(t[e].title))+'">'},De.abbr_close=function(){return"</abbr>"},De.footnote_ref=function(t,e){var s=Number(t[e].id+1).toString(),i="fnref"+s;return t[e].subId>0&&(i+=":"+t[e].subId),'<sup class="footnote-ref"><a href="#fn'+s+'" id="'+i+'">['+s+"]</a></sup>"},De.footnote_block_open=function(t,e,s){return(s.xhtmlOut?'<hr class="footnotes-sep" />\n':'<hr class="footnotes-sep">\n')+'<section class="footnotes">\n<ol class="footnotes-list">\n'},De.footnote_block_close=function(){return"</ol>\n</section>\n"},De.footnote_open=function(t,e){return'<li id="fn'+Number(t[e].id+1).toString()+'" class="footnote-item">'},De.footnote_close=function(){return"</li>\n"},De.footnote_anchor=function(t,e){var s="fnref"+Number(t[e].id+1).toString();return t[e].subId>0&&(s+=":"+t[e].subId),' <a href="#'+s+'" class="footnote-backref">↩</a>'},De.dl_open=function(){return"<dl>\n"},De.dt_open=function(){return"<dt>"},De.dd_open=function(){return"<dd>"},De.dl_close=function(){return"</dl>\n"},De.dt_close=function(){return"</dt>\n"},De.dd_close=function(){return"</dd>\n"};var Ue=De.getBreak=function(t,e){return(e=Ne(t,e))<t.length&&"list_item_close"===t[e].type?"":"\n"};function He(){this.rules=Te({},De),this.getBreak=De.getBreak}function Ve(){this.t=[],this.i=null}function We(t,e,s,i,n){this.src=t,this.env=i,this.options=s,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 Ge(t,e){var s,i,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,s=1;t.pos<r;){if(91===(n=t.src.charCodeAt(t.pos)))s++;else if(93===n&&0===--s){i=!0;break}t.parser.skipToken(t)}return i?(o=t.pos,t.labelUnmatchedScopes=0):t.labelUnmatchedScopes=s-1,t.pos=a,t.isInLabel=l,o}function Ze(t,e,s,i){var n,o,r,a,l,c;if(42!==t.charCodeAt(0)||91!==t.charCodeAt(1)||-1===t.indexOf("]:")||((o=Ge(n=new We(t,e,s,i,[]),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:(i.abbreviations||(i.abbreviations={}),typeof i.abbreviations[":"+l]>"u"&&(i.abbreviations[":"+l]=c),r)}function Ke(t){var e=Be(t);try{e=decodeURI(e)}catch{}return encodeURI(e)}function Je(t,e){var s,i,n,o=e,r=t.posMax;if(60===t.src.charCodeAt(e)){for(e++;e<r;){if(10===(s=t.src.charCodeAt(e)))return!1;if(62===s)return n=Ke(je(t.src.slice(o+1,e))),!!t.parser.validateLink(n)&&(t.pos=e+1,t.linkContent=n,!0);92===s&&e+1<r?e+=2:e++}return!1}for(i=0;e<r&&!(32===(s=t.src.charCodeAt(e))||s<32||127===s);)if(92===s&&e+1<r)e+=2;else{if(40===s&&++i>1||41===s&&--i<0)break;e++}return!(o===e||(n=je(t.src.slice(o,e)),!t.parser.validateLink(n)))&&(t.linkContent=n,t.pos=e,!0)}function Xe(t,e){var s,i=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((s=t.src.charCodeAt(e))===o)return t.pos=e+1,t.linkContent=je(t.src.slice(i+1,e)),!0;92===s&&e+1<n?e+=2:e++}return!1}function Qe(t){return t.trim().replace(/\s+/g," ").toUpperCase()}function Ye(t,e,s,i){var n,o,r,a,l,c,h,u,d;if(91!==t.charCodeAt(0)||-1===t.indexOf("]:")||((o=Ge(n=new We(t,e,s,i,[]),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(!Je(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&&Xe(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=Qe(t.slice(1,o)),typeof i.references[d]>"u"&&(i.references[d]={title:u,href:h}),r)}He.prototype.renderInline=function(t,e,s){for(var i=this.rules,n=t.length,o=0,r="";n--;)r+=i[t[o].type](t,o++,e,s,this);return r},He.prototype.render=function(t,e,s){for(var i=this.rules,n=t.length,o=-1,r="";++o<n;)"inline"===t[o].type?r+=this.renderInline(t[o].children,e,s):r+=i[t[o].type](t,o,e,s,this);return r},Ve.prototype.o=function(t){for(var e=this.t.length,s=-1;e--;)if(this.t[++s].name===t)return s;return-1},Ve.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(s){s.enabled&&(e&&s.alt.indexOf(e)<0||t.i[e].push(s.fn))})})},Ve.prototype.at=function(t,e,s){var i=this.o(t),n=s||{};if(-1===i)throw new Error("Parser rule not found: "+t);this.t[i].fn=e,this.t[i].alt=n.alt||[],this.i=null},Ve.prototype.before=function(t,e,s,i){var n=this.o(t),o=i||{};if(-1===n)throw new Error("Parser rule not found: "+t);this.t.splice(n,0,{name:e,enabled:!0,fn:s,alt:o.alt||[]}),this.i=null},Ve.prototype.after=function(t,e,s,i){var n=this.o(t),o=i||{};if(-1===n)throw new Error("Parser rule not found: "+t);this.t.splice(n+1,0,{name:e,enabled:!0,fn:s,alt:o.alt||[]}),this.i=null},Ve.prototype.push=function(t,e,s){var i=s||{};this.t.push({name:t,enabled:!0,fn:e,alt:i.alt||[]}),this.i=null},Ve.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},Ve.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},Ve.prototype.getRules=function(t){return null===this.i&&this.l(),this.i[t]||[]},We.prototype.pushPending=function(){this.tokens.push({type:"text",content:this.pending,level:this.pendingLevel}),this.pending=""},We.prototype.push=function(t){this.pending&&this.pushPending(),this.tokens.push(t),this.pendingLevel=this.level},We.prototype.cacheSet=function(t,e){for(var s=this.cache.length;s<=t;s++)this.cache.push(0);this.cache[t]=e},We.prototype.cacheGet=function(t){return t<this.cache.length?this.cache[t]:0};var ts=" \n()[]'\".,!?-";function es(t){return t.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1")}var ss=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,is=/\((c|tm|r|p)\)/gi,ns={c:"©",r:"®",p:"§",tm:"™"};function os(t){return t.indexOf("(")<0?t:t.replace(is,function(t,e){return ns[e.toLowerCase()]})}var rs=/['"]/,as=/['"]/g,ls=/[-\s()\[\]]/;function cs(t,e){return!(e<0||e>=t.length)&&!ls.test(t[e])}function hs(t,e,s){return t.substr(0,e)+s+t.substr(e+1)}var us=[["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,s,i,n,o=t.tokens;if(!t.inlineMode)for(e=1,s=o.length-1;e<s;e++)if("paragraph_open"===o[e-1].type&&"inline"===o[e].type&&"paragraph_close"===o[e+1].type){for(i=o[e].content;i.length&&!((n=Ze(i,t.inline,t.options,t.env))<0);)i=i.slice(n).trim();o[e].content=i,i.length||(o[e-1].tight=!0,o[e+1].tight=!0)}}],["references",function(t){var e,s,i,n,o=t.tokens;if(t.env.references=t.env.references||{},!t.inlineMode)for(e=1,s=o.length-1;e<s;e++)if("inline"===o[e].type&&"paragraph_open"===o[e-1].type&&"paragraph_close"===o[e+1].type){for(i=o[e].content;i.length&&!((n=Ye(i,t.inline,t.options,t.env))<0);)i=i.slice(n).trim();o[e].content=i,i.length||(o[e-1].tight=!0,o[e+1].tight=!0)}}],["inline",function(t){var e,s,i,n=t.tokens;for(s=0,i=n.length;s<i;s++)"inline"===(e=n[s]).type&&t.inline.parse(e.content,t.options,t.env,e.children)}],["footnote_tail",function(t){var e,s,i,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,s=r.length;e<s;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,i=0;i<n;i++)t.tokens.push({type:"footnote_anchor",id:e,subId:i,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,s,i,n,o,r,a,l,c,h,u,d,p=t.tokens;if(t.env.abbreviations)for(t.env.abbrRegExp||(d="(^|["+ts.split("").map(es).join("")+"])("+Object.keys(t.env.abbreviations).map(function(t){return t.substr(1)}).sort(function(t,e){return e.length-t.length}).map(es).join("|")+")($|["+ts.split("").map(es).join("")+"])",t.env.abbrRegExp=new RegExp(d,"g")),h=t.env.abbrRegExp,s=0,i=p.length;s<i;s++)if("inline"===p[s].type)for(e=(n=p[s].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[s].children=n=[].concat(n.slice(0,e),a,n.slice(e+1)))}}],["replacements",function(t){var e,s,i,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"===(s=n[e]).type&&(i=os(i=s.content),ss.test(i)&&(i=i.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")),s.content=i)}],["smartquotes",function(t){var e,s,i,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"===(s=f[e]).type&&!rs.test(s.text)){for(a=f[e].level,p=g.length-1;p>=0&&!(g[p].level<=a);p--);g.length=p+1,o=0,r=(i=s.content).length;t:for(;o<r&&(as.lastIndex=o,n=as.exec(i),n);)if(l=!cs(i,n.index-1),o=n.index+1,m="'"===n[0],(c=!cs(i,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=hs(f[h.token].content,h.pos,t.options.quotes[2]),s.content=hs(s.content,n.index,t.options.quotes[3])):(f[h.token].content=hs(f[h.token].content,h.pos,t.options.quotes[0]),s.content=hs(s.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&&(s.content=hs(s.content,n.index,"’"))}else m&&(s.content=hs(s.content,n.index,"’"))}}]];function ds(){this.options={},this.ruler=new Ve;for(var t=0;t<us.length;t++)this.ruler.push(us[t][0],us[t][1])}function ps(t,e,s,i,n){var o,r,a,l,c,h,u;for(this.src=t,this.parser=e,this.options=s,this.env=i,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 ms(t,e){var s,i,n;return(i=t.bMarks[e]+t.tShift[e])>=(n=t.eMarks[e])||42!==(s=t.src.charCodeAt(i++))&&45!==s&&43!==s||i<n&&32!==t.src.charCodeAt(i)?-1:i}function vs(t,e){var s,i=t.bMarks[e]+t.tShift[e],n=t.eMarks[e];if(i+1>=n||((s=t.src.charCodeAt(i++))<48||s>57))return-1;for(;;){if(i>=n)return-1;if(!((s=t.src.charCodeAt(i++))>=48&&s<=57)){if(41===s||46===s)break;return-1}}return i<n&&32!==t.src.charCodeAt(i)?-1:i}ds.prototype.process=function(t){var e,s,i;for(e=0,s=(i=this.ruler.getRules("")).length;e<s;e++)i[e](t)},ps.prototype.isEmpty=function(t){return this.bMarks[t]+this.tShift[t]>=this.eMarks[t]},ps.prototype.skipEmptyLines=function(t){for(var e=this.lineMax;t<e&&!(this.bMarks[t]+this.tShift[t]<this.eMarks[t]);t++);return t},ps.prototype.skipSpaces=function(t){for(var e=this.src.length;t<e&&32===this.src.charCodeAt(t);t++);return t},ps.prototype.skipChars=function(t,e){for(var s=this.src.length;t<s&&this.src.charCodeAt(t)===e;t++);return t},ps.prototype.skipCharsBack=function(t,e,s){if(t<=s)return t;for(;t>s;)if(e!==this.src.charCodeAt(--t))return t+1;return t},ps.prototype.getLines=function(t,e,s,i){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],s),r=i?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])>s&&(l=s),l<0&&(l=0),o=this.bMarks[c]+l,r=c+1<e||i?this.eMarks[c]+1:this.eMarks[c],a[n]=this.src.slice(o,r);return a.join("")};var fs={};["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){fs[t]=!0});var gs=/^<([a-zA-Z]{1,15})[\s\/>]/,bs=/^<\/([a-zA-Z]{1,15})[\s>]/;function ys(t,e){var s=t.bMarks[e]+t.blkIndent,i=t.eMarks[e];return t.src.substr(s,i-s)}function ws(t,e){var s,i,n=t.bMarks[e]+t.tShift[e],o=t.eMarks[e];return n>=o||126!==(i=t.src.charCodeAt(n++))&&58!==i||n===(s=t.skipSpaces(n))||s>=o?-1:s}var xs=[["code",function(t,e,s){var i,n;if(t.tShift[e]-t.blkIndent<4)return!1;for(n=i=e+1;i<s;)if(t.isEmpty(i))i++;else{if(!(t.tShift[i]-t.blkIndent>=4))break;n=++i}return t.line=i,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,s,i){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(i)return!0;for(a=e;!(++a>=s||(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,s,i){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(i)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<s&&!((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,s,!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,s,i){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)&&(i||(t.line=e+1,t.tokens.push({type:"hr",lines:[e,t.line],level:t.level})),!0)},["paragraph","blockquote","list"]],["list",function(t,e,s,i){var n,o,r,a,l,c,h,u,d,p,m,v,f,g,b,y,w,x,k,_,M,C=!0;if((u=vs(t,e))>=0)v=!0;else{if(!((u=ms(t,e))>=0))return!1;v=!1}if(t.level>=t.options.maxNesting)return!1;if(m=t.src.charCodeAt(u-1),i)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<s&&((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,s,!0),(!t.tight||b)&&(C=!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>=s||t.isEmpty(n)||t.tShift[n]<t.blkIndent));){for(M=!1,k=0,_=x.length;k<_;k++)if(x[k](t,n,s,!0)){M=!0;break}if(M)break;if(v){if((u=vs(t,n))<0)break}else if((u=ms(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,C&&function(t,e){var s,i,n=t.level+2;for(s=e+2,i=t.tokens.length-2;s<i;s++)t.tokens[s].level===n&&"paragraph_open"===t.tokens[s].type&&(t.tokens[s+2].tight=!0,t.tokens[s].tight=!0,s+=2)}(t,g),!0},["paragraph","blockquote"]],["footnote",function(t,e,s,i){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))&&(i||(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,s,!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,s,i){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)&&(i||(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,s){var i,n,o,r=e+1;return!(r>=s||t.tShift[r]<t.blkIndent||t.tShift[r]-t.blkIndent>3||(n=t.bMarks[r]+t.tShift[r],o=t.eMarks[r],n>=o)||(i=t.src.charCodeAt(n),45!==i&&61!==i)||(n=t.skipChars(n,i),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===i?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===i?1:2,level:t.level}),!0)}],["htmlblock",function(t,e,s,i){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(i)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(bs)))return!1}else if(!(o=t.src.slice(a,l).match(gs)))return!1;if(!0!==fs[o[1].toLowerCase()])return!1;if(i)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,s,i){var n,o,r,a,l,c,h,u,d,p,m;if(e+2>s||(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=ys(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=ys(t,e).trim()).indexOf("|")||(c=o.replace(/^\||\|$/g,"").split("|"),u.length!==c.length))return!1;if(i)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<s&&!(t.tShift[l]<t.blkIndent||(o=ys(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,s,i){var n,o,r,a,l,c,h,u,d,p,m,v,f,g;if(i)return!(t.ddIndent<0)&&ws(t,e)>=0;if(h=e+1,t.isEmpty(h)&&++h>s||t.tShift[h]<t.blkIndent||(n=ws(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,s,!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>=s||t.tShift[h]<t.blkIndent)break t;if((n=ws(t,h))<0)break;o=h}if(h>=s||(r=h,t.isEmpty(r))||t.tShift[r]<t.blkIndent||(o=r+1)>=s||(t.isEmpty(o)&&o++,o>=s)||t.tShift[o]<t.blkIndent||(n=ws(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 s,i,n=t.level+2;for(s=e+2,i=t.tokens.length-2;s<i;s++)t.tokens[s].level===n&&"paragraph_open"===t.tokens[s].type&&(t.tokens[s+2].tight=!0,t.tokens[s].tight=!0,s+=2)}(t,c),!0},["paragraph"]],["paragraph",function(t,e){var s,i,n,o,r,a,l=e+1;if(l<(s=t.lineMax)&&!t.isEmpty(l))for(a=t.parser.ruler.getRules("paragraph");l<s&&!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,s,!0)){n=!0;break}if(n)break}return i=t.getLines(e,l,t.blkIndent,!1).trim(),t.line=l,i.length&&(t.tokens.push({type:"paragraph_open",tight:!1,lines:[e,t.line],level:t.level}),t.tokens.push({type:"inline",content:i,level:t.level+1,lines:[e,t.line],children:[]}),t.tokens.push({type:"paragraph_close",tight:!1,level:t.level})),!0}]];function ks(){this.ruler=new Ve;for(var t=0;t<xs.length;t++)this.ruler.push(xs[t][0],xs[t][1],{alt:(xs[t][2]||[]).slice()})}ks.prototype.tokenize=function(t,e,s){for(var i,n=this.ruler.getRules(""),o=n.length,r=e,a=!1;r<s&&(t.line=r=t.skipEmptyLines(r),!(r>=s||t.tShift[r]<t.blkIndent));){for(i=0;i<o&&!n[i](t,r,s,!1);i++);if(t.tight=!a,t.isEmpty(t.line-1)&&(a=!0),(r=t.line)<s&&t.isEmpty(r)){if(a=!0,++r<s&&"list"===t.parentType&&t.isEmpty(r))break;t.line=r}}};var _s=/[\n\t]/g,Ms=/\r[\n\u0085]|[\u2424\u2028\u0085]/g,Cs=/\u00a0/g;function As(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}}ks.prototype.parse=function(t,e,s,i){var n,o=0,r=0;if(!t)return[];(t=(t=t.replace(Cs," ")).replace(Ms,"\n")).indexOf("\t")>=0&&(t=t.replace(_s,function(e,s){var i;return 10===t.charCodeAt(s)?(o=s+1,r=0,e):(i=" ".slice((s-o-r)%4),r=s-o+1,i)})),n=new ps(t,this,e,s,i),this.tokenize(n,n.line,n.lineMax)};for(var Ts=[],Ss=0;Ss<256;Ss++)Ts.push(0);function js(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}function Es(t,e){var s,i,n,o=e,r=!0,a=!0,l=t.posMax,c=t.src.charCodeAt(e);for(s=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===(i=o<l?t.src.charCodeAt(o):-1)||10===i)&&(r=!1),(32===s||10===s)&&(a=!1),95===c&&(js(s)&&(r=!1),js(i)&&(a=!1))),{can_open:r,can_close:a,delims:n}}"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(t){Ts[t.charCodeAt(0)]=1});var Is=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var $s=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Os=["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"],Ps=/^<([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])?)*)>/,Bs=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;function Rs(t,e){return t=t.source,e=e||"",function s(i,n){return i?(n=n.source||n,t=t.replace(i,n),s):new RegExp(t,e)}}var Fs=Rs(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",/[^"'=<>`\x00-\x20]+/)("single_quoted",/'[^']*'/)("double_quoted",/"[^"]*"/)(),Ls=Rs(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",/[a-zA-Z_:][a-zA-Z0-9:._-]*/)("attr_value",Fs)(),qs=Rs(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",Ls)(),zs=Rs(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",qs)("close_tag",/<\/[A-Za-z][A-Za-z0-9]*\s*>/)("comment",/<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->/)("processing",/<[?].*?[?]>/)("declaration",/<![A-Z]+\s+[^>]*>/)("cdata",/<!\[CDATA\[[\s\S]*?\]\]>/)();var Ds=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,Ns=/^&([a-z][a-z0-9]{1,31});/i;var Us=[["text",function(t,e){for(var s=t.pos;s<t.posMax&&!As(t.src.charCodeAt(s));)s++;return s!==t.pos&&(e||(t.pending+=t.src.slice(t.pos,s)),t.pos=s,!0)}],["newline",function(t,e){var s,i,n=t.pos;if(10!==t.src.charCodeAt(n))return!1;if(s=t.pending.length-1,i=t.posMax,!e)if(s>=0&&32===t.pending.charCodeAt(s))if(s>=1&&32===t.pending.charCodeAt(s-1)){for(var o=s-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<i&&32===t.src.charCodeAt(n);)n++;return t.pos=n,!0}],["escape",function(t,e){var s,i=t.pos,n=t.posMax;if(92!==t.src.charCodeAt(i))return!1;if(++i<n){if((s=t.src.charCodeAt(i))<256&&0!==Ts[s])return e||(t.pending+=t.src[i]),t.pos+=2,!0;if(10===s){for(e||t.push({type:"hardbreak",level:t.level}),i++;i<n&&32===t.src.charCodeAt(i);)i++;return t.pos=i,!0}}return e||(t.pending+="\\"),t.pos++,!0}],["backticks",function(t,e){var s,i,n,o,r,a=t.pos;if(96!==t.src.charCodeAt(a))return!1;for(s=a,a++,i=t.posMax;a<i&&96===t.src.charCodeAt(a);)a++;for(n=t.src.slice(s,a),o=r=a;-1!==(o=t.src.indexOf("`",r));){for(r=o+1;r<i&&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 s,i,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(i=l+2;i<a&&126===t.src.charCodeAt(i);)i++;if(i>l+3)return t.pos+=i-l,e||(t.pending+=t.src.slice(l,i)),!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))){s=!0;break}t.parser.skipToken(t)}return s?(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 s,i,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(i=l+2;i<a&&43===t.src.charCodeAt(i);)i++;if(i!==l+2)return t.pos+=i-l,e||(t.pending+=t.src.slice(l,i)),!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))){s=!0;break}t.parser.skipToken(t)}return s?(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 s,i,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(i=l+2;i<a&&61===t.src.charCodeAt(i);)i++;if(i!==l+2)return t.pos+=i-l,e||(t.pending+=t.src.slice(l,i)),!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))){s=!0;break}t.parser.skipToken(t)}return s?(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 s,i,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(s=(l=Es(t,h)).delims,!l.can_open)return t.pos+=s,e||(t.pending+=t.src.slice(h,t.pos)),!0;if(t.level>=t.options.maxNesting)return!1;for(t.pos=h+s,a=[s];t.pos<c;)if(t.src.charCodeAt(t.pos)!==u)t.parser.skipToken(t);else{if(i=(l=Es(t,t.pos)).delims,l.can_close){for(o=a.pop(),r=i;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){s=o,n=!0;break}t.pos+=i;continue}l.can_open&&a.push(i),t.pos+=i}return n?(t.posMax=t.pos,t.pos=h+s,e||((2===s||3===s)&&t.push({type:"strong_open",level:t.level++}),(1===s||3===s)&&t.push({type:"em_open",level:t.level++}),t.parser.tokenize(t),(1===s||3===s)&&t.push({type:"em_close",level:--t.level}),(2===s||3===s)&&t.push({type:"strong_close",level:--t.level})),t.pos=t.posMax+s,t.posMax=c,!0):(t.pos=h,!1)}],["sub",function(t,e){var s,i,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)){s=!0;break}t.parser.skipToken(t)}return!s||o+1===t.pos||(i=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:i.replace(Is,"$1")}),t.pos=t.posMax+1,t.posMax=n,!0)}],["sup",function(t,e){var s,i,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)){s=!0;break}t.parser.skipToken(t)}return!s||o+1===t.pos||(i=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:i.replace($s,"$1")}),t.pos=t.posMax+1,t.posMax=n,!0)}],["links",function(t,e){var s,i,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||(s=p+1,(i=Ge(t,p))<0))return!1;if((a=i+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,Je(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&&Xe(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=Ge(t,a))>=0?n=t.src.slice(p,a++):a=p-1),n||(typeof n>"u"&&(a=i+1),n=t.src.slice(s,i)),!(l=t.env.references[Qe(n)]))return t.pos=u,!1;o=l.href,r=l.title}return e||(t.pos=s,t.posMax=i,h?t.push({type:"image",src:o,title:r,alt:t.src.substr(s,i-s),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 s,i,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||(s=a+2,i=Ge(t,a+1),i<0))&&(e||(t.env.footnotes||(t.env.footnotes={}),t.env.footnotes.list||(t.env.footnotes.list=[]),n=t.env.footnotes.list.length,t.pos=s,t.posMax=i,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=i+1,t.posMax=r,!0)}],["footnote_ref",function(t,e){var s,i,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(i=a+2;i<r;i++){if(32===t.src.charCodeAt(i)||10===t.src.charCodeAt(i))return!1;if(93===t.src.charCodeAt(i))break}return!(i===a+2||i>=r||(i++,s=t.src.slice(a+2,i-1),typeof t.env.footnotes.refs[":"+s]>"u"))&&(e||(t.env.footnotes.list||(t.env.footnotes.list=[]),t.env.footnotes.refs[":"+s]<0?(n=t.env.footnotes.list.length,t.env.footnotes.list[n]={label:s,count:0},t.env.footnotes.refs[":"+s]=n):n=t.env.footnotes.refs[":"+s],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=i,t.posMax=r,!0)}],["autolink",function(t,e){var s,i,n,o,r,a=t.pos;return!(60!==t.src.charCodeAt(a)||(s=t.src.slice(a),s.indexOf(">")<0))&&((i=s.match(Bs))?!(Os.indexOf(i[1].toLowerCase())<0||(o=i[0].slice(1,-1),r=Ke(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+=i[0].length,!0):!!(n=s.match(Ps))&&(r=Ke("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 s,i,n,o=t.pos;return!(!t.options.html||(n=t.posMax,60!==t.src.charCodeAt(o)||o+2>=n)||(s=t.src.charCodeAt(o+1),33!==s&&63!==s&&47!==s&&!function(t){var e=32|t;return e>=97&&e<=122}(s))||(i=t.src.slice(o).match(zs),!i))&&(e||t.push({type:"htmltag",content:t.src.slice(o,o+i[0].length),level:t.level}),t.pos+=i[0].length,!0)}],["entity",function(t,e){var s,i,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(i=t.src.slice(n).match(Ds))return e||(s="x"===i[1][0].toLowerCase()?parseInt(i[1].slice(1),16):parseInt(i[1],10),t.pending+=Ee(s)?Ie(s):Ie(65533)),t.pos+=i[0].length,!0}else if(i=t.src.slice(n).match(Ns)){var r=Ce(i[1]);if(i[1]!==r)return e||(t.pending+=r),t.pos+=i[0].length,!0}return e||(t.pending+="&"),t.pos++,!0}]];function Hs(){this.ruler=new Ve;for(var t=0;t<Us.length;t++)this.ruler.push(Us[t][0],Us[t][1]);this.validateLink=Vs}function Vs(t){var e=t.trim().toLowerCase();return!(-1!==(e=Be(e)).indexOf(":")&&-1!==["vbscript","javascript","file","data"].indexOf(e.split(":")[0]))}Hs.prototype.skipToken=function(t){var e,s,i=this.ruler.getRules(""),n=i.length,o=t.pos;if((s=t.cacheGet(o))>0)t.pos=s;else{for(e=0;e<n;e++)if(i[e](t,!0))return void t.cacheSet(o,t.pos);t.pos++,t.cacheSet(o,t.pos)}},Hs.prototype.tokenize=function(t){for(var e,s,i=this.ruler.getRules(""),n=i.length,o=t.posMax;t.pos<o;){for(s=0;s<n&&!(e=i[s](t,!1));s++);if(e){if(t.pos>=o)break}else t.pending+=t.src[t.pos++]}t.pending&&t.pushPending()},Hs.prototype.parse=function(t,e,s,i){var n=new We(t,this,e,s,i);this.tokenize(n)};var Ws={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 Gs(t,e,s){this.src=e,this.env=s,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 Zs(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 Hs,this.block=new ks,this.core=new ds,this.renderer=new He,this.ruler=new Ve,this.options={},this.configure(Ws[t]),this.set(e||{})}Zs.prototype.set=function(t){Te(this.options,t)},Zs.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(s){t.components[s].rules&&e[s].ruler.enable(t.components[s].rules,!0)})},Zs.prototype.use=function(t,e){return t(this,e),this},Zs.prototype.parse=function(t,e){var s=new Gs(this,t,e);return this.core.process(s),s.tokens},Zs.prototype.render=function(t,e){return e=e||{},this.renderer.render(this.parse(t,e),this.options,e)},Zs.prototype.parseInline=function(t,e){var s=new Gs(this,t,e);return s.inlineMode=!0,this.core.process(s),s.tokens},Zs.prototype.renderInline=function(t,e){return e=e||{},this.renderer.render(this.parseInline(t,e),this.options,e)};const Ks=class t{static addPlugins(t,e){const s=window.remarkable_plugins;if(s&&s.forEach(e=>{t.use(e.plugin,e.options)}),null!=e&&e.math){window.katex||(console.warn("window.katex not found, use chatElementRef.refreshMessages to re-render messages"),console.warn("See https://deepchat.dev/examples/externalModules"));const s="object"==typeof e.math?e.math.delimiter:"",i="object"==typeof e.math&&e.math.options?e.math.options:{};t.use(_e.katex.bind(this,i),{delimiter:s})}}static instantiate(e){if(e)return new Zs({...t.DEFAULT_PROPERTIES,...e});if(window.hljs){const t=window.hljs;return new Zs({highlight:function(e,s){if(s&&t.getLanguage(s))try{return t.highlight(e,{language:s}).value}catch{console[l]("failed to setup the highlight dependency")}try{return t.highlightAuto(e).value}catch{console[l]("failed to automatically highlight messages")}return""},html:!1,xhtmlOut:!1,breaks:!0,langPrefix:"language-",linkTarget:"_blank",typographer:!0})}return new Zs(t.DEFAULT_PROPERTIES)}static createNew(e){const s=t.instantiate(e);return t.addPlugins(s,e),s.inline.validateLink=()=>!0,s}};Ks.DEFAULT_PROPERTIES={breaks:!0,linkTarget:"_blank"};let Js=Ks;class Xs{constructor(t){this.storageKey="deep-chat-storage",this.maxMessages=1e3,this.trackInputText=!1,this.trackScrollHeight=!1,"object"==typeof t&&(t.key&&(this.storageKey=t.key),t.maxMessages&&(this.maxMessages=t.maxMessages),void 0!==t.inputText&&(this.trackInputText=t.inputText),void 0!==t.scrollHeight&&(this.trackScrollHeight=t.scrollHeight),t.clear=this.clear.bind(this),ce.processBrowserStorage(this))}get(){const t=localStorage.getItem(this.storageKey);return t?JSON.parse(t):{messages:[]}}set(t,e,s){const i={messages:t,inputText:e,scrollHeight:s};localStorage.setItem(this.storageKey,R(i))}addMessages(t){let e=t.length-this.maxMessages;e<0&&(e=0);const s=t.slice(e,t.length),i=this.trackInputText||this.trackScrollHeight?localStorage.getItem(this.storageKey):void 0,n=i?JSON.parse(i):void 0;this.set(s,this.trackInputText?null==n?void 0:n.inputText:void 0,this.trackScrollHeight?null==n?void 0:n.scrollHeight:void 0)}addInputText(t){if(!this.trackInputText)return;const e=localStorage.getItem(this.storageKey),s=e?JSON.parse(e):void 0;this.set((null==s?void 0:s.messages)||[],t,this.trackScrollHeight?null==s?void 0:s.scrollHeight:void 0)}addScrollHeight(t){if(!this.trackScrollHeight)return;const e=localStorage.getItem(this.storageKey),s=e?JSON.parse(e):void 0;this.set((null==s?void 0:s.messages)||[],this.trackInputText?null==s?void 0:s.inputText:void 0,t)}clear(){localStorage.removeItem(this.storageKey)}}class Qs{static applyCustomStylesToElements(t,s,i){if(i&&(Object.assign(t.outerContainer[e],i.outerContainer),Object.assign(t.innerContainer[e],i.innerContainer),Object.assign(t.bubbleElement[e],i.bubble),s)){const s=t.bubbleElement.children[0],n="a"!==s.tagName.toLocaleLowerCase()?s:s.children[0];Object.assign(n[e],i.media)}}static applySideStyles(t,e,s,i){i&&(Qs.applyCustomStylesToElements(t,s,i.shared),e===u?Qs.applyCustomStylesToElements(t,s,i.user):(Qs.applyCustomStylesToElements(t,s,i.ai),Qs.applyCustomStylesToElements(t,s,i[e])))}static isElementsStyles(t){return!!(t.outerContainer||t.innerContainer||t.bubble||t.media)}static applyCustomStyles(t,e,s,i,n){var o;n&&t[rt]!==n?Qs.isElementsStyles(n)?(Qs.applyCustomStylesToElements(e,i,null==(o=t[rt])?void 0:o.shared),Qs.applyCustomStylesToElements(e,i,n)):(Qs.applySideStyles(e,s,i,t[rt]),Qs.applySideStyles(e,s,i,n)):Qs.applySideStyles(e,s,i,t[rt])}static extractParticularSharedStyles(t,e){if(null==e||!e.shared)return;const s=e.shared,i={outerContainer:{},innerContainer:{},bubble:{},media:{}};return t.forEach(t=>{var e,n,o,r;i.outerContainer[t]=(null==(e=s.outerContainer)?void 0:e[t])||"",i.innerContainer[t]=(null==(n=s.innerContainer)?void 0:n[t])||"",i.bubble[t]=(null==(o=s.bubble)?void 0:o[t])||"",i.media[t]=(null==(r=s.media)?void 0:r[t])||""}),i}}class Ys{static setElementProps(e,s,i,n){var o;i!==gt&&(e.applyCustomStyles(s,n,!0,null==(o=e.messageStyles)?void 0:o[i]),s.bubbleElement[t].add(I))}static addMessage(t,e,s,i,n){Ys.setElementProps(t,e,s,i),n?t.elementRef.insertBefore(e.outerContainer,t.elementRef.firstChild):t.appendOuterContainerElemet(e.outerContainer)}static wrapInLink(t,e,i){const n=s("a");return n.href=e,n.download=i||x,n.target="_blank",n.appendChild(t),n}static isNonLinkableDataUrl(t,e){return!(!e.startsWith("data")||t===_)&&(t===E&&e.startsWith("data:text/javascript")||!e.startsWith("data:image")&&!e.startsWith("data:application"))}static processContent(t,e,s,i){return!s||Ys.isNonLinkableDataUrl(t,s)?e:Ys.wrapInLink(e,s,i)}static waitToLoadThenScroll(t){setTimeout(()=>{t()},60)}static scrollDownOnImageLoad(t,e){if(t.startsWith("data"))Ys.waitToLoadThenScroll(e);else try{fetch(t,{mode:"no-cors"}).catch(()=>{}).finally(()=>{Ys.waitToLoadThenScroll(e)})}catch{e()}}static reAddFileRefToObject(t,e){var s;null==(s=t[k])||s.forEach((t,s)=>{var i;t.ref&&null!=(i=e[k])&&i[s]&&(e[k][s].ref=t.ref)})}static removeFileRef(t){const e={...t};return delete e.ref,e}static isAudioFile(t){const{type:e,src:s}=t;return e===T||(null==s?void 0:s.startsWith("data:audio"))||s&&/\.(mp3|ogg|wav|aac|webm|4a)$/i.test(s)}static isImageFile(t){const{type:e,src:s}=t;return e===_||(null==s?void 0:s.startsWith("data:image"))||s&&Ys.isImageFileExtension(s)}static isImageFileExtension(t){return/\.(jpg|jpeg|png|gif|bmp)$/i.test(t)}}class ti{static onMessage(t,e,s){var i;const n=F({message:e,isHistory:s,isInitial:s});Ys.reAddFileRefToObject(e,n.message),null==(i=t.onMessage)||i.call(t,n),t.dispatchEvent(new CustomEvent("message",{detail:n})),ce.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 onInput(t,e,s){var i,n;const o=F({content:e,isUser:s});e[k]&&Ys.reAddFileRefToObject({[k]:null==(i=e[k])?void 0:i.map(t=>({ref:t}))},o.content),null==(n=t.onInput)||n.call(t,o),t.dispatchEvent(new CustomEvent("input",{detail:o}))}static onError(t,e){var s;null==(s=t.onError)||s.call(t,e),t.dispatchEvent(new CustomEvent(l,{detail:e}))}}const ei=class e{static generateLoadingRingElement(){const e=s();return e[t].add("loading-history"),e.appendChild(s()),e.appendChild(s()),e.appendChild(s()),e.appendChild(s()),e}static apply(t,e,s){le.setRing(e.bubbleElement,null==s?void 0:s.bubble),null!=s&&s.bubble&&delete(s=F(s)).bubble,t.applyCustomStyles(e,"history",!1,s)}static addLoadHistoryMessage(s,i,n=!0){var o,r,a,l,c,h,u,d;s.bubbleElement[t].add(e.CLASS);const p=n?e.FULL_VIEW_CLASS:e.SMALL_CLASS;s.outerContainer[t].add(p);const m=n?null==(l=null==(a=null==(r=null==(o=i.messageStyles)?void 0:o.loading)?void 0:r.history)?void 0:a.full)?void 0:l[pt]:null==(d=null==(u=null==(h=null==(c=i.messageStyles)?void 0:c.loading)?void 0:h.history)?void 0:u.small)?void 0:d[pt];e.apply(i,s,m);let v=i.elementRef;n&&i.elementRef.id!==O&&(v=i.elementRef.parentElement),null==v||v.prepend(s.outerContainer)}static createDefaultElements(t){const s=t.createMessageElements("",h),{bubbleElement:i}=s,n=e.generateLoadingRingElement();return i.appendChild(n),s}static addMessage(t,s=!0){var i,n,o,r;const l=null==(r=null==(o=null==(n=null==(i=t.messageStyles)?void 0:i.loading)?void 0:n.history)?void 0:o.full)?void 0:r[a],c=l?ke.createElements(t,l,h,!0,!0):e.createDefaultElements(t);return e.addLoadHistoryMessage(c,t,s),pi.softRemRoleElements(c.innerContainer,t.avatar,t.name),c}static tryChangeViewToSmall(s,i){var n,o,r,l,c,h,u,d;if(null!=i&&i.outerContainer[t].contains(e.FULL_VIEW_CLASS)){i.outerContainer[t].replace(e.FULL_VIEW_CLASS,e.SMALL_CLASS);const p=null==(l=null==(r=null==(o=null==(n=s.messageStyles)?void 0:n.loading)?void 0:o.history)?void 0:r.small)?void 0:l[pt];p&&e.apply(s,i,p);const m=null==(d=null==(u=null==(h=null==(c=s.messageStyles)?void 0:c.loading)?void 0:h.history)?void 0:u.small)?void 0:d[a];return m&&(i.bubbleElement.innerHTML=m),!0}return!1}static changeFullViewToSmall(t){const s=t.messageElementRefs[t.messageElementRefs.length-1];e.tryChangeViewToSmall(t,s)||e.tryChangeViewToSmall(t,t.messageElementRefs[0])}};ei.CLASS="loading-history-message",ei.FULL_VIEW_CLASS="loading-history-message-full-view",ei.SMALL_CLASS="loading-history-message-small";let si=ei;const ii=class t{static setFade(s,i){s[e].transitionDuration="number"==typeof i?`${i}ms`:`${t.DEFAULT_FADE_MS}ms`}static async fadeAnimation(s,i){s[e].opacity="0";const n="number"==typeof i?i:t.DEFAULT_FADE_MS;await new Promise(t=>{setTimeout(()=>t(),n)}),s[e].opacity="1"}};ii.DEFAULT_FADE_MS=500;let ni=ii;class oi{constructor(t,e,s){if(this.hiddenElements=new Set,this.isScrollButton=!1,this.isScrollingToBottom=!1,this._messages=t,e){let t={};"object"==typeof e&&(t=F(e),t.onUpdate=e.onUpdate),t[pt]??(t[pt]={});const s="fit-content";t[pt].default={borderRadius:"10px",width:s,height:s,...t[pt].default},this.hiddenMessagesConfig=t,this.io=this.initIntersectionObserver(this._messages.elementRef)}if(s){const t="object"==typeof s?F(s):{};t[pt]??(t[pt]={}),t[pt].default={borderRadius:"50%",width:"1.4rem",height:"1.4rem",...t[pt].default},this.scrollButtonConfig=t}this.element=this.createElement(),this._messages.elementRef.appendChild(this.element)}static displayElement(t){t[e].opacity="1",t[e].pointerEvents="auto"}static hideElement(t){t[e].opacity="0",t[e].pointerEvents="none"}initIntersectionObserver(t){return new IntersectionObserver(t=>{t.forEach(t=>{var e;t.isIntersecting&&this.hiddenElements.has(t.target)&&(this.hiddenElements.delete(t.target),null==(e=this.io)||e.unobserve(t.target),this.updateHiddenElement())})},{root:t,threshold:.1})}createElement(){const t=s();return t.id="scroll-button",ne.assignButtonEvents(t,()=>{var t,e,s;const i=this.isScrollButton?null==(t=this.scrollButtonConfig)?void 0:t.smoothScroll:null==(e=this.hiddenMessagesConfig)?void 0:e.smoothScroll,n="boolean"!=typeof i||i;if(this.isScrollButton||"last"===(null==(s=this.hiddenMessagesConfig)?void 0:s.clickScroll))ne.scrollToBottom(this._messages,n),n&&this.element&&(oi.hideElement(this.element),this.isScrollingToBottom=!0,ne.waitForScrollEnd(this._messages.elementRef,()=>{this.isScrollingToBottom=!1}));else{const t=this.hiddenElements.values().next().value;t&&this._messages.elementRef.scrollTo({left:0,top:t.offsetTop,behavior:n?"smooth":"auto"})}}),we.apply(this._messages,t),t}assignStyles(t){if(!this.element)return;Object.assign(this.element[e],t[rt]);const s=yt.processStateful(t);fe.add(this.element,s)}updateHiddenElement(){var t,e;if(this.element){this.isScrollButton=!1;const s=this.hiddenElements.size;if(0===s)return void oi.hideElement(this.element);const i=`${s} new message${1===s?"":"s"}`;if(null!=(t=this.hiddenMessagesConfig)&&t.onUpdate){const t=this.hiddenMessagesConfig.onUpdate(i,s);this.element.innerHTML=t,we.apply(this._messages,this.element)}else this.element.innerHTML=i;null!=(e=this.hiddenMessagesConfig)&&e[pt]&&this.assignStyles(this.hiddenMessagesConfig[pt]),oi.displayElement(this.element)}}updateHidden(){var t,e;if(!this.isScrollingToBottom)if(this.hiddenMessagesConfig){const s=null==(t=this._messages.getFirstMessageContentEl())?void 0:t.outerContainer;s&&!ne.isVisibleInParent(s,this._messages.elementRef)&&(this.hiddenElements.add(s),null==(e=this.io)||e.observe(s),this.updateHiddenElement())}else this.updateScroll()}clearHidden(){this.hiddenElements.forEach(t=>{var e;return null==(e=this.io)?void 0:e.unobserve(t)}),this.hiddenElements.clear(),this.updateHiddenElement()}displayScroll(){var t,s;this.element&&"1"!==this.element[e].opacity&&(oi.displayElement(this.element),this.element.innerHTML=(null==(t=this.scrollButtonConfig)?void 0:t.content)||'<span style="font-size: 1.2rem; user-select: none;">&darr;</span>',null!=(s=this.scrollButtonConfig)&&s[pt]&&this.assignStyles(this.scrollButtonConfig[pt]))}updateScroll(){var t;this.isScrollingToBottom||!this.scrollButtonConfig||(ne.isScrollbarAtBottomOfElement(this._messages.elementRef,(null==(t=this.scrollButtonConfig)?void 0:t.scrollDelta)||80)?this.element&&"0"!==this.element[e].opacity&&oi.hideElement(this.element):(this.displayScroll(),this.isScrollButton=!0))}}const ri="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",ai="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==";class li{constructor(t){this.className=t}getAvatarContainer(t){return t.getElementsByClassName(this.className)[0]}tryHide(t){var s;(s=this.getAvatarContainer(t)[e]).visibility||(s.visibility="hidden")}tryReveal(t){this.getAvatarContainer(t)[e].visibility=""}trySoftRem(e){this.getAvatarContainer(e)[t].add("role-hidden")}}class ci extends li{constructor(t){super("avatar-container"),this._avatars=t}addBesideBubble(e,s){const i="boolean"==typeof this._avatars?void 0:this._avatars,n=this.createAvatar(s,i),o=this.getPosition(s,i);n[t].add(o===$?"start-item-position":"end-item-position"),e.insertAdjacentElement(o===$?"beforebegin":"afterend",n)}createAvatar(e,i){var n,o,r,a,l;const c=s("img");e===u?(c[y]=(null==(n=null==i?void 0:i[u])?void 0:n[y])||(null==(o=null==i?void 0:i[rt])?void 0:o[y])||ai,c.onerror=ci.errorFallback.bind(this,ai)):(c[y]=(null==(r=null==i?void 0:i[e])?void 0:r[y])||(null==(a=null==i?void 0:i[h])?void 0:a[y])||(null==(l=null==i?void 0:i[rt])?void 0:l[y])||ri,c.onerror=ci.errorFallback.bind(this,ri)),c[t].add("avatar"),c.alt=`${e} avatar`;const d=s();return d[t].add(this.className),d.appendChild(c),i&&ci.applyCustomStyles(d,c,i,e),d}getPosition(t,e){var s,i,n,o,r,a;let l=ce.processPosition(null==(i=null==(s=null==e?void 0:e[t])?void 0:s[pt])?void 0:i.position);return t!==u&&(l??(l=null==(o=null==(n=null==e?void 0:e.ai)?void 0:n[pt])?void 0:o.position)),l??(l=null==(a=null==(r=null==e?void 0:e[rt])?void 0:r[pt])?void 0:a.position),l??(l=t===u?"end":$),l}static errorFallback(t,e){const s=e.target;s.onerror=null,s[y]=t}static applyCustomStylesToElements(t,s,i){Object.assign(t[e],i.container),Object.assign(s[e],i.avatar)}static applyCustomStyles(t,e,s,i){var n,o,r,a;if(null!=(n=s[rt])&&n[pt]&&ci.applyCustomStylesToElements(t,e,s[rt][pt]),i===u)null!=(o=s.user)&&o[pt]&&ci.applyCustomStylesToElements(t,e,s.user[pt]);else{null!=(r=s.ai)&&r[pt]&&ci.applyCustomStylesToElements(t,e,s.ai[pt]);const n=null==(a=s[i])?void 0:a[pt];n&&ci.applyCustomStylesToElements(t,e,n)}}}class hi extends li{constructor(t){super("name"),this._names=t}addBesideBubble(e,s){const i="boolean"==typeof this._names?{}:this._names,n=this.createName(s,i),o=hi.getPosition(s,i);n[t].add(o===$?"start-item-position":"end-item-position"),e.insertAdjacentElement(o===$?"beforebegin":"afterend",n)}createName(e,i){const n=s();return n[t].add(this.className),n.textContent=hi.getNameText(e,i),hi.applyStyle(n,e,i),n}static getPosition(t,e){var s,i,n;let o=ce.processPosition(null==(s=null==e?void 0:e[t])?void 0:s.position);return t!==u&&(o??(o=null==(i=null==e?void 0:e[h])?void 0:i.position)),o??(o=null==(n=null==e?void 0:e[rt])?void 0:n.position),o??(o=t===u?"end":$),o}static applyStyle(t,s,i){var n,o,r,a;Object.assign(t[e],null==(n=i[rt])?void 0:n[e]),s===u?Object.assign(t[e],null==(o=i[u])?void 0:o[e]):(Object.assign(t[e],null==(r=i[h])?void 0:r[e]),Object.assign(t[e],null==(a=i[s])?void 0:a[e]))}static getNameText(t,e){var s,i,n,o,a,l;return t===u?(null==(s=e[u])?void 0:s[r])||(null==(i=e[rt])?void 0:i[r])||"User":t===h?(null==(n=e[h])?void 0:n[r])||(null==(o=e[rt])?void 0:o[r])||"AI":(null==(a=e[t])?void 0:a[r])||(null==(l=e[rt])?void 0:l[r])||t}}const ui=class e{constructor(t){var i,n,o,r;this.messageElementRefs=[],this.htmlClassUtilities={},this.messageToElements=[],this.maxVisibleMessages=4e3,this.autoScrollAllowed=!0,this.elementRef=e.createContainerElement(),this.messageStyles=ce.processMessageStyles(t.messageStyles),this._remarkable=Js.createNew(t.remarkable),this._applyHTMLToRemarkable=null==(i=t.remarkable)?void 0:i.applyHTML,t.avatars&&(this.avatar=new ci(t.avatars)),t.names&&(this.name=new hi(t.names)),t.browserStorage&&(this.browserStorage=new Xs(t.browserStorage)),this._onMessage=ti.onMessage.bind(this,t),t.htmlClassUtilities&&(this.htmlClassUtilities=t.htmlClassUtilities),(t.hiddenMessages||t.scrollButton)&&(this.scrollButton=new oi(this,t.hiddenMessages,t.scrollButton)),this.focusMode=ce.processFocusMode(t.focusMode),this.focusMode||(this._lastGroupMessagesElement=s(),this.elementRef.appendChild(this._lastGroupMessagesElement),t.upwardsMode&&(this.elementRef=this._lastGroupMessagesElement)),"boolean"!=typeof this.focusMode&&null!=(n=this.focusMode)&&n.fade&&ni.setFade(this.elementRef,this.focusMode.fade),this._customWrappers=t.htmlWrappers||ce.processStreamHTMLWrappers(null==(o=t.connect)?void 0:o.stream),"boolean"!=typeof this.focusMode&&!1===(null==(r=this.focusMode)?void 0:r.streamAutoScroll)&&(this.autoScrollAllowed=!1),t.maxVisibleMessages&&(this.maxVisibleMessages=t.maxVisibleMessages),setTimeout(()=>{this.submitUserMessage=t.submitUserMessage})}static createContainerElement(){const t=s();return t.id=O,t}addNewTextMessage(s,i,n,o=!1){if(null!=n&&n.status){const t=this.overwriteText(i,s,this.messageElementRefs);if(t)return t;n.status=!1}const r=o?this.createAndPrependNewMessageElement(s,i,o):this.createAndAppendNewMessageElement(s,i);return r.bubbleElement[t].add(e.TEXT_BUBBLE_CLASS),this.applyCustomStyles(r,i,!1),pi.fillEmptyMessageElement(r.bubbleElement,s),r}overwriteText(t,s,i){const n=pi.overwriteMessage(this.messageToElements,i,s,t,"text",e.TEXT_BUBBLE_CLASS);return n&&this.renderText(n.bubbleElement,s,t),n}createAndAppendNewMessageElement(t,e){const s=this.createNewMessageElement(t,e);return this.appendOuterContainerElemet(s.outerContainer,this.focusMode?e:void 0),s}createNewGroupElementFocusMode(){var i;null==(i=this._lastGroupMessagesElement)||i[t].remove(e.LAST_GROUP_MESSAGES_ACTIVE);const n=s();(this.messageToElements.length>1||1===this.messageToElements.length&&this.messageToElements[0][0][P]!==u)&&n[t].add(e.LAST_GROUP_MESSAGES_ACTIVE),this._lastGroupMessagesElement=n}appendOuterContainerElemet(t,e){var s;this.focusMode&&(e===u||!this._lastGroupMessagesElement)&&this.createNewGroupElementFocusMode(),null==(s=this._lastGroupMessagesElement)||s.appendChild(t),this._lastGroupMessagesElement&&(this.focusMode||!this.elementRef.contains(this._lastGroupMessagesElement))&&this.elementRef.appendChild(this._lastGroupMessagesElement)}createAndPrependNewMessageElement(s,i,n,o=!1){var r;const a=this.createNewMessageElement(s,i,n,o);if(n&&null!=(r=this.elementRef.firstChild)&&r[t].contains(e.INTRO_CLASS)){this.elementRef.firstChild.insertAdjacentElement("afterend",a.outerContainer);const t=this.messageElementRefs[0];this.messageElementRefs[0]=this.messageElementRefs[1],this.messageElementRefs[1]=t}else this.elementRef.insertBefore(a.outerContainer,this.elementRef.firstChild);return a}createMessageElementsOnOrientation(t,e,s,i=!1){return s?this.createAndPrependNewMessageElement(t,e,s,i):this.createNewMessageElement(t,e,s,i)}getNumberOfContentMessages(){var e,s;const i=this.messageElementRefs.length;return null!=(s=null==(e=this.messageElementRefs[i-1])?void 0:e.bubbleElement)&&s[t].contains(le.BUBBLE_CLASS)?i-1:i}createNewMessageElement(t,s,i=!1,n=!1){var o;!n&&this.getNumberOfContentMessages()>=this.maxVisibleMessages&&setTimeout(()=>this.removeFirstMessage()),n||null==(o=this._introPanel)||o.hide();const r=this.messageElementRefs[this.messageElementRefs.length-1];return si.changeFullViewToSmall(this),!i&&e.isTemporaryElement(r)&&(this.revealRoleElementsIfTempRemoved(r,s),this.removeLastMessage()),this.createMessageElements(t,s,i)}revealRoleElementsIfTempRemoved(e,s){if((this.avatar||this.name)&&ye.isElementTemporary(e)){const i=this.messageElementRefs[this.messageElementRefs.length-2];i&&this.messageToElements.length>0&&!e.bubbleElement[t].contains(pi.getRoleClass(s))&&pi.revealRoleElements(i.innerContainer,this.avatar,this.name)}}static isTemporaryElement(t){return e.isLoadingMessage(t)||ye.isElementTemporary(t)}createElements(t,s){const i=e.createBaseElements(s),{outerContainer:n,innerContainer:o,bubbleElement:r}=i;return n.appendChild(o),this.addInnerContainerElements(r,t,s),i}createMessageElements(t,e,s=!1){const i=this.createElements(t,e);return pi.updateRefArr(this.messageElementRefs,i,s),pi.classifyRoleMessages(this.messageElementRefs,e),i}static createBaseElements(e){const i=s(),n=s();n[t].add("inner-message-container"),i.appendChild(n),i[t].add("outer-message-container"),i[t].add(pi.buildRoleOuterContainerClass(e));const o=s();return o[t].add("message-bubble"),n.appendChild(o),{outerContainer:i,innerContainer:n,bubbleElement:o}}addInnerContainerElements(e,s,i){const n=this.messageElementRefs[this.messageElementRefs.length-1];return pi.areOuterContainerClassRolesSame(i,n)&&!this.isLastMessageError()&&pi.hideRoleElements(n.innerContainer,this.avatar,this.name),e[t].add("message-bubble",pi.getRoleClass(i),i===u?"user-message-text":"ai-message-text"),this.renderText(e,s,i),pi.addRoleElements(e,i,this.avatar,this.name),{bubbleElement:e}}applyCustomStyles(t,e,s,i){t&&this.messageStyles&&Qs.applyCustomStyles(this.messageStyles,t,e,s,i)}static createMessageContent(t){const{text:e,files:s,html:i,custom:n,_sessionId:o,role:l}=t,c={[P]:l||h};return e&&(c[r]=e),s&&(c[k]=s),i&&(c[a]=i),!e&&!s&&!i&&(c[r]=""),n&&(c.custom=n),o&&(c._sessionId=o),c}removeMessage(t){t.outerContainer.remove();const e=this.messageElementRefs.findIndex(e=>e===t);this.messageElementRefs.splice(e,1)}removeFirstMessage(){this.messageElementRefs[0].outerContainer.remove(),this.messageElementRefs.shift()}removeLastMessage(){this.messageElementRefs[this.messageElementRefs.length-1].outerContainer.remove(),this.messageElementRefs.pop()}isLastMessageError(){var e;return null==(e=pi.getLastMessageBubbleElement(this.elementRef))?void 0:e[t].contains(p)}static isLoadingMessage(e){return null==e?void 0:e.bubbleElement[t].contains(le.BUBBLE_CLASS)}sendClientUpdate(t,e=!1){var s;null==(s=this._onMessage)||s.call(this,t,e)}renderText(t,e,s){const{contentEl:i,wrapper:n}=we.tryAddWrapper(t,e,this._customWrappers,s);n&&we.apply(this,t),i.innerHTML=this._remarkable.render(e),this._applyHTMLToRemarkable&&we.apply(this,i),0===i.innerText.trim().length&&i.children.length>0&&"P"!==i.children[0].tagName&&(i.innerText=e)}refreshTextMessages(t){this._remarkable=Js.createNew(t),this.messageToElements.forEach(t=>{t[1][r]&&t[0][r]&&this.renderText(t[1][r].bubbleElement,t[0][r],t[0][P])})}getFirstMessageContentEl(){const{text:t,html:e,files:s}=this.messageToElements[this.messageToElements.length-1][1];return t||e||(null==s?void 0:s[0])}scrollToFirstElement(t,e){var s;if(t===u){const t="boolean"!=typeof this.focusMode&&(null==(s=this.focusMode)?void 0:s.smoothScroll);ne.scrollToBottom(this,t)}else if(e&&this.autoScrollAllowed){const t=this.getFirstMessageContentEl();ne.scrollToBottom(this,!1,null==t?void 0:t.outerContainer)}}};ui.TEXT_BUBBLE_CLASS="text-message",ui.INTRO_CLASS="deep-chat-intro",ui.LAST_GROUP_MESSAGES_ACTIVE="deep-chat-last-group-messages-active";let di=ui;class pi{static getLastElementsByClass(e,s,i){for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(o.bubbleElement[t].contains(s[0])&&!s.slice(1).find(e=>!o.bubbleElement[t].contains(e))){if(!i)return o;if(!i.find(e=>o.bubbleElement[t].contains(e)))return o}}}static getLastMessage(t,e,s){for(let i=t.length-1;i>=0;i-=1)if(t[i][0][P]===e){if(!s)return t[i][0];if(t[i][0][s])return t[i][0]}}static getLastTextToElement(t,e){for(let s=t.length-1;s>=0;s-=1)if(t[s][0]===e)return t[s]}static overwriteMessage(t,e,s,i,n,o){const r=pi.getLastElementsByClass(e,[pi.getRoleClass(i),o],[le.BUBBLE_CLASS]),a=pi.getLastMessage(t,i,n);return a&&(a[n]=s),r}static getRoleClass(t){return`${t}-message`}static fillEmptyMessageElement(e,s){0===s.trim().length&&(e[t].add(v),e.innerHTML='<div style="color:#00000000">.</div>')}static unfillEmptyMessageElement(e,s){e[t].contains(v)&&s.trim().length>0&&e.replaceChildren()}static getLastMessageBubbleElement(e){var s,i,n;return Array.from((null==(n=null==(i=null==(s=pi.getLastMessageElement(e))?void 0:s.children)?void 0:i[0])?void 0:n.children)||[]).find(e=>e[t].contains("message-bubble"))}static getLastMessageElement(t){var e;const s=null==(e=t.children[t.children.length-1])?void 0:e.children;return null==s?void 0:s[s.length-1]}static addRoleElements(t,e,s,i){null==s||s.addBesideBubble(t,e),null==i||i.addBesideBubble(t,e)}static hideRoleElements(t,e,s){null==e||e.tryHide(t),null==s||s.tryHide(t)}static revealRoleElements(t,e,s){null==e||e.tryReveal(t),null==s||s.tryReveal(t)}static softRemRoleElements(t,e,s){null==e||e.trySoftRem(t),null==s||s.trySoftRem(t)}static updateRefArr(t,e,s){s?t.unshift(e):t.push(e)}static buildRoleOuterContainerClass(t){return`${m}${t}`}static addNewPositionClasses(e,s){e.outerContainer[t].remove(f,g,b),e.outerContainer[t].add(...s)}static getNumberOfElements(t){let e=0;return void 0!==t[r]&&(e+=1),void 0!==t[a]&&(e+=1),t[k]&&(e+=t[k].length),e}static filterdMessageElements(e,s){return e.filter(e=>e.bubbleElement[t].contains(s))}static findMessageElements(e,s){return e.find(e=>e.bubbleElement[t].contains(s))}static generateMessageBodyElements(t,e){const s={};return t[r]&&(s[r]=pi.findMessageElements(e,di.TEXT_BUBBLE_CLASS)),t[a]&&(s[a]=pi.findMessageElements(e,ke.HTML_BUBBLE_CLASS)),t[k]&&(s[k]=pi.filterdMessageElements(e,I)),s}static generateMessageBody(t,e,s=!1){const i=pi.getNumberOfElements(t),n=s?e.slice(0,i):e.slice(e.length-i);return pi.generateMessageBodyElements(t,n)}static classifyRoleMessages(e,s){let i=s?pi.buildRoleOuterContainerClass(s):void 0;for(let n=e.length-1;n>=0;n-=1){if(s||(i=Array.from(e[n].outerContainer[t]).find(t=>t.startsWith(m))),!i)continue;const o=e[n],r=o.outerContainer[t].contains(i),a=e[n-1],l=e[n+1],c=null==a?void 0:a.outerContainer[t].contains(i),h=null==l?void 0:l.outerContainer[t].contains(i);if(r)!c&&h?pi.addNewPositionClasses(o,[f]):c&&h?pi.addNewPositionClasses(o,[g]):c&&!h?pi.addNewPositionClasses(o,[b]):!c&&!h&&pi.addNewPositionClasses(o,[f,b]);else if(s)break}}static areOuterContainerClassRolesSame(e,s){return!!s&&Array.from(s.outerContainer[t]).find(t=>t.startsWith(m))===pi.buildRoleOuterContainerClass(e)}static resetAllRoleElements(e,s,i){if(!s&&!i)return;let n="";e.forEach((o,r)=>{o.bubbleElement[t].contains(p)||pi.revealRoleElements(o.innerContainer,s,i);const a=Array.from(o.outerContainer[t]).find(t=>t.startsWith(m));n===a&&pi.hideRoleElements(e[r-1].innerContainer,s,i),n=a})}static deepCloneMessagesWithReferences(t){return t.map(t=>pi.processMessageContent(t))}static processMessageContent(t){if(null==t||typeof t!==Gt)return t;if(Array.isArray(t))return t.map(t=>pi.processMessageContent(t));const e={};return Object.entries(t).forEach(([t,s])=>{"ref"===t&&s instanceof File||"custom"===t?e[t]=s:e[t]=null!==s&&typeof s===Gt?pi.processMessageContent(s):s}),e}}const mi=class e{constructor(t,e){this._fileAdded=!1,this._streamType="",this._hasStreamEnded=!1,this._partialContent="",this._messages=t,"object"==typeof e&&(this._partialRender=e.partialRender)}upsertStreamedMessage(t){if(this._hasStreamEnded)return;if(void 0===(null==t?void 0:t[r])&&void 0===(null==t?void 0:t[a]))return console[l](J);const e=(null==t?void 0:t[r])||(null==t?void 0:t[a])||"",s=ne.isScrollbarAtBottomOfElement(this._messages.elementRef),i=void 0!==(null==t?void 0:t[r])?r:a;if(this._elements||this._message){if(this._streamType!==i)return console[l]("Cannot mix {text: string} and {html: string} responses.");null!=t&&t[P]&&(null==t?void 0:t[P])!==this._activeMessageRole?(this.finaliseStreamedMessage(!1),this.setInitialState(i,e,null==t?void 0:t[P])):this.updateBasedOnType(e,i,null==t?void 0:t.overwrite)}else this.setInitialState(i,e,null==t?void 0:t[P]);null!=t&&t._sessionId&&(this._sessionId=null==t?void 0:t._sessionId),null!=t&&t.custom&&this._message&&(this._message.custom=t.custom),s&&this._messages.autoScrollAllowed&&ne.scrollToBottom(this._messages)}setInitialState(s,i,n){var o,a,l;this._streamType=s,this._targetWrapper=void 0,this._fileAdded=!1,this._partialContent="",this._partialBubble=void 0,n??(n=h);const c=(null==(o=this._messages._customWrappers)?void 0:o[n])||(null==(a=this._messages._customWrappers)?void 0:a[rt]),u=c?"":i;this._elements=s===r?this._messages.addNewTextMessage(u,n):ke.add(this._messages,u,n),this._elements&&(this._elements.bubbleElement[t].add(e.MESSAGE_CLASS),this._activeMessageRole=n,this._message={[P]:this._activeMessageRole,[s]:u},this._messages.messageToElements.push([this._message,{[s]:this._elements}]),c&&this.setTargetWrapperIfNeeded(this._elements,i,this._streamType,c),null==(l=this._messages.scrollButton)||l.updateHidden())}setTargetWrapperIfNeeded(t,e,s,i){t.bubbleElement.innerHTML=i,this._targetWrapper=we.getTargetWrapper(t.bubbleElement),this._elements&&we.apply(this._messages,this._elements.bubbleElement),this.updateBasedOnType(e,s)}updateBasedOnType(t,e,s=!1){var i;const n=this._targetWrapper||(null==(i=this._elements)?void 0:i.bubbleElement);this._partialRender||pi.unfillEmptyMessageElement(n,t),(e===r?this.updateText:this.updateHTML).bind(this)(t,n,s)}updateText(t,e,s){this._message&&(this._message[r]=s?t:this._message[r]+t,this._partialRender&&this.isNewPartialRenderParagraph(e,s)&&this.partialRenderNewParagraph(e),this._partialBubble?this.updatePartialRenderBubble(t):this._messages.renderText(e,this._message[r]))}containsPartialRenderMark(t){const s=t.indexOf(e.PARTIAL_RENDER_MARK);return-1!==s&&!t.substring(s+e.PARTIAL_RENDER_MARK.length).startsWith("---")}isNewPartialRenderParagraph(t,e){var s;if(e)return t.innerHTML="",!0;const i=this._streamType;if(!this._partialBubble){const t=null==(s=this._message)?void 0:s[i];return!!t&&this.containsPartialRenderMark(t)}return!!this._partialContent&&this.containsPartialRenderMark(this._partialContent)}partialRenderNewParagraph(e){this._partialContent="",this._partialBubble=s(),this._partialBubble[t].add("partial-render-message"),e.appendChild(this._partialBubble)}updatePartialRenderBubble(t){this._partialContent+=t,this._streamType===r?this._messages.renderText(this._partialBubble,this._partialContent):this._partialBubble.innerHTML=this._partialContent}updateHTML(t,e,i){if(this._message)if(this._message[a]=i?t:(this._message[a]||"")+t,this._partialRender&&this.isNewPartialRenderParagraph(e,i)&&this.partialRenderNewParagraph(e),this._partialBubble)this.updatePartialRenderBubble(t);else if(i)e.innerHTML=t;else{const i=s("span");i.innerHTML=t,e.appendChild(i)}}finaliseStreamedMessage(s=!0){var i,n;if(!this._endStreamAfterOperation&&(!this._fileAdded||this._elements)){if(!this._elements)throw Error(X);this._message&&null!=(i=this._elements.bubbleElement)&&i[t].contains(e.MESSAGE_CLASS)&&(this._streamType===r?this._messages.textToSpeech&&re.speak(this._message[r]||"",this._messages.textToSpeech):this._streamType===a&&this._elements&&we.apply(this._messages,this._elements.outerContainer),this._elements.bubbleElement[t].remove(e.MESSAGE_CLASS),this._message&&(this._sessionId&&(this._message._sessionId=this._sessionId),this._messages.sendClientUpdate(di.createMessageContent(this._message),!1),null==(n=this._messages.browserStorage)||n.addMessages(this._messages.messageToElements.map(([t])=>t))),this._hasStreamEnded=s)}}markFileAdded(){this._fileAdded=!0}async endStreamAfterFileDownloaded(t,e){this._endStreamAfterOperation=!0;const{text:s,files:i}=await e();s&&this.updateBasedOnType(s,r,!0),this._endStreamAfterOperation=!1,this.finaliseStreamedMessage(),i&&t.addNewMessage({[k]:i})}};mi.MESSAGE_CLASS="streamed-message",mi.PARTIAL_RENDER_MARK="\n\n";let vi=mi;class fi{static async tempRemoveContentHeader(t,e,s){if(null==t||!t.headers)throw new Error(W);const i=t.headers[Ht];let n;delete t.headers[Ht];try{n=await e(s)}catch(e){throw t.headers[Ht]=i,e}return t.headers[Ht]=i,n}static displayError(t,e,s="Service error, please try again."){if(console[l](e),typeof e===Gt)return e instanceof Error?t.addNewErrorMessage(o,e.message):Array.isArray(e)||typeof e[l]===B?t.addNewErrorMessage(o,e):0===Object.keys(e).length?t.addNewErrorMessage(o,s):t.addNewErrorMessage(o,R(e));t.addNewErrorMessage(o,e)}static fetch(t,e,s,i){var n,o;const r={method:(null==(n=t.connectSettings)?void 0:n.method)||Xt,headers:e};return r.method!==Jt&&(r.body=s?R(i):i),t.connectSettings.credentials&&(r.credentials=t.connectSettings.credentials),console.log(t.connectSettings),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(Wt)?t.json():null!=e&&e.includes("text/plain")||!e?t:t.blob()}static async processRequestInterceptor(t,e){var s;const i=await(null==(s=t.requestInterceptor)?void 0:s.call(t,e))||e,n=i,o=i;return{body:n.body,headers:n.headers,error:o[l]}}static validateResponseFormat(t,e){if(!t)return!1;const s=Array.isArray(t)?t:[t];return e&&s.length>1?(console[l](K),!1):!s.find(t=>"object"!=typeof t||!(typeof t[l]===B||typeof t[r]===B||typeof t[a]===B||Array.isArray(t[k])))}static onInterceptorError(t,e,s){t.addNewErrorMessage(o,e),null==s||s()}static async basicResponseProcessing(t,e,s={}){const{io:i,displayError:n=!0,useRI:o=!0}=s;if(null==i||!i.extractResultData)return e;const r=o?i.deepChat.responseInterceptor:void 0,a=await(null==r?void 0:r(e))||e,l=await i.extractResultData(a);if(l&&("object"==typeof l||Array.isArray(l)))return l;if(n){const s=z(e,"response",!!r,a);fi.displayError(t,s)}}}function gi(t){let e,s,i,n=!1;return function(o){void 0===e?(e=o,s=0,i=-1):e=function(t,e){const s=new Uint8Array(t.length+e.length);return s.set(t),s.set(e,t.length),s}(e,o);const r=e.length;let a=0;for(;s<r;){n&&(10===e[s]&&(a=++s),n=!1);let o=-1;for(;s<r&&-1===o;++s)switch(e[s]){case 58:-1===i&&(i=s-a);break;case 13:n=!0;case 10:o=s}if(-1===o)break;t(e.subarray(a,o),i),a=s,i=-1}a===r?e=void 0:0!==a&&(e=e.subarray(a),s-=a)}}const bi="text/event-stream",yi="last-event-id";function wi(t,e){var{signal:s,headers:i,onopen:n,onmessage:o,onclose:r,onerror:a,openWhenHidden:l,fetch:c}=e,h=function(t,e){var s={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(s[i]=t[i]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(s[i[n]]=t[i[n]])}return s}(e,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((e,u)=>{const d=Object.assign({},i);let p;function m(){p.abort(),document.hidden||w()}d.accept||(d.accept=bi),l||document.addEventListener("visibilitychange",m);let v=1e3,f=0;function g(){document.removeEventListener("visibilitychange",m),window.clearTimeout(f),p.abort()}null==s||s.addEventListener("abort",()=>{g(),e()});const b=c??window.fetch,y=n??xi;async function w(){var s;p=new AbortController;try{const s=await b(t,Object.assign(Object.assign({},h),{headers:d,signal:p.signal}));await y(s),await async function(t,e){const s=t.getReader();let i;for(;!(i=await s.read()).done;)e(i.value)}(s.body,gi(function(t,e,s){let i={data:"",event:"",id:"",retry:void 0};const n=new TextDecoder;return function(o,r){if(0===o.length)null==s||s(i),i={data:"",event:"",id:"",retry:void 0};else if(r>0){const s=n.decode(o.subarray(0,r)),a=r+(32===o[r+1]?2:1),l=n.decode(o.subarray(a));switch(s){case"data":i.data=i.data?i.data+"\n"+l:l;break;case"event":i.event=l;break;case"id":t(i.id=l);break;case"retry":const s=parseInt(l,10);isNaN(s)||e(i.retry=s)}}}}(t=>{t?d[yi]=t:delete d[yi]},t=>{v=t},o))),null==r||r(),g(),e()}catch(t){if(!p.signal.aborted)try{const e=null!==(s=null==a?void 0:a(t))&&void 0!==s?s:v;window.clearTimeout(f),f=window.setTimeout(w,e)}catch(t){g(),u(t)}}}w()})}function xi(t){const e=t.headers.get("content-type");if(null==e||!e.startsWith(bi))throw new Error(`Expected content-type to be ${bi}, Actual: ${e}`)}class ki{static async request(t,e,s,i=!0,n=!1){var o,r,a,l,c;const h={body:e,headers:null==(o=t.connectSettings)?void 0:o.headers},{body:u,headers:d,error:p}=await fi.processRequestInterceptor(t.deepChat,h);if(p)return fi.onInterceptorError(s,p,t.streamHandlers.onClose);if(null!=(r=t.connectSettings)&&r.handler)return Ai.stream(t,u,s);if((null==(a=t.connectSettings)?void 0:a.url)===Mi.URL)return Mi.requestStream(s,t);const m=new vi(s,t.stream),v={method:(null==(l=t.connectSettings)?void 0:l.method)||Xt,headers:d,credentials:null==(c=t.connectSettings)?void 0:c.credentials,body:i?R(u):u};return"object"==typeof t.stream&&t.stream.readable?ki.handleReadableStream(t,s,m,v,n,u):ki.handleEventStream(t,s,m,v,n,u),m}static handleReadableStream(t,e,s,i,n,o){var a;const{onOpen:l,onClose:c}=t.streamHandlers;let h=!1;fetch((null==(a=t.connectSettings)?void 0:a.url)||t.url||"",i).then(async i=>{var a,u;if(!i.body)throw new Error("Readable Stream connection error.");const d=i.body.getReader(),p=new TextDecoder;l();let m=!1;for(;!m&&!h;){const{value:i,done:l}=await d.read();if(m=l,m)ki.handleClose(t,s,c,n);else{const n=p.decode(i,{stream:!0}),l=await(null==(u=(a=t.deepChat).responseInterceptor)?void 0:u.call(a,n))||n,c="object"==typeof l?l:{[r]:n};ki.handleMessage(t,e,s,c,o)}}}).catch(s=>{ki.handleError(t,e,s)}),t.streamHandlers.onAbort=()=>{s.finaliseStreamedMessage(),t.streamHandlers.onClose(),h=!0}}static handleEventStream(t,e,s,i,n,o){var r;const{onOpen:a,onClose:l}=t.streamHandlers,c=new AbortController;t.streamHandlers.onAbort=()=>{s.finaliseStreamedMessage(),t.streamHandlers.onClose(),c.abort()},wi((null==(r=t.connectSettings)?void 0:r.url)||t.url||"",{...i,openWhenHidden:!0,async onopen(t){if(t.ok)return a();throw await fi.processResponseByType(t)},async onmessage(i){var n,r;if(R(i.data)!==R("[DONE]")){let a;try{a=JSON.parse(i.data)}catch{a={}}const l=await(null==(r=(n=t.deepChat).responseInterceptor)?void 0:r.call(n,a))||a;ki.handleMessage(t,e,s,l,o)}},onerror(t){throw l(),t},onclose(){ki.handleClose(t,s,l,n)},signal:c.signal}).catch(s=>{ki.handleError(t,e,s)})}static handleMessage(t,e,s,i,n){var o;null==(o=t.extractResultData)||o.call(t,i,n).then(t=>{ki.upsertContent(e,s.upsertStreamedMessage.bind(s),s,t),e.removeError()}).catch(t=>{e.isLastMessageError()||fi.displayError(e,t)})}static handleError(t,e,s){var i;e.isLastMessageError()||null==(i=t.extractResultData)||i.call(t,s).then(()=>{fi.displayError(e,s)}).catch(t=>{fi.displayError(e,t)})}static handleClose(t,e,s,i){if(t.asyncCallInProgress)t.asyncCallInProgress=!1;else try{e.finaliseStreamedMessage(),s()}catch(t){if(!i)throw t}}static async simulate(t,e,s,i){if(!await fi.basicResponseProcessing(t,s,{io:i,useRI:!1}))return e.onClose();if(Array.isArray(s)&&(s=s[0]),s[a]){e.onOpen();let n=we.splitHTML(s[a]);0===n.length&&(n=s[a].split(""));const o=new vi(t,null==i?void 0:i.stream);ki.populateMessages(t,n,o,e,a,0,i)}if(s[k]){const n=await fi.basicResponseProcessing(t,{[k]:s[k]},{io:i});t.addNewMessage({sendUpdate:!1,...n}),!s[a]&&!s[r]&&(new vi(t,null==i?void 0:i.stream).finaliseStreamedMessage(),e.onClose())}if(s[r]){e.onOpen();const n=s[r].split(""),o=new vi(t,null==i?void 0:i.stream);ki.populateMessages(t,n,o,e,r,0,i)}s[l]&&(fi.displayError(t,s[l]),e.onClose()),e.onAbort=()=>{e.onClose()}}static async populateMessages(t,e,s,i,n,o,r){const a=e[o];if(a){try{const e=await fi.basicResponseProcessing(t,{[n]:a},{io:r});ki.upsertContent(t,s.upsertStreamedMessage.bind(s),s,e),t.removeError()}catch(e){t.isLastMessageError()||fi.displayError(t,e)}const l=setTimeout(()=>{ki.populateMessages(t,e,s,i,n,o+1,r)},i.simulationInterim||6);i.onAbort=()=>{ki.abort(l,s,i.onClose)}}else s.finaliseStreamedMessage(),i.onClose()}static isSimulation(t){return"object"==typeof t&&!!t.simulation}static isSimulatable(t,e){return ki.isSimulation(t)&&e&&(e[r]||e[a])}static abort(t,e,s){clearTimeout(t),e.finaliseStreamedMessage(),s()}static upsertContent(t,e,s,i){if(i&&Array.isArray(i)&&(i=i[0]),null!=i&&i[r]||null!=i&&i[a]){const t=e(i);s??(s=t||void 0)}if(null!=i&&i[k]&&(t.addNewMessage({[k]:i[k]}),null==s||s.markFileAdded()),null!=i&&i[l])throw i[l]}}const _i=class t{static generateResponse(t){const e=t[t.length-1][0];if(e[k]&&e[k].length>0){if(e[k].length>1)return"These are interesting files!";const t=e[k][0];return t[y]&&t[y].startsWith("data:image/gif")?"That is a nice gif!":t[w]===_?"That is a nice image!":t[w]===T?"I like the sound of that!":"That is an interesting file!"}if(e[r]){if("?"===e[r].charAt(e[r].length-1))return"I'm sorry but I can't answer that question...";if(e[r].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:s}){return e?t.getCustomResponse(e,s[s.length-1][0]):{[r]:t.generateResponse(s)}}static request(e,s){const i=t.getResponse(s);setTimeout(async()=>{const t=await fi.basicResponseProcessing(s,i,{io:e});if(!t)return e.completionsHandlers.onFinish();const n=Array.isArray(t)?t:[t],r=n.find(t=>typeof t[l]===B);r?(s.addNewErrorMessage(o,r[l]),e.completionsHandlers.onFinish()):ki.isSimulatable(e.stream,t)?ki.simulate(s,e.streamHandlers,t):(n.forEach(t=>s.addNewMessage(t)),e.completionsHandlers.onFinish())},400)}static requestStream(e,s){setTimeout(()=>{const i=t.getResponse(e);ki.simulate(e,s.streamHandlers,i,s)},400)}};_i.URL="deep-chat-demo";let Mi=_i;class Ci{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(!Ci.isElementPresentInDOM(t.deepChat))return;const s=t.connectSettings.websocket;if(s){if(t.connectSettings.handler)return Ai.websocket(t,e);try{const i="boolean"!=typeof s?s:void 0,n=new WebSocket(t.connectSettings.url||"",i);t.websocket=n,t.websocket.onopen=()=>{var s,i;e.removeError(),t.websocket&&typeof t.websocket===Gt&&Ci.assignListeners(t,n,e),null==(i=(s=t.deepChat)._validationHandler)||i.call(s)},t.websocket.onerror=s=>{console[l](s),Ci.retryConnection(t,e)}}catch(s){console[l](s),Ci.retryConnection(t,e)}}}static retryConnection(t,e){var s,i;null==(i=(s=t.deepChat)._validationHandler)||i.call(s),Ci.isElementPresentInDOM(t.deepChat)&&(t.websocket="pending",e.isLastMessageError()||e.addNewErrorMessage(o,"Connection error"),setTimeout(()=>{Ci.createConnection(t,e)},5e3))}static assignListeners(t,e,s){const i={};e.onmessage=async e=>{if(t.extractResultData)try{const n=JSON.parse(e.data),o=await fi.basicResponseProcessing(s,n,{io:t,displayError:!1});if(!o)throw Error(z(n,"server",!!t.deepChat.responseInterceptor,o));if(ki.isSimulation(t.stream)){const e=Ci.stream.bind(this,t,s,i),r=i[n[P]||h];ki.upsertContent(s,e,r,o)}else{const t=Array.isArray(o)?o:[o],e=t.find(t=>typeof t[l]===B);if(e)throw e[l];t.forEach(t=>s.addNewMessage(t))}}catch(t){fi.displayError(s,t,"Error in server message")}},e.onclose=()=>{var e,i;console[l]("Connection closed"),s.isLastMessageError()||s.addNewErrorMessage(o,"Connection error"),t.stream&&(null==(i=(e=t.streamHandlers).onAbort)||i.call(e)),Ci.createConnection(t,s)}}static async sendWebsocket(t,e,s,i=!0){var n,r;if((null==(n=t.connectSettings)?void 0:n.url)===Mi.URL)return Mi.request(t,s);const a=t.websocket;if(!a||"pending"===a)return;const c={body:e,headers:null==(r=t.connectSettings)?void 0:r.headers},{body:h,error:u}=await fi.processRequestInterceptor(t.deepChat,c);if(u)return s.addNewErrorMessage(o,u);if(!Ci.isWebSocket(a))return a.newUserMessage.listener(h);const d=i?R(h):h;void 0===a.readyState||a.readyState!==a.OPEN?(console[l]("Connection is not open"),s.isLastMessageError()||s.addNewErrorMessage(o,"Connection error")):(a.send(R(d)),t.completionsHandlers.onFinish())}static canSendMessage(t){return!t||"pending"!==t&&(Ci.isWebSocket(t)?void 0!==t.readyState&&t.readyState===t.OPEN:t.isOpen)}static isWebSocket(t){return void 0!==t.send}static stream(t,e,s,i){if(!i)return;const n=t.stream.simulation;if(typeof n===B){const o=i[P]||h,l=s[o];i[r]===n||i[a]===n?(null==l||l.finaliseStreamedMessage(),delete s[o]):(s[o]??(s[o]=new vi(e,t.stream)),s[o].upsertStreamedMessage(i))}else ki.simulate(e,t.streamHandlers,i)}}class Ai{static async request(t,e,s){var i,n;let r=!0;const a=Ai.generateOptionalSignals();null==(n=(i=t.connectSettings).handler)||n.call(i,e,{...a,onResponse:async e=>{if(!r)return;r=!1;const i=await fi.basicResponseProcessing(s,e,{io:t,displayError:!1});if(i){const e=Array.isArray(i)?i:[i],n=e.find(t=>typeof t[l]===B);n?(console[l](n[l]),s.addNewErrorMessage(o,n[l]),t.completionsHandlers.onFinish()):ki.isSimulatable(t.stream,i)?ki.simulate(s,t.streamHandlers,i):(e.forEach(t=>s.addNewMessage(t)),t.completionsHandlers.onFinish())}else console[l](z(e,"server",!!t.deepChat.responseInterceptor,i)),s.addNewErrorMessage(o,"Error in server message"),t.completionsHandlers.onFinish()}})}static attemptToFinaliseStream(t,e){try{const s=e.messageElementRefs[e.messageElementRefs.length-1];di.isLoadingMessage(s)?e.removeLastMessage():t.finaliseStreamedMessage()}catch(t){console[l](t),e.addNewErrorMessage(o,t)}}static stream(t,e,s){var i,n;let o=!0,r=!1;const a=new vi(s,t.stream);t.streamHandlers.onAbort=()=>{Ai.attemptToFinaliseStream(a,s),t.streamHandlers.onClose(),o=!1};const c=Ai.generateOptionalSignals();null==(n=(i=t.connectSettings).handler)||n.call(i,e,{...c,onOpen:()=>{r||!o||(t.streamHandlers.onOpen(),r=!0)},onResponse:async e=>{if(!o)return;const i=await fi.basicResponseProcessing(s,e,{io:t,displayError:!1});if(i)i[l]?(Ai.streamError(i[l],a,t,s),o=!1):ki.upsertContent(s,a.upsertStreamedMessage.bind(a),a,i);else{const n=z(e,"server",!!t.deepChat.responseInterceptor,i);Ai.streamError(n,a,t,s),o=!1}},onClose:()=>{o&&(Ai.attemptToFinaliseStream(a,s),t.streamHandlers.onClose(),o=!1)},stopClicked:t.streamHandlers.stopClicked})}static streamError(t,e,s,i){console[l](t),e.finaliseStreamedMessage(),i.addNewErrorMessage(o,t),s.streamHandlers.onClose()}static websocket(t,e){var s,i;const n={isOpen:!1,newUserMessage:{listener:()=>{}},roleToStream:{}};t.websocket=n;const r=Ai.generateOptionalSignals();null==(i=(s=t.connectSettings).handler)||i.call(s,void 0,{...r,onOpen:()=>{e.removeError(),n.isOpen=!0},onResponse:async s=>{const i=await fi.basicResponseProcessing(e,s,{io:t,displayError:!1});if(i){const s=Array.isArray(i)?i:[i],r=s.find(t=>typeof t[l]===B);if(r)console[l](r[l]),e.isLastMessageError()||e.addNewErrorMessage(o,r[l]);else if(ki.isSimulation(t.stream)){const s=i,o=Ci.stream.bind(this,t,e,n.roleToStream),r=n.roleToStream[s[P]||h];ki.upsertContent(e,o,r,s)}else s.forEach(t=>e.addNewMessage(t))}else console[l](z(s,"server",!!t.deepChat.responseInterceptor,i)),e.addNewErrorMessage(o,"Error in server message")},onClose:()=>{n.isOpen=!1},newUserMessage:n.newUserMessage})}static generateOptionalSignals(){return{onClose:()=>{},onOpen:()=>{},stopClicked:{listener:()=>{}},newUserMessage:{listener:()=>{}}}}}class Ti{static async request(t,e,s,i=!0){var n,o,r;const a={body:e,headers:null==(n=t.connectSettings)?void 0:n.headers},{body:c,headers:h,error:u}=await fi.processRequestInterceptor(t.deepChat,a),{onFinish:d}=t.completionsHandlers;if(u)return fi.onInterceptorError(s,u,d);if(null!=(o=t.connectSettings)&&o.handler)return Ai.request(t,c,s);if((null==(r=t.connectSettings)?void 0:r.url)===Mi.URL)return Mi.request(t,s);let p=!0;fi.fetch(t,h,i,c).then(t=>(p=!!t.ok,t)).then(t=>fi.processResponseByType(t)).then(async e=>{var i,n;if(!t.extractResultData)return;const o=await(null==(n=(i=t.deepChat).responseInterceptor)?void 0:n.call(i,e))||e,r=await t.extractResultData(o,c);if(!p)throw e;if(!r||typeof r!==Gt&&!Array.isArray(r))throw Error(z(e,"response",!!t.deepChat.responseInterceptor,o));if(r[l])throw r[l];t.asyncCallInProgress?t.asyncCallInProgress=!1:ki.isSimulatable(t.stream,r)?ki.simulate(s,t.streamHandlers,r):((Array.isArray(r)?r:[r]).forEach(t=>s.addNewMessage(t)),d())}).catch(t=>{fi.displayError(s,t),d()})}static executePollRequest(t,e,s,i){const{onFinish:n}=t.completionsHandlers;fetch(e,s).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(()=>{Ti.executePollRequest(t,e,s,i)},l.timeoutMS):ki.isSimulatable(t.stream,l)?ki.simulate(i,t.streamHandlers,l):(i.addNewMessage(l),n())}).catch(t=>{fi.displayError(i,t),n()})}static async poll(t,e,s,i=!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 fi.processRequestInterceptor(t.deepChat,a);if(h)return fi.onInterceptorError(s,h);const u=(null==(o=t.connectSettings)?void 0:o.url)||t.url||"",d={method:(null==(r=t.connectSettings)?void 0:r.method)||Xt,body:i?R(l):l,headers:c};t.connectSettings.credentials&&(d.credentials=t.connectSettings.credentials),Ti.executePollRequest(t,u,d,s)}static verifyKey(t,e,s,i,n,o,r,a,c){if(""===t)return o(H);r(),fetch(e,{method:i,headers:s,body:c||null}).then(t=>fi.processResponseByType(t)).then(e=>{a(e,t,n,o)}).catch(t=>{o(V),console[l](t)})}}class Si{static getCharacterLimitMessages(t,e){var s;if(-1===e)return t;let i=0,n=t.length-1;for(;n>=0;n-=1){const o=null==(s=t[n])?void 0:s[r];if(void 0!==o&&(i+=o.length,i>e)){t[n][r]=o.substring(0,o.length-(i-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,s){return void 0!==e?e>0&&(t=Si.getMaxMessages(t,e)):t=[t[t.length-1]],t=F(t),void 0===s?t:Si.getCharacterLimitMessages(t,s)}}const ji=class s{constructor(t,e,s){this._isLoading=!1,this._isPaginationComplete=!1,this._index=0,this._messages=e,s.fetchHistory&&this.fetchHistory(s.fetchHistory),this.setupInitialHistory(t)}async fetchHistory(t){const e=si.addMessage(this._messages),i=await t();this._messages.removeMessage(e),s.displayIntroMessages(this._messages.messageElementRefs),i.forEach(t=>this._messages.addAnyMessage(t,!0)),setTimeout(()=>ne.scrollToBottom(this._messages),0)}scrollToPreloadFirstEl(t,e){this._messages.elementRef.scrollTop=e+t.offsetTop-40}processLoadedHistory(e){var s;const{messageElementRefs:i,messageToElements:n,elementRef:o}=this._messages,r=null==(s=i.find(e=>!e.outerContainer[t].contains(di.INTRO_CLASS)))?void 0:s.outerContainer,a=o.scrollTop;null==e||e.reverse().map(t=>{const e=this._messages.addAnyMessage({...t,sendUpdate:!0},!0,!0);if(e){const t=pi.generateMessageBody(e,i,!0);n.unshift([e,t])}return e}).filter(t=>!!t).reverse().forEach(t=>this._messages.sendClientUpdate(t,!0)),r&&(this._messages.messageElementRefs.length>=this._messages.maxVisibleMessages?setTimeout(()=>this.scrollToPreloadFirstEl(r,a)):this.scrollToPreloadFirstEl(r,a))}populateMessages(t,e){this._messages.removeMessage(t),this._isPaginationComplete=e.findIndex(t=>!t)<0;const s=e.filter(t=>!!t);this.processLoadedHistory(s);const{messageElementRefs:i,avatar:n,name:o}=this._messages;pi.resetAllRoleElements(i,n,o)}async loadHistoryOnScroll(t){this._messages.elementRef.onscroll=async()=>{if(!this._isLoading&&!this._isPaginationComplete&&0===this._messages.elementRef.scrollTop){this._isLoading=!0;const e=si.addMessage(this._messages,!1);try{const s=await t(this._index++);this.populateMessages(e,s),this._isLoading=!1}catch(t){this._messages.removeMessage(e),this._isPaginationComplete=!0,this._messages.addNewErrorMessage(o,s.FAILED_ERROR_MESSAGE,!0),console[l](t)}}}}populateInitialHistory(t){t.forEach(t=>{ce.processHistoryFile(t),this._messages.addAnyMessage(t,!0)})}async loadInitialHistory(t){this._isLoading=!0;const e=si.addMessage(this._messages);try{const s=await t(this._index++),i=this._messages.elementRef.scrollTop;this.populateMessages(e,s),this.restoreScrollOrScrollToBottom(0===i)}catch(t){this._messages.removeMessage(e),this._isPaginationComplete=!0,this._messages.addNewErrorMessage(o,s.FAILED_ERROR_MESSAGE,!0),console[l](t)}s.displayIntroMessages(this._messages.messageElementRefs),this._isLoading=!1}async setupInitialHistory(t){var e;t.loadHistory&&this.loadInitialHistory(t.loadHistory);const s=null==(e=this._messages.browserStorage)?void 0:e.get(),i=t.history||ce.processHistory(t)||(null==s?void 0:s.messages);i&&(this.populateInitialHistory(i),this.restoreScrollOrScrollToBottom(!0),this._index+=1)}restoreScrollOrScrollToBottom(t){var e,s,i;const n=null==(s=null==(e=this._messages.browserStorage)?void 0:e.get())?void 0:s.scrollHeight;void 0!==n&&null!=(i=this._messages.browserStorage)&&i.trackScrollHeight?setTimeout(()=>{this._messages.elementRef.scrollTop=n},0):t&&setTimeout(()=>ne.scrollToBottom(this._messages),0)}static addErrorPrefix(t){t.permittedErrorPrefixes??(t.permittedErrorPrefixes=[]),t.permittedErrorPrefixes.push(s.FAILED_ERROR_MESSAGE)}static displayIntroMessages(s){for(let i=0;i<s.length;i+=1){const i=s[0];if(!i.outerContainer[t].contains(di.INTRO_CLASS))break;i.outerContainer[e].display=""}}};ji.FAILED_ERROR_MESSAGE="Failed to load history";let Ei=ji;class Ii{static parseConfig(t,e,s){var i;const n={files:t};if("object"==typeof s){ce.processFileConfigConnect(s);const{files:t,connect:o,button:r}=s;t&&(t.infoModal&&(n[k].infoModal=t.infoModal,null!=(i=t.infoModal)&&i.textMarkDown&&(n.infoModalTextMarkUp=e.render(t.infoModal.textMarkDown))),t.acceptedFormats&&(n[k].acceptedFormats=t.acceptedFormats),t.maxNumberOfFiles&&(n[k].maxNumberOfFiles=t.maxNumberOfFiles)),n.button=r,o&&Object.keys(o).length>0&&(n.connect=o)}return n}static processMixedFiles(t,e,s){if(s){const i={acceptedFormats:""};t.fileTypes.mixedFiles=Ii.parseConfig(i,e,s)}}static processMicrophone(t,e,s,i){var n,o,r,a,l,c;const h={acceptedFormats:"audio/*",...(null==(n=t.fileTypes[T])?void 0:n[k])||{}};s&&(void 0!==navigator.mediaDevices.getUserMedia?(t.recordAudio=Ii.parseConfig(h,e,s),"object"==typeof s&&s[k]&&((o=t.recordAudio)[k]??(o[k]={}),t.recordAudio[k].format=null==(r=s[k])?void 0:r.format,t.recordAudio[k].maxDurationSeconds=null==(a=s[k])?void 0:a.maxDurationSeconds,null!=(l=t.fileTypes[T])&&l[k]&&((c=t.fileTypes[T][k]).maxNumberOfFiles??(c.maxNumberOfFiles=s[k].maxNumberOfFiles)))):i||(t.fileTypes[T]=Ii.parseConfig(h,e,s)))}static processAudioConfig(t,e,s,i){if(!s&&!i)return;const n={acceptedFormats:"audio/*",...(null==i?void 0:i[k])||{}};t.fileTypes[T]=Ii.parseConfig(n,e,s)}static processGifConfig(t,e,s,i){if(!s&&!i)return;const n={acceptedFormats:"image/gif",...(null==i?void 0:i[k])||{}};t.fileTypes[A]=Ii.parseConfig(n,e,s)}static processCamera(t,e,s,i){var n,o,r,a;const l={acceptedFormats:"image/*",...(null==(n=t.fileTypes[M])?void 0:n[k])||{}};s&&(void 0!==navigator.mediaDevices.getUserMedia?(t[C]=Ii.parseConfig(l,e,s),"object"==typeof s&&(t[C].modalContainerStyle=s.modalContainerStyle,s[k]&&((o=t[C])[k]??(o[k]={}),t[C][k].format=null==(r=s[k])?void 0:r.format,t[C][k].dimensions=null==(a=s[k])?void 0:a.dimensions))):i||(t.fileTypes[M]=Ii.parseConfig(l,e,s)))}static processImagesConfig(t,e,s,i){if(!s&&!i)return;const n={acceptedFormats:"image/*",...(null==i?void 0:i[k])||{}};t.fileTypes[M]=Ii.parseConfig(n,e,s)}static populateDefaultFileIO(t,e){var s,i;t&&(t[k]??(t[k]={}),(s=t[k]).acceptedFormats??(s.acceptedFormats=e),(i=t[k]).maxNumberOfFiles??(i.maxNumberOfFiles=1))}static set(t,e,s){Ii.populateDefaultFileIO(null==s?void 0:s[T],".4a,.mp3,.webm,.mp4,.mpga,.wav,.mpeg,.m4a"),Ii.populateDefaultFileIO(null==s?void 0:s[M],".png,.jpg");const i=Js.createNew(t.remarkable);Ii.processImagesConfig(e,i,t[M],null==s?void 0:s[M]),Ii.processCamera(e,i,t[C],t[M]),Ii.processGifConfig(e,i,t[A],null==s?void 0:s[A]),Ii.processAudioConfig(e,i,t[T],null==s?void 0:s[T]),Ii.processMicrophone(e,i,t[S],t[T]),Ii.processMixedFiles(e,i,t[j])}}class $i{constructor(t,e,s){var i,n,o,r,a;this.rawBody={},this.validateKeyProperty=!1,this.canSendMessage=$i.canSendMessage,this.connectSettings={},this.fileTypes={},this.completionsHandlers={},this.streamHandlers={},this.deepChat=t,this.demo=s,Object.assign(this.rawBody,null==(i=t.connect)?void 0:i.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,Ii.set(t,this,e),t.connect&&(this.connectSettings=t.connect),this.demo&&((r=this.connectSettings).url??(r.url=Mi.URL)),this.connectSettings.websocket&&Ci.setup(this),this.stream=(null==(a=this.deepChat.connect)?void 0:a.stream)||ce.checkForStream(this.deepChat),t.loadHistory&&Ei.addErrorPrefix(this)}static canSendMessage(t,e,s){return!!s||(!(!t||""===t.trim())||!!(e&&e.length>0))}verifyKey(t,e){}static createCustomFormDataBody(t,e,s){const i=new FormData;s.forEach(t=>i.append("files",t)),Object.keys(t).forEach(e=>i.append(e,String(t[e])));let n=0;e.slice(0,e.length-1).forEach(t=>{i.append(`message${n+=1}`,R(t))});const o=e[e.length-1];return o[r]&&(delete o[k],i.append(`message${n+=1}`,R(o))),i}getServiceIOByType(t){if(t[w].startsWith(T)&&this.fileTypes[T])return this.fileTypes[T];if(t[w].startsWith(_)){if(this.fileTypes[A]&&t[w].endsWith("/gif"))return this.fileTypes[A];if(this.fileTypes[M])return this.fileTypes[M];if(this[C])return this[C]}return this.fileTypes[j]}async request(t,e,s=!0){return this.stream&&!ki.isSimulation(this.stream)?ki.request(this,t,e,s):Ti.request(this,t,e,s)}async callAPIWithText(t,e){var s,i,n,o;const r={messages:e,...this.rawBody};let a=!1;null!=(s=this.connectSettings.headers)&&s[Ht]||((i=this.connectSettings).headers??(i.headers={}),(n=this.connectSettings.headers)[Ht]??(n[Ht]=Wt),a=!0),await this.request(r,t),a&&(null==(o=this.connectSettings.headers)||delete o[Ht])}async callApiWithFiles(t,e,s){const i=$i.createCustomFormDataBody(this.rawBody,e,s),n=this.connectSettings,o=this.getServiceIOByType(s[0]);this.connectSettings=(null==o?void 0:o.connect)||this.connectSettings,await this.request(i,t,!1),this.connectSettings=n}async callServiceAPI(t,e,s){s?this.callApiWithFiles(t,e,s):this.callAPIWithText(t,e)}async callAPI(t,e){var s;if(!this.connectSettings)throw new Error(W);const i=Si.processMessages(e.messageToElements.map(([t])=>t),this.maxMessages,this.totalMessagesMaxCharLength);if(!this.connectSettings.websocket||this.connectSettings.handler&&this.connectSettings.url===Mi.URL)this.callServiceAPI(e,i,t[k]);else{const n={messages:i,...this.rawBody};t[k]&&null!=(s=this.getServiceIOByType(t[k][0]))&&s.connect?this.callApiWithFiles(e,i,t[k]):Ci.sendWebsocket(this,n,e,!1)}}async extractResultData(t){return t.result?ce.handleResponseProperty(t):fi.validateResponseFormat(t,!!this.stream)?t:void 0}isDirectConnection(){return!1}isWebModel(){return!1}isCustomView(){return!1}}class Oi extends $i{constructor(t,e,s,i,n){var o;super(t,n),this.insertKeyPlaceholderText="API Key",this.keyHelpUrl="",this.asyncCallInProgress=!1,this.systemMessage="",Object.assign(this.rawBody,null==(o=t.connect)?void 0:o.additionalBodyProps),this._keyVerificationDetails=e,this._buildHeadersFunc=s,i&&this.setApiKeyProperties(i),this.connectSettings=this.buildConnectSettings(this.key||"",t.connect)}setApiKeyProperties(t){this.key=t.key,t.validateKeyProperty&&(this.validateKeyProperty=t.validateKeyProperty)}buildConnectSettings(t,e){const s=e??{};return s.headers??(s.headers={}),Object.assign(s.headers,this._buildHeadersFunc(t)),s}completeConfig(t,e){t.system_prompt&&(this.systemMessage=t.system_prompt),e&&(this.functionHandler=e),delete t.system_prompt,delete t.key,delete t.function_handler,Object.assign(this.rawBody,t)}keyAuthenticated(t,e){this.connectSettings=this.buildConnectSettings(e,this.connectSettings),this.key=e,t()}verifyKey(t,e){const{url:s,method:i,handleVerificationResult:n,createHeaders:o,body:r,augmentUrl:a}=this._keyVerificationDetails,l=(null==o?void 0:o(t))||this._buildHeadersFunc(t),c=(null==a?void 0:a(t))||s;Ti.verifyKey(t,c,l,i,this.keyAuthenticated.bind(this,e.onSuccess),e.onFail,e.onLoad,n,r)}isDirectConnection(){return!0}static getRoleViaUser(t){return t===u?u:d}static getRoleViaAI(t){return t===h?d:u}processMessages(t){return Si.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this.systemMessage.length:-1)}addSystemMessage(t){this.systemMessage&&t.unshift({[P]:se,content:this.systemMessage})}async callDirectServiceServiceAPI(t,e,s,i,n){if(!this.connectSettings)throw new Error(W);const o=s(this.rawBody,e),r=!!i&&this.stream;if((!r||typeof r===Gt&&r.simulation)&&!o.stream)return await Ti.request(this,o,t,n);o.stream=!0,null!=i&&i.readable&&(this.stream={readable:!0}),ki.request(this,o,t)}async callToolFunction(t,e){var s,i;this.asyncCallInProgress=!0;const n=await t(e);if(!Array.isArray(n)){if(n[r]){const t={[r]:n[r]},e=await(null==(i=(s=this.deepChat).responseInterceptor)?void 0:i.call(s,t))||t;if(Array.isArray(e))throw Error("Function tool response interceptor cannot return an array");return{processedResponse:e}}throw Error(Y)}return{responses:await Promise.all(n)}}makeAnotherRequest(t,e,s){try{return e&&(this.stream?ki.request(this,t,e):Ti.request(this,t,e)),{[r]:s||""}}catch(t){throw this.asyncCallInProgress=!1,t}}genereteAPIKeyName(t){return`${t} API Key`}static getImageContent(t){return t.filter(t=>t[w]===_).map(t=>({[w]:ee,[ee]:{url:t[y]||""}})).filter(t=>t[ee].url.length>0)}static getTextWImagesContent(t){if(t[k]&&t[k].length>0){const e=this.getImageContent(t[k]);return t[r]&&t[r].trim().length>0&&e.unshift({[w]:r,[r]:t[r]}),e.length>0?e:t[r]||""}return t[r]||""}static getTextWFilesContent(t,e){if(t[k]&&t[k].length>0){const s=e(t[k]);return t[r]&&t[r].trim().length>0&&s.unshift({[w]:r,[r]:t[r]}),s}return t[r]||""}async extractStreamResultWToolsGeneric(t,e,s,i,n){const{delta:o,finish_reason:a}=e;if("tool_calls"===a){const e={tool_calls:t._streamToolCalls};return t._streamToolCalls=void 0,this.handleToolsGeneric(e,s,t.messages,i,n)}return null!=o&&o.tool_calls&&(t._streamToolCalls?o.tool_calls.forEach((e,s)=>{t._streamToolCalls&&(t._streamToolCalls[s].function.arguments+=e.function.arguments)}):t._streamToolCalls=o.tool_calls),{[r]:(null==o?void 0:o.content)||""}}async handleToolsGeneric(t,e,s,i,n){if(!t.tool_calls||!i||!e)throw Error(Q);const o=F(i),r=t.tool_calls.map(t=>({name:t.function.name,arguments:t.function.arguments})),{responses:a,processedResponse:l}=await this.callToolFunction(e,r);if(l)return l;if(n&&(o.messages=o.messages.slice(o.messages.length-1),n.message&&o.messages.unshift({[P]:se,content:n.message})),o.messages.push({tool_calls:t.tool_calls,[P]:d,content:null}),!a.find(({response:t})=>typeof t!==B)&&r.length===a.length)return a.forEach((e,s)=>{var i;const n=null==(i=t.tool_calls)?void 0:i[s];null==o||o.messages.push({[P]:"tool",tool_call_id:null==n?void 0:n.id,name:null==n?void 0:n.function.name,content:e.response})}),this.makeAnotherRequest(o,s);throw Error(Y)}updateSessionId(t){this.messages&&this.messages.messageToElements.length>0&&(this.messages.messageToElements[this.messages.messageToElements.length-1][0]._sessionId=t)}}class Pi{static waitForPropertiesToBeUpdatedBeforeRender(t){t._propUpdated_=!1,setTimeout(()=>{t._propUpdated_?Pi.waitForPropertiesToBeUpdatedBeforeRender(t):(t._waitingToRender_=!1,t.onRender())})}static attemptRender(t){t._propUpdated_=!0,t._waitingToRender_||(t._waitingToRender_=!0,Pi.waitForPropertiesToBeUpdatedBeforeRender(t))}}const Bi=class t extends HTMLElement{constructor(){super(),this._waitingToRender_=!1,this._propUpdated_=!1,Object.keys(t._attributeToProperty_).forEach(e=>{const s=t._attributeToProperty_[e];this.constructPropertyAccessors(s),this.hasOwnProperty(e)||this.constructPropertyAccessors(s,e)})}static get observedAttributes(){return Object.keys(t._attributes_)||[]}constructPropertyAccessors(t,e){let s;Object.defineProperty(this,e||t,{get:function(){return s},set:function(i){s=i,e?this[t]=i:Pi.attemptRender(this)}})}attributeChangedCallback(e,s,i){if(s===i)return;const n=t._attributes_[e](i);this[t._attributeToProperty_[e]]=n}onRender(){}};Bi._attributes_={},Bi._attributeToProperty_={};let Ri=Bi;class Fi{static createSVGElement(t){return(new DOMParser).parseFromString(t,"image/svg+xml").documentElement}}const Li=class i{static changeVisibility(t,s,n,o){o.target.id===i.VISIBLE_ICON_ID?(s[e].display="none",n[e].display="block",t[w]="password"):(s[e].display="block",n[e].display="none",t[w]=r)}static createIconElement(e,s){const i=Fi.createSVGElement(e);return i.id=s,i[t].add("visibility-icon"),i}static create(t){const n=s();n.id="visibility-icon-container";const o=i.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',i.VISIBLE_ICON_ID);o[e].display="none",n.appendChild(o);const r=i.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 n.appendChild(r),n.onclick=i.changeVisibility.bind(this,t,o,r),n}};Li.VISIBLE_ICON_ID="visible-icon";let qi=Li;class zi{static createCautionText(){const e=s("a");return e[t].add("insert-key-input-help-text"),e.innerText="Please exercise CAUTION when inserting your API key outside of deepchat.dev or localhost!!",e}static createHelpLink(e){const i=s("a");return i[t].add("insert-key-input-help-text"),i.href=e,i.innerText="Find more info here",i.target="_blank",i}static createFailText(){const t=s();return t.id="insert-key-input-invalid-text",t[e].display="none",t}static createHelpTextContainer(t,e=!0){const i=s();i.id="insert-key-help-text-container";const n=s();n.id="insert-key-help-text-contents";const o=zi.createFailText();if(n.appendChild(o),t){const e=zi.createHelpLink(t);n.appendChild(e)}if(!0===e){const t=zi.createCautionText();n.appendChild(t)}return i.appendChild(n),{helpTextContainerElement:i,failTextElement:o}}static onFail(s,i,n,o){s[t].replace("insert-key-input-valid","insert-key-input-invalid"),n.innerText=o,n[e].display="block",i.innerText="Start",s[t].remove(gt)}static onLoad(e,s){e[t].add(gt),s.innerHTML='<div id="loading-key"></div>'}static verifyKey(t,e,s){const i=t.value.trim();s.verifyKey(i,e)}static addVerificationEvents(e,s,i,n,o){const r={onSuccess:n,onFail:zi.onFail.bind(this,e,s,i),onLoad:zi.onLoad.bind(this,e,s)},a=zi.verifyKey.bind(this,e,r,o);s.onclick=a,e.onkeydown=s=>{!e[t].contains(gt)&&s.key===St.ENTER&&a()}}static createStartButton(){const t=s();return t.id="start-button",t.innerText="Start",t}static onInputFocus(e){e.target[t].replace("insert-key-input-invalid","insert-key-input-valid")}static createInput(e){const i=s();i.id="insert-key-input-container";const n=s("input");return n.id="insert-key-input",n.placeholder=e||"API Key",n[w]="password",n[t].add("insert-key-input-valid"),n.onfocus=zi.onInputFocus,i.appendChild(n),i}static createContents(t,e){var i;const n=s();n.id="insert-key-contents";const o=zi.createInput(e.insertKeyPlaceholderText),r=o.children[0],a=qi.create(r);o.appendChild(a),n.appendChild(o);const l=zi.createStartButton(),{helpTextContainerElement:c,failTextElement:h}=zi.createHelpTextContainer(e.keyHelpUrl,null==(i=e.deepChat._insertKeyViewStyles)?void 0:i.displayCautionText);return n.appendChild(l),n.appendChild(c),zi.addVerificationEvents(r,l,h,t,e),n}static createElements(t,e){const i=s();i.id="insert-key-view";const n=zi.createContents(t,e);return i.appendChild(n),i}static render(t,e,s){const i=zi.createElements(e,s);t.replaceChildren(i)}}const Di=class t{static enableButtons(e,s,i=0){window.webLLM?(e&&(e[ht]=!1),s&&(s[ht]=!1)):i<4*Vi.MODULE_SEARCH_LIMIT_S&&setTimeout(()=>t.enableButtons(e,s,i+1),250)}static setUpInitial(e,s,i,n){const o=(null==s?void 0:s.downloadClass)||t.DOWNLOAD_BUTTON_CLASS,r=(null==s?void 0:s.uploadClass)||t.UPLOAD_BUTTON_CLASS,a=(null==s?void 0:s.fileInputClass)||t.FILE_INPUT_CLASS;return setTimeout(()=>{const s=null==i?void 0:i.getElementsByClassName(o)[0],n=null==i?void 0:i.getElementsByClassName(a)[0],l=null==i?void 0:i.getElementsByClassName(r)[0];s&&(s.onclick=()=>e()),n&&(n.onchange=()=>{n[k]&&n[k].length>0&&e(n[k])}),l&&(l.onclick=()=>n[lt]()),(s||l)&&t.enableButtons(s,l)}),(null==s?void 0:s.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=s("a");for(let s=0;s<t.length/4;s+=1)setTimeout(()=>{const i=4*s;for(let s=i;s<Math.min(i+4,t.length);s+=1){const i=URL.createObjectURL(t[s]);e.href=i,e.download=t[s].name,document.body.appendChild(e),e[lt](),URL.revokeObjectURL(i)}},500*s)}static setUpAfterLoad(e,s,i,n){const o=(null==s?void 0:s.exportFilesClass)||t.EXPORT_BUTTON_CLASS;return setTimeout(()=>{const s=null==i?void 0:i.getElementsByClassName(o)[0];s&&(s.onclick=()=>t.exportFile(e))}),(null==s?void 0:s.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>`}};Di.DOWNLOAD_BUTTON_CLASS="deep-chat-download-button",Di.UPLOAD_BUTTON_CLASS="deep-chat-upload-button",Di.FILE_INPUT_CLASS="deep-chat-file-input",Di.EXPORT_BUTTON_CLASS="deep-chat-export-button";let Ni=Di;const Ui={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},Hi=class t extends $i{constructor(e){var s,i;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!=(s=this._webModel.load)&&s.clearCache&&t.clearAllCache(),this.findModelInWindow(e),this.canSendMessage=this.canSubmit.bind(this),this._chatEl=null==(i=e.shadowRoot)?void 0:i.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((s,i)=>{if(s[P]===u&&s[r]){const n=e[i+1];null!=n&&n[r]&&n[P]!==u&&t.push([s[r],n[r]])}})}findModelInWindow(e,s=0){var i;window.webLLM?this.configureInit(this.shouldAddIntroMessage(e.introMessage)):s>t.MODULE_SEARCH_LIMIT_S?(null==(i=this._messages)||i.addNewErrorMessage(o,t.WEB_LLM_NOT_FOUND_ERROR),console[l]("The deep-chat-web-llm module has not been attached to the window object. Please see the following guide:"),console[l]("https://deepchat.dev/examples/externalModules")):setTimeout(()=>this.findModelInWindow(e,s+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&&ne.scrollToTop(null==(e=this._messages)?void 0:e.elementRef)},t)}getIntroMessage(t){if(!this.shouldAddIntroMessage(t)||!this._chatEl)return;const e=Ni.setUpInitial(this.init.bind(this),this._webModel.introMessage,this._chatEl,!!this._webModel.worker);return this.scrollToTop(1),{[P]:h,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 s=this.attemptToCreateChat();s&&await this.loadModel(s,t)}attemptToCreateChat(){var e;if(t.chat)return null==(e=this._messages)||e.addNewErrorMessage(o,t.MULTIPLE_MODELS_ERROR),void console[l](t.MULTIPLE_MODELS_ERROR);if(this._isModelLoaded||this._isModelLoading)return;const{worker:s}=this._webModel;return Ui.use_web_worker&&s?new window.webLLM.ChatWorkerClient(s):new window.webLLM.ChatModule}getConfig(){var e;let s=t.DEFAULT_MODEL;this._webModel.model&&(s=this._webModel.model);const i=F(Ui);if(this._webModel.urls){const t=i.model_list.find(t=>t.local_id=s);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&&(i.use_cache=!1),{model:s,appConfig:i}}async loadModel(e,s){var i,n,o,a,l,c,h;this.scrollToTop(),t.chat=e,this._isModelLoading=!0;let u=!1===(null==(i=this._webModel.introMessage)?void 0:i.displayed);let d;t.chat.setInitProgressCallback(t=>{var e;null==(e=this._messages)||e.addNewMessage({html:`<div>${t[r]}</div>`,overwrite:!0,sendUpdate:!1}),u&&(setTimeout(()=>ne.scrollToBottom(this._messages)),u=!1)});try{const{model:e,appConfig:i}=this.getConfig(),n={};this._webModel.instruction&&(n.conv_config={[se]:this._webModel.instruction}),this._conversationHistory.length>0&&(n.conversation_history=this._conversationHistory),d=await t.chat.reload(e,n,i,s)}catch(t){return this.unloadChat(t)}if(null==(o=(n=this.deepChat)._validationHandler)||o.call(n),null!=(a=this._webModel.introMessage)&&a.removeAfterLoad)!1===this._webModel.introMessage.displayed?null==(c=this._messages)||c.removeLastMessage():null==(h=this._removeIntro)||h.call(this);else{const t=Ni.setUpAfterLoad(d,this._webModel.introMessage,this._chatEl,!!this._webModel.worker);null==(l=this._messages)||l.addNewMessage({html:t,overwrite:!0,sendUpdate:!1})}this._isModelLoaded=!0,this._isModelLoading=!1}async unloadChat(e){var s;null==(s=this._messages)||s.addNewErrorMessage(o,t.GENERIC_ERROR),console[l](e),this._isModelLoaded=!1,this._isModelLoading=!1,t.chat&&(await t.chat.unload(),t.chat=void 0)}async immediateResp(e,s,i){const n={[r]:await i.generate(s,void 0,0)},o=await t.processResponse(this.deepChat,e,n);o&&o.forEach(t=>e.addNewMessage(t)),this.completionsHandlers.onFinish()}async streamResp(e,s,i){this.streamHandlers.onAbort=()=>{i.interruptGenerate()},this.streamHandlers.onOpen();const n=new vi(e);await i.generate(s,async(s,i)=>{const o=await t.processResponse(this.deepChat,e,{[r]:i});o&&n.upsertStreamedMessage({[r]:o[0][r],overwrite:!0})}),n.finaliseStreamedMessage(),this.streamHandlers.onClose()}async generateRespByType(t,e,s,i){var n;try{s?await this.streamResp(t,e,i):await this.immediateResp(t,e,i)}catch(t){null==(n=this._messages)||n.addNewErrorMessage(o),console.log(t)}}async generateResp(t,e,s){const i=e[e.length-1][r],{body:n,error:o}=await fi.processRequestInterceptor(this.deepChat,{body:{[r]:i}}),a=!!this.stream;try{if(o)fi.displayError(t,new Error(o)),(a?this.streamHandlers.onClose:this.completionsHandlers.onFinish)();else if(n&&n[r])this.generateRespByType(t,n[r],!!this.stream,s);else{const e=D({body:n},!1);console[l](e);const s=a?this.streamHandlers.onClose:this.completionsHandlers.onFinish;fi.onInterceptorError(t,e,s)}}catch(t){this.unloadChat(t)}}async callServiceAPI(e,s){var i,n;if(!this._isModelLoaded){if(!this._loadOnFirstMessage)return;await this.init()}!t.chat||this._isModelLoading||(null!=(i=this._webModel.introMessage)&&i.removeAfterMessage&&(null==(n=this._removeIntro)||n.call(this)),e.addLoadingMessage(),this.generateResp(e,s,t.chat))}canSubmit(t){return!(null==t||!t.trim()||this._isModelLoading)&&(!!this._loadOnFirstMessage||!!this._isModelLoaded)}static async processResponse(t,e,s){var i,n;const o=await(null==(i=t.responseInterceptor)?void 0:i.call(t,s))||s;if(null!=(n=t.connect)&&n.stream&&Array.isArray(o)&&o.length>1)return void console[l](K);const a=Array.isArray(o)?o:[o],c=a.find(t=>typeof t[l]===B);if(!c){if(a.find(t=>!t||!t[r])){const i=N(s,!!t.responseInterceptor,o);return void fi.displayError(e,new Error(i))}return a}fi.displayError(e,new Error(c[l]))}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)})})})}};Hi.GENERIC_ERROR=`Error, please check the [troubleshooting](${c}webModel#troubleshooting) section of documentation for help.`,Hi.MULTIPLE_MODELS_ERROR="Cannot run multiple web models",Hi.WEB_LLM_NOT_FOUND_ERROR="WebLLM module not found",Hi.DEFAULT_MODEL="Llama-2-7b-chat-hf-q4f32_1",Hi.MODULE_SEARCH_LIMIT_S=5;let Vi=Hi;const Wi=(t,e,s,i)=>({url:t,method:e,handleVerificationResult:s,augmentUrl:i}),Gi=t=>({[Rt]:`${Kt}${t}`,[Ht]:Wt}),Zi=(t,e,s,i)=>{const n=t;Array.isArray(n[l])&&"Error in `parameters`: field required"===n[l][0]?s(e):i(H)},Ki=class t extends Oi{constructor(e,s,i,n,o,r){super(e,Wi("https://api-inference.huggingface.co/models/gpt2",Xt,Zi),Gi,o,r),this.insertKeyPlaceholderText="Hugging Face Token",this.keyHelpUrl="https://huggingface.co/settings/tokens",this.permittedErrorPrefixes=[qt],this.url=`${t.URL_PREFIX}${i}`,this.textInputPlaceholderText=s,"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,s){const i=F(t),n=e[e.length-1][r];if(n)return i.options??(i.options={}),i.options.wait_for_model=!0,{inputs:n,...i}}async callServiceAPI(t,e,s){if(!this.connectSettings)throw new Error(W);const i=this.preprocessBody(this.rawBody,e,s);Ti.request(this,i,t)}};Ki.URL_PREFIX="https://api-inference.huggingface.co/models/";let Ji=Ki;class Xi extends Ji{constructor(t,e,s,i,n,o){super(t,e,s,i,n,o),this.isTextInputDisabled=!0,this.canSendMessage=Xi.canSendFile}static canSendFile(t,e){return!(null==e||!e[0])}preprocessBody(t,e,s){return s[0]}async callServiceAPI(t,e,s){if(!this.connectSettings)throw new Error(W);if(null==s||!s[0])throw new Error(G);Ti.poll(this,s[0],t,!1)}}class Qi extends Xi{constructor(t){var e,s,i;const n=null==(s=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:s.audioClassification,o=null==(i=t.directConnection)?void 0:i.huggingFace;super(t,`Attach an audio ${x}`,"ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition",n,o,{audio:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t[l])throw t[l];return{[r]:(null==(e=t[0])?void 0:e.label)||""}}}class Yi extends Xi{constructor(t){var e,s,i;const n=null==(s=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:s.imageClassification,o=null==(i=t.directConnection)?void 0:i.huggingFace;super(t,`Attach an image ${x}`,"google/vit-base-patch16-224",n,o,{images:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t[l])throw t[l];return{[r]:(null==(e=t[0])?void 0:e.label)||""}}}const tn=t=>({[Rt]:`${Kt}${t}`,[Ht]:Wt}),en=(t,e,s,i)=>{t.message?i(H):s(e)},sn=()=>Wi("https://api.stability.ai/v1/engines/list",Jt,en),nn="data:image/png;base64,";class on extends Oi{constructor(t,e,s,i,n){super(t,e,s,i,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Stability AI"),this.keyHelpUrl="https://platform.stability.ai/docs/getting-started/authentication",this.permittedErrorPrefixes=[Dt,"invalid_"]}}class rn extends on{constructor(t){var e;const s=F(t.directConnection),i=null==s?void 0:s.stabilityAI;super(t,sn(),tn,i,{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";const n=null==(e=null==s?void 0:s.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`),rn.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=rn.canSendFileMessage}static cleanConfig(t){delete t.engine_id}static canSendFileMessage(t,e){return!(null==e||!e[0])}createFormDataBody(t,e){const s=new FormData;return s.append(_,e),Object.keys(t).forEach(e=>{s.append(e,String(t[e]))}),s}async callServiceAPI(t,e,s){if(!this.connectSettings)throw new Error(W);if(!s)throw new Error(Z);const i=this.createFormDataBody(this.rawBody,s[0]);fi.tempRemoveContentHeader(this.connectSettings,Ti.request.bind(this,this,i,t),!1)}async extractResultData(t){if(t.message)throw t.message;const e=t.artifacts.map(t=>({[y]:`${nn}${t.base64}`,[w]:_}));return{[k]:e}}}class an extends on{constructor(t){var e;const s=F(t.directConnection),i=null==s?void 0:s.stabilityAI,n={[M]:{[k]:{acceptedFormats:".png",maxNumberOfFiles:2}}};super(t,sn(),tn,i,n),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";const o=null==(e=null==s?void 0:s.stabilityAI)?void 0:e.imageToImageMasking;"object"==typeof o&&(o.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${o.engine_id}/image-to-image/masking`),void 0!==o.weight&&null!==o.weight&&(this._imageWeight=o.weight),void 0!==o.mask_source&&null!==o.mask_source&&(this._maskSource=o.mask_source),an.cleanConfig(o),Object.assign(this.rawBody,o)),this.canSendMessage=an.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,s,i){const n=new FormData;return n.append("init_image",e),n.append("mask_source",String(this._maskSource)),n.append("mask_image",s),i&&""!==i&&n.append("text_prompts[0][text]",i),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,s){var i,n;if(!this.connectSettings)throw new Error(W);if(!s||!s[0]||!s[1])throw new Error(Z);const o=null==(n=null==(i=e[e.length-1])?void 0:i[r])?void 0:n.trim(),a=this.createFormDataBody(this.rawBody,s[0],s[1],o);fi.tempRemoveContentHeader(this.connectSettings,Ti.request.bind(this,this,a,t),!1)}async extractResultData(t){if(t.message)throw t.message;const e=t.artifacts.map(t=>({[y]:`${nn}${t.base64}`,[w]:_}));return{[k]:e}}}class ln extends Xi{constructor(t){var e,s,i;const n=null==(s=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:s.audioSpeechRecognition,o=null==(i=t.directConnection)?void 0:i.huggingFace;super(t,`Attach an audio ${x}`,"facebook/wav2vec2-large-960h-lv60-self",n,o,{audio:{}})}async extractPollResultData(t){if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t[l])throw t[l];return{[r]:t[r]||""}}}class cn extends Ji{constructor(t){var e,s,i;super(t,"Once upon a time","gpt2",null==(s=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:s.textGeneration,null==(i=t.directConnection)?void 0:i.huggingFace)}async extractResultData(t){var e;if(t[l])throw t[l];return{[r]:(null==(e=t[0])?void 0:e.generated_text)||""}}}class hn extends Ji{constructor(t){var e,s,i;const n=null==(s=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:s.questionAnswer;super(t,"Ask a question","bert-large-uncased-whole-word-masking-finetuned-squad",n,null==(i=t.directConnection)?void 0:i.huggingFace),this.permittedErrorPrefixes=[qt,"Error in"],this._context=n.context}preprocessBody(t,e){const s=e[e.length-1][r];if(s)return{inputs:{question:s,context:this._context,options:{wait_for_model:!0}}}}async extractResultData(t){if(t[l])throw t[l];return{[r]:t.answer||""}}}class un extends Ji{constructor(t){var e,s,i;super(t,"Insert text to summarize","facebook/bart-large-cnn",null==(s=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:s.summarization,null==(i=t.directConnection)?void 0:i.huggingFace)}async extractResultData(t){var e;if(t[l])throw t[l];return{[r]:(null==(e=t[0])?void 0:e.summary_text)||""}}}class dn extends Ji{constructor(t){var e,s,i;super(t,"Ask me anything!","facebook/blenderbot-400M-distill",null==(s=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:s.conversation,null==(i=t.directConnection)?void 0:i.huggingFace),this.maxMessages??(this.maxMessages=-1)}processMessagesI(t){const e=t.filter(t=>t[r]),s=e[e.length-1][r],i=e.slice(0,e.length-1);if(!s)return;return{past_user_inputs:i.filter(t=>t[P]===u).map(t=>t[r]),generated_responses:i.filter(t=>t[P]===h).map(t=>t[r]),mostRecentMessageText:s}}preprocessBody(t,e){const s=F(t),i=this.processMessagesI(e);if(i)return s.options??(s.options={}),s.options.wait_for_model=!0,{inputs:{past_user_inputs:i.past_user_inputs,generated_responses:i.generated_responses,[r]:i.mostRecentMessageText},...s}}async extractResultData(t){if(t[l])throw t[l];return{[r]:t.generated_text||""}}}class pn extends on{constructor(t){var e;const s=F(t.directConnection),i=s.stabilityAI,n={[M]:{[k]:{acceptedFormats:".png",maxNumberOfFiles:1}}};super(t,sn(),tn,i,n),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/image-to-image",this.textInputPlaceholderText="Describe image changes";const o=null==(e=s.stabilityAI)?void 0:e.imageToImage;"object"==typeof o&&(o.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${o.engine_id}/text-to-image`),void 0!==o.weight&&null!==o.weight&&(this._imageWeight=o.weight),pn.cleanConfig(o),Object.assign(this.rawBody,o)),this.canSendMessage=pn.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,s){const i=new FormData;return i.append("init_image",e),s&&""!==s&&i.append("text_prompts[0][text]",s),void 0!==this._imageWeight&&null!==this._imageWeight&&i.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach(e=>{i.append(e,String(t[e]))}),void 0===i.get("weight")&&i.append("weight",String(1)),i}async callServiceAPI(t,e,s){var i,n;if(!this.connectSettings)throw new Error(W);if(!s)throw new Error(Z);const o=null==(n=null==(i=e[e.length-1])?void 0:i[r])?void 0:n.trim(),a=this.createFormDataBody(this.rawBody,s[0],o);fi.tempRemoveContentHeader(this.connectSettings,Ti.request.bind(this,this,a,t),!1)}async extractResultData(t){if(t.message)throw t.message;const e=t.artifacts.map(t=>({[y]:`${nn}${t.base64}`,[w]:_}));return{[k]:e}}}class mn extends Ji{constructor(t){var e,s,i;super(t,"Insert text to translate","Helsinki-NLP/opus-tatoeba-en-ja",null==(s=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:s.translation,null==(i=t.directConnection)?void 0:i.huggingFace)}async extractResultData(t){var e;if(t[l])throw t[l];return{[r]:(null==(e=t[0])?void 0:e.translation_text)||""}}}class vn extends on{constructor(t){var e;const s=F(t.directConnection),i=s.stabilityAI;super(t,sn(),tn,i),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/text-to-image",this.textInputPlaceholderText="Describe an image";const n=null==(e=s.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),vn.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=vn.canSendTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendTextMessage(t){return!(!t||""===t.trim())}preprocessBody(t,e){const s=e[e.length-1][r],i=F(t),n={[r]:s};return this._imageWeight&&(n.weight=this._imageWeight),i.text_prompts=[n],i}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){if(t.message)throw t.message;const e=t.artifacts.map(t=>({[y]:`${nn}${t.base64}`,[w]:_}));return{[k]:e}}}class fn extends Ji{constructor(t){var e,s,i;super(t,"The goal of life is [MASK].","bert-base-uncased",null==(s=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:s.fillMask,null==(i=t.directConnection)?void 0:i.huggingFace),this.permittedErrorPrefixes=[qt,"No mask_token"]}async extractResultData(t){var e;if(t[l])throw t[l];return{[r]:(null==(e=t[0])?void 0:e.sequence)||""}}}const gn=t=>({[Ht]:Wt,[Rt]:`${Kt}${t}`}),bn=(t,e,s,i)=>{const n=t;n[l]?n[l].message===Lt?i(H):i(V):s(e)},yn=()=>Wi("https://open.bigmodel.cn/api/paas/v4/models",Jt,bn);class wn extends Oi{constructor(t){var e,s,i;const n=F(t.directConnection),o=n.bigModel;super(t,yn(),gn,o),this.insertKeyPlaceholderText=this.genereteAPIKeyName("BigModel"),this.keyHelpUrl="https://open.bigmodel.cn/usercenter/apikeys",this.url="https://open.bigmodel.cn/api/paas/v4/audio/speech",this.permittedErrorPrefixes=[Rt,Nt];const r=null==(e=n.bigModel)?void 0:e.textToSpeech;typeof r===Gt&&(this.cleanConfig(r),Object.assign(this.rawBody,r)),(s=this.rawBody).model??(s.model="cogtts"),(i=this.rawBody).voice??(i.voice="tongtong")}cleanConfig(t){delete t.key}preprocessBody(t,e){const s=F(t),i=e[e.length-1];return s.input=(null==i?void 0:i[r])||"",s}async callServiceAPI(t,e){return this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){const e=new Blob([t],{[w]:"audio/mpeg"}),s=URL.createObjectURL(e);return{[k]:[{[y]:s,[w]:T}]}}}const xn=t=>({[Ht]:Wt,[Rt]:`${Kt}${t}`}),kn=(t,e,s,i)=>{const n=t;n[l]?n[l].message===Lt?i(H):i(V):s(e)},_n=()=>Wi("https://api.together.xyz/v1/models",Jt,kn);class Mn extends Oi{constructor(t){var e,s,i;const n=F(t.directConnection),o=n.together;super(t,_n(),xn,o),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Together AI"),this.keyHelpUrl="https://api.together.xyz/settings/api-keys",this.url="https://api.together.xyz/v1/audio/speech",this.permittedErrorPrefixes=[Ut,Nt];const r=null==(e=n.together)?void 0:e.textToSpeech;typeof r===Gt&&this.completeConfig(r),(s=this.rawBody).model??(s.model="cartesia/sonic"),(i=this.rawBody).voice??(i.voice="laidback woman")}preprocessBody(t,e){const s=F(t),i=e[e.length-1];return s.input=(null==i?void 0:i[r])||"",s}async callServiceAPI(t,e){return this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){const e=new Blob([t],{[w]:"audio/mpeg"}),s=URL.createObjectURL(e);return{[k]:[{[y]:s,[w]:T}]}}}const Cn="https://api.openai.com/v1/",An="https://platform.openai.com/account/api-keys",Tn="input_text",Sn="input_image",jn="output_text",En="image_generation_call",In="function_call_output",$n="response",On=t=>({[Rt]:`${Kt}${t}`,[Ht]:Wt}),Pn=(t,e,s,i)=>{const n=t;n[l]?"invalid_api_key"===n[l].code?i(H):i(V):s(e)},Bn=()=>Wi(`${Cn}models`,Jt,Pn),Rn=async(t,e,s,i=!0)=>{const{connectSettings:n,deepChat:o,completionsHandlers:r,messages:a}=t;n.method=s;const c={body:e,headers:n.headers},{body:h,headers:u,error:d}=await fi.processRequestInterceptor(o,c),{onFinish:p}=r;if(d&&a)return fi.onInterceptorError(a,d,p);const m=await fi.fetch(t,u,i,h).then(t=>fi.processResponseByType(t));if(m[l])throw m[l].message;return m},Fn=class t{static async storeFiles(t,e,s,i){const n=t.connectSettings.headers;if(!n)return;t.url=i;const o=n[Ht];delete n[Ht];const r=s.map(async e=>{const s=new FormData;return s.append("purpose","assistants"),s.append("file",e),new Promise(e=>{e(Rn(t,s,Xt,!1))})});try{const t=(await Promise.all(r)).map(t=>({id:t.id,name:t.filename}));return n[Ht]=o,t}catch(s){throw n[Ht]=o,fi.displayError(e,s),t.completionsHandlers.onFinish(),s}}static getType(t,e){const{path:s}=t[e];return!s||s.endsWith("png")?_:E}static async getFiles(e,s,i,n){const o=s.map(({fileId:t})=>(e.url=`${i}${t}${n}`,new Promise(t=>{t(Rn(e,void 0,"GET",!1))}))),r=(await Promise.all(o)).map((e,i)=>new Promise(n=>{const o=new FileReader;o.readAsDataURL(e),o.onload=e=>{n({[y]:e.target.result,name:s[i].name,[w]:t.getType(s,i)})}}));return await Promise.all(r)}static getFileName(t){const e=t.split("/");return e[e.length-1]}static async getFilesAndNewText(e,s,i,n,o){var a,l;let c;const{getFilesPrefix:h,getFilesPostfix:u}=i;return s.length>0&&(c=await t.getFiles(e,s,h,u),null!=(a=null==o?void 0:o[r])&&a.value&&c.forEach((t,e)=>{var i;if(!t[y])return;const n=s[e].path;null!=(i=null==o?void 0:o[r])&&i.value&&n&&(o[r].value=o[r].value.replace(n,t[y]))})),null!=(l=null==o?void 0:o[r])&&l.value?{[r]:o[r].value,[P]:n}:{[k]:c,[P]:n}}static getFileDetails(e,s){var i;const n=[];return null!=(i=null==s?void 0:s[r])&&i.value&&e.content.forEach(e=>{var s,i;null==(i=null==(s=e[r])?void 0:s.annotations)||i.forEach(e=>{var s;e[r]&&e[r].startsWith("sandbox:")&&null!=(s=e.file_path)&&s.file_id&&n.push({path:e[r],fileId:e.file_path.file_id,name:t.getFileName(e[r])})})}),null!=s&&s.image_file&&n.push({fileId:s.image_file.file_id}),n}static async getFilesAndText(e,s,i,n){const o=t.getFileDetails(s,n);return await t.getFilesAndNewText(e,o,i,s.role,n)}static parseResult(t,e){let s=[];if(e)s=t.data;else for(let e=0;e<t.data.length;e+=1){const i=t.data[e];if(i.role!==d)break;s.push(i)}return s.reverse()}static parseMessages(e,s,i){const n=[];return s.forEach(async s=>{s.content.filter(t=>!!t[r]||!!t.image_file).sort(t=>t[r]?-1:t.image_file?1:0).forEach(async o=>{n.push(t.getFilesAndText(e,s,i,o))})}),Promise.all(n)}static async processStreamMessages(e,s,i){return t.parseMessages(e,[{content:s,role:d}],i)}static async processAPIMessages(e,s,i,n){const o=t.parseResult(s,i);return t.parseMessages(e,o,n)}};Fn.FILES_WITH_TEXT_ERROR="content with type `text` must have `text` values",Fn.FUNCTION_TOOL_RESP_ERROR=`Response must contain an array of strings for each individual function/tool_call, see ${c}directConnection/OpenAI/#assistant-functions.`;let Ln=Fn;const qn=class t extends Oi{constructor(t,e,s,i,n,o){if(super(t,i,n,o),this.insertKeyPlaceholderText=this.genereteAPIKeyName("OpenAI"),this.keyHelpUrl=An,this.url="",this.permittedErrorPrefixes=[Dt,"Please send text",Ei.FAILED_ERROR_MESSAGE],this.shouldFetchHistory=!1,this._searchedForThreadId=!1,this._config={},this._newAssistantDetails={model:"gpt-4"},this._waitingForStreamResponse=!1,this._isSSEStream=!1,this.urlSegments=s,"object"==typeof e){this._config=e;const{new_assistant:t,thread_id:s,load_thread_history:i}=this._config;Object.assign(this._newAssistantDetails,t),s&&(this.sessionId=s),i&&(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[{[l]:tt}]}}static processImageMessage(t,e){const s=null==e?void 0:e.filter(t=>Ys.isImageFileExtension(t.name)).map(t=>({[w]:"image_file",image_file:{file_id:t.id}}));if(s&&s.length>0)return t[r]&&t[r].length>0&&s.push({[w]:r,[r]:t[r]}),{content:s,[P]:u}}static processAttachmentsMessage(t,e,s){return{attachments:e.map(t=>({tools:[{[w]:s}],file_id:t.id})),content:[{[w]:r,[r]:t[r]}],[P]:u}}processMessage(e,s){const i=this.totalMessagesMaxCharLength||-1,n=Si.getCharacterLimitMessages(e,i)[0];if(s&&s.length>0){let e=this.filesToolType;if("function"==typeof this.filesToolType){const t=this.filesToolType(s.map(({name:t})=>t));"code_interpreter"===t||"file_search"===t||t===M?e=t:(console[l](`Tool type "${t}" is not valid`),console[l]('Expected "code_interpreter" or "file_search" or "images". Going to default to "images"'))}if("file_search"===e)return t.processAttachmentsMessage(n,s,"file_search");if("code_interpreter"===e)return t.processAttachmentsMessage(n,s,"code_interpreter");if(s.find(({name:t})=>!Ys.isImageFileExtension(t)))console[l]("The uploaded files contained a non-image file"),console[l]('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,s);if(e)return e}}return{content:n[r]||"",[P]:u}}createNewThreadMessages(t,e,s){const i=F(t),n=this.processMessage(e,s);return i.thread={messages:[n]},i}callService(t,e,s){if(this.messages=t,this.sessionId){this.url=`${this.urlSegments.threadsPrefix}/${this.sessionId}/messages${this.urlSegments.createMessagePostfix}`;const i=this.processMessage(e,s);Ti.request(this,i,t)}else{this.url=`${this.urlSegments.threadsPrefix}/runs${this.urlSegments.threadsPosfix}`;const i=this.createNewThreadMessages(this.rawBody,e,s);this._isSSEStream?this.createStreamRun(i):Ti.request(this,i,t)}}async callServiceAPI(t,e,s){var i;if(this._waitingForStreamResponse=!1,!this.connectSettings)throw new Error(W);(i=this.rawBody).assistant_id??(i.assistant_id=this._config.assistant_id||await this.createNewAssistant()),this._searchedForThreadId||this.searchPreviousMessagesForThreadId(t.messageToElements);const n=s?await Ln.storeFiles(this,t,s,this.urlSegments.storeFiles):void 0;this.connectSettings.method=Xt,this.callService(t,e,n)}async createNewAssistant(){try{this.url=this.urlSegments.newAssistantUrl;const t=await Rn(this,F(this._newAssistantDetails),Xt);return this._config.assistant_id=t.id,this._config.assistant_id}catch(t){console[l](t),console[l]("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[l])throw t[l].message.startsWith(Ln.FILES_WITH_TEXT_ERROR)?Error("Please send text with your file(s)"):t[l].message;this.asyncCallInProgress=!0,await this.assignThreadAndRun(t);const s=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs/${this.run_id}${this.urlSegments.threadsPosfix}`,i={method:Jt,headers:null==(e=this.connectSettings)?void 0:e.headers};return Ti.executePollRequest(this,s,i,this.messages),{[r]:""}}async assignThreadAndRun(t){if(this.sessionId){this.url=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs${this.urlSegments.threadsPosfix}`;const t=await Rn(this,F(this.rawBody),Xt);this.run_id=t.id}else this.sessionId=t.thread_id,this.run_id=t.id,this.updateSessionId(this.sessionId)}async getThreadMessages(t,e=!1){var s,i;this.url=`${this.urlSegments.threadsPrefix}/${t}/messages?${this.urlSegments.listMessagesPostfix}`;let n=await Rn(this,{},Jt);return!e&&this.deepChat.responseInterceptor&&(n=await(null==(i=(s=this.deepChat).responseInterceptor)?void 0:i.call(s,n))),Ln.processAPIMessages(this,n,e,this.urlSegments)}async extractPollResultData(e){var s;const{status:i,required_action:n}=e;if("queued"===i||"in_progress"===i)return{timeoutMS:t.POLLING_TIMEOUT_MS};if(i===Zt&&this.messages){const t=await this.getThreadMessages(e.thread_id),{text:s,files:i}=t.shift();return setTimeout(()=>{t.forEach(t=>this.deepChat.addMessage(t))}),{text:s,_sessionId:this.sessionId,[k]:i}}const o=null==(s=null==n?void 0:n.submit_tool_outputs)?void 0:s.tool_calls;if("requires_action"===i&&o)return await this.handleTools(o);throw Error(`Thread run status: ${i}`)}async handleTools(e){if(!this._functionHandlerI)throw Error(Q);const s=e.map(t=>({name:t.function.name,arguments:t.function.arguments})),i=await this._functionHandlerI(s);if(!Array.isArray(i)||e.length!==i.length)throw Error(Ln.FUNCTION_TOOL_RESP_ERROR);const n=await Promise.all(i);if(n.find(t=>typeof t!==B))throw Error(Ln.FUNCTION_TOOL_RESP_ERROR);const o=n.map((t,s)=>({tool_call_id:e[s].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 Rn(this,{tool_outputs:o},Xt),{timeoutMS:t.POLLING_TIMEOUT_MS}}async handleStream(t){var e,s;const i=null==(s=null==(e=t.required_action)?void 0:e.submit_tool_outputs)?void 0:s.tool_calls;if("requires_action"===t.status&&i)return this.run_id=t.id,await this.handleTools(i);if(this._waitingForStreamResponse)return this.parseStreamResult(t);if(this._isSSEStream&&this.sessionId){this.asyncCallInProgress=!0,this.url=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs${this.urlSegments.threadsPosfix}`;const t=F(this.rawBody);this.createStreamRun(t)}return{[r]:""}}async parseStreamResult(t){var e,s,i,n,o;if(t.content&&t.content.length>0&&this.messages){const i=t.content.find(t=>t[r]);if(null!=(e=null==i?void 0:i[r])&&e.annotations&&i[r].annotations.length>0){const e=t.content.find(t=>!!t[r])||t.content[0],i=Ln.getFilesAndText.bind(this,this,{[P]:d,content:t.content},this.urlSegments,e);return null==(s=this._messageStream)||s.endStreamAfterFileDownloaded(this.messages,i),{[r]:""}}}if(null!=(i=t.delta)&&i.content){if(t.delta.content.length>1){const e=t.delta.content.find(t=>t[r]);if(null!=(n=null==e?void 0:e[r])&&n.annotations&&0===e[r].annotations.length){const e=await Ln.processStreamMessages(this,t.delta.content,this.urlSegments);return{[r]:e[0][r],[k]:e[1][k]}}}return{[r]:null==(o=t.delta.content[0][r])?void 0:o.value}}return!this.sessionId&&t.thread_id&&(this.sessionId=t.thread_id),{[r]:""}}async createStreamRun(t){t.stream=!0,this._waitingForStreamResponse=!0,this._messageStream=await ki.request(this,t,this.messages,!0,!0)}};qn.POLLING_TIMEOUT_MS=500;let zn=qn;class Dn extends zn{constructor(t){var e,s,i,n,o;const r=F(t.directConnection),a=r.openAI,l=null==(e=r.openAI)?void 0:e.assistant;if(super(t,l,Dn.buildUrlSegments(l),Bn(),On,a),(s=this.connectSettings).headers??(s.headers={}),(i=this.connectSettings.headers)["OpenAI-Beta"]??(i["OpenAI-Beta"]="assistants=v2"),this.shouldFetchHistory&&this.sessionId&&(this.fetchHistory=this.fetchHistoryFunc.bind(this)),typeof l===Gt){const{function_handler:e,files_tool_type:s}=null==(o=null==(n=t.directConnection)?void 0:n.openAI)?void 0:o.assistant;e&&(this._functionHandlerI=e),s&&(this.filesToolType=s)}}static buildUrlSegments(t){const e="object"==typeof t&&t.custom_base_url||Cn;return{threadsPrefix:`${e}/threads`,threadsPosfix:"",newAssistantUrl:`${e}/assistants`,createMessagePostfix:"",listMessagesPostfix:"order=desc",storeFiles:`${e}/${k}`,getFilesPrefix:`${e}/${k}/`,getFilesPostfix:"/content"}}}const Nn=`Please define the Azure URL Details. [More Information](${c}directConnection/Azure)`,Un=t=>({"api-key":t,[Ht]:Wt}),Hn=t=>Wi(`${t.endpoint}/openai/models?api-version=${t.version}`,Jt,Pn),Vn=t=>{const{endpoint:e,version:s,deploymentId:i}=t;return e&&s&&i},Wn=class t extends zn{constructor(e){var s,i,n,o,r,a,c,h;const u=F(e.directConnection),d=u.azure,p=null==(s=u.azure)?void 0:s.openAI,m=(null==p?void 0:p.urlDetails)||{},v=`${null==(i=null==p?void 0:p.urlDetails)?void 0:i.endpoint}/openai/`,f=`?api-version=${null==(n=null==p?void 0:p.urlDetails)?void 0:n.version}`,g={threadsPrefix:`${v}${t.THREAD_RESOURCE}`,threadsPosfix:f,newAssistantUrl:`${v}${t.NEW_ASSISTANT_RESOURCE}${f}`,createMessagePostfix:f,listMessagesPostfix:`order=desc&api-version=${null==(o=null==p?void 0:p.urlDetails)?void 0:o.version}`,storeFiles:`${v}${k}${f}`,getFilesPrefix:`${v}${k}/`,getFilesPostfix:`/content${f}`};if(super(e,null==p?void 0:p.assistant,g,Hn(m),Un,d),this.permittedErrorPrefixes=[Nn],this.insertKeyPlaceholderText=this.genereteAPIKeyName("Azure OpenAI"),this.keyHelpUrl="https://learn.microsoft.com/en-us/answers/questions/1193991/how-to-get-the-value-of-openai-api-key",this.isTextInputDisabled=!1,typeof(null==p?void 0:p.assistant)===Gt){const{function_handler:t,files_tool_type:s}=null==(c=null==(a=null==(r=e.directConnection)?void 0:r.azure)?void 0:a.openAI)?void 0:c.assistant;t&&(this._functionHandlerI=t),s&&(this.filesToolType=s)}Vn(m)?(h=this.connectSettings).headers??(h.headers={}):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout(()=>{e.addMessage({[l]:Nn})}))}};Wn.THREAD_RESOURCE="threads",Wn.NEW_ASSISTANT_RESOURCE="assistants";let Gn=Wn;class Zn{static addAttributes(t){t[P]="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-${ht}`,"true")}static removeAriaDisabled(t){t.removeAttribute(`aria-${ht}`)}static removeAriaAttributes(t){Zn.removeAriaBusy(t),Zn.removeAriaDisabled(t)}}const Kn='<?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',Jn=class e{static createTextElement(i){const n=s();return n[t].add(e.INPUT_BUTTON_INNER_TEXT_CLASS),n.innerText=i,n}static tryAddSVGElement(t,e,s,i){s?t.push(Fi.createSVGElement(s)):""!==s&&i&&t.push(e)}static createCustomElements(t,s,i){var n,o;const a=null==i?void 0:i[t],l=null==(n=null==a?void 0:a[r])?void 0:n.content,c=null==(o=null==a?void 0:a[ut])?void 0:o.content,h=[];return e.tryAddSVGElement(h,s,c,l),l&&h.push(e.createTextElement(l)),h.length>0?h:void 0}static reassignClassBasedOnChildren(s,i){s[t].remove(e.INPUT_BUTTON_SVG_CLASS,e.INPUT_BUTTON_SVG_TEXT_CLASS),i.find(s=>s[t].contains(e.INPUT_BUTTON_INNER_TEXT_CLASS))?i.length>1&&s[t].add(e.INPUT_BUTTON_SVG_TEXT_CLASS):s[t].add(e.INPUT_BUTTON_SVG_CLASS)}};Jn.INPUT_BUTTON_SVG_TEXT_CLASS="input-button-svg-text",Jn.INPUT_BUTTON_INNER_TEXT_CLASS="text-button",Jn.INPUT_BUTTON_SVG_CLASS="input-button-svg";let Xn=Jn;class Qn{static parseSVGTextElements(t){return{[ut]:t.find(t=>t.tagName.toLowerCase()===ut),[r]:t.find(t=>"div"===t.tagName.toLowerCase())}}}class Yn{static unsetAllCSS(t,e){var s,i;e.container&&yt.unsetAllCSSMouseStates(t,e.container);const{svg:n,text:o}=Qn.parseSVGTextElements(Array.from(t.children));null!=(s=e[ut])&&s[pt]&&n&&yt.unsetAllCSSMouseStates(n,e[ut][pt]),null!=(i=e[r])&&i[pt]&&o&&yt.unsetAllCSSMouseStates(o,e[r][pt])}static unsetActionCSS(t,e){var s,i;e.container&&yt.unsetActivityCSSMouseStates(t,e.container);const{svg:n,text:o}=Qn.parseSVGTextElements(Array.from(t.children));null!=(s=e[ut])&&s[pt]&&n&&yt.unsetActivityCSSMouseStates(n,e[ut][pt]),null!=(i=e[r])&&i[pt]&&o&&yt.unsetActivityCSSMouseStates(o,e[r][pt])}static setElementsCSS(t,s,i){var n,o,a,l,c;Object.assign(t[e],null==(n=s.container)?void 0:n[i]);const{svg:h,text:u}=Qn.parseSVGTextElements(Array.from(t.children));h&&Object.assign(h[e],null==(a=null==(o=s[ut])?void 0:o[pt])?void 0:a[i]),u&&Object.assign(u[e],null==(c=null==(l=s[r])?void 0:l[pt])?void 0:c[i])}static setElementCssUpToState(t,e,s){Yn.setElementsCSS(t,e,rt),s!==rt&&(Yn.setElementsCSS(t,e,at),s!==at&&Yn.setElementsCSS(t,e,lt))}}class to{constructor(t,e,s,i,n,o){this._mouseState={state:"default"},this.isCustom=!1,Zn.addAttributes(t),this.elementRef=t,this[ut]=Fi.createSVGElement(e),this.customStyles=n,this.position=ce.processPosition(s),this._tooltipSettings=i,this.dropupText=o}buttonMouseLeave(t){var s;this._mouseState.state=rt,"visible"===(null==(s=this._activeTooltip)?void 0:s.element[e].visibility)&&this._tooltipSettings&&Ct.hide(this._activeTooltip,this._tooltipSettings),t&&(Yn.unsetAllCSS(this.elementRef,t),Yn.setElementsCSS(this.elementRef,t,rt))}buttonMouseEnter(t){var e;this._mouseState.state=at,this._tooltipSettings&&(this._activeTooltip=Ct.display(this.elementRef,this._tooltipSettings,null==(e=this._activeTooltip)?void 0:e.element)),t&&Yn.setElementsCSS(this.elementRef,t,at)}buttonMouseUp(t){t&&Yn.unsetActionCSS(this.elementRef,t),this.buttonMouseEnter(t)}buttonMouseDown(t){this._mouseState.state=lt,t&&Yn.setElementsCSS(this.elementRef,t,lt)}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 s=t[e],i=s&&this.customStyles[s];i&&Yn.unsetActionCSS(this.elementRef,i)}}reapplyStateStyle(t,e){if(!this.customStyles)return;e&&this.unsetCustomStateStyles(e);const s=this.customStyles[t];s&&Yn.setElementCssUpToState(this.elementRef,s,this._mouseState.state),this.setEvents(s)}changeElementsByState(t){this.elementRef.replaceChildren(...t),Xn.reassignClassBasedOnChildren(this.elementRef,t)}buildDefaultIconElement(t){const e=this[ut].cloneNode(!0);return e.id=t,[e]}createInnerElements(t,e,s){const i=Xn.createCustomElements(e,this[ut],s);if(i&&i.length>0){if(this.position===ot){const e=i[0].cloneNode(!0);e.id=i[0]===this[ut]?t:"dropup-menu-item-icon-element-custom",i[0]=e}return i}return this.buildDefaultIconElement(t)}}const eo=class e extends to{constructor(t){var i,n;const o=(null==(n=null==(i=null==t?void 0:t[rt])?void 0:i[ut])?void 0:n.content)||e.EMPTY_SVG;super(s(),o,void 0,void 0,t),this.isActive=!1,this._innerElements=this.createInnerElementsForStates(this.customStyles),this.changeToDefault()}createInnerElementsForStates(t){return{[rt]:this.createInnerButtonElements(rt,t),[ct]:this.createInnerButtonElements(ct,t),[dt]:this.createInnerButtonElements(dt,t)}}createInnerButtonElements(t,e){return Xn.createCustomElements(t,this[ut],e)||[this[ut]]}changeState(e){this.changeElementsByState(e),this.elementRef[t].replace(Xn.INPUT_BUTTON_SVG_CLASS,"deep-chat-openai-realtime-button")}changeToActive(){this.changeState(this._innerElements[ct]),this.reapplyStateStyle(ct,[dt,rt]),this.isActive=!0}changeToDefault(){var t,e,s,i;this.changeState(this._innerElements[rt]),null!=(t=this.customStyles)&&t[ct]&&Yn.unsetAllCSS(this.elementRef,null==(e=this.customStyles)?void 0:e[ct]),null!=(s=this.customStyles)&&s[dt]&&Yn.unsetAllCSS(this.elementRef,null==(i=this.customStyles)?void 0:i[dt]),this.reapplyStateStyle(rt,[ct,dt]),this.isActive=!1}changeToUnavailable(){var t,e,s,i;this.changeState(this._innerElements[dt]),null!=(t=this.customStyles)&&t[ct]&&Yn.unsetAllCSS(this.elementRef,null==(e=this.customStyles)?void 0:e[ct]),null!=(s=this.customStyles)&&s[rt]&&Yn.unsetAllCSS(this.elementRef,null==(i=this.customStyles)?void 0:i[rt]),this.reapplyStateStyle(dt,[rt,ct]),this.isActive=!1}};eo.EMPTY_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"></svg>';let so=eo;class io{static setPropertyValueIfDoesNotExist(t,e,s){const i=e[0];1===e.length?t[i]??(t[i]=s):(t[i]??(t[i]={}),e.shift(),io.setPropertyValueIfDoesNotExist(t[i],e,s))}static setPropertyValue(t,e,s){const i=e[0];1===e.length?t[i]=s:(t[i]??(t[i]={}),e.shift(),io.setPropertyValue(t[i],e,s))}static getObjectValue(t,e){const s=t[e[0]];return void 0===s||1===e.length?s:io.getObjectValue(s,e.slice(1))}static overwritePropertyObjectFromAnother(t,e,s){const i=io.getObjectValue(e,s);if(i){const e={...i,...io.getObjectValue(t,s)||{}};io.setPropertyValue(t,s,e)}}static isJson(t){try{return R(t),!0}catch{return!1}}static assignPropertyFromOneToAnother(t,e,s){e[t]??(e[t]={}),Object.assign(e[t],null==s?void 0:s[t])}}const no='<?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="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>',oo='<?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="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>',ro=class i extends Oi{constructor(t){var e,s,n,o,r;const a=F(t.directConnection),c=i.getKey(t);super(t,Bn(),On,{key:c}),this.insertKeyPlaceholderText=this.genereteAPIKeyName("OpenAI"),this.keyHelpUrl=An,this._microphoneButton=null,this._toggleButton=null,this._errorElement=null,this._loadingElement=null,this._pc=null,this._mediaStream=null,this._isMuted=!1;const h=null==(e=a.openAI)?void 0:e.realtime;if(typeof h===Gt){this._avatarConfig=h.avatar,this._ephemeralKey=h.ephemeralKey,this._errorConfig=h[l],this._loadingConfig=h.loading,Object.assign(this.rawBody,h.config);const e=null==(n=null==(s=t.directConnection)?void 0:s.openAI)?void 0:n.realtime,{function_handler:i}=e.config||{};i&&(this._functionHandlerI=i),this._events=h.events,e.methods=this.generateMethods(),this.setInputAudioTranscribe(t,null==(o=e.config)?void 0:o.input_audio_transcription)}(r=this.rawBody).model??(r.model="gpt-4o-realtime-preview-2025-06-03"),this._avatarConfig=i.buildAvatarConfig(h),this._buttonsConfig=i.buildButtonsConfig(h),this._avatarEl=i.createAvatar(this._avatarConfig),this._containerEl=this.createContainer(),this._deepChat=t}static getKey(t){const e=t.directConnection.openAI;if(null!=e&&e.key)return e.key;const s=null==e?void 0:e.realtime;return"object"==typeof s&&(s.ephemeralKey||s.fetchEphemeralKey)?"placeholder":void 0}setInputAudioTranscribe(t,e){if(e){const t="whisper-1";this.rawBody.input_audio_transcription="object"==typeof e?{model:e.model||t,language:e.language,prompt:e.prompt}:{model:t}}else t.onMessage&&(console.warn("To get user audio transcription, set `input_audio_transcription` in the `realtime` config."),console.warn(`See: ${c}directConnection/OpenAI/OpenAIRealtime#OpenAIRealtimeConfig`))}setUpView(t,s){t[e].display="none",s.appendChild(this._containerEl),this.setup()}async setup(){var t;const e=null==(t=this._deepChat.directConnection)?void 0:t.openAI;if(!e)return;const s=null==e?void 0:e.realtime;if("object"!=typeof s||!s.autoStart&&!s.autoFetchEphemeralKey)return;const i=this.key||e.key;(s.fetchEphemeralKey||i)&&s.autoStart&&(this.changeToUnavailable(),this.displayLoading()),this.fetchEphemeralKey(s.autoStart)}async fetchEphemeralKey(t){var e;const s=null==(e=this._deepChat.directConnection)?void 0:e.openAI,i="object"==typeof(null==s?void 0:s.realtime)?null==s?void 0:s.realtime.fetchEphemeralKey:void 0,n=null==s?void 0:s.realtime,o=this.key||s.key;if("object"==typeof n){if(!this._ephemeralKey)try{if(i){const t=i();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(`${Cn}realtime/sessions`,{method:Xt,body:R(this.rawBody),headers:{[Ht]:Wt,[Rt]:`${Kt}${t}`}})).json()).client_secret.value}generateMethods(){return{updateConfig:t=>{var e;null==(e=this._dc)||e.send(R({[w]:"session.update",session:t}))},sendMessage:(t,e)=>{const s=e||se,i=[{[w]:s===se||s===u?Tn:r,text:t}],n={[P]:s,[w]:"message",content:i};this.sendMessage(n)}}}static buildAvatarConfig(t){const e="object"==typeof t&&t.avatar?F(t.avatar):{};return e.maxScale=e.maxScale&&e.maxScale>=1?e.maxScale:2.5,e}static buildButtonsConfig(t){var e,s,i,n,o,a,l,c,h,u,d,p,m,v,f;const g="object"==typeof t&&t.buttons?F(t.buttons):{};return null!=(i=null==(s=null==(e=g[S])?void 0:e[rt])?void 0:s[r])&&i.content||(g[S]??(g[S]={}),(n=g[S])[rt]??(n[rt]={}),(o=g[S][rt])[ut]??(o[ut]={}),(a=g[S][rt][ut]).content??(a.content=Kn)),null!=(h=null==(c=null==(l=g.toggle)?void 0:l[rt])?void 0:c[r])&&h.content||(g.toggle??(g.toggle={}),(u=g.toggle)[rt]??(u[rt]={}),(d=g.toggle[rt])[ut]??(d[ut]={}),(p=g.toggle[rt][ut]).content??(p.content=no),(m=g.toggle)[ct]??(m[ct]={}),(v=g.toggle[ct])[ut]??(v[ut]={}),(f=g.toggle[ct][ut]).content??(f.content=oo)),g}createContainer(){const t=s();return t.id="deep-chat-openai-realtime-container",t.appendChild(this.createAvatarContainer()),t.appendChild(this.createButtonsContainer()),t.appendChild(this.createError()),t}createAvatarContainer(){var t,i;const n=s();return n.id="deep-chat-openai-realtime-avatar-container",Object.assign(n[e],null==(i=null==(t=this._avatarConfig)?void 0:t[pt])?void 0:i.container),n.appendChild(this._avatarEl),n}static createAvatar(t){var i;const n=s("img");return n.id="deep-chat-openai-realtime-avatar",Object.assign(n[e],null==(i=null==t?void 0:t[pt])?void 0:i[_]),n[y]=(null==t?void 0:t[y])||ai,n}createButtonsContainer(){var t;const n=s();n.id="deep-chat-openai-realtime-buttons-container",Object.assign(n[e],null==(t=this._buttonsConfig)?void 0:t.container),this._microphoneButton=this.createMicophoneButton();const o=i.createButtonContainer(this._microphoneButton.elementRef);this._toggleButton=this.createToggleButton();const r=i.createButtonContainer(this._toggleButton.elementRef);return n.appendChild(o),n.appendChild(r),n.appendChild(this.createLoading()),n}static createButtonContainer(e){const i=s();return i[t].add("deep-chat-openai-realtime-button-container"),i.appendChild(e),i}createMicophoneButton(){var e;const s=new so(null==(e=this._buttonsConfig)?void 0:e[S]);return s.elementRef[t].add(i.BUTTON_DEFAULT,"deep-chat-openai-realtime-microphone"),ne.assignButtonEvents(s.elementRef,()=>{s.isActive?(this.toggleMicorphone(!0),s.elementRef[t].replace(i.MICROPHONE_ACTIVE,i.BUTTON_DEFAULT),s.changeToDefault(),this._isMuted=!1):(this.toggleMicorphone(!1),s.elementRef[t].replace(i.BUTTON_DEFAULT,i.MICROPHONE_ACTIVE),Zn.removeAriaAttributes(s.elementRef),s.changeToActive(),this._isMuted=!0)}),s}toggleMicorphone(t){var e;null==(e=this._mediaStream)||e.getAudioTracks().forEach(e=>e.enabled=t)}createToggleButton(){var e;const s=new so(null==(e=this._buttonsConfig)?void 0:e.toggle);return s.elementRef[t].add(i.BUTTON_DEFAULT,"deep-chat-openai-realtime-toggle"),ne.assignButtonEvents(s.elementRef,async()=>{var t;if(s.isActive)s.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[l]("Failed to start conversation:",t),this.displayError(),this.hideLoading()}}),s}async init(t){const e=new RTCPeerConnection;this._pc=e;const i=s(T);i.autoplay=!0;const n=new AudioContext,o=n.createAnalyser();o.fftSize=256;const a=new Uint8Array(o.frequencyBinCount);this._pc.ontrack=async t=>{if(t.streams[0]){i.srcObject=t.streams[0];const e=n.createMediaStreamSource(t.streams[0]);"suspended"===n.state&&await n.resume(),e.connect(o),this.monitorFrequencies(o,a)}else console[l]("No streams found in the ontrack event."),this.displayError()},await navigator.mediaDevices.getUserMedia({audio:!0}).then(t=>{var s;e===this._pc&&(this._mediaStream=t,null==(s=this._pc)||s.addTrack(this._mediaStream.getTracks()[0]),this._isMuted&&this.toggleMicorphone(!1))}).catch(t=>{console[l]("Error accessing microphone:",t),this.displayError()}),this._dc=this._pc.createDataChannel("oai-events"),this._dc.addEventListener("message",async t=>{var e,s,i;const n=JSON.parse(t.data);if("session.created"===n[w])this.removeUnavailable(),this._toggleButton&&(Zn.removeAriaAttributes(this._toggleButton.elementRef),this._toggleButton.changeToActive()),null==(s=null==(e=this._events)?void 0:e.started)||s.call(e),this._deepChat.dispatchEvent(new CustomEvent("sts-session-started")),this.hideLoading();else if("response.done"===n[w]){const e=null==(i=JSON.parse(t.data).response.output)?void 0:i[0];if((null==e?void 0:e[w])===Yt){const{name:t,call_id:s}=e;try{await this.handleTool(t,e.arguments,s)}catch(t){this.stopOnError(t)}}}else n[w]===l?this.stopOnError(n[l].message):n[w]===Ut?this.stopOnError(n.message):"response.audio_transcript.delta"===n[w]||("response.audio_transcript.done"===n[w]?n.transcript&&ti.onMessage(this._deepChat,{[P]:h,[r]:n.transcript},!1):"conversation.item.input_audio_transcription.completed"===n[w]&&n.transcript&&ti.onMessage(this._deepChat,{[P]:u,[r]:n.transcript},!1))});try{const s=await this._pc.createOffer();if(e!==this._pc||(await this._pc.setLocalDescription(s),e!==this._pc))return;const i=await fetch(`${Cn}realtime`,{method:Xt,body:s.sdp,headers:{[Rt]:`${Kt}${t}`,[Ht]:"application/sdp"}});if(e!==this._pc)return;const n={[w]:"answer",sdp:await i[r]()};if(e!==this._pc||(await this._pc.setRemoteDescription(n),e!==this._pc))return}catch(t){console[l](t),this.displayError()}}monitorFrequencies(t,s){const i=()=>{var n;t.getByteFrequencyData(s);const o=1+s.reduce((t,e)=>t+e,0)/(255*s.length)*100/100*((null==(n=this._avatarConfig)?void 0:n.maxScale)-1);this._avatarEl[e].transform=`scale(${o})`,requestAnimationFrame(i)};i()}stopOnError(t){this.stop(),console[l](t),this.displayError()}stop(){var t,e,s;null==(t=this._mediaStream)||t.getTracks().forEach(t=>t.stop()),this._mediaStream=null,this._pc&&(this._pc.close(),this._pc=null,null==(s=null==(e=this._events)?void 0:e.stopped)||s.call(e),this._deepChat.dispatchEvent(new CustomEvent("sts-session-stopped")),this._dc=void 0)}changeToUnavailable(){this._microphoneButton&&i.changeButtonToUnavailable(this._microphoneButton),this._toggleButton&&i.changeButtonToUnavailable(this._toggleButton)}static changeButtonToUnavailable(e){e.elementRef[t].add(i.UNAVAILABLE),Zn.removeAriaBusy(e.elementRef),Zn.addAriaDisabled(e.elementRef),e.changeToUnavailable()}changeToAvailable(){this._microphoneButton&&i.changeButtonToAvailable(this._microphoneButton),this._toggleButton&&i.changeButtonToAvailable(this._toggleButton)}static changeButtonToAvailable(t){i.removeButtonUnavailable(t),t.changeToDefault()}removeUnavailable(){this._microphoneButton&&i.removeButtonUnavailable(this._microphoneButton),this._toggleButton&&i.removeButtonUnavailable(this._toggleButton)}static removeButtonUnavailable(e){Zn.removeAriaDisabled(e.elementRef),e.elementRef[t].remove(i.UNAVAILABLE)}createError(){var t;const i=s();return i.id="deep-chat-openai-realtime-error",Object.assign(i[e],null==(t=this._errorConfig)?void 0:t[e]),this._errorElement=i,i}displayFailedToRetrieveEphemeralKey(t){console[l]("Failed to retrieve ephemeral key"),console[l](t),this.displayError()}displayError(){var t;this._errorElement&&(this._errorElement[e].display="block",this._errorElement.textContent=(null==(t=this._errorConfig)?void 0:t[r])||"Error",this.changeToUnavailable()),this.hideLoading()}createLoading(){var t,i;const n=s();return n.id="deep-chat-openai-realtime-loading",this._loadingElement=n,null!=(t=this._loadingConfig)&&t[a]&&(this._loadingElement.innerHTML=this._loadingConfig[a]),Object.assign(n[e],null==(i=this._loadingConfig)?void 0:i[e]),n[e].display="none",n}displayLoading(){var s,n,o;this._toggleButton&&(this._toggleButton.changeToActive(),this._toggleButton.elementRef[t].add(i.BUTTON_LOADING),Zn.removeAriaDisabled(this._toggleButton.elementRef),Zn.addAriaBusy(this._toggleButton.elementRef)),("boolean"!=typeof(null==(s=this._loadingConfig)?void 0:s.display)||this._loadingConfig.display)&&this._loadingElement&&(this._loadingElement[e].display="block",null!=(n=this._loadingConfig)&&n[a]||(this._loadingElement.textContent=(null==(o=this._loadingConfig)?void 0:o[r])||"Loading"))}hideLoading(){this._toggleButton&&(this._toggleButton.elementRef[t].remove(i.BUTTON_LOADING),Zn.removeAriaBusy(this._toggleButton.elementRef)),this._loadingElement&&(this._loadingElement[e].display="none")}async handleTool(t,e,s){if(!this._functionHandlerI)throw Error(Q);const i=await this._functionHandlerI({name:t,arguments:e});if("object"!=typeof i||!io.isJson(i))throw Error('The `function_handler` response must be a JSON object, e.g. {response: "My response"}');const n={[w]:In,call_id:s,output:R(i)};this.sendMessage(n)}sendMessage(t){if(!this._dc)return;const e=R({[w]:"conversation.item.create",item:t});this._dc.send(e);const s={[w]:"response.create"};this._dc.send(R(s))}isCustomView(){return!0}};ro.BUTTON_DEFAULT="deep-chat-openai-realtime-button-default",ro.BUTTON_LOADING="deep-chat-openai-realtime-button-loading",ro.MICROPHONE_ACTIVE="deep-chat-openai-realtime-microphone-active",ro.UNAVAILABLE="deep-chat-openai-realtime-button-unavailable";let ao=ro;const lo=class t extends Oi{constructor(e){var s,i,n;const o=F(e.directConnection),r=null==o?void 0:o.openAI;super(e,Bn(),On,r),this.insertKeyPlaceholderText=this.genereteAPIKeyName("OpenAI"),this.keyHelpUrl=An,this.url=`${Cn}audio/speech`,this.permittedErrorPrefixes=[zt];const a=null==(s=null==o?void 0:o.openAI)?void 0:s.textToSpeech;typeof a===Gt&&Object.assign(this.rawBody,a),(i=this.rawBody).model??(i.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 s,i;const n=F(t),o=null==(i=null==(s=e[e.length-1])?void 0:s[r])?void 0:i.trim();return o&&""!==o&&(n.input=o),n}async callServiceAPI(t,e){this.url=this.connectSettings.url||this.url,this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){if(t instanceof Blob)return new Promise(e=>{const s=new FileReader;s.readAsDataURL(t),s.onload=t=>{e({[k]:[{[y]:t.target.result,[w]:T}]})}});if(t[l])throw t[l].message;return{[l]:l}}};lo.DEFAULT_MODEL="tts-1",lo.DEFAULT_VOIDE="alloy";let co=lo;const ho=class t extends Oi{constructor(e){var s,i;const n=F(e.directConnection),o=null==n?void 0:n.openAI;super(e,Bn(),On,o,{audio:{}}),this.insertKeyPlaceholderText=this.genereteAPIKeyName("OpenAI"),this.keyHelpUrl=An,this.url="",this.permittedErrorPrefixes=[zt],this.textInputPlaceholderText=Qt,this._service_url=t.AUDIO_TRANSCRIPTIONS_URL;const r=null==(s=null==n?void 0:n.openAI)?void 0:s[T];"object"==typeof r&&(this.processConfig(r),t.cleanConfig(r),Object.assign(this.rawBody,r)),(i=this.rawBody).model??(i.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[w]&&"translation"===e[w]&&(this._service_url=t.AUDIO_TRANSLATIONS_URL,delete e.language)}static cleanConfig(t){delete t[w]}static createFormDataBody(t,e){const s=new FormData;return s.append(x,e),Object.keys(t).forEach(e=>{s.append(e,String(t[e]))}),s}preprocessBody(t,e){var s,i;const n=F(t),o=null==(i=null==(s=e[e.length-1])?void 0:s[r])?void 0:i.trim();return o&&""!==o&&(n.prompt=o),n}async callServiceAPI(e,s,i){var n;if(null==(n=this.connectSettings)||!n.headers)throw new Error(W);if(null==i||!i[0])throw new Error(G);this.url=this.connectSettings.url||this._service_url;const o=this.preprocessBody(this.rawBody,s),r=t.createFormDataBody(o,i[0]);fi.tempRemoveContentHeader(this.connectSettings,Ti.request.bind(this,this,r,e),!1)}async extractResultData(t){if(t[l])throw t[l].message;return{[r]:t[r]}}};ho.AUDIO_TRANSCRIPTIONS_URL=`${Cn}audio/transcriptions`,ho.AUDIO_TRANSLATIONS_URL=`${Cn}audio/translations`,ho.DEFAULT_MODEL="whisper-1";let uo=ho;const po="Ocp-Apim-Subscription-Key",mo="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",vo=(t,e)=>({[po]:e,[Ht]:"application/ssml+xml","X-Microsoft-OutputFormat":t}),fo=t=>({[po]:t,Accept:Wt}),go=(t,e,s,i)=>{t[l]?i(H):s(e)},bo=t=>({[po]:t,[Ht]:Wt}),yo=(t,e,s,i)=>{var n;"401"===(null==(n=t[l])?void 0:n.code)?i(H):s(e)},wo=(t,e,s,i)=>{t.json().then(t=>{Array.isArray(t)||401e3!==t[l].code?s(e):i(H)})},xo=(t,e)=>{const s={[po]:e,[Ht]:Wt};return t&&(s["Ocp-Apim-Subscription-Region"]=t),s};class ko extends Oi{constructor(t,e,s,i,n){super(t,{url:`${s}/language/analyze-text/jobs?api-version=2022-10-01-preview`,method:Xt,createHeaders:t=>({[po]:`${t}`}),handleVerificationResult:yo},e,i,n),this.insertKeyPlaceholderText="Azure Language Subscription Key",this.keyHelpUrl=mo,this.permittedErrorPrefixes=["Access"]}}const _o=class t extends ko{constructor(e){var s,i,n,o;const r=null==(i=null==(s=e.directConnection)?void 0:s.azure)?void 0:i.summarization,a=null==(n=e.directConnection)?void 0:n.azure;super(e,bo,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({[l]:t.ENDPOINT_ERROR_MESSAGE})}))}preprocessBody(t,e){const s=e[e.length-1][r];if(s)return{analysisInput:{documents:[{id:"1",language:t.language,[r]:s}]},tasks:[{kind:"ExtractiveSummarization"}]}}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this)),this.messages=t}async extractResultData(t){var e;if(t[l])throw t[l].message;if(this.messages&&this.completionsHandlers){this.asyncCallInProgress=!0;const s=t.headers.get("operation-location"),i={method:Jt,headers:null==(e=this.connectSettings)?void 0:e.headers};Ti.executePollRequest(this,s,i,this.messages)}return{[r]:""}}async extractPollResultData(t){if(t[l])throw t[l];if("running"===t.status||"notStarted"===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 s of t.tasks.items[0].results.documents[0].sentences)e+=s[r];return{[r]:e||""}}};_o.ENDPOINT_ERROR_MESSAGE=`Please define the azure endpoint. [More Information](${c}directConnection/Azure#Summarization)`;let Mo=_o;const Co=t=>({[Rt]:t,[Ht]:"application/octet-stream"}),Ao=(t,e,s,i)=>{const n=t;n[l]?"invalid_api_key"===n[l].code?i(H):i(V):s(e)};class To extends Oi{constructor(t){var e;const s=null==(e=t.directConnection)?void 0:e.assemblyAI;super(t,Wi("https://api.assemblyai.com/v2/upload",Xt,Ao),Co,s,{audio:{}}),this.insertKeyPlaceholderText=this.genereteAPIKeyName("AssemblyAI"),this.keyHelpUrl="https://www.assemblyai.com/app/account",this.url="https://api.assemblyai.com/v2/upload",this.isTextInputDisabled=!0,this.textInputPlaceholderText=Qt,this.permittedErrorPrefixes=[Bt,zt],this.canSendMessage=To.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])}async callServiceAPI(t,e,s){var i;if(null==(i=this.connectSettings)||!i.headers)throw new Error(W);if(null==s||!s[0])throw new Error(G);Ti.request(this,s[0],t,!1)}async extractResultData(t){var e,s;if(t[l])throw t[l];const i=null==(s=null==(e=this.connectSettings)?void 0:e.headers)?void 0:s[Rt],n=await(async(t,e)=>{const s={[Ft]:t,[Vt]:Wt},i=`https://api.assemblyai.com/v2/transcript/${(await(await fetch("https://api.assemblyai.com/v2/transcript",{method:Xt,body:R({audio_url:e}),headers:s})).json()).id}`;let n;for(;!n;){const t=await(await fetch(i,{headers:s})).json();if(t.status===Zt)n=t;else{if(t.status===l)throw new Error(`Transcription failed: ${t[l]}`);await new Promise(t=>setTimeout(t,3e3))}}return n})(i,t.upload_url);return{[r]:n[r]}}}class So extends Oi{constructor(t,e,s,i,n){var o,r;const a=F(t.directConnection);super(t,e||Bn(),s||On,i||a.openAI),this.insertKeyPlaceholderText=this.genereteAPIKeyName("OpenAI"),this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.permittedErrorPrefixes=[Dt,"Invalid value"];const l=n||(null==(o=a.openAI)?void 0:o.chat);typeof l===Gt&&this.processConfig(l,t),this.maxMessages??(this.maxMessages=-1),(r=this.rawBody).model??(r.model="gpt-4o")}processConfig(t,e){var s,i,n;this.completeConfig(t,null==(n=null==(i=null==(s=e.directConnection)?void 0:s.openAI)?void 0:i.chat)?void 0:n.function_handler)}static getBaseFileContent(t){return t.map(t=>{var e,s,i;if(t[w]===T){const n=null==(e=t[y])?void 0:e.split(",")[1],o=(null==(i=null==(s=t.name)?void 0:s.split(".").pop())?void 0:i.toLowerCase())||"wav";return{[w]:te,[te]:{data:n,format:o}}}return t})}static getBaseContent(t,e=!0){if(e&&t[k]&&t[k].length>0){const e=this.getBaseFileContent(t[k]);return t[r]&&t[r].trim().length>0&&e.unshift({[w]:r,[r]:t[r]}),e}return t[r]}}class jo extends So{constructor(){super(...arguments),this.url=`${Cn}chat/completions`}static getFileContent(t){return So.getBaseFileContent(t).map(t=>t[w]===te?t:{[w]:ee,[ee]:{url:t[y]}})}static getContent(t){if(t[k]&&t[k].length>0){const e=jo.getFileContent(t[k]);return t[r]&&t[r].trim().length>0&&e.unshift({[w]:r,[r]:t[r]}),e}return t[r]}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>({content:jo.getContent(t),[P]:Oi.getRoleViaUser(t[P])}));return this.addSystemMessage(i),s.messages=i,s}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){var s,i,n,o,a,c;if(t[l])throw t[l].message;if(null!=(i=null==(s=t.choices)?void 0:s[0])&&i.delta)return this.extractStreamResult(t.choices[0],e);if(null!=(o=null==(n=t.choices)?void 0:n[0])&&o.message){if(t.choices[0].message.tool_calls)return this.handleToolsGeneric(t.choices[0].message,this.functionHandler,this.messages,e);if(null!=(a=t.choices[0].message)&&a[T]){const e=this.deepChat.textToSpeech,s="object"==typeof e&&"boolean"==typeof(null==(c=null==e?void 0:e[T])?void 0:c.displayText);return{[k]:[{[y]:`data:audio/wav;base64,${t.choices[0].message[T].data}`,[w]:T}],[r]:s?t.choices[0].message[T].transcript:void 0}}return{[r]:t.choices[0].message.content}}return{[r]:""}}async extractStreamResult(t,e){return this.extractStreamResultWToolsGeneric(this,t,this.functionHandler,e)}}const Eo=class extends Oi{constructor(t,e,s,i,n){super(t,{url:`https://${s}.api.cognitive.microsoft.com/sts/v1.0/issuetoken`,method:Xt,createHeaders:t=>({[po]:`${t}`}),handleVerificationResult:go},e,i,n),this.insertKeyPlaceholderText="Azure Speech Subscription Key",this.keyHelpUrl=mo}};Eo.REGION_ERROR_PREFIX=`Please define a region config property. [More Information](${c}directConnection/Azure#`;let Io=Eo;const $o=class t extends Io{constructor(e){var s,i,n,o,r,a;const c=null==(i=null==(s=e.directConnection)?void 0:s.azure)?void 0:i.textToSpeech,h=null==(n=e.directConnection)?void 0:n.azure;super(e,vo.bind({},(null==c?void 0:c.outputFormat)||"audio-16khz-128kbitrate-mono-mp3"),c.region,h),this.permittedErrorPrefixes=[t.REGION_ERROR_MESSAGE],this.isTextInputDisabled=!1,this.url="",c.region?(Object.assign(this.rawBody,c),(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://${c.region}.tts.speech.microsoft.com/cognitiveservices/v1`):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout(()=>{e.addMessage({[l]:t.REGION_ERROR_MESSAGE})}))}preprocessBody(t,e){const s=e[e.length-1][r];if(s)return`<speak version='1.0' xml:lang='${t.lang}'>\n <voice xml:lang='${t.lang}' xml:gender='${t.gender}' name='${t.name}'>\n ${s}\n </voice>\n </speak>`}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),void 0,!1)}async extractResultData(t){return new Promise(e=>{const s=new FileReader;s.readAsDataURL(t),s.onload=t=>{e({[k]:[{[y]:t.target.result,[w]:T}]})}})}};$o.REGION_ERROR_MESSAGE=`${Io.REGION_ERROR_PREFIX}TextToSpeech)`;let Oo=$o;const Po=class t extends Io{constructor(e){var s,i,n;const o=null==(i=null==(s=e.directConnection)?void 0:s.azure)?void 0:i.speechToText,r=null==(n=e.directConnection)?void 0:n.azure,a={audio:{[k]:{acceptedFormats:".wav,.ogg"}}};if(super(e,fo,o.region,r,a),this.permittedErrorPrefixes=[t.REGION_ERROR_MESSAGE],this.url="",this.isTextInputDisabled=!0,this.textInputPlaceholderText=Qt,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({[l]:t.REGION_ERROR_MESSAGE})})}static canFileSendMessage(t,e){return!(null==e||!e[0])}async callServiceAPI(t,e,s){var i,n;if(null==(i=this.connectSettings)||!i.headers)throw new Error(W);if(null==s||!s[0])throw new Error(G);null!=(n=this.connectSettings)&&n.headers&&(this.connectSettings.headers[Ht]=s[0].name.toLocaleLowerCase().endsWith(".wav")?"audio/wav; codecs=audio/pcm; samplerate=16000":"audio/ogg; codecs=opus"),Ti.request(this,s[0],t,!1)}async extractResultData(t){if(t[l])throw t[l];return{[r]:t.DisplayText||""}}};Po.REGION_ERROR_MESSAGE=`${Io.REGION_ERROR_PREFIX}SpeechToText)`;let Bo=Po;class Ro extends Oi{constructor(t){var e,s,i;const n=null==(s=null==(e=t.directConnection)?void 0:e.azure)?void 0:s.translation,o=null==(i=t.directConnection)?void 0:i.azure;var r;super(t,(r=n.region,{url:"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es",method:Xt,createHeaders:t=>xo(r,t),handleVerificationResult:wo}),xo.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][r];if(e)return[{Text:e}]}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){var e;if(Array.isArray(t))return{[r]:(null==(e=t[0].translations)?void 0:e[0][r])||""};throw t[l]}}class Fo extends Oi{constructor(t){var e,s;const i=F(t.directConnection),n=i.bigModel;super(t,yn(),gn,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("BigModel"),this.keyHelpUrl="https://open.bigmodel.cn/usercenter/apikeys",this.url="https://open.bigmodel.cn/api/paas/v4/images/generations",this.permittedErrorPrefixes=[Rt,Nt];const o=null==(e=i.bigModel)?void 0:e[M];typeof o===Gt&&(this.cleanConfig(o),Object.assign(this.rawBody,o)),(s=this.rawBody).model??(s.model="cogview-4-250304")}cleanConfig(t){delete t.key}preprocessBody(t,e){const s=F(t),i=e[e.length-1];return s.prompt=(null==i?void 0:i[r])||"",s}async callServiceAPI(t,e){return this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){const e=t.data.map(t=>null!=t&&t.url?{[y]:t.url,[w]:_}:{[y]:"",[w]:_});return{[k]:e}}}const Lo=t=>({[Ht]:Wt,[Rt]:`${Kt}${t}`}),qo=(t,e,s,i)=>{const n=t;n[l]?n[l].message===Lt?i(H):i(V):s(e)},zo=()=>Wi("https://api.groq.com/openai/v1/models",Jt,qo);class Do extends Oi{constructor(t){var e,s,i,n;const o=F(t.directConnection),r=o.groq;super(t,zo(),Lo,r),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Groq"),this.keyHelpUrl="https://console.groq.com/keys",this.url="https://api.groq.com/openai/v1/audio/speech",this.permittedErrorPrefixes=[zt,"property"];const a=null==(e=o.groq)?void 0:e.textToSpeech;typeof a===Gt&&this.completeConfig(a),(s=this.rawBody).model??(s.model="playai-tts"),(i=this.rawBody).voice??(i.voice="Fritz-PlayAI"),(n=this.rawBody).response_format??(n.response_format="mp3")}preprocessBody(t,e){const s=F(t),i=e[e.length-1];return s.input=(null==i?void 0:i[r])||"",s}async callServiceAPI(t,e){return this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){const e=this.rawBody.response_format||"mp3",s=new Blob([t],{[w]:`audio/${e}`}),i=URL.createObjectURL(s);return{[k]:[{[y]:i,[w]:T}]}}}class No extends Oi{constructor(t){var e,s;const i=F(t.directConnection),n=i.together;super(t,_n(),xn,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Together AI"),this.keyHelpUrl="https://api.together.xyz/settings/api-keys",this.url="https://api.together.xyz/v1/images/generations",this.permittedErrorPrefixes=[Ut,Nt];const o=null==(e=i.together)?void 0:e[M];typeof o===Gt&&this.completeConfig(o),(s=this.rawBody).model??(s.model="black-forest-labs/FLUX.1-schnell-Free")}preprocessBody(t,e){const s=F(t),i=e[e.length-1];return s.prompt=(null==i?void 0:i[r])||"",s}async callServiceAPI(t,e){return this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){const e=t.data.map(t=>null!=t&&t.url?{[y]:t.url,[w]:_}:null!=t&&t.b64_json?{[y]:`data:image/png;base64,${t.b64_json}`,[w]:_}:{[y]:"",[w]:_});return{[k]:e}}}const Uo=class t extends So{constructor(e,s,i,n,o){var r,a;super(e,s,i,n,o),this.keyHelpUrl=An,this.url=`${Cn}responses`,this._functionStreamInProgress=!1,this._useConversation=!1,this._conversationLoadLimit=50;const l=o||(null==(a=null==(r=e.directConnection)?void 0:r.openAI)?void 0:a.chat);this._urlSegments=t.buildUrlSegments(l),this.url=this._urlSegments.responsesUrl,typeof l===Gt&&!0!==l&&l&&(l.conversation&&(this._useConversation=!0,"string"==typeof l.conversation&&(this._conversationId=l.conversation)),"number"==typeof l.conversationLoadLimit&&(this._conversationLoadLimit=l.conversationLoadLimit),this.cleanConfig(l)),this._conversationId&&(this.fetchHistory=this.fetchHistoryFunc.bind(this))}processConfig(t,e){super.processConfig(t,e)}static buildUrlSegments(t){const e="object"==typeof t&&(null==t?void 0:t.custom_base_url)||Cn;return{responsesUrl:`${e}responses`,conversationsUrl:`${e}conversations`}}cleanConfig(t){delete t.conversation,delete t.conversationLoadLimit,delete t.custom_base_url}static getFileContent(t){return So.getBaseFileContent(t).map(t=>t[w]===te?t:{detail:"auto",[w]:Sn,[ee]:t[y]})}static getContent(e){if(e[P]===u&&e[k]&&e[k].length>0){const s=t.getFileContent(e[k]);return e[r]&&e[r].trim().length>0&&s.unshift({[w]:Tn,[r]:e[r]}),s}return e[r]}async fetchHistoryFunc(){setTimeout(()=>this.deepChat.disableSubmitButton(),2);try{const t=this.url,{conversationsUrl:e}=this._urlSegments;this.url=`${e}/${this._conversationId}/items?limit=${this._conversationLoadLimit}`;const s=await Rn(this,{},Jt);return this.connectSettings.method=Xt,this.url=t,this.deepChat.disableSubmitButton(!1),this.processConversationHistory(s)}catch{return this.deepChat.disableSubmitButton(!1),[{[l]:tt}]}}static filterCompleted(t){return(null==t?void 0:t.filter(t=>t.status===Zt))||[]}processConversationHistory(e){if(!e.data||!Array.isArray(e.data))return[];const s=[];for(const i of t.filterCompleted(e.data.reverse()))if("message"===i[w]&&i.content&&Array.isArray(i.content))for(const e of i.content)e[w]!==Tn&&e[w]!==jn||!e[r]?e[w]===Sn&&s.push({[P]:i[P],[k]:t.generateImageFile(e[ee]||"")}):s.push({[P]:i[P],[r]:e[r]});else i[w]===En&&s.push({[P]:h,[k]:t.generateImageFile(i.result)});return s}preprocessBody(e,s){const i=F(e);s=this.processMessages(s);const n=(s=this._useConversation?[s[s.length-1]]:s).map(e=>({content:t.getContent(e),[P]:Oi.getRoleViaUser(e[P])}));return i.input=n,this._conversationId&&(i.conversation=this._conversationId),i}async createConversation(){try{const t=this.url;this.url=this._urlSegments.conversationsUrl;const e=await Rn(this,{},Xt);return this.url=t,e.id}catch(t){throw console[l]("Failed to create conversation:",t),t}}async callServiceAPI(t,e){this.messages??(this.messages=t),this._useConversation&&!this._conversationId&&(this._conversationId=await this.createConversation()),this._conversationId&&this.updateSessionId(this._conversationId),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){const s=await this.extractResult(t,e);return this._conversationId&&(s._sessionId=this._conversationId),s}async extractResult(e,s){var i,n,o,a;if(e[l])throw e[l].message;if(e.status){const a=t.filterCompleted(e.output);if(a.length>0){const t=null==(o=null==(n=null==(i=a.find(t=>{var e,s;return typeof(null==(s=null==(e=t.content)?void 0:e[0])?void 0:s[r])===B}))?void 0:i.content)?void 0:n[0])?void 0:o[r],e=await this.handleResponsesFunctionCalls(a,s,t);if(e)return e;return this.handleFileGenerationResponse(a,t)||{[r]:t}}return{[r]:""}}return(null==(a=e.item)?void 0:a[w])===Yt&&e[w]?this.handleStreamedResponsesFunctionCall(e,s):e[w]===`${$n}.${En}.partial_image`&&e.partial_image_b64?{[k]:[{[y]:`${t.IMAGE_BASE64_PREFIX}${e.partial_image_b64}`,[w]:_}]}:e.delta&&!this._functionStreamInProgress&&e[w]===`${$n}.${jn}.delta`?{[r]:e.delta}:{[r]:""}}async handleStreamedResponsesFunctionCall(t,e){var s;if(t[w]===`${$n}.output_item.done`){if(this._functionStreamInProgress=!1,(null==(s=t.item)?void 0:s[w])===Yt)return this.handleResponsesFunctionCalls([t.item],e)}else t[w]===`${$n}.output_item.added`&&(this._functionStreamInProgress=!0);return{[r]:""}}handleFileGenerationResponse(e,s){const i=e.find(t=>t[w]===En);return i?{[k]:t.generateImageFile(i.result),[r]:s}:null}static generateImageFile(e){return[{[y]:`${t.IMAGE_BASE64_PREFIX}${e}`,[w]:_}]}async handleResponsesFunctionCalls(t,e,s){const i=t.filter(t=>t[w]===Yt);if(0===i.length)return null;if(!e||!this.functionHandler)throw Error(Q);const n=i.map(t=>({name:t.name,arguments:t.arguments})),{responses:o,processedResponse:r}=await this.callToolFunction(this.functionHandler,n);if(r)return r;const a=F(e);if(a.input&&(i.forEach(t=>a.input.push(t)),!o.find(({response:t})=>typeof t!==B)&&n.length===o.length))return o.forEach((t,e)=>{const s=i[e];a.input.push({[w]:In,call_id:s.call_id,output:t[$n]})}),this.makeAnotherRequest(a,this.messages,s);throw Error(Y)}};Uo.IMAGE_BASE64_PREFIX="data:image/png;base64,";let Ho=Uo;class Vo extends Ho{constructor(t){var e,s,i,n,o,r,a;const c=F(t.directConnection),h=c.azure,u=(null==(s=null==(e=c.azure)?void 0:e.openAI)?void 0:s.urlDetails)||{},d=null==(n=null==(i=c.azure)?void 0:i.openAI)?void 0:n.chat;if(super(t,Hn(u),Un,h,d),this.permittedErrorPrefixes=[Nn],this.isTextInputDisabled=!1,typeof d===Gt){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)}Vn(u)?this.url=Vo.buildURL(u):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout(()=>{t.addMessage({[l]:Nn})}))}static buildURL(t){const{endpoint:e,deploymentId:s,version:i}=t;return`${e}/openai/deployments/${s}/chat/completions?api-version=${i}`}}class Wo extends Oi{constructor(t){var e,s,i,n,o;const r=F(t.directConnection),a=r.bigModel;super(t,yn(),gn,a),this.insertKeyPlaceholderText=this.genereteAPIKeyName("BigModel"),this.keyHelpUrl="https://open.bigmodel.cn/usercenter/apikeys",this.url="https://open.bigmodel.cn/api/paas/v4/chat/completions",this.permittedErrorPrefixes=[Rt,Nt];const l=null==(e=r.bigModel)?void 0:e.chat;typeof l===Gt&&this.completeConfig(l,null==(n=null==(i=null==(s=t.directConnection)?void 0:s.bigModel)?void 0:i.chat)?void 0:n.function_handler),this.maxMessages??(this.maxMessages=-1),(o=this.rawBody).model??(o.model="glm-4.5")}static getFileContent(t){return t.map(t=>t[w]===_?{[w]:ee,[ee]:{url:t[y]||""}}:{[w]:x,file_url:{url:t[y]||""}})}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>({content:Wo.getTextWFilesContent(t,Wo.getFileContent),[P]:Oi.getRoleViaAI(t[P])}));return this.addSystemMessage(i),s.messages=i,s}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){if(t[l])throw t[l].message;if(t.choices.length>0){if(void 0!==t.choices[0].delta)return this.extractStreamResult(t.choices[0],e);if(void 0!==t.choices[0].message){const s=t.choices[0].message;return s.tool_calls?this.handleToolsGeneric({tool_calls:s.tool_calls},this.functionHandler,this.messages,e):{[r]:s.content}}}return{[r]:""}}async extractStreamResult(t,e){var s,i,n,o;const{delta:a,finish_reason:l}=t,c=null==(s=this.messages)?void 0:s.messageToElements[this.messages.messageToElements.length-2];if((null==c?void 0:c[0][P])===h&&0===(null==(i=null==c?void 0:c[0][r])?void 0:i.replace(/\n/g,"").trim().length)&&(null==(n=this.messages)||n.removeMessage(c[1][r]),null==(o=this.messages)||o.messageToElements.splice(this.messages.messageToElements.length-2,1)),"tool_calls"===l){if(a.tool_calls){const t={tool_calls:a.tool_calls};return this.handleToolsGeneric(t,this.functionHandler,this.messages,e)}return{[r]:(null==a?void 0:a.content)||""}}return{[r]:(null==a?void 0:a.content)||""}}}class Go extends Oi{constructor(t){var e,s;const i=F(t.directConnection),n=i.together;super(t,_n(),xn,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Together AI"),this.keyHelpUrl="https://api.together.xyz/settings/api-keys",this.url="https://api.together.xyz/v1/chat/completions",this.permittedErrorPrefixes=[Ut,Nt];const o=null==(e=i.together)?void 0:e.chat;typeof o===Gt&&this.completeConfig(o),this.maxMessages??(this.maxMessages=-1),(s=this.rawBody).model??(s.model="meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo")}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>({content:t[r]||"",[P]:t[P]===h?d:t[P]}));return this.addSystemMessage(i),s.messages=i,s}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t){if(t[l])throw t[l].message;if(t.choices.length>0){if(void 0!==t.choices[0].message)return{[r]:t.choices[0].message.content};if(void 0!==t.choices[0].delta)return{[r]:t.choices[0].delta.content}}return{[r]:""}}}const Zo=class t extends Oi{constructor(e){var s;const{directConnection:i}=e,n=null==i?void 0:i.openAI,o={images:{[k]:{acceptedFormats:".png",maxNumberOfFiles:2}}};super(e,Bn(),On,n,o),this.insertKeyPlaceholderText=this.genereteAPIKeyName("OpenAI"),this.keyHelpUrl=An,this.url="",this.permittedErrorPrefixes=[Dt,"Invalid input image"];const r=null==(s=null==i?void 0:i.openAI)?void 0:s[M];if(this[C]){const t="object"==typeof r&&r.size?Number.parseInt(r.size):1024;this[C][k]={dimensions:{width:t,height:t}}}typeof r===Gt&&Object.assign(this.rawBody,r),this.canSendMessage=t.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])||!(!t||""===t.trim())}static createFormDataBody(t,e,s){const i=new FormData;return i.append(_,e),s&&i.append("mask",s),Object.keys(t).forEach(e=>{i.append(e,String(t[e]))}),i}preprocessBody(t,e){const s=F(t);return e&&""!==e&&(s.prompt=e),s}callApiWithImage(e,s,i){var n,o;let a;const l=null==(o=null==(n=s[s.length-1])?void 0:n[r])?void 0:o.trim();if(i[1]||l&&""!==l){this.url=t.IMAGE_EDIT_URL;const e=this.preprocessBody(this.rawBody,l);a=t.createFormDataBody(e,i[0],i[1])}else this.url=t.IMAGE_VARIATIONS_URL,a=t.createFormDataBody(this.rawBody,i[0]);fi.tempRemoveContentHeader(this.connectSettings,Ti.request.bind(this,this,a,e),!1)}async callServiceAPI(e,s,i){var n;if(null==(n=this.connectSettings)||!n.headers)throw new Error(W);if(null!=i&&i[0])this.callApiWithImage(e,s,i);else{if(!this.connectSettings)throw new Error(W);this.url=t.IMAGE_GENERATION_URL;const i=this.preprocessBody(this.rawBody,s[s.length-1][r]);Ti.request(this,i,e)}}async extractResultData(t){if(t[l])throw t[l].message;const e=t.data.map(t=>t.url?{[y]:t.url,[w]:_}:{[y]:`${nn}${t.b64_json}`,[w]:_});return{[k]:e}}};Zo.IMAGE_GENERATION_URL=`${Cn}images/generations`,Zo.IMAGE_VARIATIONS_URL=`${Cn}images/variations`,Zo.IMAGE_EDIT_URL=`${Cn}images/edits`;let Ko=Zo;const Jo=t=>({[Rt]:`${Kt}${t}`,[Ht]:Wt}),Xo=(t,e,s,i)=>{const n=t;n[l]?n[l][w]===Nt?i(H):i(V):s(e)};class Qo extends Oi{constructor(t){var e,s,i,n;const o=F(t.directConnection).openRouter;super(t,Wi("https://openrouter.ai/api/v1/key",Jt,Xo),Jo,o),this.insertKeyPlaceholderText=this.genereteAPIKeyName("OpenRouter"),this.keyHelpUrl="https://openrouter.ai/keys",this.url="https://openrouter.ai/api/v1/chat/completions",this.permittedErrorPrefixes=[Ut,Nt],typeof o===Gt&&this.completeConfig(o,null==(s=null==(e=t.directConnection)?void 0:e.openRouter)?void 0:s.function_handler),this.maxMessages??(this.maxMessages=-1),(i=this.rawBody).model??(i.model="openai/gpt-4o"),(n=this.rawBody).max_tokens??(n.max_tokens=1e3)}static getAudioContent(t){return t.filter(t=>t[w]===T).map(t=>{var e,s,i;const n=null==(e=t[y])?void 0:e.split(",")[1],o=null==(i=null==(s=t[y])?void 0:s.match(/data:audio\/([^;]+)/))?void 0:i[1];return{[w]:te,[te]:{data:n||"",format:"wav"===o||"mp3"===o?o:"mp3"}}}).filter(t=>t[te].data.length>0)}static getContent(t){if(t[k]&&t[k].length>0){const e=[...Qo.getImageContent(t[k]),...Qo.getAudioContent(t[k])];return t[r]&&t[r].trim().length>0&&e.unshift({[w]:r,[r]:t[r]}),e.length>0?e:t[r]||""}return t[r]||""}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>({content:Qo.getContent(t),[P]:Oi.getRoleViaUser(t[P])})),n=[];return this.systemMessage&&n.push({[P]:se,content:this.systemMessage}),n.push(...i),s.messages=n,s}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){var s,i,n,o;if(t[l])throw t[l].message;if("chat.completion.chunk"===t.object){const n=null==(s=t.choices)?void 0:s[0];if(null!=n&&n.delta)return this.extractStreamResult(n,e);if(null!=(i=t.message)&&i[M]){const e=t.message[M].map(t=>({[y]:t[ee].url}));return{[r]:t.message.content||"",[k]:e}}return{[r]:""}}if("chat.completion"===t.object){const s=null==(n=t.choices)?void 0:n[0];if(null!=s&&s.message){if(s.message.tool_calls)return this.handleToolsGeneric({tool_calls:s.message.tool_calls},this.functionHandler,this.messages,e);const t=(null==(o=s.message[M])?void 0:o.map(t=>({[y]:t[ee].url})))||[];return{[r]:s.message.content||"",files:t}}}return{[r]:""}}async extractStreamResult(t,e){const{delta:s}=t;if(null!=s&&s[M]){const t=s[M].map(t=>({[y]:t[ee].url}));return{[r]:s.content||"",[k]:t}}return this.extractStreamResultWToolsGeneric(this,t,this.functionHandler,e)}}const Yo=t=>({[Rt]:`${Kt}${t}`,[Ht]:Wt}),tr=(t,e,s,i)=>{t[l]?i(H):s(e)};class er extends Oi{constructor(t){var e;const s=F(t.directConnection).perplexity;super(t,Wi("https://api.perplexity.ai/chat/completions",Xt,tr),Yo,s),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Perplexity"),this.keyHelpUrl="https://www.perplexity.ai/settings/api",this.url="https://api.perplexity.ai/chat/completions",this.permittedErrorPrefixes=[zt,Bt,"Permission denied"],typeof s===Gt&&this.completeConfig(s),this.maxMessages??(this.maxMessages=-1),(e=this.rawBody).model??(e.model="sonar")}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>({content:t[r]||"",[P]:Oi.getRoleViaUser(t[P])}));return this.addSystemMessage(i),s.messages=i,s}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t){if(t[l])throw t[l].message;if(t.choices&&t.choices.length>0){const e=t.choices[0];if(e.delta&&e.delta.content)return{[r]:e.delta.content};if(e.message&&e.message.content)return{[r]:e.message.content}}return{[r]:""}}}const sr=t=>({[Rt]:`Bearer ${t}`,[Ht]:Wt}),ir=(t,e,s,i)=>{const n=t;n.detail?i(n.detail):s(e)};class nr extends Oi{constructor(t){var e,s,i,n;const o=F(t.directConnection).openWebUI;super(t,Wi("http://localhost:3000/api/v1/models",Jt,ir),sr,o),this.insertKeyPlaceholderText="Open WebUI API Key",this.keyHelpUrl="https://docs.openwebui.com/getting-started/api-endpoints/",this.url="http://localhost:3000/api/chat/completions",this.permittedErrorPrefixes=["Error"],typeof o===Gt&&(this.completeConfig(o,null==(s=null==(e=t.directConnection)?void 0:e.openWebUI)?void 0:s.function_handler),o[k]&&o[k].length>0&&(this.rawBody[k]=o[k])),this.maxMessages??(this.maxMessages=-1),(i=this.rawBody).model??(i.model="llama3.2"),(n=this.rawBody).stream??(n.stream=!1)}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>({content:Oi.getTextWImagesContent(t),[P]:Oi.getRoleViaUser(t[P])}));return this.addSystemMessage(i),s.messages=i,s}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{readable:!0})}async extractResultData(t,e){var s;if(t[l])throw t[l].message;if(t[r]){const s=t[r].trim();return this.processStreamingResponse(s,e)}if(t.choices&&null!=(s=t.choices[0])&&s.message){const s=t.choices[0].message;return s.tool_calls?this.handleTools({tool_calls:s.tool_calls},e):{[r]:s.content||""}}return{[r]:""}}async processStreamingResponse(t,e){var s;const i=t.split("\n").filter(t=>""!==t.trim());let n="";for(const t of i){let i=t.trim();if(i.startsWith("data: ")&&(i=i.substring(6)),"[DONE]"!==i)try{const t=JSON.parse(i);if(t.choices&&null!=(s=t.choices[0])&&s.delta){const s=t.choices[0].delta;if(s.tool_calls)return this.handleTools({tool_calls:s.tool_calls},e);s.content&&(n+=s.content)}}catch{continue}}return{[r]:n}}async handleTools(t,e){if(!t.tool_calls||!e||!this.functionHandler)throw Error(Q);const s=F(e),i=t.tool_calls.map(t=>({name:t.function.name,arguments:t.function.arguments})),{responses:n,processedResponse:o}=await this.callToolFunction(this.functionHandler,i);if(o)return o;if(s.messages.push({tool_calls:t.tool_calls,[P]:d,content:""}),!n.find(({response:t})=>typeof t!==B)&&i.length===n.length)return n.forEach((e,i)=>{var n;const o=null==(n=t.tool_calls)?void 0:n[i];null==s||s.messages.push({[P]:"tool",tool_name:null==o?void 0:o.function.name,content:e.response})}),this.makeAnotherRequest(s,this.messages);throw Error(Y)}}const or=t=>({[Rt]:`${Kt}${t}`,[Ht]:Wt}),rr=(t,e,s,i)=>{const n=t;n[l]?n[l][w]===Nt?i(H):i(V):s(e)};class ar extends Oi{constructor(t){var e,s,i;const n=F(t.directConnection).deepSeek;super(t,Wi("https://api.deepseek.com/models",Jt,rr),or,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("DeepSeek"),this.keyHelpUrl="https://platform.deepseek.com/api_keys",this.url="https://api.deepseek.com/v1/chat/completions",this.permittedErrorPrefixes=[Ut,Nt],typeof n===Gt&&this.completeConfig(n),this.maxMessages??(this.maxMessages=-1),(e=this.rawBody).model??(e.model="deepseek-chat"),(s=this.rawBody).temperature??(s.temperature=1),(i=this.rawBody).max_tokens??(i.max_tokens=4096)}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>({content:t[r]||"",[P]:Oi.getRoleViaUser(t[P])}));return this.addSystemMessage(i),s.messages=i,s}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t){if(t[l])throw t[l].message;if(t.choices&&t.choices.length>0){const e=t.choices[0];if(e.delta&&e.delta.content)return{[r]:e.delta.content};if(e.message&&e.message.content)return{[r]:e.message.content}}return{[r]:""}}}const lr=t=>({[Rt]:`${Kt}${t}`,[Ht]:Wt}),cr=(t,e,s,i)=>{var n;1004===(null==(n=t.base_resp)?void 0:n.status_code)?i(H):s(e)};class hr extends Oi{constructor(t){var e;const s=F(t.directConnection).miniMax;super(t,Wi("https://api.minimax.io/v1/files/delete",Xt,cr),lr,s),this.insertKeyPlaceholderText=this.genereteAPIKeyName("MiniMax"),this.keyHelpUrl="https://www.minimaxi.com",this.url="https://api.minimax.io/v1/text/chatcompletion_v2",this.permittedErrorPrefixes=[Ut,Nt,"insufficient balance"],typeof s===Gt&&this.completeConfig(s),this.maxMessages??(this.maxMessages=-1),(e=this.rawBody).model??(e.model="MiniMax-M1")}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>({content:t[r]||"",[P]:Oi.getRoleViaUser(t[P])}));return this.addSystemMessage(i),s.messages=i,s}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t){var e;if(t[l])throw t[l].message;if(t.choices&&t.choices.length>0){const e=t.choices[0];if(e.delta&&e.delta.content)return{[r]:e.delta.content};if(e.message&&e.message.content)return{[r]:e.message.content}}if("number"==typeof(null==(e=t.base_resp)?void 0:e.status_code)&&t.base_resp.status_code>0)throw t.base_resp.status_msg;return{[r]:""}}}const ur=t=>({[Rt]:`${Kt}${t}`,[Ht]:Wt,accept:Wt}),dr=(t,e,s,i)=>{t.detail?i(H):s(e)};class pr extends Oi{constructor(t){var e,s,i;const n=F(t.directConnection).mistral;super(t,Wi("https://api.mistral.ai/v1/models",Jt,dr),ur,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Mistral"),this.keyHelpUrl="https://console.mistral.ai/api-keys/",this.url="https://api.mistral.ai/v1/chat/completions",this.permittedErrorPrefixes=[zt],typeof n===Gt&&this.completeConfig(n,null==(s=null==(e=t.directConnection)?void 0:e.mistral)?void 0:s.function_handler),this.maxMessages??(this.maxMessages=-1),(i=this.rawBody).model??(i.model="mistral-small-latest")}static getFileContent(t){return t.map(t=>t[w]===_?{[w]:ee,[ee]:t[y]||""}:{[w]:r,[r]:`[Unsupported ${x} ${w}: ${t[w]}]`})}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>({[P]:Oi.getRoleViaAI(t[P]),content:Oi.getTextWFilesContent(t,pr.getFileContent)}));return this.addSystemMessage(i),s.messages=i,s}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){if(t.message)throw t.message;if(t[l])throw t[l].message;if(t.choices&&t.choices.length>0){const s=t.choices[0];if(s.delta)return this.extractStreamResult(s,e);if(s.message)return s.message.tool_calls?this.handleToolsGeneric({tool_calls:s.message.tool_calls},this.functionHandler,this.messages,e):{[r]:s.message.content||""}}return{[r]:""}}async extractStreamResult(t,e){const{delta:s,finish_reason:i}=t;if("tool_calls"===i&&null!=s&&s.tool_calls){const t={tool_calls:s.tool_calls};return this.handleToolsGeneric(t,this.functionHandler,this.messages,e)}return{[r]:(null==s?void 0:s.content)||""}}}class mr extends Oi{constructor(t){var e,s,i,n,o;const r=F(t.directConnection),a=r.groq;super(t,zo(),Lo,a),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Groq"),this.keyHelpUrl="https://console.groq.com/keys",this.url="https://api.groq.com/openai/v1/chat/completions",this.permittedErrorPrefixes=[zt,"property"];const l=null==(e=r.groq)?void 0:e.chat;typeof l===Gt&&this.completeConfig(l,null==(n=null==(i=null==(s=t.directConnection)?void 0:s.groq)?void 0:i.chat)?void 0:n.function_handler),this.maxMessages??(this.maxMessages=-1),(o=this.rawBody).model??(o.model="llama-3.3-70b-versatile")}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>({content:mr.getTextWImagesContent(t),[P]:t[P]===h?d:t[P]}));return this.addSystemMessage(i),s.messages=i,s}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){var s,i,n,o;if(t[l])throw t[l].message;return null!=(i=null==(s=t.choices)?void 0:s[0])&&i.delta?this.extractStreamResult(t.choices[0],e):null!=(o=null==(n=t.choices)?void 0:n[0])&&o.message?t.choices[0].message.tool_calls?this.handleToolsGeneric(t.choices[0].message,this.functionHandler,this.messages,e,{message:this.systemMessage}):{[r]:t.choices[0].message.content||""}:{[r]:""}}async extractStreamResult(t,e){return this.extractStreamResultWToolsGeneric(this,t,this.functionHandler,e)}}const vr=t=>({[Rt]:`${Kt}${t}`,[Ht]:Wt,accept:Wt}),fr=(t,e,s,i)=>{typeof t.message===B?i(H):s(e)};class gr extends Oi{constructor(t){var e;const s=F(t.directConnection).cohere;if(super(t,Wi("https://api.cohere.ai/v1/models",Jt,fr),vr,s),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Cohere"),this.keyHelpUrl="https://dashboard.cohere.ai/api-keys",this.permittedErrorPrefixes=["invalid"],this.url="https://api.cohere.com/v2/chat",typeof s===Gt){const t=ce.processCohere(s);this.canSendMessage=()=>t,this.cleanConfig(s),Object.assign(this.rawBody,s)}this.maxMessages??(this.maxMessages=-1),(e=this.rawBody).model??(e.model="command-a-03-2025")}cleanConfig(t){delete t.key}preprocessBody(t,e){const s=F(t),i=e.filter(t=>t[r]);return s.messages=i.map(t=>({[P]:Oi.getRoleViaAI(t[P]),content:t[r]})),s}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{readable:!0})}async extractResultData(t){var e,s,i;if("string"==typeof t.message)throw t.message;if(this.stream&&t[r]){const e=gr.parseBundledEvents(t[r]);return{text:gr.aggregateBundledEventsText(e)}}if("message"in t&&null!=(i=null==(s=null==(e=t.message)?void 0:e.content)?void 0:s[0])&&i[r])return{[r]:t.message.content[0][r]};throw new Error("Invalid response format from Cohere API")}static parseBundledEvents(t){const e=t.trim().split("\n"),s=[];for(const t of e)if(t.trim())try{const e=JSON.parse(t);s.push(e)}catch(e){console[l]("Failed to parse line:",t,e)}return s}static aggregateBundledEventsText(t){return t.filter(t=>{var e,s,i;return"content-delta"===t[w]&&(null==(i=null==(s=null==(e=t.delta)?void 0:e.message)?void 0:s.content)?void 0:i[r])}).map(t=>{var e,s,i;return null==(i=null==(s=null==(e=t.delta)?void 0:e.message)?void 0:s.content)?void 0:i[r]}).join("")}}const br=()=>({[Ht]:Wt}),yr=(t,e,s,i)=>{var n;const o=t;o[l]?403===o[l].code||null!=(n=o[l].message)&&n.includes("API key")?i(H):i(V):s(e)};class wr extends Oi{constructor(t){var e,s;const i=F(t.directConnection).gemini;if(super(t,(()=>{const t="https://generativelanguage.googleapis.com/v1beta/models?key=";return Wi(t,Jt,yr,e=>`${t}${e}`)})(),br,i),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Gemini"),this.keyHelpUrl="https://aistudio.google.com/app/apikey",this.urlPrefix="https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent",this.url="",this.permittedErrorPrefixes=["API_KEY_INVALID"],typeof i===Gt){const n=i;n.model&&(this.urlPrefix=`https://generativelanguage.googleapis.com/v1beta/models/${n.model}:generateContent`),this.cleanConfig(n),this.completeConfig(n,null==(s=null==(e=t.directConnection)?void 0:e.gemini)?void 0:s.function_handler)}this.maxMessages??(this.maxMessages=-1)}cleanConfig(t){delete t.model}static getContent(t){const e=[];return t[r]&&t[r].trim().length>0&&e.push({[r]:t[r]}),t[k]&&t[k].length>0&&t[k].forEach(t=>{if(t[y]&&t[y].includes("data:")){const[s,i]=t[y].split(",");e.push({inlineData:{mimeType:s.replace("data:","").replace(";base64",""),data:i}})}}),{parts:e,[P]:t[P]===u?u:"model"}}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>wr.getContent(t));return s.contents=i,this.systemMessage&&(s.systemInstruction={parts:[{[r]:this.systemMessage}]}),s}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error(W);this.messages??(this.messages=t);const s=this.preprocessBody(this.rawBody,e),i=this.stream;i&&(typeof i!==Gt||!i.simulation)||s.stream?(this.url=`${this.urlPrefix.replace(":generateContent",":streamGenerateContent")}?alt=sse&key=${this.key}`,ki.request(this,s,t)):(this.url=`${this.urlPrefix}?key=${this.key}`,Ti.request(this,s,t))}async extractResultData(t,e){var s,i,n,o;if(t[l])throw t[l].message||"Gemini API Error";if(null!=(n=null==(i=null==(s=t.candidates)?void 0:s[0])?void 0:i.content)&&n.parts){const s=t.candidates[0].content.parts,i=s.find(t=>t.functionCall);if(null!=i&&i.functionCall)return this.handleTools([i.functionCall],e);const n=s.find(t=>t[r]),a=s.find(t=>{var e;return"image/png"===(null==(e=t.inlineData)?void 0:e.mimeType)});return{[r]:(null==n?void 0:n[r])||"",[k]:null!=(o=null==a?void 0:a.inlineData)&&o.data?[{[y]:`data:image/png;base64,${a.inlineData.data}`}]:[]}}return{[r]:""}}async handleTools(t,e){if(!t||!e||!this.functionHandler)throw Error(Q);const s=F(e),i=t.map(t=>({name:t.name,arguments:R(t.args)})),{responses:n,processedResponse:o}=await this.callToolFunction(this.functionHandler,i);if(o)return o;const r={parts:t.map(t=>({functionCall:{name:t.name,args:t.args}})),[P]:"model"};if(s.contents.push(r),!n.find(({response:t})=>typeof t!==B)&&i.length===n.length){const e={parts:n.map((e,s)=>({functionResponse:{name:t[s].name,response:{result:e.response}}})),[P]:u};return s.contents.push(e),this.makeAnotherRequest(s,this.messages)}throw Error(Y)}}const xr=t=>({"x-api-key":t,[Ht]:Wt,"anthropic-version":"2023-06-01","anthropic-dangerous-direct-browser-access":"true"}),kr=(t,e,s,i)=>{const n=t;n[l]?n[l][w]===Nt?i(H):i(V):s(e)};class _r extends Oi{constructor(t){var e,s,i,n;const o=F(t.directConnection).claude;super(t,Wi("https://api.anthropic.com/v1/models",Jt,kr),xr,o),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Claude"),this.keyHelpUrl="https://console.anthropic.com/settings/keys",this.url="https://api.anthropic.com/v1/messages",this.permittedErrorPrefixes=[Nt,Ut],this._streamToolCalls={[w]:"tool_use",id:"",name:"",input:""},typeof o===Gt&&this.completeConfig(o,null==(s=null==(e=t.directConnection)?void 0:e.claude)?void 0:s.function_handler),this.maxMessages??(this.maxMessages=-1),(i=this.rawBody).model??(i.model="claude-sonnet-4-5-20250929"),(n=this.rawBody).max_tokens??(n.max_tokens=4096)}static getFileContent(t){return t.map(t=>{var e,s,i;if(t[w]===_){const n=null==(e=t[y])?void 0:e.split(",")[1],o=(null==(i=null==(s=t[y])?void 0:s.match(/data:([^;]+)/))?void 0:i[1])||"image/jpeg";return{[w]:_,source:{[w]:"base64",media_type:o,data:n||""}}}return{[w]:r,[r]:`[Unsupported ${x} ${w}: ${t[w]}]`}})}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>({content:_r.getTextWFilesContent(t,_r.getFileContent),[P]:Oi.getRoleViaUser(t[P])}));return s.messages=i,this.systemMessage&&(s.system=this.systemMessage),s}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){var s,i,n;if(t[l])throw t[l].message;if(t.content&&t.content.length>0){const s=t.content.find(t=>"tool_use"===t[w]);if(s)return this.handleTools([s],e);const i=t.content.find(t=>t[w]===r);if(i)return{[r]:i[r]}}if("content_block_delta"===t[w]&&t.delta&&"text_delta"===t.delta[w])return{[r]:t.delta[r]||""};if("content_block_start"===t[w]&&"tool_use"===(null==(s=t.content_block)?void 0:s[w]))this._streamToolCalls=t.content_block,this._streamToolCalls.input="";else if("content_block_delta"===t[w]&&"input_json_delta"===(null==(i=t.delta)?void 0:i[w]))this._streamToolCalls.input+=t.delta.partial_json||"";else if("message_delta"===t[w]&&"tool_use"===(null==(n=t.delta)?void 0:n.stop_reason))return this._streamToolCalls.input=JSON.parse(this._streamToolCalls.input),this.handleTools([this._streamToolCalls],e);return{[r]:""}}async handleTools(t,e){if(!t||!e||!this.functionHandler)throw Error(Q);const s=F(e),i=t.map(t=>({name:t.name,arguments:R(t.input)})),{responses:n,processedResponse:o}=await this.callToolFunction(this.functionHandler,i);if(o)return o;const r=t.map(t=>({[w]:"tool_use",id:t.id,name:t.name,input:t.input}));if(s.messages.push({[P]:"assistant",content:r}),!n.find(({response:t})=>typeof t!==B)&&i.length===n.length){const e=n.map((e,s)=>({[w]:"tool_result",tool_use_id:t[s].id,content:e.response}));return s.messages.push({[P]:u,content:e}),this.makeAnotherRequest(s,this.messages)}throw Error(Y)}}const Mr=()=>({}),Cr=()=>{},Ar=class t extends Oi{constructor(t){var e,s,i,n;const o=F(t.directConnection);super(t,Wi("",Jt,Cr),Mr,{key:"placeholder"}),this.insertKeyPlaceholderText="",this.keyHelpUrl="",this.validateKeyProperty=!1,this.url="http://localhost:11434/api/chat",this.permittedErrorPrefixes=["Error"];const r=o.ollama;typeof r===Gt&&this.completeConfig(r,null==(s=null==(e=t.directConnection)?void 0:e.ollama)?void 0:s.function_handler),this.maxMessages??(this.maxMessages=-1),(i=this.rawBody).model??(i.model="llama3.2"),(n=this.rawBody).stream??(n.stream=!1)}static getImageData(t){return t.filter(t=>t[w]===_).map(t=>{var e;return(null==(e=t[y])?void 0:e.split(",")[1])||""}).filter(t=>t.length>0)}preprocessBody(e,s){const i=F(e),n=this.processMessages(s).map(e=>{const s={content:e[r]||"",[P]:Oi.getRoleViaUser(e[P])};if(e[k]&&e[k].length>0){const i=t.getImageData(e[k]);i.length>0&&(s[M]=i)}return s});return this.addSystemMessage(n),i.messages=n,i}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{readable:!0})}parseMessage(t){return t.split("\n").filter(t=>t.trim()).map(t=>JSON.parse(t))}async extractResultData(e,s){var i,n;if(e[l])throw e[l].message;if(e[r]){const o=this.parseMessage(e[r]),a=[];for(const t of o)null!=(i=t.message)&&i.tool_calls&&a.push(await this.handleTools({tool_calls:t.message.tool_calls},s)),a.push({[r]:(null==(n=t.message)?void 0:n.content)||""});const l=a.map(t=>t[r]),c=l.lastIndexOf(t.THINK_END);return-1===c||null!=s&&s.think?{[r]:l.join("")}:{[r]:l.slice(c+1).join(""),overwrite:!0}}return e.message?e.message.tool_calls?this.handleTools({tool_calls:e.message.tool_calls},s):{[r]:e.message.content||""}:{[r]:""}}async handleTools(t,e){if(!t.tool_calls||!e||!this.functionHandler)throw Error(Q);const s=F(e),i=t.tool_calls.map(t=>({name:t.function.name,arguments:R(t.function.arguments)})),{responses:n,processedResponse:o}=await this.callToolFunction(this.functionHandler,i);if(o)return o;if(s.messages.push({tool_calls:t.tool_calls,[P]:d,content:""}),!n.find(({response:t})=>typeof t!==B)&&i.length===n.length)return n.forEach((e,i)=>{var n;const o=null==(n=t.tool_calls)?void 0:n[i];null==s||s.messages.push({[P]:"tool",tool_name:null==o?void 0:o.function.name,content:e.response})}),this.makeAnotherRequest(s,this.messages);throw Error(Y)}};Ar.THINK_END="</think>";let Tr=Ar;const Sr=t=>({Authorization:`${Kt}${t}`,[Ht]:Wt}),jr=(t,e,s,i)=>{const n=t;n[l]?n[l][w]===Nt||n[l][w]===Ut?i(H):i(V):s(e)},Er=()=>Wi("https://api.x.ai/v1/models",Jt,jr),Ir=class t extends Oi{constructor(e){var s,i;const{directConnection:n}=e,o=null==n?void 0:n.x;super(e,Er(),Sr,o),this.insertKeyPlaceholderText=this.genereteAPIKeyName("X"),this.keyHelpUrl="https://console.x.ai/team/default/api-keys",this.url=t.IMAGE_GENERATION_URL,this.permittedErrorPrefixes=[Ut,Nt];const r=null==(s=null==n?void 0:n.x)?void 0:s[M];typeof r===Gt&&Object.assign(this.rawBody,r),(i=this.rawBody).model??(i.model="grok-2-image")}preprocessBody(t,e){const s=e[e.length-1][r],i=F(t);return s&&""!==s&&(i.prompt=s),i}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){if(t[l])throw t[l].message;const e=t.data.map(t=>t.url?{[y]:t.url,[w]:_}:{[y]:`${nn}${t.b64_json}`,[w]:_});return{[k]:e}}};Ir.IMAGE_GENERATION_URL="https://api.x.ai/v1/images/generations";let $r=Ir;const Or=t=>({[Rt]:`${Kt}${t}`,[Ht]:Wt}),Pr=(t,e,s,i)=>{const n=t;n[l]?n[l][w]===Ut?i(H):i(V):s(e)};class Br extends Oi{constructor(t){var e,s,i;const n=F(t.directConnection).qwen;super(t,Wi("https://dashscope-intl.aliyuncs.com/compatible-mode/v1/models",Jt,Pr),Or,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Qwen"),this.keyHelpUrl="https://www.alibabacloud.com/help/en/model-studio/get-api-key",this.url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions",this.permittedErrorPrefixes=["No static","The model",Dt],typeof n===Gt&&this.completeConfig(n,null==(s=null==(e=t.directConnection)?void 0:e.qwen)?void 0:s.function_handler),this.maxMessages??(this.maxMessages=-1),(i=this.rawBody).model??(i.model="qwen-plus")}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>({content:Br.getTextWImagesContent(t),[P]:Oi.getRoleViaUser(t[P])}));return this.addSystemMessage(i),s.messages=i,s}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){if(t[l])throw t[l].message;if(t.choices&&t.choices.length>0){const s=t.choices[0];if(s.delta)return this.extractStreamResult(s,e);if(s.message)return s.message.tool_calls?this.handleToolsGeneric({tool_calls:s.message.tool_calls},this.functionHandler,this.messages,e):{[r]:s.message.content||""}}return{[r]:""}}async extractStreamResult(t,e){return this.extractStreamResultWToolsGeneric(this,t,this.functionHandler,e)}}const Rr=t=>({[Rt]:`${Kt}${t}`,[Ht]:Wt}),Fr=(t,e,s,i)=>{const n=t;n[l]?n[l][w]===Nt?i(H):i(V):s(e)};class Lr extends Oi{constructor(t){var e,s,i;const n=F(t.directConnection).kimi;super(t,Wi("https://api.moonshot.ai/v1/models",Jt,Fr),Rr,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Kimi"),this.keyHelpUrl="https://platform.moonshot.ai/console/api-keys",this.url="https://api.moonshot.ai/v1/chat/completions",this.permittedErrorPrefixes=[zt,"Not found"],typeof n===Gt&&this.completeConfig(n,null==(s=null==(e=t.directConnection)?void 0:e.kimi)?void 0:s.function_handler),this.maxMessages??(this.maxMessages=-1),(i=this.rawBody).model??(i.model="moonshot-v1-8k")}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>({content:Lr.getTextWImagesContent(t),[P]:Oi.getRoleViaUser(t[P])}));return this.addSystemMessage(i),s.messages=i,s}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){if(t[l])throw t[l].message;if(t.choices&&t.choices.length>0){const s=t.choices[0];if(s.delta)return this.extractStreamResult(s,e);if(s.message)return s.message.tool_calls?this.handleToolsGeneric({tool_calls:s.message.tool_calls},this.functionHandler,this.messages,e):{[r]:s.message.content||""}}return{[r]:""}}async extractStreamResult(t,e){return this.extractStreamResultWToolsGeneric(this,t,this.functionHandler,e)}}class qr extends Oi{constructor(t){var e,s;const i=F(t.directConnection),n=i.x;super(t,Er(),Sr,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("X"),this.keyHelpUrl="https://console.x.ai/team/default/api-keys",this.url="https://api.x.ai/v1/chat/completions",this.permittedErrorPrefixes=[Ut,Nt];const o=null==(e=i.x)?void 0:e.chat;typeof o===Gt&&this.completeConfig(o),this.maxMessages??(this.maxMessages=-1),(s=this.rawBody).model??(s.model="grok-3-latest")}preprocessBody(t,e){const s=F(t),i=this.processMessages(e).map(t=>({content:t[r]||"",[P]:Oi.getRoleViaUser(t[P])}));return this.addSystemMessage(i),s.messages=i,s}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t){var e,s,i,n;if(t[l])throw t[l].message;if("chat.completion.chunk"===t.object){const i=null==(e=t.choices)?void 0:e[0];return null!=(s=null==i?void 0:i.delta)&&s.content?{[r]:i.delta.content}:{[r]:""}}return"chat.completion"===t.object&&null!=(n=null==(i=t.choices)?void 0:i[0])&&n.message?{[r]:t.choices[0].message.content||""}:{[r]:""}}}var zr=(t=>(t.BLOCKING="blocking",t.STREAMING="streaming",t))(zr||{}),Dr=(t=>(t.MESSAGE="message",t.AGENT_MESSAGE="agent_message",t.WORKFLOW_FINISHED="workflow_finished",t.ERROR="error",t))(Dr||{});const Nr=t=>{const e=t.trim();if(!e.startsWith("data:"))return null;const s=e.replace(/^data:\s*/,"").trim();return s?JSON.parse(s):null};async function Ur(t,e){if(0===t.length)return[];const s=t.map(async t=>{const s=await async function(t,e){const s=new FormData;s.append(x,t),s.append(u,e[u]);const{[Ht]:i,...n}=e.headers,o=await fetch(e.url,{method:Xt,headers:n,body:s});if(!o.ok){const t=await o.text();throw new Error(t)}const r=await o.json();if(!r.id)throw new Error("Upload response missing file ID");return r.id}(t,e);return((t,e)=>({type:e,transfer_method:"local_file",upload_file_id:t}))(s,t[w].startsWith("image/")?_:x)});return(await Promise.all(s)).filter(t=>null!==t)}const Hr=(t,e,s)=>{var i,n;switch(!e.conversationIdSet&&t.conversation_id&&(s(t.conversation_id),e.conversationIdSet=!0),t.event){case Dr.MESSAGE:case Dr.AGENT_MESSAGE:e.fullAnswer+=t.answer||"";break;case Dr.WORKFLOW_FINISHED:!e.fullAnswer&&null!=(n=null==(i=t.data)?void 0:i.outputs)&&n.answer&&(e.fullAnswer=t.data.outputs.answer);break;case Dr.ERROR:e.errorMessage=t.message||Dr.ERROR}};const Vr=t=>({[Ht]:Wt,[Rt]:`${Kt}${t}`}),Wr=(t,e,s,i)=>{const n=t;n[l]?n[l].message===Lt?i(H):i(V):"user_input_form"in t||"opening_statement"in t||"file_upload"in t?s(e):i(V)};class Gr extends Oi{constructor(t){var e;const s=F(t.directConnection),i=null==s?void 0:s.dify,n=(null==(e=t.connect)?void 0:e.url)??"https://api.dify.ai/v1";super(t,Wi(`${n}/parameters`,Jt,Wr),Vr,i),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Dify"),this.keyHelpUrl="https://docs.dify.ai/en/use-dify/publish/developing-with-apis",this.permittedErrorPrefixes=[Nt],this._conversationId="",this._user=u,this._inputs={},this.url=`${n}/chat-messages`,this._uploadUrl=`${n}/${k}/upload`,typeof i===Gt&&(i[u]&&(this._user=i[u]),i.inputs&&(this._inputs=i.inputs),this.completeConfig(i)),this.maxMessages??(this.maxMessages=-1),this._mode=this.stream?zr.STREAMING:zr.BLOCKING}preprocessBody(t,e,s){const i=this.processMessages(e),n=i[i.length-1],o=(null==n?void 0:n[r])||" ",a={inputs:this._inputs,query:o,response_mode:this._mode,[u]:this._user};return this._conversationId&&(a.conversation_id=this._conversationId),s&&s.length>0&&(a[k]=s),a}async callServiceAPI(t,e,s){this.messages??(this.messages=t);let i=[];s&&s.length>0&&(i=await Ur(s,{url:this._uploadUrl,[u]:this._user,headers:this.connectSettings.headers})),this.callDirectServiceServiceAPI(t,e,(t,e)=>this.preprocessBody(t,e,i))}async extractResultData(t){const e=t=>{this._conversationId=t};return this._mode!==zr.BLOCKING||this.stream?async function(t,e){const s={fullAnswer:"",conversationIdSet:!1,errorMessage:""},i=(await t.text()).split(/\r?\n\r?\n/);for(const t of i){const i=Nr(t);i&&Hr(i,s,e)}return s.errorMessage?{[l]:s.errorMessage}:{[r]:s.fullAnswer}}(t,e):function(t,e){return t.conversation_id&&e(t.conversation_id),t.code&&t.message&&!t.answer?{[l]:t.message}:{[r]:t.answer||""}}(t,e)}}class Zr{static create(t){const{directConnection:e,connect:s,demo:i,webModel:n}=t;if(n)return new Vi(t);if(e){if(e.openAI)return e.openAI[M]?new Ko(t):e.openAI.speechToText?new uo(t):e.openAI.textToSpeech?new co(t):e.openAI.assistant?new Dn(t):e.openAI.realtime?new ao(t):e.openAI.completions?new jo(t):new Ho(t);if(e.assemblyAI)return new To(t);if(e.cohere)return new gr(t);if(e.huggingFace)return e.huggingFace.textGeneration?new cn(t):e.huggingFace.summarization?new un(t):e.huggingFace.translation?new mn(t):e.huggingFace.fillMask?new fn(t):e.huggingFace.questionAnswer?new hn(t):e.huggingFace.audioSpeechRecognition?new ln(t):e.huggingFace.audioClassification?new Qi(t):e.huggingFace.imageClassification?new Yi(t):new dn(t);if(e.azure){if(e.azure.openAI){if(e.azure.openAI.chat)return new Vo(t);if(e.azure.openAI.assistant)return new Gn(t)}if(e.azure.speechToText)return new Bo(t);if(e.azure.textToSpeech)return new Oo(t);if(e.azure.summarization)return new Mo(t);if(e.azure.translation)return new Ro(t)}if(e.stabilityAI)return e.stabilityAI.imageToImage?new pn(t):e.stabilityAI.imageToImageUpscale?new rn(t):e.stabilityAI.imageToImageMasking?new an(t):new vn(t);if(e.mistral)return new pr(t);if(e.gemini)return new wr(t);if(e.claude)return new _r(t);if(e.deepSeek)return new ar(t);if(e.miniMax)return new hr(t);if(e.openRouter)return new Qo(t);if(e.kimi)return new Lr(t);if(e.x)return e.x[M]?new $r(t):new qr(t);if(e.qwen)return new Br(t);if(e.together)return e.together[M]?new No(t):e.together.textToSpeech?new Mn(t):new Go(t);if(e.bigModel)return e.bigModel[M]?new Fo(t):e.bigModel.textToSpeech?new wn(t):new Wo(t);if(e.groq)return e.groq.textToSpeech?new Do(t):new mr(t);if(e.perplexity)return new er(t);if(e.ollama)return new Tr(t);if(e.openWebUI)return new nr(t);if(e.dify)return new Gr(t)}return s&&Object.keys(s).length>0&&!i?new $i(t):new $i(t,void 0,i||!0)}}const Kr=class{};Kr.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 Jr=Kr;function Xr(t){return function(e,s){Object.defineProperty(e,s,{});const i=e.constructor,n=s.toLocaleLowerCase();i._attributes_[n]=Jr.attibutes[t],i._attributeToProperty_[n]=s}}const Qr="submit-button",Yr="loading-button",ta="disabled-button",ea="text-input-container-start-adjustment",sa="text-input-container-end-adjustment",ia="text-input-container-start-small-adjustment",na="text-input-container-end-small-adjustment";class oa{constructor(t){this._isDisplayed=!1,this._elementRef=this.createIntroPanelWithChild(t),this._isDisplayed=!0}static createIntroPanel(){const i=s();return i[t].add("intro-panel"),Object.assign(i[e]),i}createIntroPanelWithChild(t){const s=oa.createIntroPanel();return"none"===t[e].display&&(t[e].display="block"),s.appendChild(t),s}hide(){this._isDisplayed&&(this._elementRef[e].display="none",this._isDisplayed=!1)}display(){this._isDisplayed||(this._elementRef[e].display="",this._isDisplayed=!0)}}const ra=class e{static createImage(t,e){const s=new Image;return s[y]=t[y],e&&Ys.scrollDownOnImageLoad(s[y],e),Ys.processContent(_,s,s[y],t.name)}static createImageMessage(s,i,n,o,r){const a=s.createNewMessageElement("",n,o),l=!o&&r?s.scrollToFirstElement.bind(s,n,r):void 0,c=e.createImage(i,l);return a.bubbleElement.appendChild(c),a.bubbleElement[t].add(e.IMAGE_BUBBLE_CLASS),{[w]:_,elements:a}}static createAudioElement(e,i){const n=s(T);return n[y]=e[y],n[t].add("audio-player"),n.controls=!0,Tt.IS_SAFARI&&(n[t].add("audio-player-safari"),n[t].add(i===u?"audio-player-safari-end":"audio-player-safari-start")),n}static autoPlayAudio(t){t.addEventListener("loadeddata",()=>{t.play().catch(t=>{console.warn("Auto-play failed:",t)})})}static createNewAudioMessage(s,i,n,o){const r=e.createAudioElement(i,n),a=s.createMessageElementsOnOrientation("",n,o);return a.bubbleElement.appendChild(r),a.bubbleElement[t].add(e.AUDIO_BUBBLE_CLASS),{[w]:T,elements:a,audioElement:r}}static createAnyFile(e){const i=s();i[t].add("any-file-message-contents");const n=s();n[t].add("any-file-message-icon-container");const o=Fi.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>');o[t].add("any-file-message-icon"),n.appendChild(o);const r=s();return r[t].add("any-file-message-text"),r.textContent=e.name||x,i.appendChild(n),i.appendChild(r),Ys.processContent(E,i,e[y],r.textContent)}static createNewAnyFileMessage(s,i,n,o){const r=s.createMessageElementsOnOrientation("",n,o),a=e.createAnyFile(i);return r.bubbleElement[t].add(e.ANY_FILE_BUBBLE_CLASS),r.bubbleElement.appendChild(a),{[w]:x,elements:r}}static createMessages(t,s,i,n,o=!1){return s.map((s,r)=>{var a;if(s.ref&&(s=Ys.removeFileRef(s)),Ys.isAudioFile(s)){const n=e.createNewAudioMessage(t,s,i,o),r=null==(a=t.textToSpeech)?void 0:a.audio;return r&&(r.autoPlay&&e.autoPlayAudio(n.audioElement),"boolean"==typeof r.displayAudio&&!r.displayAudio)?void 0:n}return Ys.isImageFile(s)?e.createImageMessage(t,s,i,o,n&&0===r):e.createNewAnyFileMessage(t,s,i,o)}).filter(t=>void 0!==t)}static addMessages(t,s,i,n,o){e.createMessages(t,s,i,n,o).filter(t=>void 0!==t).forEach(({[w]:e,elements:s})=>{Ys.addMessage(t,s,e,i,o)})}};ra.IMAGE_BUBBLE_CLASS="image-message",ra.AUDIO_BUBBLE_CLASS="audio-message",ra.ANY_FILE_BUBBLE_CLASS="any-file-message";let aa=ra;class la{static removeElements(t,e){if(!e)return;const s=t.findIndex(t=>t===e);t.splice(s,1),null==e||e.outerContainer.remove()}static removeFilesMessages(t,e){var s;null==(s=e[1][k])||s.forEach(e=>{la.removeElements(t.messageElementRefs,e)}),delete e[0][k],delete e[1][k]}static removeTextHTMLMessage(t,e,s){const i=e[1][s];la.removeElements(t.messageElementRefs,i),delete e[0][s],delete e[1][s]}static updateHTMLMessage(t,e,s){var i,n,o;if(e[1][a])ke.overwriteElements(t,s,e[1][a]);else{const l=ke.create(t,s,e[0][P]),c=(null==(n=e[1][k])?void 0:n[(null==(i=e[1][k])?void 0:i.length)-1])||e[1][r],{nextSibling:h}=c.outerContainer;null==(o=null==h?void 0:h.parentElement)||o.insertBefore(l.outerContainer,h),t.messageElementRefs.splice(t.messageElementRefs.length-1,1);const u=t.messageElementRefs.findIndex(t=>t===c);t.messageElementRefs.splice(u+1,0,l),e[1][a]=l}e[0][a]=s}static updateFileMessages(t,e,s){var i,n;const o=e[0][P],l=aa.createMessages(t,s,o,!1),c=e[1][a],h=(null==(n=e[1][k])?void 0:n[(null==(i=e[1][k])?void 0:i.length)-1])||e[1][r],u=c||h;let d=t.messageElementRefs.findIndex(t=>t===u);h&&(d+=1);const p=(null==c?void 0:c.outerContainer)||(null==h?void 0:h.outerContainer.nextSibling);l.forEach(({type:e,elements:s},i)=>{var n;Ys.setElementProps(t,s,e,o),null==(n=p.parentElement)||n.insertBefore(s.outerContainer,p),t.messageElementRefs.splice(t.messageElementRefs.length-1,1),t.messageElementRefs.splice(d+i,0,s)}),la.removeFilesMessages(t,e),e[1][k]=l.map(({elements:t})=>t),e[0][k]=s}static updateTextMessage(t,e,s){var i,n;if(e[1][r])t.renderText(e[1][r].bubbleElement,s,e[0][P]);else{const o=t.createElements(s,e[0][P]),l=(null==(i=e[1][k])?void 0:i[0])||e[1][a];null==(n=l.outerContainer.parentElement)||n.insertBefore(o.outerContainer,l.outerContainer);const c=t.messageElementRefs.findIndex(t=>t===l);t.messageElementRefs.splice(c,0,o),e[1][r]=o}e[0][r]=s}static isElementActive(e){var s,i;return ha.isActiveElement(null==(s=e[r])?void 0:s.bubbleElement[t])||ha.isActiveElement(null==(i=e[a])?void 0:i.bubbleElement[t])}static update(t,e,s){const i=t.messageToElements[s];if(i){if(la.isElementActive(i[1]))return console[l]("Cannot update a message that is being streamed");e[r]&&la.updateTextMessage(t,i,e[r]),e[k]?la.updateFileMessages(t,i,e[k]):la.removeFilesMessages(t,i),e[a]&&la.updateHTMLMessage(t,i,e[a]),!e[r]&&i[1][r]&&la.removeTextHTMLMessage(t,i,r),!e[a]&&i[1][a]&&la.removeTextHTMLMessage(t,i,a);const{messageElementRefs:s,avatar:n,name:o}=t;pi.classifyRoleMessages(s),pi.resetAllRoleElements(s,n,o)}else console[l]("Message index not found. Please use the `getMessages` method to find the correct index")}}class ca{static getText(t,e){var s,i;if(!(t.directConnection||t.connect||t.webModel||t.demo))return`Connect to any API using the [connect](${c}connect#connect-1) property or a popular service via [directConnection](${c}directConnection/#directConnection).\n Host AI entirely on your browser via a [webModel](${c}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](${c}modes#demo) property to true.`;if(t.directConnection){if(!e.isDirectConnection())return`Please define a valid service inside\n the [directConnection](${c}directConnection/#directConnection) object.`;const n=null==(s=t.directConnection.openAI)?void 0:s.chat;if("object"==typeof n&&null!=(i=n.tools)&&i.find(t=>"function"===t[w])&&!n.function_handler)return`Please define the \`function_handler\` property inside the openAI [chat](${c}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](${c}connect#connect-1) object.`;return null}}class ha extends di{constructor(t,e,s){var i,n;super(t);const{permittedErrorPrefixes:o,demo:r}=e;this._errorMessageOverrides=null==(i=t.errorMessages)?void 0:i.overrides,this._onClearMessages=ti.onClearMessages.bind(this,t),this._onError=ti.onError.bind(this,t),this._isLoadingMessageAllowed=ha.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(s),r&&this.prepareDemo(ce.processDemo(r),t.loadHistory),this.addIntroductoryMessages(t,e);const a=new Ei(t,this,e);this._displayServiceErrorMessages=null==(n=t.errorMessages)?void 0:n.displayServiceErrorMessages,t.getMessages=()=>pi.deepCloneMessagesWithReferences(this.messageToElements.map(([t])=>t)),t.clearMessages=this.clearMessages.bind(this,e),t.refreshMessages=this.refreshTextMessages.bind(this,t.remarkable),t.scrollToBottom=ne.scrollToBottom.bind(this,this),t.addMessage=(t,e)=>{this.addAnyMessage({...t,sendUpdate:!!e},!e)},t.updateMessage=(t,e)=>la.update(this,t,e),e.isWebModel()&&e.setUpMessages(this),t.textToSpeech&&re.processConfig(t.textToSpeech,t=>{this.textToSpeech=t}),this.elementRef.onscroll=async()=>{var e,s;t.loadHistory&&a.loadHistoryOnScroll(t.loadHistory),null==(e=this.scrollButton)||e.updateScroll(),null!=(s=this.browserStorage)&&s.trackScrollHeight&&this.browserStorage.addScrollHeight(this.elementRef.scrollTop)}}static getDefaultDisplayLoadingMessage(t,e){return("object"!=typeof t.displayLoadingBubble||!t.displayLoadingBubble.toggle)&&(e.websocket?typeof t.displayLoadingBubble!==Gt&&!!t.displayLoadingBubble:(typeof t.displayLoadingBubble===Gt||t.displayLoadingBubble)??!0)}setLoadingToggle(t){const e=this.messageElementRefs[this.messageElementRefs.length-1],s=di.isLoadingMessage(e);if(!t&&s)this.removeLastMessage(),delete this._activeLoadingConfig;else{if(this._activeLoadingConfig&&s){const s=we.getTargetWrapper(e.bubbleElement);if(s)return this._activeLoadingConfig=t||{},this.updateLoadingMessage(s);this.removeLastMessage()}this._activeLoadingConfig=t||{},this.addLoadingMessage(!0)}}prepareDemo(t,e){var s;if("object"==typeof t){if(!e&&t.displayLoading){const{history:e}=t.displayLoading;null!=e&&e.small&&si.addMessage(this,!1),null!=e&&e.full&&si.addMessage(this)}t.displayErrors&&(t.displayErrors[rt]&&this.addNewErrorMessage("",""),t.displayErrors.service&&this.addNewErrorMessage(o,""),t.displayErrors.speechToText&&this.addNewErrorMessage("speechToText","")),null!=(s=t.displayLoading)&&s.message&&this.addLoadingMessage(),t.response&&(this.customDemoResponse=t.response)}}addSetupMessageIfNeeded(t,e){const s=ca.getText(t,e);if(s){const t=this.createAndAppendNewMessageElement(s,h);this.applyCustomStyles(t,h,!1)}return!!s}addIntroductoryMessages(t,e){null!=t&&t.shadowRoot&&(this._introMessage=t.introMessage);let s=this._introMessage;null!=e&&e.isWebModel()&&(s??(s=e.getIntroMessage(s)));const i=!(null!=t&&t.history||!(null!=t&&t.loadHistory||null!=e&&e.fetchHistory));s&&(Array.isArray(s)?s.forEach((t,e)=>{if(0!==e){const t=this.messageElementRefs[this.messageElementRefs.length-1].innerContainer;pi.hideRoleElements(t,this.avatar,this.name)}this.addIntroductoryMessage(t,i)}):this.addIntroductoryMessage(s,i))}addIntroductoryMessage(s,i){var n;let o;return null!=s&&s[r]?o=this.createAndAppendNewMessageElement(s[r],h):null!=s&&s[a]&&(o=ke.add(this,s[a],h)),o&&(this.applyCustomStyles(o,h,!1,null==(n=this.messageStyles)?void 0:n.intro),o.outerContainer[t].add(di.INTRO_CLASS),i&&(o.outerContainer[e].display="none")),o}removeIntroductoryMessage(){const e=this.messageElementRefs[0];e.outerContainer[t].contains(di.INTRO_CLASS)&&(e.outerContainer.remove(),this.messageElementRefs.shift())}addAnyMessage(t,e=!1,s=!1){return t[l]?this.addNewErrorMessage(o,t[l],s):this.addNewMessage(t,e,s)}tryAddTextMessage(t,e,s,i=!1,n=!1){void 0!==t[r]&&null!==s[r]&&(this.addNewTextMessage(t[r],t[P],e,n),!i&&this.textToSpeech&&t[P]!==u&&re.speak(t[r],this.textToSpeech))}tryAddFileMessages(t,e,s=!1){t[k]&&Array.isArray(t[k])&&aa.addMessages(this,t[k],t[P],e,s)}tryAddHTMLMessage(t,e,s=!1){if(void 0!==t[a]&&null!==t[a]){const i=ke.add(this,t[a],t[P],e,s);!s&&ye.isElementTemporary(i)&&delete t[a]}}addNewMessage(t,e=!1,s=!1){var i,n,o,a;t[P]!==u&&(null==(i=this._hiddenAttachments)||i.removeHiddenFiles());const l=ha.createMessageContent(t),c=null==(o=null==(n=this.textToSpeech)?void 0:n.audio)?void 0:o.displayText;"boolean"==typeof c&&!c&&delete l[r];const h=ne.isScrollbarAtBottomOfElement(this.elementRef),d={status:t.overwrite};return s?(this.tryAddFileMessages(l,h,s),this.tryAddHTMLMessage(l,d,s),this.tryAddTextMessage(l,d,t,e,s)):(this.tryAddTextMessage(l,d,t,e,s),this.tryAddHTMLMessage(l,d,s),this.tryAddFileMessages(l,h,s)),this.isValidMessageContent(l)&&!s&&(this.updateStateOnMessage(l,t.overwrite,t.sendUpdate,e),d.status||setTimeout(()=>this.scrollToFirstElement(l[P],h)),e||null==(a=this.browserStorage)||a.addMessages(this.messageToElements.map(([t])=>t)),this.scrollButton&&l[P]!==u&&this.tryUpdateHiddenMessageCount(e,t)),this._activeLoadingConfig&&this.addLoadingMessage(!1),l}tryUpdateHiddenMessageCount(t,e){(!t||void 0!==e.sendUpdate)&&setTimeout(()=>{var t,e;return null==(e=null==(t=this.scrollButton)?void 0:t.updateHidden)?void 0:e.call(t)})}isValidMessageContent(t){return t[r]||t[a]||t[k]&&t[k].length>0}updateStateOnMessage(t,e,s=!0,i=!1){if(!e){const e=pi.generateMessageBody(t,this.messageElementRefs);this.messageToElements.push([t,e])}s&&this.sendClientUpdate(t,i)}removeMessageOnError(){const e=this.messageElementRefs[this.messageElementRefs.length-1],s=null==e?void 0:e.bubbleElement;(null!=s&&s[t].contains(vi.MESSAGE_CLASS)&&""===s.textContent||ha.isTemporaryElement(e))&&this.removeLastMessage()}addNewErrorMessage(e,s,i=!1){var n,o,r,a,c,h;null==(n=this._hiddenAttachments)||n.readdHiddenFiles(),this.removeMessageOnError();const u=this.getPermittedMessage(s)||(null==(o=this._errorMessageOverrides)?void 0:o[e])||(null==(r=this._errorMessageOverrides)?void 0:r[rt])||"Error, please try again.",d=this.createMessageElementsOnOrientation(u,l,i);pi.hideRoleElements(d.innerContainer,this.avatar,this.name);const{bubbleElement:m,outerContainer:v}=d;m[t].add(p),this.renderText(m,u);const f=Qs.extractParticularSharedStyles(["fontSize","fontFamily"],null==(a=this.messageStyles)?void 0:a[rt]);Qs.applyCustomStylesToElements(d,!1,f),Qs.applyCustomStylesToElements(d,!1,null==(c=this.messageStyles)?void 0:c[l]),i||this.appendOuterContainerElemet(v),this.textToSpeech&&re.speak(u,this.textToSpeech),null==(h=this._onError)||h.call(this,u),setTimeout(()=>ne.scrollToBottom(this))}static checkPermittedErrorPrefixes(t,e){for(let s=0;s<t.length;s+=1)if(e.startsWith(t[s]))return e}static extractErrorMessages(t){return Array.isArray(t)?t:t instanceof Error?[t.message]:"string"==typeof t?[t]:"object"==typeof t&&t[l]?[t[l]]:[]}getPermittedMessage(t){if(t){const e=ha.extractErrorMessages(t);for(let t=0;t<e.length;t+=1){const s=e[t];if(typeof s===B){if(this._displayServiceErrorMessages)return s;if(this._permittedErrorPrefixes){const t=ha.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,s);if(t)return t}}}}}removeError(){this.isLastMessageError()&&pi.getLastMessageElement(this.elementRef).remove()}addDefaultLoadingMessage(e,i=h){const n=this.createMessageElements("",i),{bubbleElement:o}=n;n.bubbleElement[t].add(le.DOTS_CONTAINER_CLASS);const r=s();return r[t].add("loading-message-dots"),o.appendChild(r),le.setDots(o,e),n}addLoadingMessage(s=!1){var i,n,o,r,l,c;if(di.isLoadingMessage(this.messageElementRefs[this.messageElementRefs.length-1])||!this._activeLoadingConfig&&!s&&!this._isLoadingMessageAllowed)return;const u=(null==(i=this._activeLoadingConfig)?void 0:i[P])||h,d=(null==(n=this._activeLoadingConfig)?void 0:n[e])||(null==(r=null==(o=this.messageStyles)?void 0:o.loading)?void 0:r.message),p=null==d?void 0:d[a],m=p?ke.createElements(this,p,u,!1):this.addDefaultLoadingMessage(d,u);this.appendOuterContainerElemet(m.outerContainer),m.bubbleElement[t].add(le.BUBBLE_CLASS),this.applyCustomStyles(m,u,!1,null==d?void 0:d[pt]),null==(c=null==(l=this.avatar)?void 0:l.getAvatarContainer(m.innerContainer))||c[t].add("loading-avatar-container"),!this.focusMode&&ne.isScrollbarAtBottomOfElement(this.elementRef)&&ne.scrollToBottom(this)}updateLoadingMessage(t){var s;const i=null==(s=this._activeLoadingConfig)?void 0:s[e],n=null==i?void 0:i[a];t.innerHTML=n||""}populateIntroPanel(t){t&&(this._introPanel=new oa(t),we.apply(this,this._introPanel._elementRef),this.elementRef.appendChild(this._introPanel._elementRef))}async addMultipleFiles(t,e){return this._hiddenAttachments=e,Promise.all((t||[]).map(t=>new Promise(e=>{if(t[w]&&t[w]!==E){const s=new FileReader;s.readAsDataURL(t[x]),s.onload=()=>{const i=t[x].name;e({[y]:s.result,name:i,[w]:t[w],ref:t[x]})}}else{const s=t[x].name||x;e({name:s,[w]:E,ref:t[x]})}})))}static isActiveElement(t){return!!t&&(t.contains(le.BUBBLE_CLASS)||t.contains(si.CLASS)||t.contains(vi.MESSAGE_CLASS))}clearMessages(e,s){var i,n,o,l;const c=[];this.messageElementRefs.forEach(e=>{ha.isActiveElement(e.bubbleElement[t])?c.push(e):e.outerContainer.remove()}),Array.from(this.elementRef.children).forEach(e=>{var s;const i=null==(s=e.children[0])?void 0:s.children[0];null!=i&&i[t].contains(p)&&e.remove()}),this.messageElementRefs=c;const h=this.messageToElements.filter(e=>e[1][r]&&ha.isActiveElement(e[1][r].bubbleElement[t])||e[1][a]&&ha.isActiveElement(e[1][a].bubbleElement[t]));this.messageToElements.splice(0,this.messageToElements.length,...h),!1!==s&&(null!=(i=this._introPanel)&&i._elementRef&&this._introPanel.display(),this.addIntroductoryMessages()),null==(n=this.browserStorage)||n.clear(),null==(o=this.scrollButton)||o.clearHidden(),null==(l=this._onClearMessages)||l.call(this),delete e.sessionId}}class ua{static adjustInputPadding(e,s){s[et].length>0&&e[t].add("text-input-inner-start-adjustment"),s[st].length>0&&e[t].add("text-input-inner-end-adjustment")}static adjustForOutsideButton(e,s,i){0===i[nt].length&&i[it].length>0?(e[0][t].add(ia),s[t].add(ia)):0===i[it].length&&i[nt].length>0&&(e[3][t].add(na),s[t].add(na))}static adjustOutsideSubmit(e,s,i){if(!(i[et].length>0||i[st].length>0)){if(0===i[nt].length&&i[it].length>0)return e[0][t].add(ea),s[t].add(ea),i[it].map(e=>e.button.elementRef[t].add("submit-button-enlarged"));if(0===i[it].length&&i[nt].length>0)return e[3][t].add(sa),s[t].add(sa),i[nt].map(e=>e.button.elementRef[t].add("submit-button-enlarged"))}}static set(t,e,s,i){!!ua.adjustOutsideSubmit(e,s,i)||ua.adjustForOutsideButton(e,s,i),ua.adjustInputPadding(t,i)}}class da{static create(){return Array.from({length:4}).map((e,i)=>{const n=s();return n[t].add("input-button-container"),(0===i||3===i)&&n[t].add("outer-button-container"),(1===i||2===i)&&n[t].add("inner-button-container"),n})}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 t===it?0:t===et?1:t===st?2:3}static addButton(e,s,i){s[t].add(i);const n=da.getContainerIndex(i);e[n].appendChild(s),3===n&&s[t].add(nt)}}const pa=["camera","gifs","images","audio","mixedFiles",ft,"microphone"],ma=class i{static addHighlightEvents(t,e){e.addEventListener(mt,e=>{t.highlightedItem=e.target}),e.addEventListener(vt,()=>{t.highlightedItem=void 0})}static addItemEvents(t,e,s,n){fe.add(e,n),e.addEventListener(lt,()=>{s[lt]()}),i.addHighlightEvents(t,e)}static createItemText(n,o){const r=s();return Object.assign(r[e],o),r[t].add(i.TEXT_CLASS),r.textContent=n||"File",r}static createItemIcon(n,o){const r=s();return Object.assign(r[e],o),r[t].add(i.ICON_CLASS),r.appendChild(n),r}static populateItem(e,s,n){const{elementRef:o,dropupText:a,svg:l,customStyles:c}=e,h=o.children[0],u=c&&Object.values(c).find(t=>{var e;return""===(null==(e=t[ut])?void 0:e.content)});h[t].contains(Xn.INPUT_BUTTON_INNER_TEXT_CLASS)?(u||s.appendChild(i.createItemIcon(l,null==n?void 0:n.iconContainer)),s.appendChild(i.createItemText(h.textContent,null==n?void 0:n[r]))):(u||s.appendChild(i.createItemIcon(o.children[0],null==n?void 0:n.iconContainer)),s.appendChild(i.createItemText(a,null==n?void 0:n[r])))}static createItem(n,o,r){var a;const l=s();Object.assign(l[e],null==(a=null==r?void 0:r.item)?void 0:a[rt]),i.populateItem(o,l,r),l[t].add(i.MENU_ITEM_CLASS),l.tabIndex=0;const{elementRef:c}=o;if(o.isCustom)o.setDropupItem(n,l);else{const t=yt.processStateful((null==r?void 0:r.item)||{});i.addItemEvents(n,l,c,t)}return l}};ma.MENU_ITEM_CLASS="dropup-menu-item",ma.CUSTOM_BUTTON_ITEM_CLASS="dropup-menu-item-custom-button",ma.TEXT_CLASS="dropup-menu-item-text",ma.ICON_CLASS="dropup-menu-item-icon";let va=ma;const fa=class i extends to{constructor(t,e,s,n){var o,a,l,c,h,u;const d=(null==(c=null==(l=null==(a=null==(o=null==t?void 0:t[pt])?void 0:o.button)?void 0:a[rt])?void 0:l[r])?void 0:c.content)||`Custom ${e}`,p=Ct.tryCreateConfig(`Custom ${e}`,null==t?void 0:t.tooltip);super(i.createButtonElement(),'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 22" fill="none">\n <rect x="2.5" y="2.5" width="17" height="17" rx="2" stroke="#000000" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>\n',null==t?void 0:t.position,p,(null==(h=null==t?void 0:t[pt])?void 0:h.button)||p&&{},d),this._state=rt,this.isCustom=!0,this._innerElements=this.createInnerElementsForStates(this.customStyles),this._menuStyles=n,this._onClick=t.onClick,this._dropupStyles=null==(u=t[pt])?void 0:u.dropup,this.setSetState(t),this.addClickListener(s),this.changeState(t.initialState,!0)}static createButtonElement(){const e=s();return e[t].add("input-button",i.BUTTON_CLASS),e}createInnerElementsForStates(t){const e="custom-icon",s=this.createInnerElements(e,rt,t);return{[rt]:s,[ct]:this.genStateInnerElements(e,ct,s,t),[ht]:this.genStateInnerElements(e,ht,s,t)}}setSetState(t){t.setState=t=>{t===rt&&this.changeToDefault(),t===ct&&this.changeToActive(),t===ht&&this.changeToDisabled()}}addClickListener(t){ne.assignButtonEvents(this.elementRef,()=>{var e;const s=null==(e=this._onClick)?void 0:e.call(this,this._state);null==t||t(),(s===rt||s===ct||s===ht)&&this.changeState(s)})}changeState(t,e){t===ht?this.changeToDisabled(e):t===ct?this.changeToActive(e):this.changeToDefault(e)}applyDropupContentStyles(s){const i=Array.from(this.elementRef.children);if(null!=s&&s[r]){const n=i.find(e=>e[t].contains(va.TEXT_CLASS));n&&Object.assign(n[e],s[r])}if(null!=s&&s.iconContainer){const n=i.find(e=>e[t].contains(va.ICON_CLASS));n&&Object.assign(n[e],s.iconContainer)}}resetDropupItem(t){var e,s,i;this.elementRef=we.replaceElementWithNewClone(this.elementRef,this._originalElementRef),this.elementRef.innerHTML="",""===(null==(e=null==t?void 0:t[ut])?void 0:e.content)||this.elementRef.appendChild(va.createItemIcon(this[ut],null==(s=this._menuStyles)?void 0:s.iconContainer)),this.elementRef.appendChild(va.createItemText(this.dropupText,null==(i=this._menuStyles)?void 0:i[r]))}assignDropupItemStyle(t,s){var i;this.elementRef.parentElement&&this._originalElementRef&&this.resetDropupItem(s),va.addHighlightEvents(this._menu,this.elementRef),this.applyDropupContentStyles(t),Object.assign(this.elementRef[e],null==(i=null==t?void 0:t.item)?void 0:i[rt]);const n=yt.processStateful((null==t?void 0:t.item)||{});fe.add(this.elementRef,n),this.addClickListener()}changeToDefault(e){var s,n,o,r,a,l;!e&&this._state===rt||(this.elementRef[t].contains(va.MENU_ITEM_CLASS)?this.assignDropupItemStyle(null==(s=this._dropupStyles)?void 0:s[rt],null==(n=this.customStyles)?void 0:n[rt]):(this.changeElementsByState(this._innerElements[rt]),null!=(o=this.customStyles)&&o[ct]&&Yn.unsetAllCSS(this.elementRef,null==(r=this.customStyles)?void 0:r[ct]),null!=(a=this.customStyles)&&a[ht]&&Yn.unsetAllCSS(this.elementRef,null==(l=this.customStyles)?void 0:l[ht]),this.reapplyStateStyle(rt,[ct,ht])),this.elementRef[t].remove(i.DISABLED_CONTAINER_CLASS,i.ACTIVE_CONTAINER_CLASS),this.elementRef[t].add(i.DEFAULT_CONTAINER_CLASS),Zn.removeAriaDisabled(this.elementRef),this._state=rt)}changeToActive(e){var s,n;!e&&this._state===ct||(this.elementRef[t].contains(va.MENU_ITEM_CLASS)?this.assignDropupItemStyle(null==(s=this._dropupStyles)?void 0:s[ct],null==(n=this.customStyles)?void 0:n[ct]):(this.changeElementsByState(this._innerElements[ct]),this.reapplyStateStyle(ct,[ht,rt])),this.elementRef[t].remove(i.DISABLED_CONTAINER_CLASS,i.DEFAULT_CONTAINER_CLASS),this.elementRef[t].add(i.ACTIVE_CONTAINER_CLASS),Zn.removeAriaDisabled(this.elementRef),this._state=ct)}changeToDisabled(e){var s,n,o,r,a,l;!e&&this._state===ht||(this.elementRef[t].contains(va.MENU_ITEM_CLASS)?this.assignDropupItemStyle(null==(s=this._dropupStyles)?void 0:s[ht],null==(n=this.customStyles)?void 0:n[ht]):(this.changeElementsByState(this._innerElements[ht]),null!=(o=this.customStyles)&&o[ct]&&Yn.unsetAllCSS(this.elementRef,null==(r=this.customStyles)?void 0:r[ct]),null!=(a=this.customStyles)&&a[rt]&&Yn.unsetAllCSS(this.elementRef,null==(l=this.customStyles)?void 0:l[rt]),this.reapplyStateStyle(ht,[rt,ct])),this.elementRef[t].remove(i.ACTIVE_CONTAINER_CLASS,i.DEFAULT_CONTAINER_CLASS),this.elementRef[t].add(i.DISABLED_CONTAINER_CLASS),Zn.addAriaDisabled(this.elementRef),this._state=ht)}setDropupItem(t,e){this._menu=t,this.elementRef=e,this._originalElementRef=e.cloneNode(!0),this.changeState(this._state,!0)}genStateInnerElements(t,e,s,n){var o,a,l,c;let h=this.createInnerElements(t,e,n);const u=null==(a=null==(o=null==n?void 0:n[e])?void 0:o[ut])?void 0:a.content,d=null==(c=null==(l=null==n?void 0:n[e])?void 0:l[r])?void 0:c.content;if(void 0===u||void 0===d){const{svg:t,[r]:e}=Qn.parseSVGTextElements(s),{svg:n,[r]:o}=Qn.parseSVGTextElements(h),a=[];i.addToInnerElements(a,u,t,n),i.addToInnerElements(a,d,e,o),h=a}return h}static addToInnerElements(t,e,s,i){void 0===e&&s?t.push(s.cloneNode(!0)):i&&t.push(i)}static add(t,e){const{customButtons:s,focusInput:n,dropupStyles:o}=t;null==s||s.forEach((t,s)=>{const r={button:new i(t,s+1,n,null==o?void 0:o.menu)};e[`${i.INDICATOR_PREFIX}${s+1}`]=r})}};fa.INDICATOR_PREFIX="custom",fa.BUTTON_CLASS="custom-button",fa.DISABLED_CONTAINER_CLASS="custom-button-container-disabled",fa.DEFAULT_CONTAINER_CLASS="custom-button-container-default",fa.ACTIVE_CONTAINER_CLASS="custom-button-container-active";let ga=fa;class ba{static focusItemWhenOnEdge(t,e){const s=t.elementRef,i=e?s.children[0]:s.children[s.children.length-1];ba.focusSiblingItem(t,i,e,!0)}static focusSiblingItem(t,e,s,i=!1){const n=i?e:e[s?"nextSibling":"previousSibling"];n?(e.dispatchEvent(new MouseEvent(vt)),n.dispatchEvent(new MouseEvent(mt)),n.focus()):(e.dispatchEvent(new MouseEvent(vt)),ba.focusItemWhenOnEdge(t,s))}}class ya{constructor(t,e){var s;this._isOpen=!0,this._styles=e,this.elementRef=ya.createElement(null==(s=this._styles)?void 0:s.container),this.close(),setTimeout(()=>this.addWindowEvents(t))}static createElement(t){const i=s();return i.id=ot,Object.assign(i[e],t),i}open(){this.elementRef[e].display="block",this._isOpen=!0}close(){this._isOpen&&(this.elementRef[e].display="none",this._isOpen=!1)}toggle(){this._isOpen?this.close():this.open()}addItem(t){const e=va.createItem(this,t,this._styles);this.elementRef.appendChild(e)}addWindowEvents(t){this.clickEvent=this.windowClick.bind(this,t),window.addEventListener(lt,this.clickEvent),this.keyDownEvent=this.windowKeyDown.bind(this,t),window.addEventListener("keydown",this.keyDownEvent)}windowClick(t,e){var s;!t.isConnected&&this.clickEvent?window.removeEventListener(lt,this.clickEvent):t.parentElement!==(null==(s=e.target.shadowRoot)?void 0:s.children[0])&&this.close()}windowKeyDown(t,e){var s,i,n;!t.isConnected&&this.keyDownEvent?window.removeEventListener("keydown",this.keyDownEvent):this._isOpen&&(e.key===St.ESCAPE?(this.close(),null==(s=this.highlightedItem)||s.dispatchEvent(new MouseEvent(vt))):e.key===St.ENTER?(null==(i=this.highlightedItem)||i[lt](),null==(n=this.highlightedItem)||n.dispatchEvent(new MouseEvent(vt))):e.key===St.ARROW_DOWN?ba.focusSiblingItem(this,this.highlightedItem||this.elementRef.children[this.elementRef.children.length-1],!0):e.key===St.ARROW_UP&&ba.focusSiblingItem(this,this.highlightedItem||this.elementRef.children[0],!1))}}const wa=class e extends to{constructor(s,i){var n,o;const r=Ct.tryCreateConfig("Options",null==(n=null==i?void 0:i.button)?void 0:n.tooltip);super(e.createButtonElement(),'<?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>',void 0,r,{[pt]:null==(o=null==i?void 0:i.button)?void 0:o[pt]});const a=this.createInnerElementsForStates(this.customStyles);this._menu=new ya(s,null==i?void 0:i.menu),this.addClickEvent(),this.buttonContainer=e.createButtonContainer(),this.changeElementsByState(a[pt]),this.buttonContainer.appendChild(this.elementRef),this.elementRef[t].add(e.BUTTON_ICON_CLASS),this.buttonContainer.appendChild(this._menu.elementRef),this.reapplyStateStyle(pt),this.addContainerEvents(s)}static createButtonElement(){const e=s();return e[t].add("input-button"),e}createInnerElementsForStates(t){return{[pt]:this.createInnerElements("dropup-icon",pt,t)}}addClickEvent(){this.elementRef.onclick=this._menu.toggle.bind(this._menu),this.elementRef.onkeydown=t=>{t.key===St.ENTER&&setTimeout(()=>{this._menu.toggle();const t=this._menu.elementRef.children[0];t.focus(),t.dispatchEvent(new MouseEvent(mt))})}}static createButtonContainer(){const t=s();return t.id="dropup-container",t}addItem(t){this._menu.addItem(t)}addContainerEvents(s){s.addEventListener(lt,s=>{const i=s.target[t];!i.contains(e.BUTTON_ICON_CLASS)&&!i.contains(ga.DISABLED_CONTAINER_CLASS)&&this._menu.close()})}static getPosition(t,e){var s,i;return null!=(s=null==e?void 0:e.button)&&s.position?ce.processPosition(null==(i=null==e?void 0:e.button)?void 0:i.position):t[it].length>0&&0===t[nt].length?nt:it}};wa.BUTTON_ICON_CLASS="dropup-button";let xa=wa;class ka{static addToDropup(t,e,s,i){const n=new xa(s,i);pa.forEach(t=>{const s=e[ot].findIndex(e=>e.buttonType===t),i=e[ot][s];i&&(n.addItem(i.button),e[ot].splice(s,1))}),e[ot].forEach(({button:t})=>n.addItem(t));const o=xa.getPosition(e,i);da.addButton(t,n.buttonContainer,o),e[o].push({})}static addToSideContainer(t,e){[et,st,it,nt].forEach(s=>{const i=s;e[i].forEach(e=>{da.addButton(t,e.button.elementRef,i)})})}static setPosition(t,e,s){const i={...t[e],buttonType:e};s.push(i),delete t[e]}static createPositionsToButtonsObj(){return{[ot]:[],[it]:[],[et]:[],[st]:[],[nt]:[]}}static generatePositionToButtons(t){const e=ka.createPositionsToButtonsObj();Object.keys(t).forEach(s=>{var i;const n=null==(i=t[s])?void 0:i.button.position;n&&ka.setPosition(t,s,e[n])}),0===e[st].length&&t.submit&&ka.setPosition(t,ft,e[st]),0===e[nt].length&&(t.submit?ka.setPosition(t,ft,e[nt]):t.microphone?ka.setPosition(t,S,e[nt]):t.camera?ka.setPosition(t,C,e[nt]):t[`${ga.INDICATOR_PREFIX}1`]&&ka.setPosition(t,`${ga.INDICATOR_PREFIX}1`,e[nt])),t.submit&&ka.setPosition(t,ft,0===e[it].length?e[it]:e[st]),t.microphone&&ka.setPosition(t,S,0===e[it].length?e[it]:e[st]);const s=Object.keys(t);return s.length>1||e[ot].length>0?(pa.forEach(s=>{t[s]&&e[ot].push({...t[s],buttonType:s})}),s.forEach(s=>{const i=s;i.startsWith(ga.INDICATOR_PREFIX)&&t[i]&&e[ot].push({...t[i],customType:i})})):1===s.length&&ka.setPosition(t,s[0],0===e[nt].length?e[nt]:e[it]),e}static addButtons(t,e,s,i){const n=ka.generatePositionToButtons(e);return ka.addToSideContainer(t,n),n[ot].length>0&&ka.addToDropup(t,n,s,i),n}}const _a={[M]:{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"},[A]:{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"},[T]:{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<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 Ma extends to{constructor(t){(null==t?void 0:t.position)===ot&&(t.position=nt);const e=Ct.tryCreateConfig("Microphone",null==t?void 0:t.tooltip);super(Ma.createMicrophoneElement(),Kn,null==t?void 0:t.position,e,t),this.isActive=!1,this._innerElements=this.createInnerElementsForStates(this.customStyles),this.changeToDefault()}createInnerElementsForStates(t){const e="microphone-icon";return{[rt]:this.createInnerElements(e,rt,t),[ct]:this.createInnerElements(e,ct,t),unsupported:this.createInnerElements(e,"unsupported",t),commandMode:this.createInnerElements(e,"commandMode",t)}}static createMicrophoneElement(){const e=s();return e.id="microphone-button",e[t].add("input-button"),e}changeToActive(){this.changeElementsByState(this._innerElements[ct]),this.toggleIconFilter(ct),this.reapplyStateStyle(ct,[rt,"commandMode"]),this.isActive=!0}changeToDefault(){this.changeElementsByState(this._innerElements[rt]),this.toggleIconFilter(rt),this.reapplyStateStyle(rt,[ct,"commandMode"]),this.isActive=!1}changeToCommandMode(){this.changeElementsByState(this._innerElements.commandMode),this.toggleIconFilter("command"),this.reapplyStateStyle("commandMode",[ct])}changeToUnsupported(){this.changeElementsByState(this._innerElements.unsupported),this.elementRef[t].add("unsupported-microphone"),this.reapplyStateStyle("unsupported",[ct])}toggleIconFilter(e){const s=this.elementRef.children[0];if(s.tagName.toLocaleLowerCase()===ut)switch(e){case rt:s[t].remove("active-microphone-icon","command-microphone-icon"),s[t].add("default-microphone-icon");break;case ct:s[t].remove("default-microphone-icon","command-microphone-icon"),s[t].add("active-microphone-icon");break;case"command":s[t].remove("active-microphone-icon","default-microphone-icon"),s[t].add("command-microphone-icon")}}}function Ca(t){return t&&t.h&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Aa,Ta,Sa,ja={},Ea={},Ia={},$a={},Oa={};function Pa(){if(Aa)return Oa;Aa=1,Object.defineProperty(Oa,"h",{value:!0}),Oa.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 Oa.Text=t,t.FIRST_CHAR_REGEX=/\S/,t.DOUBLE_LINE=/\n\n/g,t.ONE_LINE=/\n/g,Oa}function Ba(){if(Ta)return $a;Ta=1,Object.defineProperty($a,"h",{value:!0}),$a.Translate=void 0;const t=Pa();return $a.Translate=class{static translate(e,s){const i=t.Text.breakupIntoWordsArr(e);for(let t=0;t<i.length;t+=1)s[i[t]]&&(i[t]=s[i[t]]);return i.join("")}},$a}var Ra,Fa={};function La(){if(Ra)return Fa;Ra=1,Object.defineProperty(Fa,"h",{value:!0}),Fa.Browser=void 0;class t{}return Fa.Browser=t,t.IS_SAFARI=()=>(void 0===t._IS_SAFARI&&(t._IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),t._IS_SAFARI),Fa}var qa,za={},Da={};var Na,Ua={};var Ha,Va={},Wa={};function Ga(){if(Ha)return Wa;Ha=1,Object.defineProperty(Wa,"h",{value:!0}),Wa.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,s){return e&&t.isElementOverflown(s)}}return Wa.AutoScroll=t,Wa}var Za,Ka={};function Ja(){if(Za)return Ka;Za=1,Object.defineProperty(Ka,"h",{value:!0}),Ka.Elements=void 0;return Ka.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 s=e.getRangeAt(0);return s.insertNode(t.scrollingSpan),s.insertNode(t.interimSpan),s.insertNode(t.finalSpan),s.collapse(!1),e.removeAllRanges(),void e.addRange(s)}}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}},Ka}var Xa,Qa,Ya={};function tl(){if(Xa)return Ya;Xa=1,Object.defineProperty(Ya,"h",{value:!0}),Ya.Cursor=void 0;class t{static setOffsetForGeneric(e,s,i=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,s,i);if(-1===e)return-1;i+=e}else if(null!==r.textContent){if(i+r.textContent.length>s){const t=document.createRange();t.setStart(r,s-i),t.collapse(!0);const n=window.getSelection();return null==n||n.removeAllRanges(),null==n||n.addRange(t),e.focus(),-1}i+=r.textContent.length,n+=r.textContent.length}}return n}static focusEndOfGeneric(t){const e=document.createRange();e.selectNodeContents(t),e.collapse(!1);const s=window.getSelection();s&&(s.removeAllRanges(),s.addRange(e))}static setOffsetForSafariGeneric(e,s){const i=window.getSelection();if(i){const n=t.getGenericElementCursorOffset(e,i,!0);t.setOffsetForGeneric(e,n+s)}}static setOffsetForPrimitive(t,e,s){s&&t.blur(),t.setSelectionRange(e,e),t.focus()}static getGenericElementCursorOffset(t,e,s){let i=0;if(e.rangeCount>0){const n=e.getRangeAt(0),o=n.cloneRange();o.selectNodeContents(t),s?o.setEnd(n.startContainer,n.startOffset):o.setEnd(n.endContainer,n.endOffset),i=o.toString().length}return i}}return Ya.Cursor=t,Ya}function el(){if(Qa)return Va;Qa=1,Object.defineProperty(Va,"h",{value:!0}),Va.CommandUtils=void 0;const t=Ga(),e=Ja(),s=La(),i=tl(),n=Pa();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,s)=>{const i=t[s];return e[s]="string"==typeof i?o.processCommand(i,t.settings):i,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||i.Cursor.setOffsetForPrimitive(l,a.length,!0),s.Browser.IS_SAFARI()&&n.autoScroll&&t.AutoScroll.scrollSafariPrimitiveToEnd(l)):(l.textContent=a,n.isTargetInShadow||i.Cursor.focusEndOfGeneric(l),setTimeout(()=>t.AutoScroll.scrollGeneric(n,l))),n.resetRecording(r)}static checkIfMatchesSubstring(t,e){return e.includes(t)}static checkIfMatchesWord(t,e,s){const i=t;for(let t=s.length-1;t>=0;t-=1){let e=t,n=i.length-1;for(;s[e]===i[n]&&n>=0;)e-=1,n-=1;if(n<0)return!0}return!1}static execCommand(t,e,s,i,r){var a,l,c;const h=t.commands;if(!h||!i||!s)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(s),{doNotProcessTranscription:!0};if(h.reset&&p(h.reset,u,d))return void 0!==r&&o.setText(t,s,r,i),{doNotProcessTranscription:!0};if(h.removeAllText&&p(h.removeAllText,u,d))return o.setText(t,s,"",i),{doNotProcessTranscription:!0}}}}return Va.CommandUtils=o,Va}var sl,il={};var nl,ol,rl,al={};function ll(){if(ol)return za;ol=1,Object.defineProperty(za,"h",{value:!0}),za.Speech=void 0;const t=function(){if(qa)return Da;qa=1,Object.defineProperty(Da,"h",{value:!0}),Da.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,s){this.mouseDownElement=t.getElementIfFocusedOnAvailable(e,s.target)}static mouseUpWindow(t){this.mouseDownElement&&this.resetRecording(t),this.mouseDownElement=void 0}static add(e,s){const i=void 0===(null==s?void 0:s.insertInCursorLocation)||(null==s?void 0:s.insertInCursorLocation);null!=s&&s.element&&i&&(e.mouseDownEvent=t.mouseDownWindow.bind(e,s.element),document.addEventListener("mousedown",e.mouseDownEvent),e.mouseUpEvent=t.mouseUpWindow.bind(e,s),document.addEventListener("mouseup",e.mouseUpEvent),e.keyDownEvent=t.keyDownWindow.bind(e,s),document.addEventListener("keydown",e.keyDownEvent))}static remove(t){document.removeEventListener("mousedown",t.mouseDownEvent),document.removeEventListener("mouseup",t.mouseUpEvent),document.removeEventListener("keydown",t.keyDownEvent)}}return Da.EventListeners=t,t.KEY_DOWN_TIMEOUT=null,Da}(),e=(Na||(Na=1,Object.defineProperty(Ua,"h",{value:!0}),Ua.PreResultUtils=void 0,Ua.PreResultUtils=class{static process(t,e,s,i,n){const o=null==i?void 0:i(e,s);return!!o&&(setTimeout(()=>{o.restart?t.resetRecording(n):o.stop&&t.stop()}),(o.stop||o.restart)&&o.removeNewText)}}),Ua),s=el(),i=Ga(),n=function(){if(sl)return il;sl=1,Object.defineProperty(il,"h",{value:!0}),il.Highlight=void 0;const t=Ja(),e=tl();class s{static setStateForPrimitive(t,e){let s,i;null!==e.selectionStart&&(s=e.selectionStart),null!==e.selectionEnd&&(i=e.selectionEnd),t.isHighlighted=s!==i}static setStateForGeneric(t,s){const i=window.getSelection();if(null!=i&&i.focusNode){const n=e.Cursor.getGenericElementCursorOffset(s,i,!0),o=e.Cursor.getGenericElementCursorOffset(s,i,!1);t.isHighlighted=n!==o}}static setState(e,i){document.activeElement===i&&(t.Elements.isPrimitiveElement(i)?s.setStateForPrimitive(e,i):s.setStateForGeneric(e,i))}static removeForGeneric(t,s){const i=window.getSelection();if(i){const n=e.Cursor.getGenericElementCursorOffset(s,i,!0);i.deleteFromDocument(),e.Cursor.setOffsetForGeneric(s,n),t.isHighlighted=!1}}static removeForPrimitive(t,s){const i=s.selectionStart,n=s.selectionEnd,o=s.value;if(i&&n){const r=o.substring(0,i)+o.substring(n);s.value=r,e.Cursor.setOffsetForPrimitive(s,i,t.autoScroll)}t.isHighlighted=!1}}return il.Highlight=s,il}(),o=Ja(),r=function(){if(nl)return al;nl=1,Object.defineProperty(al,"h",{value:!0}),al.Padding=void 0;const t=Ja(),e=tl(),s=Pa();class i{static setStateForPrimitiveElement(t,e){if(document.activeElement===e&&null!==e.selectionStart){const i=e.selectionStart,n=e.value[i-1],o=null===e.selectionEnd?i:e.selectionEnd,r=e.value[o];return s.Text.isCharDefined(n)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),s.Text.isCharDefined(r)&&(t.endPadding=" ",t.numberOfSpacesAfterNewText=1),void(t.isCursorAtEnd=e.value.length===o)}const i=e.value[e.value.length-1];s.Text.isCharDefined(i)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),t.isCursorAtEnd=!0}static setStateForGenericElement(t,i){var n,o,r;if(document.activeElement===i){const a=window.getSelection();if(null!=a&&a.focusNode){const l=e.Cursor.getGenericElementCursorOffset(i,a,!0),c=null===(n=i.textContent)||void 0===n?void 0:n[l-1],h=e.Cursor.getGenericElementCursorOffset(i,a,!1),u=null===(o=i.textContent)||void 0===o?void 0:o[h];return s.Text.isCharDefined(c)&&(t.startPadding=" "),s.Text.isCharDefined(u)&&(t.endPadding=" "),void(t.isCursorAtEnd=(null===(r=i.textContent)||void 0===r?void 0:r.length)===h)}}const a=i.innerText.charAt(i.innerText.length-1);s.Text.isCharDefined(a)&&(t.startPadding=" "),t.isCursorAtEnd=!0}static setState(e,s){t.Elements.isPrimitiveElement(s)?i.setStateForPrimitiveElement(e,s):i.setStateForGenericElement(e,s)}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 al.Padding=i,al}(),a=La(),l=tl(),c=Pa();return za.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 i,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===(i=null==e?void 0:e.textColor)||void 0===i?void 0:i.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=s.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,i,n){var o;const r=c.Text.capitalize(i);if(this.finalTranscript===r&&""===t)return;e.PreResultUtils.process(this,n,""===t,this._onPreResult,this._options)&&(t="",n="");const a=this.commands&&s.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,s){this.isHighlighted&&n.Highlight.removeForPrimitive(this,t),this.primitiveTextRecorded||r.Padding.adjustStateAfterRecodingPrimitiveElement(this,t),s&&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&&i.AutoScroll.scrollSafariPrimitiveToEnd(t)}updateGenericElement(t,e,s){this.isHighlighted&&n.Highlight.removeForGeneric(this,t),this.spansPopulated||o.Elements.appendSpans(this,t);const r=(s?"":this.startPadding)+c.Text.lineBreak(this.finalTranscript);this.finalSpan.innerHTML=r;const h=i.AutoScroll.isRequired(this.autoScroll,t);i.AutoScroll.changeStateIfNeeded(this,h);const u=c.Text.lineBreak(e)+(s?"":this.endPadding);this.interimSpan.innerHTML=u,a.Browser.IS_SAFARI()&&this.insertInCursorLocation&&l.Cursor.setOffsetForSafariGeneric(t,r.length+u.length),h&&i.AutoScroll.scrollGeneric(this,t),s&&(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}},za}function cl(){if(rl)return Ea;rl=1,Object.defineProperty(Ea,"h",{value:!0}),Ea.WebSpeech=void 0;const t=function(){if(Sa)return Ia;Sa=1,Object.defineProperty(Ia,"h",{value:!0}),Ia.WebSpeechTranscript=void 0;const t=Ba();return Ia.WebSpeechTranscript=class{static extract(e,s,i){let n="";for(let o=e.resultIndex;o<e.results.length;++o){let r=e.results[o][0].transcript;i&&(r=t.Translate.translate(r,i)),e.results[o].isFinal?s+=r:n+=r}return{interimTranscript:n,finalTranscript:s,newText:n||s}}static extractSafari(e,s,i){let n="";for(let s=e.resultIndex;s<e.results.length;++s){let o=e.results[s][0].transcript;i&&(o=t.Translate.translate(o,i)),n+=o}return{interimTranscript:"",finalTranscript:n,newText:n}}},Ia}(),e=La(),s=ll();class i extends s.Speech{constructor(){super()}start(s){var i;void 0===this._extractText&&(this._extractText=e.Browser.IS_SAFARI()?t.WebSpeechTranscript.extractSafari:t.WebSpeechTranscript.extract),this.validate()&&(this.prepareBeforeStart(s),this.instantiateService(s),null===(i=this._service)||void 0===i||i.start(),this._translations=null==s?void 0:s.translations)}validate(){return!!i.getAPI()||(this.error("Speech Recognition is unsupported"),!1)}instantiateService(t){var e,s;const n=i.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===(s=null==t?void 0:t.language)||void 0===s?void 0:s.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:s,newText:i}=this._extractText(t,this.finalTranscript,this._translations);this.updateElements(e,s,i)}})}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 Ea.WebSpeech=i,Ea}var hl,ul={};var dl,pl={},ml={};var vl,fl,gl={},bl={};function yl(){if(fl)return gl;fl=1,Object.defineProperty(gl,"h",{value:!0}),gl.AzureSpeechConfig=void 0;const t=(vl||(vl=1,Object.defineProperty(bl,"h",{value:!0}),bl.README_URL=void 0,bl.README_URL="https://github.com/OvidijusParsiunas/speech-to-element"),bl);class e{static validateOptions(e,s){return s?s.subscriptionKey||s.token||s.retrieveToken?!!s.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(s=>e.region?t.fromAuthorizationToken((null==s?void 0:s.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,s){const i=await e.getNewSpeechConfig(t,s);return i&&e.process(i,s),i}}return gl.AzureSpeechConfig=e,gl}var wl,xl={};var kl,_l={};var Ml,Cl,Al,Tl={};function Sl(){if(Cl)return pl;Cl=1,Object.defineProperty(pl,"h",{value:!0}),pl.Azure=void 0;const t=(dl||(dl=1,Object.defineProperty(ml,"h",{value:!0}),ml.PreventConnectionStop=void 0,ml.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}}),ml),e=yl(),s=function(){if(wl)return xl;wl=1,Object.defineProperty(xl,"h",{value:!0}),xl.StopTimeout=void 0;class t{static set(t){t.stopTimeout=setTimeout(()=>t.stop(),t.stopTimeoutMS)}static reset(e,s){e.stopTimeoutMS=s||t.DEFAULT_MS,t.stop(e),t.set(e)}static stop(t){t.stopTimeout&&clearTimeout(t.stopTimeout)}}return xl.StopTimeout=t,t.DEFAULT_MS=2e4,xl}(),i=(kl||(kl=1,Object.defineProperty(_l,"h",{value:!0}),_l.AzureAudioConfig=void 0,_l.AzureAudioConfig=class{static get(t,e){return e?t.fromMicrophoneInput(e):t.fromDefaultMicrophoneInput()}}),_l),n=function(){if(Ml)return Tl;Ml=1,Object.defineProperty(Tl,"h",{value:!0}),Tl.AzureTranscript=void 0;const t=Ba();return Tl.AzureTranscript=class{static extract(e,s,i,n){return n&&(e=t.Translate.translate(e,n)),i?{interimTranscript:"",finalTranscript:s+e,newText:e}:{interimTranscript:e,finalTranscript:s,newText:e}}},Tl}(),o=ll();class r extends o.Speech{constructor(){super(...arguments),this._newTextPadding=""}start(e,i){this._newTextPadding="",void 0===this.stopTimeout&&s.StopTimeout.reset(this,null==e?void 0:e.stopAfterSilenceMs),this.prepareBeforeStart(e),this.startAsync(e),i||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 s=r.getAPI(),n=i.AzureAudioConfig.get(s.AudioConfig,t.deviceId),o=await e.AzureSpeechConfig.get(s.SpeechConfig,t);if(o){let e;if(t.autoLanguage&&t.autoLanguage.languages.length>0){const{type:i,languages:r}=t.autoLanguage,a=r.slice(0,"Continuous"===i?10:4),l=s.AutoDetectSourceLanguageConfig.fromLanguages(a);"Continuous"===i&&(l.mode=1),e=s.SpeechRecognizer.FromConfig(o,l,n)}else e=new s.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:i,finalTranscript:o,newText:r}=n.AzureTranscript.extract(this._newTextPadding+e.result.text,this.finalTranscript,!1,this._translations);s.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(i,o,r)}onRecognized(t,e){const i=e.result;switch(i.reason){case window.SpeechSDK.ResultReason.Canceled:break;case window.SpeechSDK.ResultReason.RecognizedSpeech:if(i.text&&!this._stopping){const{interimTranscript:t,finalTranscript:e,newText:o}=n.AzureTranscript.extract(this._newTextPadding+i.text,this.finalTranscript,!0,this._translations);s.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(),s.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 pl.Azure=r,pl}const jl=Ca(function(){if(Al)return ja;Al=1,Object.defineProperty(ja,"h",{value:!0});const t=cl(),e=el(),s=function(){if(hl)return ul;hl=1,Object.defineProperty(ul,"h",{value:!0}),ul.GlobalState=void 0;class t{static doubleClickDetector(){return!!t.doubleClickPending||(t.doubleClickPending=!0,setTimeout(()=>{t.doubleClickPending=!1},300),!1)}}return ul.GlobalState=t,t.doubleClickPending=!1,ul}(),i=Sl();class n{static toggle(t,e){var i,o;const r=t.toLocaleLowerCase().trim();null!==(i=s.GlobalState.service)&&void 0!==i&&i.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()||(s.GlobalState.service=new t.WebSpeech,s.GlobalState.service.start(e))}static isWebSpeechSupported(){return!!t.WebSpeech.getAPI()}static startAzure(t){var e;n.stop()||null!==(e=s.GlobalState.service)&&void 0!==e&&e.cannotBeStopped||(s.GlobalState.service=new i.Azure,s.GlobalState.service.start(t))}static stop(){var t;return!!s.GlobalState.doubleClickDetector()||(!(null===(t=s.GlobalState.service)||void 0===t)&&t.recognizing&&s.GlobalState.service.stop(),!1)}static endCommandMode(){s.GlobalState.service&&e.CommandUtils.toggleCommandModeOff(s.GlobalState.service)}}return ja.default=n,ja}());class El{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 s;null==(s=t.submit)||s.call(t),jl.stop(),this._stop||setTimeout(e,$l.MICROPHONE_RESET_TIMEOUT_MS)},this._silenceMS)}clearSilenceTimeout(){this._silenceTimeout&&clearTimeout(this._silenceTimeout)}resetSilenceTimeout(t,e){this.clearSilenceTimeout(),this.setSilenceTimeout(t,e)}onPause(t,e,s){t?this.resetSilenceTimeout(e,s):this.clearSilenceTimeout()}}const Il=class t extends Ma{constructor(t,e,s){const i="object"==typeof t.speechToText?t.speechToText:{};super(null==i?void 0:i.button);const{serviceName:n,processedConfig:o}=this.processConfiguration(e,t.speechToText);if(this._addErrorMessage=s,"webspeech"!==n||jl.isWebSpeechSupported()){const s=!t.textInput||!t.textInput[ht];ne.assignButtonEvents(this.elementRef,this.buttonClick.bind(this,e,s,n,o))}else this.changeToUnsupported();setTimeout(()=>{this._validationHandler=t._validationHandler})}processConfiguration(e,s){var i;const n="object"==typeof s?s:{},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==(i=n.commands)?void 0:i.submit;return l&&(a.onPreResult=t=>t.toLowerCase().includes(l)?(setTimeout(()=>{var t;return null==(t=e.submit)?void 0:t.call(e)}),jl.endCommandMode(),{restart:!0,removeNewText:!0}):null),n.submitAfterSilence&&(this._silenceSubmit=new El(n.submitAfterSilence,n.stopAfterSubmit)),{serviceName:t.getServiceName(n),processedConfig:a}}static getServiceName(t){return t.azure?"azure":"webspeech"}buttonClick(t,e,s,i){const n=null==i?void 0:i.events;t.removePlaceholderStyle(),jl.toggle(s,{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,s;null==(t=this._validationHandler)||t.call(this),null==(e=this._silenceSubmit)||e.clearSilenceTimeout(),this.changeToDefault(),null==(s=null==n?void 0:n.onStop)||s.call(n)},onPauseTrigger:e=>{var s,i;null==(s=this._silenceSubmit)||s.onPause(e,t,this.elementRef.onclick),null==(i=null==n?void 0:n.onPauseTrigger)||i.call(n,e)},onPreResult:(t,e)=>{var s;null==(s=null==n?void 0:n.onPreResult)||s.call(n,t,e)},onResult:(e,s)=>{var i,o,r;s&&(null==(i=this._validationHandler)||i.call(this)),null==(o=this._silenceSubmit)||o.resetSilenceTimeout(t,this.elementRef.onclick),null==(r=null==n?void 0:n.onResult)||r.call(n,e,s)},onCommandModeTrigger:t=>{var e;this.onCommandModeTrigger(t),null==(e=null==n?void 0:n.onCommandModeTrigger)||e.call(n,t)},...i})}onCommandModeTrigger(t){t?this.changeToCommandMode():this.changeToActive()}onError(){this._addErrorMessage("speechToText","speech input error")}static toggleSpeechAfterSubmit(e,s=!0){e[lt](),s||setTimeout(()=>e[lt](),t.MICROPHONE_RESET_TIMEOUT_MS)}};Il.MICROPHONE_RESET_TIMEOUT_MS=300;let $l=Il;class Ol{constructor(t,e,s,i,n){this._attachments=[],this._fileCountLimit=99,this._acceptedFormat="",this._hiddenAttachments=new Set,s.maxNumberOfFiles&&(this._fileCountLimit=s.maxNumberOfFiles),this._toggleContainerDisplay=i,this._fileAttachmentsContainerRef=n,s.acceptedFormats&&(this._acceptedFormat=s.acceptedFormats),setTimeout(()=>{this._validationHandler=t._validationHandler,this._onInput=e.onInput})}attemptAddFile(t,e){var s;return!!Ol.isFileTypeValid(t,this._acceptedFormat)&&(this.addAttachmentBasedOnType(t,e,!0),null==(s=this._onInput)||s.call(this,!0),!0)}static isFileTypeValid(t,e){if(""===e)return!0;const s=e.split(",");for(let e=0;e<s.length;e++){const i=s[e].trim();if(t[w]===i)return!0;if(i.startsWith(".")){const e=i.slice(1);if(t.name.endsWith(e))return!0}else{if(t.name.endsWith(i))return!0;if(i.endsWith("/*")&&t[w].startsWith(i.slice(0,-2)))return!0}}return!1}static getTypeFromBlob(t){const{type:e}=t;return e.startsWith(_)?_:e.startsWith(T)?T:E}addAttachmentBasedOnType(t,e,s){const i=Ol.getTypeFromBlob(t);if(i===_){const i=Ol.createImageAttachment(e);this.addFileAttachment(t,_,i,s)}else if(i===T){const i=Bl.createAudioAttachment(e);this.addFileAttachment(t,T,i,s)}else{const e=Ol.createAnyFileAttachment(t.name);this.addFileAttachment(t,E,e,s)}}static createImageAttachment(e){const s=new Image;return s[y]=e,s[t].add("image-attachment"),s}static createAnyFileAttachment(e){const i=s();i[t].add("border-bound-attachment"),Tt.IS_SAFARI&&i[t].add("border-bound-attachment-safari");const n=s();n[t].add("any-file-attachment-text");const o=s();return o[t].add("file-attachment-text-container"),o.appendChild(n),n.textContent=e,i.appendChild(o),i}addFileAttachment(t,e,s,i){var n;const o=Ol.createContainer(s);if(this._attachments.length>=this._fileCountLimit){const t=this._attachments[this._attachments.length-1].removeButton;null==t||t[lt]();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 i&&(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(e){const i=s();return i[t].add("file-attachment"),i.appendChild(e),i}createRemoveAttachmentButton(e){const i=s();i[t].add("remove-file-attachment-button"),i.onclick=this.removeAttachment.bind(this,e);const n=s();return n[t].add("x-icon"),n.innerText="×",i.appendChild(n),i}removeAttachment(t,e){var s,i;const n=this._attachments.findIndex(e=>e===t);if(n<0)return;null==(s=this._onInput)||s.call(this,!(null==e||!e.isTrusted));const o=this._attachments[n].attachmentContainerElement;this._attachments.splice(n,1),Bl.stopAttachmentPlayback(o),o.remove(),this._toggleContainerDisplay(!1),null==(i=this._validationHandler)||i.call(this)}getFiles(){return Array.from(this._attachments).map(t=>({[x]:t[x],[w]:t.fileType}))}hideAttachments(){this._hiddenAttachments.clear(),this._attachments.forEach(t=>{setTimeout(()=>{var e;return null==(e=t.removeButton)?void 0:e[lt]()}),this._hiddenAttachments.add(t)})}removeAttachments(){this._attachments.forEach(t=>{setTimeout(()=>{var e;return null==(e=t.removeButton)?void 0:e[lt]()})}),this._hiddenAttachments.clear()}readdAttachments(){var t;Array.from(this._hiddenAttachments).forEach(t=>{this._fileAttachmentsContainerRef.appendChild(t.attachmentContainerElement),this._attachments.push(t)}),null==(t=this._onInput)||t.call(this,!1),this._hiddenAttachments.clear()}}const Pl=class e extends Ol{constructor(t,e,s,i,n){super(t,e,s,i,n)}static createAudioContainer(){const e=s();return e[t].add("border-bound-attachment","audio-attachment-icon-container"),Tt.IS_SAFARI&&e[t].add("border-bound-attachment-safari"),e}static addAudioElements(e,i){const n=e.parentElement?ne.cloneElement(e):e,o=s(T);o[y]=i;const r=Fi.createSVGElement(no);r[t].add("attachment-icon","play-icon");const a=Fi.createSVGElement(oo);a[t].add("attachment-icon","stop-icon"),n.replaceChildren(r),o.onplay=()=>{n.replaceChildren(a)},o.onpause=()=>{n.replaceChildren(r),o.currentTime=0},o.onended=()=>{n.replaceChildren(r)},ne.assignButtonEvents(n,()=>{o.paused?o.play():o.pause()})}static createAudioAttachment(t){const s=e.createAudioContainer();return e.addAudioElements(s,t),s}createTimer(s,i){let n=0;const o=void 0!==i&&i<e.TIMER_LIMIT_S?i:e.TIMER_LIMIT_S;return setInterval(()=>{var e;n+=1,n===o&&(null==(e=this.stopPlaceholderCallback)||e.call(this),this.clearTimer()),600===n&&s[t].add("audio-placeholder-text-4-digits");const i=Math.floor(n/60),r=(n%60).toString().padStart(2,"0");s.textContent=`${i}:${r}`},1e3)}createPlaceholderAudioAttachment(i){const n=e.createAudioContainer(),o=s();o[t].add("audio-placeholder-text-3-digits");const r=s();r[t].add("file-attachment-text-container","audio-placeholder-text-3-digits-container"),r.appendChild(o);const a=Fi.createSVGElement(oo);return a[t].add("attachment-icon","stop-icon","not-removable-attachment-icon"),o.textContent="0:00",this._activePlaceholderTimer=this.createTimer(o,i),n.appendChild(r),this.addPlaceholderAudioAttachmentEvents(n,a,r),n}addPlaceholderAudioAttachmentEvents(t,e,s){t.addEventListener(mt,()=>t.replaceChildren(e));t.addEventListener(vt,()=>t.replaceChildren(s));t.addEventListener(lt,()=>{var t;return null==(t=this.stopPlaceholderCallback)?void 0:t.call(this)})}addPlaceholderAttachment(t,e){const s=this.createPlaceholderAudioAttachment(e);this._activePlaceholderAttachment=this.addFileAttachment(new File([],""),T,s,!1),this.stopPlaceholderCallback=t}completePlaceholderAttachment(t,s){const i=this._activePlaceholderAttachment;i&&(i[x]=t,e.addAudioElements(i.attachmentContainerElement.children[0],s),i.removeButton=this.createRemoveAttachmentButton(i),i.attachmentContainerElement.appendChild(i.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(e){var s,i,n;null!=(n=null==(i=null==(s=e.children[0])?void 0:s.children)?void 0:i[0])&&n[t].contains("stop-icon")&&e.children[0][lt]()}};Pl.TIMER_LIMIT_S=5999;let Bl=Pl;class Rl{static create(t,e,s,i,n,o){return o===T?new Bl(t,e,s,i,n):new Ol(t,e,s,i,n)}}class Fl{constructor(t,s,i){this._fileAttachmentsTypes=[],this.elementRef=this.createAttachmentContainer();const n="object"==typeof i&&!!i.displayFileAttachmentContainer;this.toggleContainerDisplay(n),t.appendChild(this.elementRef),s&&Object.assign(this.elementRef[e],s)}addType(t,e,s,i){const n=Rl.create(t,e,s,this.toggleContainerDisplay.bind(this),this.elementRef,i);return this._fileAttachmentsTypes.push(n),n}createAttachmentContainer(){const t=s();return t.id="file-attachment-container",t}toggleContainerDisplay(t){t?this.elementRef[e].display="block":0===this.elementRef.children.length&&(this.elementRef[e].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 s=new FileReader;s.readAsDataURL(t),s.onload=s=>{for(let i=0;i<e.length&&!e[i].attemptAddFile(t,s.target.result);i+=1);}})}addFilesToAnyType(t){Fl.addFilesToType(t,this._fileAttachmentsTypes)}hideFiles(){this._fileAttachmentsTypes.forEach(t=>t.hideAttachments()),this.elementRef.replaceChildren(),this.toggleContainerDisplay(!1)}removeHiddenFiles(){this._fileAttachmentsTypes.forEach(t=>t.removeAttachments())}readdHiddenFiles(){this._fileAttachmentsTypes.forEach(t=>t.readdAttachments()),this.toggleContainerDisplay(!0)}getNumberOfTypes(){return this._fileAttachmentsTypes.length}}const Ll=class i{constructor(t,e,s){this._isOpen=!1,this._contentRef=i.createModalContent(e,null==s?void 0:s.backgroundColor),this._buttonPanel=i.createButtonPanel(null==s?void 0:s.backgroundColor),this._elementRef=i.createContainer(this._contentRef,s),this._elementRef.appendChild(this._buttonPanel),t.appendChild(this._elementRef),this._backgroundPanelRef=i.createDarkBackgroundPanel(),t.appendChild(this._backgroundPanelRef),this.addWindowEvents(t)}isOpen(){return this._isOpen}static createContainer(i,n){const o=s();return o[t].add("modal"),o.appendChild(i),n&&delete n.backgroundColor,Object.assign(o[e],n),o}static createModalContent(i,n){const o=s();return o[t].add(...i),n&&(o[e].backgroundColor=n),s().appendChild(o),o}static createButtonPanel(i){const n=s();return n[t].add("modal-button-panel"),i&&(n[e].backgroundColor=i),n}static createDarkBackgroundPanel(){const t=s();return t.id="modal-background-panel",t}addButtons(...t){t.forEach(t=>{Zn.addAttributes(t),this._buttonPanel.appendChild(t)})}static createTextButton(e){const i=s();return i[t].add("modal-button"),i.textContent=e,i}static createSVGButton(e){const i=s();i[t].add("modal-button","modal-svg-button");const n=Fi.createSVGElement(e);return n[t].add("modal-svg-button-icon"),i.appendChild(n),i}close(){this._elementRef[t].remove("show-modal"),this._elementRef[t].add("hide-modal"),this._backgroundPanelRef[t].remove("show-modal-background"),this._backgroundPanelRef[t].add("hide-modal-background"),this._isOpen=!1,setTimeout(()=>{this._elementRef[e].display="none",this._backgroundPanelRef[e].display="none"},i.MODAL_CLOSE_TIMEOUT_MS)}displayModalElements(){this._elementRef[e].display="flex",this._elementRef[t].remove("hide-modal"),this._elementRef[t].add("show-modal"),this._backgroundPanelRef[e].display="block",this._backgroundPanelRef[t].remove("hide-modal-background"),this._backgroundPanelRef[t].add("show-modal-background"),this._isOpen=!0}openTextModal(t){this._contentRef.innerHTML=t,this.displayModalElements()}addCloseButton(t,e,s){const n=e?i.createSVGButton(t):i.createTextButton(t);return this.addButtons(n),ne.assignButtonEvents(n,()=>{this.close(),setTimeout(()=>{null==s||s()},140)}),n}static createTextModalFunc(t,e,s){var n;if("object"==typeof e&&null!=(n=e[k])&&n.infoModal){const n=new i(t,["modal-content"],e[k].infoModal.containerStyle);return n.addCloseButton("OK",!1,s),n.openTextModal.bind(n,e.infoModalTextMarkUp||"")}}addWindowEvents(t){this.keyDownEvent=this.windowKeyDown.bind(this,t),window.addEventListener("keydown",this.keyDownEvent)}windowKeyDown(t,e){var s,i;!t.isConnected&&this.keyDownEvent?window.removeEventListener("keydown",this.keyDownEvent):this._isOpen&&(e.key===St.ESCAPE?(this.close(),null==(s=this.extensionCloseCallback)||s.call(this)):e.key===St.ENTER&&(this.close(),null==(i=this.extensionCloseCallback)||i.call(this)))}};Ll.MODAL_CLOSE_TIMEOUT_MS=190;let ql=Ll;class zl extends to{constructor(t,e,s,i,n,o){var a,l,c,h,u,d,p,m,v,f;const g=ce.processPosition(null==(a=null==s?void 0:s.button)?void 0:a.position),b=(null==(h=null==(c=null==(l=null==s?void 0:s.button)?void 0:l[pt])?void 0:c[r])?void 0:h.content)||o,y=Ct.tryCreateConfig("Upload File",null==(u=null==s?void 0:s.button)?void 0:u.tooltip);super(zl.createButtonElement(),n,g,y,s.button,b);const w=this.createInnerElementsForStates(i,this.customStyles);this._inputElement=zl.createInputElement(null==(d=null==s?void 0:s[k])?void 0:d.acceptedFormats),this.addClickEvent(t,s),this.changeElementsByState(w[pt]),this.reapplyStateStyle(pt),this._fileAttachmentsType=e,this._openModalOnce=!1===(null==(m=null==(p=s[k])?void 0:p.infoModal)?void 0:m.openModalOnce)||null==(f=null==(v=s[k])?void 0:v.infoModal)?void 0:f.openModalOnce}createInnerElementsForStates(t,e){return{[pt]:this.createInnerElements(t,pt,e)}}triggerImportPrompt(t){t.onchange=this.import.bind(this,t),t[lt]()}import(t){Fl.addFilesToType(Array.from(t[k]||[]),[this._fileAttachmentsType]),t.value=""}static createInputElement(t){const e=s("input");return e[w]=x,e.accept=t||"",e.hidden=!0,e.multiple=!0,e}static createButtonElement(){const e=s();return e[t].add("input-button"),e}addClickEvent(t,e){const s=this.triggerImportPrompt.bind(this,this._inputElement),i=ql.createTextModalFunc(t,e,s);this.elementRef.onclick=this[lt].bind(this,i)}click(t){!t||void 0!==this._openModalOnce&&!0!==this._openModalOnce?this.triggerImportPrompt(this._inputElement):(t(),!0===this._openModalOnce&&(this._openModalOnce=!1))}}class Dl{static create(t,e,s){const i=Dl.createElement(s);Dl.addEvents(i,t,e),t.appendChild(i)}static createElement(t){const i=s();return i.id="drag-and-drop",typeof t===Gt&&Object.assign(i[e],t),i}static addEvents(t,e,s){e.ondragenter=e=>{e.preventDefault(),Dl.display(t)},t.ondragleave=e=>{e.preventDefault(),Dl.hide(t)},t.ondragover=t=>{t.preventDefault()},t.ondrop=e=>{e.preventDefault(),Dl.uploadFile(s,e),Dl.hide(t)}}static uploadFile(t,e){var s;const i=null==(s=e.dataTransfer)?void 0:s[k];i&&t.addFilesToAnyType(Array.from(i))}static display(t){t[e].display="block"}static hide(t){t[e].display="none"}static isEnabled(t,e){return(void 0===e||!1!==e)&&(!!e||t.getNumberOfTypes()>0)}}class Nl{static validate(t,e,s,i,n,o,r){const a=!s.isSubmitProgrammaticallyDisabled&&t(i,n,r);return a?e.changeToSubmitIcon():e.changeToDisabledIcon(),null==o||o.addInputText(i||""),a}static async useValidationFunc(t,e,s,i,n,o){const r=e.isTextInputEmpty()?"":e.inputElementRef.textContent;await s.completePlaceholders();const a=s.getAllFileData(),l=null==a?void 0:a.map(t=>t[x]);return Nl.validate(t,i,n,r,l,o)}static async useValidationFuncProgrammatic(t,e,s,i,n){var o;const a=null==(o=e[k])?void 0:o.map(t=>t[x]);return Nl.validate(t,s,i,e[r],a,n,!0)}static validateWebsocket(t,e){const{websocket:s,connectSettings:i}=t;return!(s&&i.url!==Mi.URL&&!Ci.canSendMessage(s))||(e.changeToDisabledIcon(),!1)}static attach(t,e,s,i,n,o){const r=t.validateInput||ce.processValidateInput(t);t._validationHandler=async t=>{if(n.status.loadingActive||n.status.requestInProgress||!Nl.validateWebsocket(e,n))return!1;const a=r||e.canSendMessage;return a?t?Nl.useValidationFuncProgrammatic(a,t,n,e,o):Nl.useValidationFunc(a,s,i,n,e,o):null}}}class Ul{static getFileName(t,e){const s=new Date;return`${t}-${String(s.getHours()).padStart(2,"0")}-${String(s.getMinutes()).padStart(2,"0")}-${String(s.getSeconds()).padStart(2,"0")}.${e}`}}class Hl extends Ma{constructor(t,e){var s,i;super(e.button),this._waitingForBrowserApproval=!1,this._audioType=t,this._extension=(null==(s=e[k])?void 0:s.format)||"mp3",this._maxDurationSeconds=null==(i=e[k])?void 0:i.maxDurationSeconds,ne.assignButtonEvents(this.elementRef,this.buttonClick.bind(this))}buttonClick(){this._waitingForBrowserApproval||(this.isActive?this.stop():(this._waitingForBrowserApproval=!0,this.record()))}stop(){return new Promise(t=>{var e,s;this.changeToDefault(),null==(e=this._mediaRecorder)||e.stop(),null==(s=this._mediaStream)||s.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[$]()}).catch(t=>{console[l](t),this.stop()}).finally(()=>{this._waitingForBrowserApproval=!1})}createFile(t){const e=new Blob([t.data],{type:`audio/${this._extension}`}),s=Ul.getFileName(this._newFilePrefix||T,this._extension),i=new File([e],s,{type:e[w]}),n=new FileReader;n.readAsDataURL(i),n.onload=t=>{this._audioType.completePlaceholderAttachment(i,t.target.result)}}}class Vl{static resetSubmit(t,e){e?t.unsetCustomStateStyles([gt,ft]):t.unsetCustomStateStyles([bt,gt,ft]),t.reapplyStateStyle(ft)}static overwriteDefaultStyleWithSubmit(t,e){if(!t.submit)return;const s=F(t[e]||{});io.overwritePropertyObjectFromAnother(s,t.submit,["container",rt]),io.overwritePropertyObjectFromAnother(s,t.submit,[r,"styles",rt]),io.overwritePropertyObjectFromAnother(s,t.submit,[ut,"styles",rt]),t[e]=s}static setUpDisabledButton(t){io.setPropertyValueIfDoesNotExist(t,[ft,"container",rt,"backgroundColor"],""),io.setPropertyValueIfDoesNotExist(t,[ht,"container",rt,"backgroundColor"],"unset"),io.setPropertyValueIfDoesNotExist(t.submit,[ut,"styles",rt,"filter"],""),io.setPropertyValueIfDoesNotExist(t[ht],[ut,"styles",rt,"filter"],"brightness(0) saturate(100%) invert(70%) sepia(0%) saturate(5564%) hue-rotate(207deg) brightness(100%) contrast(97%)"),io.setPropertyValueIfDoesNotExist(t[ht],[r,"styles",rt,"color"],"grey"),Vl.overwriteDefaultStyleWithSubmit(t,ht)}static process(t){const e=F(t||{});return Vl.overwriteDefaultStyleWithSubmit(e,gt),Vl.overwriteDefaultStyleWithSubmit(e,bt),null!=t&&t.alwaysEnabled||Vl.setUpDisabledButton(e),e}}class Wl extends to{constructor(t,e,s,i,n,o){const r=Vl.process(t.submitButtonStyles),a=Ct.tryCreateConfig("Submit",null==r?void 0:r.tooltip);super(Wl.createButtonContainerElement(),'<?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',null==r?void 0:r.position,a,r),this._isSVGLoadingIconOverriden=!1,this.status={requestInProgress:!1,loadingActive:!1},this._messages=s,this._textInput=e,this._fileAttachments=n,this._innerElements=this.createInnerElementsForStates(),this._stopClicked={listener:()=>{}},this._serviceIO=i,this._alwaysEnabled=!(null==r||!r.alwaysEnabled),t.disableSubmitButton=this.disableSubmitButton.bind(this,i),this.attemptOverwriteLoadingStyle(t),o.microphone&&this.setUpSpeechToText(o.microphone.button,t.speechToText),setTimeout(()=>{var e;this._validationHandler=t._validationHandler,this.assignHandlers(this._validationHandler),null==(e=this._validationHandler)||e.call(this)})}createInnerElementsForStates(){const{submit:t,loading:e,stop:s}=this.createCustomElements();return{submit:t,loading:e||[Wl.createLoadingIconElement()],stop:s||[Wl.createStopIconElement()],[ht]:this.createDisabledIconElement(t)}}createCustomElements(){const t=Xn.createCustomElements(ft,this[ut],this.customStyles),e={loading:void 0,stop:void 0};return Object.keys(e).forEach(t=>{const s=t,i=Xn.createCustomElements(s,this[ut],this.customStyles);i&&(e[s]=i)}),e.submit=t||this.buildDefaultIconElement("submit-icon"),e}static createButtonContainerElement(){const e=s();return e[t].add("input-button"),e}static createLoadingIconElement(){const e=s();return e[t].add("loading-submit-button"),e}static createStopIconElement(){const t=s();return t.id="stop-icon",t}createDisabledIconElement(t){return Xn.createCustomElements(ht,this[ut],this.customStyles)||[t[0].cloneNode(!0)]}attemptOverwriteLoadingStyle(t){var e,i,n,o,a,l,c,h,u;if(!(null!=(i=null==(e=this.customStyles)?void 0:e.submit)&&i[ut]||null!=(a=null==(o=null==(n=this.customStyles)?void 0:n.loading)?void 0:o[ut])&&a.content||null!=(h=null==(c=null==(l=this.customStyles)?void 0:l.loading)?void 0:c[r])&&h.content||void 0!==t.displayLoadingBubble&&!0!==t.displayLoadingBubble)){const e=s("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==(u=t.shadowRoot)||u.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),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({[r]:"",[k]:t});else{const e=this._textInput.inputElementRef.innerText.trim();this.attemptSubmit({[r]:e,[k]:t})}(Tt.IS_SAFARI||Tt.IS_MOBILE)&&setTimeout(()=>Pt.focusEndOfInput(this._textInput.inputElementRef))}async programmaticSubmit(t){"string"==typeof t&&(t=ce.processSubmitUserMessage(t));const e={[r]:t[r]};t[k]&&(e[k]=Array.from(t[k]).map(t=>({file:t,[w]:Ol.getTypeFromBlob(t)}))),t.custom&&(e.custom=t.custom),setTimeout(()=>this.attemptSubmit(e,!0))}async attemptSubmit(t,e=!1){var s,i,n,o;if(!1===await(null==(s=this._validationHandler)?void 0:s.call(this,e?t:void 0)))return;this.changeToLoadingIcon(),this._textInput.clear(),Tt.IS_MOBILE&&setTimeout(()=>this._textInput.inputElementRef.focus()),"boolean"!=typeof this._messages.focusMode&&null!=(i=this._messages.focusMode)&&i.fade&&await ni.fadeAnimation(this._messages.elementRef,this._messages.focusMode.fade),await this.addNewMessage(t),this._serviceIO.isWebModel()||this._messages.addLoadingMessage();const a=null==(n=t[k])?void 0:n.map(t=>t[x]),l={[r]:""===t[r]?void 0:t[r],[k]:a};await this._serviceIO.callAPI(l,this._messages),null==(o=this._fileAttachments)||o.hideFiles()}async addNewMessage({text:t,files:e,custom:s}){const i={[P]:u,custom:s};t&&(i[r]=t),e&&(i[k]=await this._messages.addMultipleFiles(e,this._fileAttachments)),this._serviceIO.sessionId&&(i._sessionId=this._serviceIO.sessionId),Object.keys(i).length>0&&this._messages.addNewMessage(i)}stopStream(){var t,e,s;null==(e=(t=this._serviceIO.streamHandlers).onAbort)||e.call(t),null==(s=this._stopClicked)||s.listener(),this._validationHandler&&this.resetSubmit(this._validationHandler)}changeToStopIcon(){this._serviceIO.websocket||(this.elementRef[t].remove(Yr,ta,Qr),Zn.removeAriaAttributes(this.elementRef),this.changeElementsByState(this._innerElements.stop),this.reapplyStateStyle(bt,[gt,ft]),ne.assignButtonEvents(this.elementRef,this.stopStream.bind(this)),this.status.loadingActive=!1)}changeToLoadingIcon(){this._serviceIO.websocket||(this._isSVGLoadingIconOverriden||this.changeElementsByState(this._innerElements.loading),this.elementRef[t].remove(Qr,ta),Zn.removeAriaDisabled(this.elementRef),this.elementRef[t].add(Yr),Zn.addAriaBusy(this.elementRef),this.reapplyStateStyle(gt,[ft]),ne.assignButtonEvents(this.elementRef,()=>{}),this.status.requestInProgress=!0,this.status.loadingActive=!0)}changeToSubmitIcon(){this.elementRef[t].contains(Qr)||(this.elementRef[t].remove(Yr,ta),Zn.removeAriaAttributes(this.elementRef),this.elementRef[t].add(Qr),this.changeElementsByState(this._innerElements.submit),Vl.resetSubmit(this,this.status.loadingActive),ne.assignButtonEvents(this.elementRef,()=>{var t;this.submitFromInput(),null!=(t=this._microphoneButton)&&t.isActive&&$l.toggleSpeechAfterSubmit(this._microphoneButton.elementRef,!!this._stopSTTAfterSubmit),setTimeout(()=>Pt.focusEndOfInput(this._textInput.inputElementRef))}))}changeToDisabledIcon(e=!1){this._alwaysEnabled&&!e?this.changeToSubmitIcon():this.elementRef[t].contains(ta)||(this.elementRef[t].remove(Yr,Qr),Zn.removeAriaBusy(this.elementRef),this.elementRef[t].add(ta),Zn.addAriaDisabled(this.elementRef),this.changeElementsByState(this._innerElements[ht]),this.reapplyStateStyle(ht,[ft]),ne.assignButtonEvents(this.elementRef,()=>{}))}disableSubmitButton(t,e){var s;t.isSubmitProgrammaticallyDisabled=!1!==e,!this.status.requestInProgress&&!this.status.loadingActive&&(!1===e?null==(s=this._validationHandler)||s.call(this):this.changeToDisabledIcon(!0))}}class Gl extends ql{constructor(e,i,n,o){super(e,["modal-content","modal-camera-content"],n),this._stopped=!1,this._format="image/png",this._canvas=s("canvas"),this._canvas[t].add("camera-modal-canvas");const{captureButton:r,submitButton:a}=this.addButtonsAndTheirEvents(i);this._captureButton=r,this._submitButton=a,this._captureIcon=this._captureButton.children[0],this._refreshIcon=Fi.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[t].add("modal-svg-button-icon","modal-svg-refresh-icon"),"jpeg"===(null==o?void 0:o.format)&&(this._format="image/jpeg"),null!=o&&o.dimensions&&(this._dimensions=o.dimensions),this._contentRef.appendChild(this._canvas),this.extensionCloseCallback=this.stop}addButtonsAndTheirEvents(e){const s=ql.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 <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');s[t].add("modal-svg-camera-button"),s.children[0][t].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[t].add("modal-svg-close-button"),i.children[0][t].add("modal-svg-close-icon");const n=ql.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 n[t].add("modal-svg-submit-button"),this.addButtons(s,n),this.addButtonEvents(s,i,n,e),{captureButton:s,submitButton:n}}addButtonEvents(t,e,s,i){ne.assignButtonEvents(t,this.capture.bind(this)),ne.assignButtonEvents(e,this.stop.bind(this)),ne.assignButtonEvents(s,()=>{const t=this.getFile();t&&Fl.addFilesToType([t],[i]),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[t].replace("modal-svg-refresh-button","modal-svg-camera-button");const e=this._canvas.getContext("2d");null==e||e.clearRect(0,0,this._canvas.width,this._canvas.height)},ql.MODAL_CLOSE_TIMEOUT_MS)}start(){this._dataURL=void 0,this._submitButton[t].add(`modal-svg-submit-${ht}`),this._stopped=!1,navigator.mediaDevices.getUserMedia({video:this._dimensions||!0}).then(t=>{if(this._mediaStream=t,!this.isOpen())return this.stop();const e=s("video");e.srcObject=t,e.play(),requestAnimationFrame(this.updateCanvas.bind(this,e,this._canvas))}).catch(t=>{console[l](t),this.stop(),this.close()})}capture(){this._dataURL?(this._captureButton.replaceChildren(this._captureIcon),this._captureButton[t].replace("modal-svg-refresh-button","modal-svg-camera-button"),this._submitButton[t].add(`modal-svg-submit-${ht}`),this._dataURL=void 0):(this._captureButton.replaceChildren(this._refreshIcon),this._captureButton[t].replace("modal-svg-camera-button","modal-svg-refresh-button"),this._submitButton[t].remove(`modal-svg-submit-${ht}`),this._dataURL=this._canvas.toDataURL())}getFile(){if(this._dataURL){const t=atob(this._dataURL.split(",")[1]),e=new Array(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);const s=new Uint8Array(e),i=new Blob([s],{type:this._format}),n="image/jpeg"===this._format?"jpeg":"png",o=Ul.getFileName(this._newFilePrefix||"photo",n);return new File([i],o,{type:i[w]})}}updateCanvas(t,e){if(!this._stopped){if(!this._dataURL){e.width=t.videoWidth,e.height=t.videoHeight;const s=e.getContext("2d");null==s||s.drawImage(t,0,0,e.width,e.height)}requestAnimationFrame(this.updateCanvas.bind(this,t,e))}}openCameraModal(t){this.displayModalElements(),t[$]()}static createCameraModalFunc(t,e,s,i){const n=new Gl(t,e,s,i);return n.openCameraModal.bind(n,n)}}class Zl extends to{constructor(t,e,s){var i,n,o,a,l,c;const h=ce.processPosition(null==(i=null==s?void 0:s.button)?void 0:i.position),u=(null==(a=null==(o=null==(n=null==s?void 0:s.button)?void 0:n[pt])?void 0:o[r])?void 0:a.content)||"Photo",d=Ct.tryCreateConfig("Camera",null==(l=null==s?void 0:s.button)?void 0:l.tooltip),p=(null==(c=null==s?void 0:s.button)?void 0:c[pt])||{};super(Zl.createButtonElement(),'<?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>',h,d,p,u);const m=this.createInnerElementsForStates(this.customStyles);s&&this.addClickEvent(t,e,s.modalContainerStyle,s[k]),this.changeElementsByState(m[pt]),this.reapplyStateStyle(pt)}createInnerElementsForStates(t){return{[pt]:this.createInnerElements("camera-icon",pt,t)}}static createButtonElement(){const e=s();return e[t].add("input-button"),e}addClickEvent(t,e,s,i){const n=Gl.createCameraModalFunc(t,e,s,i);ne.assignButtonEvents(this.elementRef,n)}}class Kl{constructor(t,e,s,i){this.elementRef=Kl.createPanelElement(t.inputAreaStyle);const n={},o=this.createFileUploadComponents(t,s,i,n),r=new Ot(t,s,o,e.browserStorage);t.speechToText&&!n.microphone&&(n.microphone={button:new $l(t,r,e.addNewErrorMessage.bind(e))});const a=new Wl(t,r,e,s,o,n);r.submit=a.submitFromInput.bind(a),Nl.attach(t,s,r,o,a,e.browserStorage),t.submitUserMessage=a.programmaticSubmit.bind(a),n.submit={button:a},t.customButtons&&ga.add(t,n),Kl.addElements(this.elementRef,r,n,i,o,t.dropupStyles),Kl.assignOnInput(t,s,o,r)}static createPanelElement(t){const i=s();return i.id="input",Object.assign(i[e],t),i}createFileUploadComponents(t,e,s,i){var n,o,r,a;const l=new Fl(this.elementRef,t.attachmentContainerStyle,e.demo);if(Kl.createUploadButtons(t,e,e.fileTypes||{},l,s,i),null!=(n=e[C])&&n[k]){const n=(null==(o=i[M])?void 0:o.fileType)||l.addType(t,e,e[C][k],M);i[C]={button:new Zl(s,n,e[C])}}if(null!=(r=e.recordAudio)&&r[k]){const s=(null==(a=i[T])?void 0:a.fileType)||l.addType(t,e,e.recordAudio[k],T);i.microphone={button:new Hl(s,e.recordAudio)}}return Dl.isEnabled(l,t.dragAndDrop)&&Dl.create(s,l,t.dragAndDrop),l}static createUploadButtons(t,e,s,i,n,o){Object.keys(s).forEach(r=>{const a=r,l=s[a];if(l[k]){const s=i.addType(t,e,l[k],a),{id:r,svgString:c,dropupText:h}=_a[a],u=new zl(n,s,l,r,c,h);o[a]={button:u,fileType:s}}})}static addElements(t,e,s,i,n,o){ne.addElements(t,e.elementRef);const r=da.create(),a=ka.addButtons(r,s,i,o);ua.set(e.inputElementRef,r,n.elementRef,a),da.add(t,r)}static assignOnInput(t,e,s,i){e.onInput=e=>{setTimeout(()=>{const n=s.getAllFileData(),o=i.inputElementRef.innerText.trim(),a={[r]:o};n&&(a[k]=n.map(t=>t[x])),ti.onInput(t,a,e)})}}}class Jl{static createElements(t,e,i){const n=s();n.id="chat-view";const o=!t.focusMode&&t.upwardsMode;n.classList.add(o?"deep-chat-upwards-mode":"deep-chat-downwards-mode");const r=new ha(t,e,i);e.websocket&&Ci.createConnection(e,r);const a=new Kl(t,r,e,n),l=o?r.elementRef.parentElement:r.elementRef;return ne.addElements(n,l,a.elementRef),n}static render(t,e,s,i){const n=Jl.createElements(t,s,i);e.replaceChildren(n),s.isCustomView()&&s.setUpView(n,e)}}var Xl=Object.defineProperty,Ql=(t,e,s,i)=>{for(var n,o=void 0,r=t.length-1;r>=0;r--)(n=t[r])&&(o=n(e,s,o)||o);return o&&Xl(e,s,o),o};class Yl extends Ri{constructor(){var t;super(),this.getMessages=()=>[],this.submitUserMessage=()=>console.warn(U("submitUserMessage")),this.addMessage=()=>console.warn(U("addMessage")),this.updateMessage=()=>{},this.clearMessages=()=>{},this.focusInput=()=>Pt.focusFromParentElement(this._elementRef),this.refreshMessages=()=>{},this.scrollToBottom=()=>{},this.disableSubmitButton=()=>{},this.setPlaceholderText=()=>{},this._hasBeenRendered=!1,this._auxiliaryStyleApplied=!1,this._elementRef=s(),this._elementRef.id="container",this.attachShadow({mode:"open"}).appendChild(this._elementRef),null==(t=this.shadowRoot)||t.appendChild(Ct.buildElement()),_t.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-microphone-active{background-color:#ffe7e7}.deep-chat-openai-realtime-microphone-active:hover{background-color:#ffdede}.deep-chat-openai-realtime-microphone-active:active{background-color:#ffd2d2}.deep-chat-openai-realtime-microphone>*{height:30px;width:30px}.deep-chat-openai-realtime-microphone-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-inline-start: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);inset-inline-start:50%;transform:translate(-50%,-50%);font-size:17px}#deep-chat-openai-realtime-loading{position:absolute;font-size:15px;top:50%;inset-inline-start:50%;transform:translate(-50%,-50%)}#insert-key-view{height:100%;position:relative}#insert-key-contents{text-align:center;position:absolute;inset-block-start:44%;inset-inline-start:50%;transform:translate(-50%,-50%);width:82%;display:flex;max-width:700px}#insert-key-title{margin-bottom:15px}#insert-key-input-container{margin-inline-end: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:inline-end;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;inset-inline-end:-1.7em;inset-block-start:-1.43em}#visible-icon{inset-block-start:-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-inline: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}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,.deep-chat-upwards-mode #messages>div{overflow:auto;overflow-anchor:none}.deep-chat-upwards-mode #messages{height:100%;display:flex;flex-direction:column;justify-content:flex-end}.outer-message-container:last-child{margin-bottom:5px}.inner-message-container{display:flex;margin-inline: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.26}.user-message-text{color:#fff;background-color:#0084ff;margin-inline-end:0px;margin-inline-start:auto}.ai-message-text{color:#000;background-color:#e4e6eb;margin-inline-start:0px;margin-inline-end:auto}.deep-chat-last-group-messages-active{height:100%}#scroll-button{position:absolute;top:75%;left:50%;right:50%;transform:translate(-50%,-50%);transition:opacity .1s ease;display:flex;opacity:0;padding:8px;background-color:#fff;border:.5px solid #000000;justify-content:center;align-items:center;white-space:nowrap;cursor:pointer}#scroll-button:hover{background-color:#fafafa}.loading-history-message-full-view{position:absolute;height:70%;width:100%;display:flex;align-items:center}.deep-chat-upwards-mode #messages .loading-history-message-full-view{height:100%}.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-inline:auto;background-color:#f4c0c0;color:#474747;text-align:center;max-width:95%;margin-top:14px;margin-bottom:10px}.deep-chat-loading-message-dots-container{width:1em;padding-top:.6em;padding-bottom:.6em;padding-inline-start:1.3em;padding-inline-end:.75em}.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{inset-inline-start:-.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{inset-inline-start:.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,.message-bubble>.partial-render-message>p:first-child,.html-wrapper>p:first-child{margin-top:0}.message-bubble>p:last-child,.message-bubble>.partial-render-message:last-child>p,.html-wrapper>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-start{float:inline-start}.audio-player-safari-end{float:inline-end}.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-inline-start:6px;margin-inline-end: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-inline-end:7px}.message-bubble>a{color:inherit}.start-item-position{margin-inline-end:10px}.end-item-position{margin-inline-start:10px}.role-hidden{display:none}.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:start;background-color:#d7d7d73b;padding-inline-start:4px}.file-attachment{width:2.85em;height:2.85em;display:inline-flex;margin-inline-end:.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{inset-inline: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-inline-start:.26rem}.audio-placeholder-text-4-digits{padding-inline-start:.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-inline-start:.13em;margin-inline:auto}.remove-file-attachment-button{height:1.25em;width:1.25em;border:1px solid #cfcfcf;border-radius:25px;background-color:#fff;top:-4px;inset-inline-end:-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:3}.modal-content{border-top:1px solid rgb(217,217,217);border-inline:1px solid rgb(217,217,217);border-start-start-radius:inherit;border-start-end-radius:inherit;background-color:#fff;overflow-y:auto;height:fit-content;max-height:calc(100% - 3.3em);width:100%}.modal-content>p{margin-inline:1em}.modal-content>ul{margin-inline-end: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-end-start-radius:inherit;border-end-end-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;inset-block:0;margin-top:auto;margin-bottom:auto;cursor:pointer;-webkit-user-select:none;user-select:none;margin-inline:.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:2;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-end{position:absolute;inset-inline-end:calc(10% + .35em);inset-block-end:.85em}.inside-start{position:absolute;inset-inline-start:calc(10% + .35em);inset-block-end:.85em}.outside-start{position:absolute;inset-inline-end:calc(11px - .55em);inset-block-end:.88em}.outside-end{position:absolute;inset-inline-start:calc(11px - .55em);inset-block-end:.88em}#upload-images-icon{position:absolute;pointer-events:none;width:1.45em;height:1.45em;inset-inline-start:.11em;inset-block-end:.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;inset-inline-start:.07em;inset-block-end:.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;inset-inline-start:.17em;inset-block-end:.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;inset-inline-start:.23em;inset-block-end:.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;inset-inline-start:.25em;inset-block-end:.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;inset-inline-start:.25em;inset-block-end:.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;inset-inline-start:.35em;inset-block-end:.35em;border-radius:2px}.submit-button-enlarged{scale:1.1;margin-inline:.3em}.loading-submit-button{position:relative;inset-inline-start: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;inset-block-end:-.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}}.tooltip{position:absolute;visibility:hidden;z-index:1;pointer-events:none;padding:5px;padding-inline:7px;background-color:#333;border-radius:5px;width:max-content}.tooltip-text{color:#fff;font-size:13px}.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-svg-text{padding:1px;height:1.65em;display:flex}.input-button-svg-text>svg{padding:.22rem}.input-button-svg-text>div{margin-inline-start:2px}.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-inline:4px;height:1.6em;width:max-content}#custom-icon{height:100%;width:1.2em}.custom-button-container-default{color:#505050}.custom-button-container-default>.dropup-menu-item-icon{color:unset}.custom-button-container-default>svg{filter:brightness(0) saturate(100%) invert(39%) sepia(1%) saturate(0%) hue-rotate(83deg) brightness(93%) contrast(90%)}.custom-button-container-default>.dropup-menu-item-icon>svg{position:absolute;inset-inline-start:.2em}.custom-button-container-active{background-color:#edf7ff;color:#0285ff}.custom-button-container-active:hover,.custom-button-container-active:focus-visible{background-color:#def0ff}.custom-button-container-active:active{background-color:#d2eaff}.custom-button-container-active>svg{filter:brightness(0) saturate(100%) invert(32%) sepia(34%) saturate(4196%) hue-rotate(196deg) brightness(107%) contrast(104%)}.custom-button-container-disabled{color:#aeaeae;cursor:auto}.custom-button-container-disabled>div{pointer-events:none}.custom-button-container-disabled:hover,.custom-button-container-disabled:focus-visible{background-color:transparent}.custom-button-container-disabled:active{background-color:transparent}.custom-button-container-disabled>svg{filter:brightness(0) saturate(100%) invert(67%) sepia(0%) saturate(818%) hue-rotate(28deg) brightness(102%) contrast(100%)}#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-start-adjustment{margin-inline-start:1.5em}.text-input-container-end-adjustment{margin-inline-end:1.5em}.text-input-container-start-small-adjustment{margin-inline-start:1.1em}.text-input-container-start-small-adjustment>.outside-start{inset-inline-end:calc(14px - .55em)}.text-input-container-end-small-adjustment{margin-inline-end:1.1em}.text-input-container-end-small-adjustment>.outside-end{inset-inline-start:calc(14px - .55em)}#text-input{text-align:start;outline:none;word-wrap:break-word;line-break:auto}.text-input-styling{padding:.4em .5em;overflow:overlay;width:100%}.text-input-inner-start-adjustment{padding-inline-start:2.2em}.text-input-inner-end-adjustment{padding-inline-end: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-end>#dropup-menu,.inside-end>#dropup-menu{inset-inline-end:0px}#dropup-icon{position:absolute;pointer-events:none;width:1.16em;height:1.2em;inset-inline-start:.265em;bottom:.43em;filter:brightness(0) saturate(100%) invert(54%) sepia(0%) saturate(724%) hue-rotate(6deg) brightness(92%) contrast(90%)}.dropup-button>*{pointer-events:none}#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-inline-start:.35em;padding-inline-end:.84em;padding-top:.28em;padding-bottom:.28em;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-start-start-radius:inherit;border-start-end-radius:inherit}.dropup-menu-item:last-child{padding-bottom:.45em;border-end-start-radius:inherit;border-end-end-radius:inherit}.dropup-menu-item-icon{width:1.39em;position:relative}.dropup-menu-item-icon>svg{bottom:0!important;top:0!important;margin-bottom:auto;margin-top:auto}#dropup-menu-item-icon-element-custom{position:absolute;pointer-events:none;width:1.21em;height:1.21em;inset-inline-start:.28em;filter:brightness(0) saturate(100%) invert(15%) sepia(0%) saturate(337%) hue-rotate(125deg) brightness(91%) contrast(94%)}.dropup-menu-item-text{margin-inline-start:.56em;margin-top:.08em;width:max-content}#input{width:100%;display:inline-flex;text-align:center;margin-inline:auto;margin-top:auto;position:relative;justify-content:center}#chat-view{height:100%;grid-template-columns:100%}.deep-chat-downwards-mode{display:grid}.deep-chat-upwards-mode{display:flex;flex-direction:column}::-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-inline-start: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(){xt.attemptAppendStyleSheetToHead(this.style),ce.processConnect(this),(!this._activeService||this._activeService.demo)&&(this._activeService=Zr.create(this)),this.auxiliaryStyle&&!this._auxiliaryStyleApplied&&(_t.apply(this.auxiliaryStyle,this.shadowRoot),this._auxiliaryStyleApplied=!0),_t.applyDefaultStyleToComponent(this.style,this.chatStyle),ce.checkForContainerStyles(this,this._elementRef),this._activeService.key&&this._activeService.validateKeyProperty?n.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):this._activeService instanceof Oi&&!this._activeService.key?this._activeService instanceof Oi&&zi.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):(this._childElement??(this._childElement=this.children[0]),Jl.render(this,this._elementRef,this._activeService,this._childElement)),this._hasBeenRendered||ti.onRender(this),this._hasBeenRendered=!0}disconnectedCallback(){Vi.chat=void 0}}Ql([Xr("object")],Yl.prototype,"connect"),Ql([Xr("object")],Yl.prototype,"directConnection"),Ql([Xr("object")],Yl.prototype,"webModel"),Ql([Xr("object")],Yl.prototype,"requestBodyLimits"),Ql([Xr("function")],Yl.prototype,"requestInterceptor"),Ql([Xr("function")],Yl.prototype,"responseInterceptor"),Ql([Xr("function")],Yl.prototype,"validateInput"),Ql([Xr("function")],Yl.prototype,"loadHistory"),Ql([Xr("object")],Yl.prototype,"chatStyle"),Ql([Xr("object")],Yl.prototype,"attachmentContainerStyle"),Ql([Xr("object")],Yl.prototype,"dropupStyles"),Ql([Xr("object")],Yl.prototype,"inputAreaStyle"),Ql([Xr("object")],Yl.prototype,"textInput"),Ql([Xr("object")],Yl.prototype,"defaultInput"),Ql([Xr("object")],Yl.prototype,"submitButtonStyles"),Ql([Xr("object")],Yl.prototype,"customButtons"),Ql([Xr("string")],Yl.prototype,"auxiliaryStyle"),Ql([Xr("array")],Yl.prototype,"history"),Ql([Xr("object")],Yl.prototype,"browserStorage"),Ql([Xr("object")],Yl.prototype,"introMessage"),Ql([Xr("object")],Yl.prototype,"avatars"),Ql([Xr("object")],Yl.prototype,"names"),Ql([Xr("object")],Yl.prototype,"displayLoadingBubble"),Ql([Xr("object")],Yl.prototype,"errorMessages"),Ql([Xr("object")],Yl.prototype,"messageStyles"),Ql([Xr("object")],Yl.prototype,"textToSpeech"),Ql([Xr("object")],Yl.prototype,"speechToText"),Ql([Xr("object")],Yl.prototype,"images"),Ql([Xr("object")],Yl.prototype,"gifs"),Ql([Xr("object")],Yl.prototype,"camera"),Ql([Xr("object")],Yl.prototype,"audio"),Ql([Xr("object")],Yl.prototype,"microphone"),Ql([Xr("object")],Yl.prototype,"mixedFiles"),Ql([Xr("object")],Yl.prototype,"dragAndDrop"),Ql([Xr("object")],Yl.prototype,"htmlWrappers"),Ql([Xr("object")],Yl.prototype,"htmlClassUtilities"),Ql([Xr("object")],Yl.prototype,"remarkable"),Ql([Xr("object")],Yl.prototype,"focusMode"),Ql([Xr("boolean")],Yl.prototype,"upwardsMode"),Ql([Xr("object")],Yl.prototype,"scrollButton"),Ql([Xr("object")],Yl.prototype,"hiddenMessages"),Ql([Xr("number")],Yl.prototype,"maxVisibleMessages"),Ql([Xr("function")],Yl.prototype,"onMessage"),Ql([Xr("function")],Yl.prototype,"onClearMessages"),Ql([Xr("function")],Yl.prototype,"onComponentRender"),Ql([Xr("function")],Yl.prototype,"onInput"),Ql([Xr("function")],Yl.prototype,"onError"),Ql([Xr("object")],Yl.prototype,"demo"),Ql([Xr("object")],Yl.prototype,"_insertKeyViewStyles"),customElements.define("deep-chat",Yl);export{Yl as DeepChat};
1
+ const t="classList",e="style",i=(t="div")=>document.createElement(t);class s{static render(t,e){const s=i();s.id="error-view",s.innerText=e,t.replaceChildren(s)}}class n{static onLoad(t){t.innerHTML='<div id="loading-validate-key-property"></div>'}static createElements(){const t=i();return t.id="validate-property-key-view",t}static render(t,e,i){const o=n.createElements(),r={onSuccess:e,onFail:s.render.bind(this,t,"Your 'key' has failed authentication"),onLoad:n.onLoad.bind(this,o)};i.key&&i.verifyKey(i.key,r),t.replaceChildren(o)}}const o="service",r="text",a="html",l="error",c="https://deepchat.dev/docs/",h="ai",u="user",d="assistant",p="error-message-text",m="deep-chat-outer-container-role-",v="empty-message",f="deep-chat-top-message",g="deep-chat-middle-message",b="deep-chat-bottom-message",y="src",w="type",x="file",k="files",_="image",C="images",A="camera",M="gifs",T="audio",S="microphone",j="mixedFiles",E="any",I="file-message",$="start",O="messages",P="role",B="string",R=t=>JSON.stringify(t),F=t=>JSON.parse(R(t));function L(t){return t.charAt(0).toUpperCase()+t.slice(1)}function q(t,e,i,s){const n=`\n${L(e)} message: ${R(t)} \n`,o=i?`${L(e)} message after interceptor: ${function(t){return t&&R(t)}(s)} \n`:"";return n+o}const z=function(t,e,i,s){return`${q(t,e,i,s)}Make sure the ${e} message is using the Response format: ${c}connect/#Response \nYou can also augment it using the responseInterceptor property: ${c}interceptors#responseInterceptor`},D=function(t,e){const i="request";return`${q(t,i,e)}Make sure the ${i} message is using the {body: {text: string}} format, e.g: {body: {text: "Model Response"}}`},N=function(t,e,i){const s="response";return`${q(t,s,e,i)}Make sure the ${s} message is using the {text: string} format, e.g: {text: "Model Response"}`},U=function(t){return`${t} failed - please wait for chat view to render before calling this property.`},H="Invalid API Key",V="Failed to connect",W="Request settings have not been set up",G="No file was added",Z="Image was not found",K="Multi-response arrays are not supported for streaming",J=`Make sure the events are using {text: string} or {html: string} format.\nYou can also augment them using the responseInterceptor property: ${c}interceptors#responseInterceptor`,X=`No valid stream events were sent.\n${J}`,Q="Please define a `function_handler` property inside the service config.",Y="Function tool response must be an array or contain a text property",tt="Failed to fetch history",et="inside-start",it="inside-end",st="outside-start",nt="outside-end",ot="dropup-menu",rt="default",at="hover",lt="click",ct="active",ht="disabled",ut="svg",dt="unavailable",pt="styles",mt="mouseenter",vt="mouseleave",ft="submit",gt="loading",bt="stop",yt="unsupported",wt="commandMode";class xt{static unsetStyle(t,i){const s=Object.keys(i).reduce((t,e)=>(t[e]="",t),{});Object.assign(t[e],s)}static unsetActivityCSSMouseStates(t,e){e[lt]&&xt.unsetStyle(t,e[lt]),e[at]&&xt.unsetStyle(t,e[at])}static unsetAllCSSMouseStates(t,e){xt.unsetActivityCSSMouseStates(t,e),e[rt]&&xt.unsetStyle(t,e[rt])}static processStateful(t){const e=t[rt]||{},i=Object.assign(F(e),null==t?void 0:t[at]),s=Object.assign(F(i),null==t?void 0:t[lt]);return{[rt]:e,[at]:i,[lt]:s}}static mergeStatefulStyles(t){const e={[rt]:{},[at]:{},[lt]:{}};return t.forEach(t=>{e[rt]=Object.assign(e[rt],t[rt]),e[at]=Object.assign(e[at],t[at]),e[lt]=Object.assign(e[lt],t[lt])}),e}static overwriteDefaultWithAlreadyApplied(t,i){Object.keys(t[rt]||[]).forEach(s=>{var n;const o=s;i[e][o]&&null!=(n=t[rt])&&n[o]&&(t[rt][s]=i[e][o])})}static applyToStyleIfNotDefined(t,e){for(const i in e){const s=e[i];""===t[i]&&s&&(t[i]=s)}}}const kt=class t{static attemptAppendStyleSheetToHead(e){if(e.fontFamily&&e.fontFamily!==t.DEFAULT_FONT_FAMILY)return;const s=document.getElementsByTagName("head")[0];if(!Array.from(s.getElementsByTagName("link")).some(e=>e.getAttribute("href")===t.FONT_URL)){const e=i("link");e.rel="stylesheet",e.href=t.FONT_URL,s.appendChild(e)}}};kt.FONT_URL="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap",kt.DEFAULT_FONT_FAMILY="'Inter', sans-serif, Avenir, Helvetica, Arial";let _t=kt;const Ct=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 s=i("style");s.innerHTML=t,e.appendChild(s)}static applyDefaultStyleToComponent(e,i){i&&xt.applyToStyleIfNotDefined(e,i),xt.applyToStyleIfNotDefined(e,t.DEFAULT_COMPONENT_STYLE)}};Ct.DEFAULT_COMPONENT_STYLE={height:"350px",width:"320px",borderTop:"1px solid #cacaca",borderRight:"1px solid #cacaca",borderLeft:"1px solid #cacaca",borderBottom:"1px solid #cacaca",fontFamily:_t.DEFAULT_FONT_FAMILY,fontSize:"0.9rem",backgroundColor:"white",position:"relative",overflow:"hidden"};let At=Ct;const Mt=class s{static buildElement(){const e=i();e[t].add("tooltip");const s=i("span");return s[t].add("tooltip-text"),e.appendChild(s),e}static tryCreateConfig(t,i){if(i)return"boolean"==typeof i?{[r]:t}:{[r]:i[r]||t,timeout:i.timeout||0,style:i[e]}}static traverseParentUntilContainer(t){let e=t;for(;e.parentElement;)e=e.parentElement;return e}static setPosition(t,i){const n=i.getRootNode().host.getBoundingClientRect(),o=t.getBoundingClientRect(),r=i.getBoundingClientRect().width/2,a=o.left+o.width/2;i[e].left=a-r-n.left+"px",i[e].top=o.top-36-n.top+"px";const l=i.getBoundingClientRect();l.left<n.left?i[e].left=`${s.OVERFLOW_NEW_POSITION_PX}px`:l.right>n.right&&(i[e].left=n.width-l.width-s.OVERFLOW_NEW_POSITION_PX+"px")}static display(t,i,n){return n||(n=s.traverseParentUntilContainer(t).nextSibling),i[r]&&(n.children[0].textContent=i[r]),{timeout:setTimeout(()=>{n[e].visibility="visible",s.setPosition(t,n),i[e]&&Object.assign(n[e],i[e])},i.timeout||0),element:n}}static hide(t,i){clearTimeout(t.timeout),t.element[e].visibility="hidden",i[e]&&xt.unsetStyle(t.element,i[e]),t.element[e].left="",t.element[e].top=""}};Mt.OVERFLOW_NEW_POSITION_PX=4;let Tt=Mt;const St=class{};St.IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),St.IS_CHROMIUM=window.chrome,St.IS_MOBILE=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent);let jt=St;var Et=(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))(Et||{});const It=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[k].length&&i.addFilesToAnyType(Array.from(t.clipboardData[k]))})}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),Rt.focusEndOfInput(s)),null==e||e()}};It.PERMITTED_KEYS=new Set([Et.BACKSPACE,Et.DELETE,Et.ARROW_RIGHT,Et.ARROW_LEFT,Et.ARROW_DOWN,Et.ARROW_UP,Et.META,Et.CONTROL,Et.ENTER]);let $t=It;class Ot{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 Pt=class s{constructor(t,e,i,n){var o,a,l,c;this._isComposing=!1;const h=s.processConfig(e,t.textInput);this.elementRef=s.createContainerElement(null==(o=null==h?void 0:h[pt])?void 0:o.container),this._config=h,this.inputElementRef=this.createInputElement(null==(a=t.defaultInput)?void 0:a[r],n),s.addFilesToAnyType(i,null==(l=t.defaultInput)?void 0:l[k]),this.elementRef.appendChild(this.inputElementRef),t.setPlaceholderText=this.setPlaceholderText.bind(this),t.setPlaceholderText((null==(c=this._config.placeholder)?void 0:c[r])||"Ask me anything!"),this._browserStorage=n,setTimeout(()=>{$t.add(this.inputElementRef,i,this._config.characterLimit,t._validationHandler),this._onInput=e.onInput})}static processConfig(t,e){var i;return e??(e={}),e[ht]??(e[ht]=t.isTextInputDisabled),e.placeholder??(e.placeholder={}),(i=e.placeholder)[r]??(i[r]=t.textInputPlaceholderText),e}static createContainerElement(t){const s=i();return s.id="text-input-container",Object.assign(s[e],t),s}static preventAutomaticScrollUpOnNewLine(t){let e;t.addEventListener("keydown",()=>{e=window.scrollY}),t.addEventListener("input",()=>{e!==window.scrollY&&window.scrollTo({top:e})})}clear(){var i,s,n;const o=window.scrollY;this.inputElementRef[t].contains(`text-input-${ht}`)||(Object.assign(this.inputElementRef[e],null==(i=this._config.placeholder)?void 0:i[e]),this.inputElementRef.textContent="",Rt.focusEndOfInput(this.inputElementRef),null==(s=this._onInput)||s.call(this,!1),null==(n=this._browserStorage)||n.addInputText("")),jt.IS_CHROMIUM&&window.scrollTo({top:o})}createInputElement(n,o){var a,l,c,h;const u=i();return u.id=s.TEXT_INPUT_ID,u[t].add("text-input-styling"),u[P]="textbox","string"==typeof n?u.innerText=n:null!=o&&o.trackInputText&&(u.innerText=o.get().inputText||""),jt.IS_MOBILE&&u.setAttribute("tabindex","0"),jt.IS_CHROMIUM&&s.preventAutomaticScrollUpOnNewLine(u),"boolean"==typeof this._config[ht]&&!0===this._config[ht]?(u.contentEditable="false",u[t].add(`text-input-${ht}`),u.setAttribute(`aria-${ht}`,"true")):(u.contentEditable="true",u.removeAttribute(`aria-${ht}`),this.addEventListeners(u)),Object.assign(u[e],null==(a=this._config[pt])?void 0:a[r]),Object.assign(u[e],null==(l=this._config.placeholder)?void 0:l[e]),null!=(h=null==(c=this._config.placeholder)?void 0:c[e])&&h.color||u.setAttribute("textcolor",""),u}static addFilesToAnyType(t,e){e&&t.addFilesToAnyType(Array.from(e).map(t=>t))}removePlaceholderStyle(){var i,s,n,o;!this.inputElementRef[t].contains(`text-input-${ht}`)&&null!=(i=this._config.placeholder)&&i[e]&&(xt.unsetStyle(this.inputElementRef,null==(s=this._config.placeholder)?void 0:s[e]),Object.assign(this.inputElementRef[e],null==(o=null==(n=this._config)?void 0:n[pt])?void 0:o[r]))}addEventListeners(t){var i,s;null!=(i=this._config[pt])&&i.focus&&(t.onfocus=()=>{var t;return Object.assign(this.elementRef[e],null==(t=this._config[pt])?void 0:t.focus)},t.onblur=this.onBlur.bind(this,this._config[pt].focus,null==(s=this._config[pt])?void 0:s.container)),t.addEventListener("keydown",this.onKeydown.bind(this)),t.addEventListener("input",this.onInput.bind(this)),t.addEventListener("paste",Ot.sanitizePastedTextContent),t.addEventListener("compositionstart",()=>this._isComposing=!0),t.addEventListener("compositionend",()=>this._isComposing=!1)}onBlur(t,i){xt.unsetStyle(this.elementRef,t),i&&Object.assign(this.elementRef[e],i)}onKeydown(t){var e;t.key===Et.ENTER&&!jt.IS_MOBILE&&!this._isComposing&&!t.ctrlKey&&!t.shiftKey&&(t.preventDefault(),null==(e=this.submit)||e.call(this))}onInput(){var t,i;this.isTextInputEmpty()?Object.assign(this.inputElementRef[e],null==(t=this._config.placeholder)?void 0:t[e]):this.removePlaceholderStyle(),null==(i=this._onInput)||i.call(this,!0)}setPlaceholderText(t){this.inputElementRef.setAttribute("deep-chat-placeholder-text",t),this.inputElementRef.setAttribute("aria-label",t)}isTextInputEmpty(){return""===this.inputElementRef.textContent}};Pt.TEXT_INPUT_ID="text-input";let Bt=Pt;class Rt{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),(jt.IS_MOBILE||jt.IS_SAFARI)&&t.focus()}static focusFromParentElement(t){const e=t.querySelector(`#${Bt.TEXT_INPUT_ID}`);e&&Rt.focusEndOfInput(e)}}const Ft="Authentication",Lt="Authorization",qt="authorization",zt="Unauthorized",Dt="Authorization header",Nt="Invalid",Ut="Incorrect",Ht="authentication_error",Vt="invalid_request_error",Wt="Content-Type",Gt="content-type",Zt="application/json",Kt="object",Jt="completed",Xt="Bearer ",Qt="GET",Yt="POST",te="Upload an audio file",ee="function_call",ie="input_audio",se="image_url",ne="system",oe=class t{static addElements(t,...e){e.forEach(e=>t.appendChild(e))}static isScrollbarAtBottomOfElement(e,i=t.CODE_SNIPPET_GENERATION_JUMP){const s=e.scrollHeight,n=e.clientHeight;return e.scrollTop>=s-n-i}static cloneElement(t){const e=t.cloneNode(!0);return t.parentNode.replaceChild(e,t),e}static scrollToBottom(t,e=!1,i){t.scrollButton&&t.scrollButton.hiddenElements.size>0&&t.scrollButton.clearHidden(),i?t.elementRef.scrollTo({left:0,top:i.offsetTop}):e?t.elementRef.scrollTo({left:0,top:t.elementRef.scrollHeight,behavior:"smooth"}):t.elementRef.scrollTop=t.elementRef.scrollHeight}static scrollToTop(t){t.scrollTop=0}static isVisibleInParent(t,e){const i=t.getBoundingClientRect(),s=e.getBoundingClientRect();return i.bottom>s.top&&i.top<s.bottom}static waitForScrollEnd(t,e){let i=-1,s=0;const n=()=>{const o=t.scrollTop;if(o===i){if(s++,s>2)return void e()}else s=0,i=o;requestAnimationFrame(n)};requestAnimationFrame(n)}static assignButtonEvents(t,e){t.onclick=e,t.onkeydown=t=>{t.key===Et.ENTER&&setTimeout(e)}}};oe.CODE_SNIPPET_GENERATION_JUMP=1;let re=oe;const ae=class t{static speak(t,e){if(!e.audio&&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.audio&&(s.audio=e.audio),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)}};ae.LOAD_VOICES_MS=200;let le=ae;const ce=class t{static colorToHex(t){const s=i();return s[e].color=t,document.body.appendChild(s),`#${window.getComputedStyle(s).color.match(/\d+/g).map(t=>parseInt(t).toString(16).padStart(2,"0")).join("")}`}static setDots(i,s){var n,o;if(null!=(o=null==(n=null==s?void 0:s[pt])?void 0:n.bubble)&&o.color){const n=t.colorToHex(s[pt].bubble.color);i[e].setProperty("--loading-message-color",n),i[e].setProperty("--loading-message-color-fade",`${n}33`)}else i[e].setProperty("--loading-message-color","#848484"),i[e].setProperty("--loading-message-color-fade","#55555533")}static setRing(i,s){const{color:n,width:o,height:r,margin:a,border:l}=s||{};if(n){const s=t.colorToHex(n);i[e].setProperty("--loading-history-color",s)}else i[e].setProperty("--loading-history-color","#dbdbdb");i[e].setProperty("--loading-history-height",r||"57px"),i[e].setProperty("--loading-history-width",o||"57px"),i[e].setProperty("--loading-history-margin",a||"7px"),i[e].setProperty("--loading-history-border",l||"6px solid")}};ce.BUBBLE_CLASS="deep-chat-loading-message-bubble",ce.DOTS_CONTAINER_CLASS="deep-chat-loading-message-dots-container";let he=ce;class ue{static checkForContainerStyles(t,i){const s=t.containerStyle;s&&(Object.assign(i[e],s),console[l](`The containerStyle property${pe}1.3.14.`),console[l](`${me}the style property instead: ${c}styles#style`))}static handleResponseProperty(t){return console[l](`The {result: ....} response object type${pe}1.3.0.`),console[l](`${me}the new response object: ${c}connect#Response`),t.result}static processHistory(t){const e=t.initialMessages;if(e)return console[l](`The initialMessages property${pe}2.0.0.`),console[l](`${me}the history property instead: ${c}messages/#history`),e}static processHistoryFile(t){const e=t[x];e&&(console[l](`The file property in MessageContent${pe}1.3.17.`),console[l](`${me}the files array property: ${c}messages/#MessageContent`),t[k]=[e])}static processValidateInput(t){const e=t.validateMessageBeforeSending;if(e)return console[l](`The validateMessageBeforeSending property${pe}1.3.24.`),console[l](`${me}validateInput: ${c}interceptors#validateInput`),e}static processSubmitUserMessage(t){return console[l](`The submitUserMessage(text: string) argument string type${pe}1.4.4.`),console[l](`${me}the new argument type: ${c}methods#submitUserMessage`),{[r]:t}}static flagHTMLUpdateClass(e){var i;null!=(i=e.children[0])&&i[t].contains("deep-chat-update-message")&&(console[l](`The "deep-chat-update-message" html class${pe}1.4.4.`),console[l](`${me}using {..., overwrite: true} object: ${c}connect#Response`))}static processConnect(t){const e=t;e.request&&(e.connect?Object.assign(e.connect,e.request):e.connect=e.request,console[l](`The request property${pe}2.0.0.`),console[l](`${ve}connect object: ${c}connect#connect-1`))}static checkForStream(t){const e=t.stream;if(e)return console[l](`The stream property${ge}the connect object in version 2.0.0.`),console[l](`${ve}connect object: ${c}connect#connect-1`),e}static fireOnNewMessage(t,e){var i;const s=t;s.onNewMessage&&(console[l](`The onNewMessage event${pe}2.0.0.`),console[l](`${ve}onMessage event: ${c}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[l](`The request property in file configuration${pe}2.0.0.`),console[l](`Please use the connect property instead: ${c}files`),e.connect||(e.connect=e.request))}static processMessageStyles(t){if(!t)return;const e=F(t),i=e.loading;return i&&(i.outerContainer||i.innerContainer||i.bubble||i.media)&&(console[l](`The loading message styles are defined using LoadingMessageStyles interface${de}2.1.0.`),console[l](`Check it out here: ${c}messages/styles#LoadingMessageStyles`),e.loading={message:{styles:i}}),e}static processDemo(t){return"boolean"==typeof t||t.displayLoadingBubble&&(console[l](`The demo displayLoadingBubble property${pe}2.1.0.`),console[l](`Please use displayLoading instead: ${c}modes#demo`),t.displayLoading={message:!0}),t}static processCohere(t){const e=t,i=`${ve}official documentation: ${c}directConnection/Cohere`;return e.chat&&(console[l](`Cohere chat property${pe}2.2.3.`),console[l](i),delete e.chat),e.textGeneration?(console[l](`Cohere textGeneration${fe}2.2.3.`),console[l](i),delete e.textGeneration,!1):!e.summarization||(console[l](`Cohere summarization${fe}2.2.3.`),console[l](i),delete e.summarization,!1)}static processStreamHTMLWrappers(t){if(!t||typeof t!==Kt)return;const e=t.htmlWrappers;return e?(console[l](`The htmlWrappers property${ge}Deep Chat's base${de}2.3.0.`),console[l](`Check it out here: ${c}messages/HTML#htmlWrappers`),e):void 0}static processFocusMode(t){return!t||"boolean"==typeof t||t.scroll&&(console[l](`The scroll property in focusMode has been changed to smoothScroll${de}2.3.0.`),console[l](`Check it out here: ${c}modes#focusMode`),t.smoothScroll=!0),t}static processPosition(t){if(!t)return t;const e=`Position names have been updated${de}2.3.1.`;return"inside-left"===t?(console[l](e),et):"inside-right"===t?(console[l](e),it):"outside-left"===t?(console[l](e),st):"outside-right"===t?(console[l](e),nt):t}static processBrowserStorage(t){const e=t.get();e&&Array.isArray(e)&&t.addMessages(e)}}const de=" since version ",pe=` is deprecated ${de}`,me="Please change to using ",ve="Please see the ",fe=` is not supported ${de}`,ge=" has been moved to ";class be{static mouseUp(t,i){xt.unsetAllCSSMouseStates(t,i),Object.assign(t[e],i[rt]),Object.assign(t[e],i[at])}static mouseDown(t,i){Object.assign(t[e],i[lt])}static mouseLeave(t,i){xt.unsetAllCSSMouseStates(t,i),Object.assign(t[e],i[rt])}static mouseEnter(t,i){Object.assign(t[e],i[at])}static add(t,e){t.addEventListener(mt,be.mouseEnter.bind(this,t,e)),t.addEventListener(vt,be.mouseLeave.bind(this,t,e)),t.addEventListener("mousedown",be.mouseDown.bind(this,t,e)),t.addEventListener("mouseup",be.mouseUp.bind(this,t,e))}}const ye={"deep-chat-button":{styles:{[rt]:{backgroundColor:"white",padding:"5px",paddingLeft:"7px",paddingRight:"7px",border:"1px solid #c2c2c2",borderRadius:"6px",cursor:"pointer"},[at]:{backgroundColor:"#fafafa"},[lt]:{backgroundColor:"#f1f1f1"}}}},we=Object.keys(ye);class xe{static applySuggestionEvent(t,e){setTimeout(()=>{e.addEventListener(lt,()=>{var i,s;null==(s=t.submitUserMessage)||s.call(t,{[r]:(null==(i=e.textContent)?void 0:i.trim())||""})})})}static isElementTemporary(e){var i;return!!e&&(null==(i=e.bubbleElement.children[0])?void 0:i[t].contains("deep-chat-temporary-message"))}static doesElementContainDeepChatClass(e){return we.find(i=>e[t].contains(i))}static applyEvents(t,e){const i=ye[e].events;Object.keys(i||[]).forEach(e=>{t.addEventListener(e,null==i?void 0:i[e])})}static getProcessedStyles(e,i,s){const n=Array.from(i[t]).reduce((t,i)=>{var s;const n=null==(s=e[i])?void 0:s[pt];return n&&e[i][pt]&&t.push(n),t},[]),o=ye[s][pt];if(o){const t=F(o);t[rt]&&xt.overwriteDefaultWithAlreadyApplied(t,i),n.unshift(t)}const r=xt.mergeStatefulStyles(n);return xt.processStateful(r)}static applyDeepChatUtilities(t,e,i){we.forEach(t=>{const s=i.getElementsByClassName(t);Array.from(s||[]).forEach(i=>{const s=xe.getProcessedStyles(e,i,t);ke.applyStylesToElement(i,s),xe.applyEvents(i,t)})});const s=i.getElementsByClassName("deep-chat-suggestion-button");Array.from(s).forEach(e=>xe.applySuggestionEvent(t,e))}}class ke{static applyStylesToElement(t,i){const s=xt.processStateful(i);be.add(t,s),Object.assign(t[e],s[rt])}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&&ke.applyEventsToElement(t,i),s&&!xe.doesElementContainDeepChatClass(t)&&ke.applyStylesToElement(t,s)}static applyCustomClassUtilities(t,e){Object.keys(t).forEach(i=>{const s=e.getElementsByClassName(i);Array.from(s).forEach(e=>{t[i]&&ke.applyClassUtilitiesToElement(e,t[i])})})}static apply(t,e){xe.applyDeepChatUtilities(t,t.htmlClassUtilities,e),ke.applyCustomClassUtilities(t.htmlClassUtilities,e)}static traverseNodes(t,e){t.nodeType===Node.ELEMENT_NODE&&e.push(t.outerHTML),t.childNodes.forEach(t=>{ke.traverseNodes(t,e)})}static splitHTML(t){const e=(new DOMParser).parseFromString(t,"text/html"),i=[];return e.body.childNodes.forEach(t=>{ke.traverseNodes(t,i)}),i}static isTemporaryBasedOnHTML(t){const e=i();return e.innerHTML=t,xe.isElementTemporary({outerContainer:e,bubbleElement:e,innerContainer:e})}static replaceElementWithNewClone(t,e){var i;const s=(e||t).cloneNode(!0);return null==(i=t.parentNode)||i.replaceChild(s,t),s}static tryAddWrapper(t,e,i,s){if(e&&s){const e=(null==i?void 0:i[s])||(null==i?void 0:i[rt]);if(e)return t.innerHTML=e,{contentEl:ke.getTargetWrapper(t),wrapper:!0}}return{contentEl:t,wrapper:!1}}static getTargetWrapper(t){return t.getElementsByClassName("html-wrapper")[0]||t}}const _e=class e{static createElements(i,s,n,o,r=!1){const a=i.createMessageElementsOnOrientation("",n,o,r);a.bubbleElement[t].add(e.HTML_BUBBLE_CLASS);const{contentEl:l}=ke.tryAddWrapper(a.bubbleElement,s,i._customWrappers,n);return l.innerHTML=s,a}static overwriteElements(t,e,i){i.bubbleElement.innerHTML=e,ke.apply(t,i.outerContainer),ue.flagHTMLUpdateClass(i.bubbleElement)}static overwrite(t,i,s,n){const{messageToElements:o}=t,r=vs.overwriteMessage(o,n,i,s,a,e.HTML_BUBBLE_CLASS);return r&&e.overwriteElements(t,i,r),r}static create(t,i,s,n=!1){var o;const r=e.createElements(t,i,s,n);return vs.fillEmptyMessageElement(r.bubbleElement,i),ke.apply(t,r.outerContainer),ue.flagHTMLUpdateClass(r.bubbleElement),t.applyCustomStyles(r,s,!1,null==(o=t.messageStyles)?void 0:o[a]),r}static add(t,i,s,n,o=!1){if(null!=n&&n.status){const e=this.overwrite(t,i,s,t.messageElementRefs);if(e)return e;n.status=!1}if(o&&t.messageElementRefs.length>0&&ke.isTemporaryBasedOnHTML(i))return;const r=e.create(t,i,s,o);return o||t.appendOuterContainerElemet(r.outerContainer),r}};_e.HTML_BUBBLE_CLASS="html-message";let Ce=_e;class Ae{static katex(t,e,i){const s=(i||{}).delimiter||"$";if(1!==s.length)throw new Error("invalid delimiter");e.inline.ruler.push("katex",(t,e)=>{const i=t.pos,n=t.posMax;let o=i;if(t[y].charAt(o)!==s)return!1;for(++o;o<n&&t[y].charAt(o)===s;)++o;const r=t[y].slice(i,o);if(r.length>2)return!1;const a=o;let l=0;for(;o<n;){const i=t[y].charAt(o);if("{"!==i||0!==o&&"\\"===t[y].charAt(o-1)){if("}"!==i||0!==o&&"\\"===t[y].charAt(o-1)){if(i===s&&0===l){const i=o;let l=o+1;for(;l<n&&t[y].charAt(l)===s;)++l;if(l-i===r.length){if(!e){const e=t[y].slice(a,i).replace(/[ \n]+/g," ").trim();t.push({type:"katex",content:e,block:r.length>1,level:t.level})}return t.pos=l,!0}}}else if(l-=1,l<0)return!1}else l+=1;o+=1}return e||(t.pending+=r),t.pos+=r.length,!0},i),e.block.ruler.push("katex",(t,e,i)=>{let n=!1,o=t.bMarks[e]+t.tShift[e],r=t.eMarks[e];if(o+1>r)return!1;const a=t[y].charAt(o);if(a!==s)return!1;let l=o;o=t.skipChars(o,a);let c=o-l;if(2!==c)return!1;let h=e;for(;++h,!(h>=i||(o=l=t.bMarks[h]+t.tShift[h],r=t.eMarks[h],o<r&&t.tShift[h]<t.blkIndent));)if(!(t[y].charAt(o)!==s||t.tShift[h]-t.blkIndent>=4||(o=t.skipChars(o,a),o-l<c||(o=t.skipSpaces(o),o<r)))){n=!0;break}c=t.tShift[e],t.line=h+(n?1:0);const u=t.getLines(e+1,h,c,!0).replace(/[ \n]+/g," ").trim();return t.tokens.push({type:"katex",params:null,content:u,lines:[e,t.line],level:t.level,block:!0}),!0},i),e.renderer.rules.katex=(e,i)=>((e,i)=>{var s;return(null==(s=window.katex)?void 0:s.renderToString(e,{displayMode:i,throwOnError:!1,output:"mathml",...t}))||""})(e[i].content,e[i].block),e.renderer.rules.katex.delimiter=s}}var Me;function Te(t){return(Me=Me||document.createElement("textarea")).innerHTML="&"+t+";",Me.value}var Se=Object.prototype.hasOwnProperty;function je(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 Ee=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function Ie(t){return t.indexOf("\\")<0?t:t.replace(Ee,"$1")}function $e(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 Oe(t){if(t>65535){var e=55296+((t-=65536)>>10),i=56320+(1023&t);return String.fromCharCode(e,i)}return String.fromCharCode(t)}var Pe=/&([a-z#][a-z0-9]{1,31});/gi,Be=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;function Re(t,e){var i=0,s=Te(e);return e!==s?s:35===e.charCodeAt(0)&&Be.test(e)&&$e(i="x"===e[1].toLowerCase()?parseInt(e.slice(2),16):parseInt(e.slice(1),10))?Oe(i):t}function Fe(t){return t.indexOf("&")<0?t:t.replace(Pe,Re)}var Le=/[&<>"]/,qe=/[&<>"]/g,ze={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function De(t){return ze[t]}function Ne(t){return Le.test(t)?t.replace(qe,De):t}var Ue={};function He(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?He(t,e+2):e}Ue.blockquote_open=function(){return"<blockquote>\n"},Ue.blockquote_close=function(t,e){return"</blockquote>"+Ve(t,e)},Ue.code=function(t,e){return t[e].block?"<pre><code>"+Ne(t[e].content)+"</code></pre>"+Ve(t,e):"<code>"+Ne(t[e].content)+"</code>"},Ue.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&&Se.call(t,e)}(n.rules.fence_custom,o[0]))return n.rules.fence_custom[o[0]](t,e,i,s,n);l=' class="'+c+Ne(Fe(Ie(r)))+'"'}return"<pre><code"+l+">"+(i.highlight&&i.highlight.apply(i.highlight,[a.content].concat(o))||Ne(a.content))+"</code></pre>"+Ve(t,e)},Ue.fence_custom={},Ue.heading_open=function(t,e){return"<h"+t[e].hLevel+">"},Ue.heading_close=function(t,e){return"</h"+t[e].hLevel+">\n"},Ue.hr=function(t,e,i){return(i.xhtmlOut?"<hr />":"<hr>")+Ve(t,e)},Ue.bullet_list_open=function(){return"<ul>\n"},Ue.bullet_list_close=function(t,e){return"</ul>"+Ve(t,e)},Ue.list_item_open=function(){return"<li>"},Ue.list_item_close=function(){return"</li>\n"},Ue.ordered_list_open=function(t,e){var i=t[e];return"<ol"+(i.order>1?' start="'+i.order+'"':"")+">\n"},Ue.ordered_list_close=function(t,e){return"</ol>"+Ve(t,e)},Ue.paragraph_open=function(t,e){return t[e].tight?"":"<p>"},Ue.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?Ve(t,e):"")},Ue.link_open=function(t,e,i){var s=t[e].title?' title="'+Ne(Fe(t[e].title))+'"':"",n=i.linkTarget?' target="'+i.linkTarget+'"':"";return'<a href="'+Ne(t[e].href)+'"'+s+n+">"},Ue.link_close=function(){return"</a>"},Ue.image=function(t,e,i){var s=' src="'+Ne(t[e].src)+'"',n=t[e].title?' title="'+Ne(Fe(t[e].title))+'"':"";return"<img"+s+(' alt="'+(t[e].alt?Ne(Fe(Ie(t[e].alt))):"")+'"')+n+(i.xhtmlOut?" /":"")+">"},Ue.table_open=function(){return"<table>\n"},Ue.table_close=function(){return"</table>\n"},Ue.thead_open=function(){return"<thead>\n"},Ue.thead_close=function(){return"</thead>\n"},Ue.tbody_open=function(){return"<tbody>\n"},Ue.tbody_close=function(){return"</tbody>\n"},Ue.tr_open=function(){return"<tr>"},Ue.tr_close=function(){return"</tr>\n"},Ue.th_open=function(t,e){var i=t[e];return"<th"+(i.align?' style="text-align:'+i.align+'"':"")+">"},Ue.th_close=function(){return"</th>"},Ue.td_open=function(t,e){var i=t[e];return"<td"+(i.align?' style="text-align:'+i.align+'"':"")+">"},Ue.td_close=function(){return"</td>"},Ue.strong_open=function(){return"<strong>"},Ue.strong_close=function(){return"</strong>"},Ue.em_open=function(){return"<em>"},Ue.em_close=function(){return"</em>"},Ue.del_open=function(){return"<del>"},Ue.del_close=function(){return"</del>"},Ue.ins_open=function(){return"<ins>"},Ue.ins_close=function(){return"</ins>"},Ue.mark_open=function(){return"<mark>"},Ue.mark_close=function(){return"</mark>"},Ue.sub=function(t,e){return"<sub>"+Ne(t[e].content)+"</sub>"},Ue.sup=function(t,e){return"<sup>"+Ne(t[e].content)+"</sup>"},Ue.hardbreak=function(t,e,i){return i.xhtmlOut?"<br />\n":"<br>\n"},Ue.softbreak=function(t,e,i){return i.breaks?i.xhtmlOut?"<br />\n":"<br>\n":"\n"},Ue.text=function(t,e){return Ne(t[e].content)},Ue.htmlblock=function(t,e){return t[e].content},Ue.htmltag=function(t,e){return t[e].content},Ue.abbr_open=function(t,e){return'<abbr title="'+Ne(Fe(t[e].title))+'">'},Ue.abbr_close=function(){return"</abbr>"},Ue.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>"},Ue.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'},Ue.footnote_block_close=function(){return"</ol>\n</section>\n"},Ue.footnote_open=function(t,e){return'<li id="fn'+Number(t[e].id+1).toString()+'" class="footnote-item">'},Ue.footnote_close=function(){return"</li>\n"},Ue.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>'},Ue.dl_open=function(){return"<dl>\n"},Ue.dt_open=function(){return"<dt>"},Ue.dd_open=function(){return"<dd>"},Ue.dl_close=function(){return"</dl>\n"},Ue.dt_close=function(){return"</dt>\n"},Ue.dd_close=function(){return"</dd>\n"};var Ve=Ue.getBreak=function(t,e){return(e=He(t,e))<t.length&&"list_item_close"===t[e].type?"":"\n"};function We(){this.rules=je({},Ue),this.getBreak=Ue.getBreak}function Ge(){this.t=[],this.i=null}function Ze(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 Ke(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 Je(t,e,i,s){var n,o,r,a,l,c;if(42!==t.charCodeAt(0)||91!==t.charCodeAt(1)||-1===t.indexOf("]:")||((o=Ke(n=new Ze(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 Xe(t){var e=Fe(t);try{e=decodeURI(e)}catch{}return encodeURI(e)}function Qe(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=Xe(Ie(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=Ie(t.src.slice(o,e)),!t.parser.validateLink(n)))&&(t.linkContent=n,t.pos=e,!0)}function Ye(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=Ie(t.src.slice(s+1,e)),!0;92===i&&e+1<n?e+=2:e++}return!1}function ti(t){return t.trim().replace(/\s+/g," ").toUpperCase()}function ei(t,e,i,s){var n,o,r,a,l,c,h,u,d;if(91!==t.charCodeAt(0)||-1===t.indexOf("]:")||((o=Ke(n=new Ze(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(!Qe(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&&Ye(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=ti(t.slice(1,o)),typeof s.references[d]>"u"&&(s.references[d]={title:u,href:h}),r)}We.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},We.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},Ge.prototype.o=function(t){for(var e=this.t.length,i=-1;e--;)if(this.t[++i].name===t)return i;return-1},Ge.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))})})},Ge.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},Ge.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},Ge.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},Ge.prototype.push=function(t,e,i){var s=i||{};this.t.push({name:t,enabled:!0,fn:e,alt:s.alt||[]}),this.i=null},Ge.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},Ge.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},Ge.prototype.getRules=function(t){return null===this.i&&this.l(),this.i[t]||[]},Ze.prototype.pushPending=function(){this.tokens.push({type:"text",content:this.pending,level:this.pendingLevel}),this.pending=""},Ze.prototype.push=function(t){this.pending&&this.pushPending(),this.tokens.push(t),this.pendingLevel=this.level},Ze.prototype.cacheSet=function(t,e){for(var i=this.cache.length;i<=t;i++)this.cache.push(0);this.cache[t]=e},Ze.prototype.cacheGet=function(t){return t<this.cache.length?this.cache[t]:0};var ii=" \n()[]'\".,!?-";function si(t){return t.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1")}var ni=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,oi=/\((c|tm|r|p)\)/gi,ri={c:"©",r:"®",p:"§",tm:"™"};function ai(t){return t.indexOf("(")<0?t:t.replace(oi,function(t,e){return ri[e.toLowerCase()]})}var li=/['"]/,ci=/['"]/g,hi=/[-\s()\[\]]/;function ui(t,e){return!(e<0||e>=t.length)&&!hi.test(t[e])}function di(t,e,i){return t.substr(0,e)+i+t.substr(e+1)}var pi=[["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=Je(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=ei(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="(^|["+ii.split("").map(si).join("")+"])("+Object.keys(t.env.abbreviations).map(function(t){return t.substr(1)}).sort(function(t,e){return e.length-t.length}).map(si).join("|")+")($|["+ii.split("").map(si).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=ai(s=i.content),ni.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&&!li.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&&(ci.lastIndex=o,n=ci.exec(s),n);)if(l=!ui(s,n.index-1),o=n.index+1,m="'"===n[0],(c=!ui(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=di(f[h.token].content,h.pos,t.options.quotes[2]),i.content=di(i.content,n.index,t.options.quotes[3])):(f[h.token].content=di(f[h.token].content,h.pos,t.options.quotes[0]),i.content=di(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=di(i.content,n.index,"’"))}else m&&(i.content=di(i.content,n.index,"’"))}}]];function mi(){this.options={},this.ruler=new Ge;for(var t=0;t<pi.length;t++)this.ruler.push(pi[t][0],pi[t][1])}function vi(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 fi(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 gi(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}mi.prototype.process=function(t){var e,i,s;for(e=0,i=(s=this.ruler.getRules("")).length;e<i;e++)s[e](t)},vi.prototype.isEmpty=function(t){return this.bMarks[t]+this.tShift[t]>=this.eMarks[t]},vi.prototype.skipEmptyLines=function(t){for(var e=this.lineMax;t<e&&!(this.bMarks[t]+this.tShift[t]<this.eMarks[t]);t++);return t},vi.prototype.skipSpaces=function(t){for(var e=this.src.length;t<e&&32===this.src.charCodeAt(t);t++);return t},vi.prototype.skipChars=function(t,e){for(var i=this.src.length;t<i&&this.src.charCodeAt(t)===e;t++);return t},vi.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},vi.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 bi={};["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){bi[t]=!0});var yi=/^<([a-zA-Z]{1,15})[\s\/>]/,wi=/^<\/([a-zA-Z]{1,15})[\s>]/;function xi(t,e){var i=t.bMarks[e]+t.blkIndent,s=t.eMarks[e];return t.src.substr(i,s-i)}function ki(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 _i=[["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,_,C,A=!0;if((u=gi(t,e))>=0)v=!0;else{if(!((u=fi(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(C=!1,k=0,_=x.length;k<_;k++)if(x[k](t,n,i,!0)){C=!0;break}if(C)break;if(v){if((u=gi(t,n))<0)break}else if((u=fi(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(wi)))return!1}else if(!(o=t.src.slice(a,l).match(yi)))return!1;if(!0!==bi[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=xi(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=xi(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=xi(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)&&ki(t,e)>=0;if(h=e+1,t.isEmpty(h)&&++h>i||t.tShift[h]<t.blkIndent||(n=ki(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=ki(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=ki(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 Ci(){this.ruler=new Ge;for(var t=0;t<_i.length;t++)this.ruler.push(_i[t][0],_i[t][1],{alt:(_i[t][2]||[]).slice()})}Ci.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 Ai=/[\n\t]/g,Mi=/\r[\n\u0085]|[\u2424\u2028\u0085]/g,Ti=/\u00a0/g;function Si(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}}Ci.prototype.parse=function(t,e,i,s){var n,o=0,r=0;if(!t)return[];(t=(t=t.replace(Ti," ")).replace(Mi,"\n")).indexOf("\t")>=0&&(t=t.replace(Ai,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 vi(t,this,e,i,s),this.tokenize(n,n.line,n.lineMax)};for(var ji=[],Ei=0;Ei<256;Ei++)ji.push(0);function Ii(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}function $i(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&&(Ii(i)&&(r=!1),Ii(s)&&(a=!1))),{can_open:r,can_close:a,delims:n}}"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(t){ji[t.charCodeAt(0)]=1});var Oi=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Pi=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Bi=["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"],Ri=/^<([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])?)*)>/,Fi=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;function Li(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 qi=Li(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",/[^"'=<>`\x00-\x20]+/)("single_quoted",/'[^']*'/)("double_quoted",/"[^"]*"/)(),zi=Li(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",/[a-zA-Z_:][a-zA-Z0-9:._-]*/)("attr_value",qi)(),Di=Li(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",zi)(),Ni=Li(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",Di)("close_tag",/<\/[A-Za-z][A-Za-z0-9]*\s*>/)("comment",/<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->/)("processing",/<[?].*?[?]>/)("declaration",/<![A-Z]+\s+[^>]*>/)("cdata",/<!\[CDATA\[[\s\S]*?\]\]>/)();var Ui=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,Hi=/^&([a-z][a-z0-9]{1,31});/i;var Vi=[["text",function(t,e){for(var i=t.pos;i<t.posMax&&!Si(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!==ji[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=$i(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=$i(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(Oi,"$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(Pi,"$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=Ke(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,Qe(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&&Ye(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=Ke(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[ti(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=Ke(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(Fi))?!(Bi.indexOf(s[1].toLowerCase())<0||(o=s[0].slice(1,-1),r=Xe(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(Ri))&&(r=Xe("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(Ni),!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(Ui))return e||(i="x"===s[1][0].toLowerCase()?parseInt(s[1].slice(1),16):parseInt(s[1],10),t.pending+=$e(i)?Oe(i):Oe(65533)),t.pos+=s[0].length,!0}else if(s=t.src.slice(n).match(Hi)){var r=Te(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 Wi(){this.ruler=new Ge;for(var t=0;t<Vi.length;t++)this.ruler.push(Vi[t][0],Vi[t][1]);this.validateLink=Gi}function Gi(t){var e=t.trim().toLowerCase();return!(-1!==(e=Fe(e)).indexOf(":")&&-1!==["vbscript","javascript","file","data"].indexOf(e.split(":")[0]))}Wi.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)}},Wi.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()},Wi.prototype.parse=function(t,e,i,s){var n=new Ze(t,this,e,i,s);this.tokenize(n)};var Zi={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 Ki(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 Ji(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 Wi,this.block=new Ci,this.core=new mi,this.renderer=new We,this.ruler=new Ge,this.options={},this.configure(Zi[t]),this.set(e||{})}Ji.prototype.set=function(t){je(this.options,t)},Ji.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)})},Ji.prototype.use=function(t,e){return t(this,e),this},Ji.prototype.parse=function(t,e){var i=new Ki(this,t,e);return this.core.process(i),i.tokens},Ji.prototype.render=function(t,e){return e=e||{},this.renderer.render(this.parse(t,e),this.options,e)},Ji.prototype.parseInline=function(t,e){var i=new Ki(this,t,e);return i.inlineMode=!0,this.core.process(i),i.tokens},Ji.prototype.renderInline=function(t,e){return e=e||{},this.renderer.render(this.parseInline(t,e),this.options,e)};const Xi=class t{static addPlugins(t,e){const i=window.remarkable_plugins;if(i&&i.forEach(e=>{t.use(e.plugin,e.options)}),null!=e&&e.math){window.katex||(console.warn("window.katex not found, use chatElementRef.refreshMessages to re-render messages"),console.warn("See https://deepchat.dev/examples/externalModules"));const i="object"==typeof e.math?e.math.delimiter:"",s="object"==typeof e.math&&e.math.options?e.math.options:{};t.use(Ae.katex.bind(this,s),{delimiter:i})}}static instantiate(e){if(e)return new Ji({...t.DEFAULT_PROPERTIES,...e});if(window.hljs){const t=window.hljs;return new Ji({highlight:function(e,i){if(i&&t.getLanguage(i))try{return t.highlight(e,{language:i}).value}catch{console[l]("failed to setup the highlight dependency")}try{return t.highlightAuto(e).value}catch{console[l]("failed to automatically highlight messages")}return""},html:!1,xhtmlOut:!1,breaks:!0,langPrefix:"language-",linkTarget:"_blank",typographer:!0})}return new Ji(t.DEFAULT_PROPERTIES)}static createNew(e){const i=t.instantiate(e);return t.addPlugins(i,e),i.inline.validateLink=()=>!0,i}};Xi.DEFAULT_PROPERTIES={breaks:!0,linkTarget:"_blank"};let Qi=Xi;class Yi{constructor(t){this.storageKey="deep-chat-storage",this.maxMessages=1e3,this.trackInputText=!1,this.trackScrollHeight=!1,"object"==typeof t&&(t.key&&(this.storageKey=t.key),t.maxMessages&&(this.maxMessages=t.maxMessages),void 0!==t.inputText&&(this.trackInputText=t.inputText),void 0!==t.scrollHeight&&(this.trackScrollHeight=t.scrollHeight),t.clear=this.clear.bind(this),ue.processBrowserStorage(this))}get(){const t=localStorage.getItem(this.storageKey);return t?JSON.parse(t):{messages:[]}}set(t,e,i){const s={messages:t,inputText:e,scrollHeight:i};localStorage.setItem(this.storageKey,R(s))}addMessages(t){let e=t.length-this.maxMessages;e<0&&(e=0);const i=t.slice(e,t.length),s=this.trackInputText||this.trackScrollHeight?localStorage.getItem(this.storageKey):void 0,n=s?JSON.parse(s):void 0;this.set(i,this.trackInputText?null==n?void 0:n.inputText:void 0,this.trackScrollHeight?null==n?void 0:n.scrollHeight:void 0)}addInputText(t){if(!this.trackInputText)return;const e=localStorage.getItem(this.storageKey),i=e?JSON.parse(e):void 0;this.set((null==i?void 0:i.messages)||[],t,this.trackScrollHeight?null==i?void 0:i.scrollHeight:void 0)}addScrollHeight(t){if(!this.trackScrollHeight)return;const e=localStorage.getItem(this.storageKey),i=e?JSON.parse(e):void 0;this.set((null==i?void 0:i.messages)||[],this.trackInputText?null==i?void 0:i.inputText:void 0,t)}clear(){localStorage.removeItem(this.storageKey)}}class ts{static applyCustomStylesToElements(t,i,s){if(s&&(Object.assign(t.outerContainer[e],s.outerContainer),Object.assign(t.innerContainer[e],s.innerContainer),Object.assign(t.bubbleElement[e],s.bubble),i)){const i=t.bubbleElement.children[0],n="a"!==i.tagName.toLocaleLowerCase()?i:i.children[0];Object.assign(n[e],s.media)}}static applySideStyles(t,e,i,s){s&&(ts.applyCustomStylesToElements(t,i,s.shared),e===u?ts.applyCustomStylesToElements(t,i,s.user):(ts.applyCustomStylesToElements(t,i,s.ai),ts.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[rt]!==n?ts.isElementsStyles(n)?(ts.applyCustomStylesToElements(e,s,null==(o=t[rt])?void 0:o.shared),ts.applyCustomStylesToElements(e,s,n)):(ts.applySideStyles(e,i,s,t[rt]),ts.applySideStyles(e,i,s,n)):ts.applySideStyles(e,i,s,t[rt])}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 es{static setElementProps(e,i,s,n){var o;s!==gt&&(e.applyCustomStyles(i,n,!0,null==(o=e.messageStyles)?void 0:o[s]),i.bubbleElement[t].add(I))}static addMessage(t,e,i,s,n){es.setElementProps(t,e,i,s),n?t.elementRef.insertBefore(e.outerContainer,t.elementRef.firstChild):t.appendOuterContainerElemet(e.outerContainer)}static wrapInLink(t,e,s){const n=i("a");return n.href=e,n.download=s||x,n.target="_blank",n.appendChild(t),n}static isNonLinkableDataUrl(t,e){return!(!e.startsWith("data")||t===_)&&(t===E&&e.startsWith("data:text/javascript")||!e.startsWith("data:image")&&!e.startsWith("data:application"))}static processContent(t,e,i,s){return!i||es.isNonLinkableDataUrl(t,i)?e:es.wrapInLink(e,i,s)}static waitToLoadThenScroll(t){setTimeout(()=>{t()},60)}static scrollDownOnImageLoad(t,e){if(t.startsWith("data"))es.waitToLoadThenScroll(e);else try{fetch(t,{mode:"no-cors"}).catch(()=>{}).finally(()=>{es.waitToLoadThenScroll(e)})}catch{e()}}static reAddFileRefToObject(t,e){var i;null==(i=t[k])||i.forEach((t,i)=>{var s;t.ref&&null!=(s=e[k])&&s[i]&&(e[k][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 e===T||(null==i?void 0:i.startsWith("data:audio"))||i&&/\.(mp3|ogg|wav|aac|webm|4a)$/i.test(i)}static isImageFile(t){const{type:e,src:i}=t;return e===_||(null==i?void 0:i.startsWith("data:image"))||i&&es.isImageFileExtension(i)}static isImageFileExtension(t){return/\.(jpg|jpeg|png|gif|bmp)$/i.test(t)}}class is{static onMessage(t,e,i){var s;const n=F({message:e,isHistory:i,isInitial:i});es.reAddFileRefToObject(e,n.message),null==(s=t.onMessage)||s.call(t,n),t.dispatchEvent(new CustomEvent("message",{detail:n})),ue.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 onInput(t,e,i){var s,n;const o=F({content:e,isUser:i});e[k]&&es.reAddFileRefToObject({[k]:null==(s=e[k])?void 0:s.map(t=>({ref:t}))},o.content),null==(n=t.onInput)||n.call(t,o),t.dispatchEvent(new CustomEvent("input",{detail:o}))}static onError(t,e){var i;null==(i=t.onError)||i.call(t,e),t.dispatchEvent(new CustomEvent(l,{detail:e}))}}const ss=class e{static generateLoadingRingElement(){const e=i();return e[t].add("loading-history"),e.appendChild(i()),e.appendChild(i()),e.appendChild(i()),e.appendChild(i()),e}static apply(t,e,i){he.setRing(e.bubbleElement,null==i?void 0:i.bubble),null!=i&&i.bubble&&delete(i=F(i)).bubble,t.applyCustomStyles(e,"history",!1,i)}static addLoadHistoryMessage(i,s,n=!0){var o,r,a,l,c,h,u,d;i.bubbleElement[t].add(e.CLASS);const p=n?e.FULL_VIEW_CLASS:e.SMALL_CLASS;i.outerContainer[t].add(p);const m=n?null==(l=null==(a=null==(r=null==(o=s.messageStyles)?void 0:o.loading)?void 0:r.history)?void 0:a.full)?void 0:l[pt]:null==(d=null==(u=null==(h=null==(c=s.messageStyles)?void 0:c.loading)?void 0:h.history)?void 0:u.small)?void 0:d[pt];e.apply(s,i,m);let v=s.elementRef;n&&s.elementRef.id!==O&&(v=s.elementRef.parentElement),null==v||v.prepend(i.outerContainer)}static createDefaultElements(t){const i=t.createMessageElements("",h),{bubbleElement:s}=i,n=e.generateLoadingRingElement();return s.appendChild(n),i}static addMessage(t,i=!0){var s,n,o,r;const l=null==(r=null==(o=null==(n=null==(s=t.messageStyles)?void 0:s.loading)?void 0:n.history)?void 0:o.full)?void 0:r[a],c=l?Ce.createElements(t,l,h,!0,!0):e.createDefaultElements(t);return e.addLoadHistoryMessage(c,t,i),vs.softRemRoleElements(c.innerContainer,t.avatar,t.name),c}static tryChangeViewToSmall(i,s){var n,o,r,l,c,h,u,d;if(null!=s&&s.outerContainer[t].contains(e.FULL_VIEW_CLASS)){s.outerContainer[t].replace(e.FULL_VIEW_CLASS,e.SMALL_CLASS);const p=null==(l=null==(r=null==(o=null==(n=i.messageStyles)?void 0:n.loading)?void 0:o.history)?void 0:r.small)?void 0:l[pt];p&&e.apply(i,s,p);const m=null==(d=null==(u=null==(h=null==(c=i.messageStyles)?void 0:c.loading)?void 0:h.history)?void 0:u.small)?void 0:d[a];return m&&(s.bubbleElement.innerHTML=m),!0}return!1}static changeFullViewToSmall(t){const i=t.messageElementRefs[t.messageElementRefs.length-1];e.tryChangeViewToSmall(t,i)||e.tryChangeViewToSmall(t,t.messageElementRefs[0])}};ss.CLASS="loading-history-message",ss.FULL_VIEW_CLASS="loading-history-message-full-view",ss.SMALL_CLASS="loading-history-message-small";let ns=ss;const os=class t{static setFade(i,s){i[e].transitionDuration="number"==typeof s?`${s}ms`:`${t.DEFAULT_FADE_MS}ms`}static async fadeAnimation(i,s){i[e].opacity="0";const n="number"==typeof s?s:t.DEFAULT_FADE_MS;await new Promise(t=>{setTimeout(()=>t(),n)}),i[e].opacity="1"}};os.DEFAULT_FADE_MS=500;let rs=os;class as{constructor(t,e,i){if(this.hiddenElements=new Set,this.isScrollButton=!1,this.isScrollingToBottom=!1,this._messages=t,e){let t={};"object"==typeof e&&(t=F(e),t.onUpdate=e.onUpdate),t[pt]??(t[pt]={});const i="fit-content";t[pt].default={borderRadius:"10px",width:i,height:i,...t[pt].default},this.hiddenMessagesConfig=t,this.io=this.initIntersectionObserver(this._messages.elementRef)}if(i){const t="object"==typeof i?F(i):{};t[pt]??(t[pt]={}),t[pt].default={borderRadius:"50%",width:"1.4rem",height:"1.4rem",...t[pt].default},this.scrollButtonConfig=t}this.element=this.createElement(),this._messages.elementRef.appendChild(this.element)}static displayElement(t){t[e].opacity="1",t[e].pointerEvents="auto"}static hideElement(t){t[e].opacity="0",t[e].pointerEvents="none"}initIntersectionObserver(t){return new IntersectionObserver(t=>{t.forEach(t=>{var e;t.isIntersecting&&this.hiddenElements.has(t.target)&&(this.hiddenElements.delete(t.target),null==(e=this.io)||e.unobserve(t.target),this.updateHiddenElement())})},{root:t,threshold:.1})}createElement(){const t=i();return t.id="scroll-button",re.assignButtonEvents(t,()=>{var t,e,i;const s=this.isScrollButton?null==(t=this.scrollButtonConfig)?void 0:t.smoothScroll:null==(e=this.hiddenMessagesConfig)?void 0:e.smoothScroll,n="boolean"!=typeof s||s;if(this.isScrollButton||"last"===(null==(i=this.hiddenMessagesConfig)?void 0:i.clickScroll))re.scrollToBottom(this._messages,n),n&&this.element&&(as.hideElement(this.element),this.isScrollingToBottom=!0,re.waitForScrollEnd(this._messages.elementRef,()=>{this.isScrollingToBottom=!1}));else{const t=this.hiddenElements.values().next().value;t&&this._messages.elementRef.scrollTo({left:0,top:t.offsetTop,behavior:n?"smooth":"auto"})}}),ke.apply(this._messages,t),t}assignStyles(t){if(!this.element)return;Object.assign(this.element[e],t[rt]);const i=xt.processStateful(t);be.add(this.element,i)}updateHiddenElement(){var t,e;if(this.element){this.isScrollButton=!1;const i=this.hiddenElements.size;if(0===i)return void as.hideElement(this.element);const s=`${i} new message${1===i?"":"s"}`;if(null!=(t=this.hiddenMessagesConfig)&&t.onUpdate){const t=this.hiddenMessagesConfig.onUpdate(s,i);this.element.innerHTML=t,ke.apply(this._messages,this.element)}else this.element.innerHTML=s;null!=(e=this.hiddenMessagesConfig)&&e[pt]&&this.assignStyles(this.hiddenMessagesConfig[pt]),as.displayElement(this.element)}}updateHidden(){var t,e;if(!this.isScrollingToBottom)if(this.hiddenMessagesConfig){const i=null==(t=this._messages.getFirstMessageContentEl())?void 0:t.outerContainer;i&&!re.isVisibleInParent(i,this._messages.elementRef)&&(this.hiddenElements.add(i),null==(e=this.io)||e.observe(i),this.updateHiddenElement())}else this.updateScroll()}clearHidden(){this.hiddenElements.forEach(t=>{var e;return null==(e=this.io)?void 0:e.unobserve(t)}),this.hiddenElements.clear(),this.updateHiddenElement()}displayScroll(){var t,i;this.element&&"1"!==this.element[e].opacity&&(as.displayElement(this.element),this.element.innerHTML=(null==(t=this.scrollButtonConfig)?void 0:t.content)||'<span style="font-size: 1.2rem; user-select: none;">&darr;</span>',null!=(i=this.scrollButtonConfig)&&i[pt]&&this.assignStyles(this.scrollButtonConfig[pt]))}updateScroll(){var t;this.isScrollingToBottom||!this.scrollButtonConfig||(re.isScrollbarAtBottomOfElement(this._messages.elementRef,(null==(t=this.scrollButtonConfig)?void 0:t.scrollDelta)||80)?this.element&&"0"!==this.element[e].opacity&&as.hideElement(this.element):(this.displayScroll(),this.isScrollButton=!0))}}const ls="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",cs="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==";class hs{constructor(t){this.className=t}getAvatarContainer(t){return t.getElementsByClassName(this.className)[0]}tryHide(t){var i;(i=this.getAvatarContainer(t)[e]).visibility||(i.visibility="hidden")}tryReveal(t){this.getAvatarContainer(t)[e].visibility=""}trySoftRem(e){this.getAvatarContainer(e)[t].add("role-hidden")}}class us extends hs{constructor(t){super("avatar-container"),this._avatars=t}addBesideBubble(e,i){const s="boolean"==typeof this._avatars?void 0:this._avatars,n=this.createAvatar(i,s),o=this.getPosition(i,s);n[t].add(o===$?"start-item-position":"end-item-position"),e.insertAdjacentElement(o===$?"beforebegin":"afterend",n)}createAvatar(e,s){var n,o,r,a,l;const c=i("img");e===u?(c[y]=(null==(n=null==s?void 0:s[u])?void 0:n[y])||(null==(o=null==s?void 0:s[rt])?void 0:o[y])||cs,c.onerror=us.errorFallback.bind(this,cs)):(c[y]=(null==(r=null==s?void 0:s[e])?void 0:r[y])||(null==(a=null==s?void 0:s[h])?void 0:a[y])||(null==(l=null==s?void 0:s[rt])?void 0:l[y])||ls,c.onerror=us.errorFallback.bind(this,ls)),c[t].add("avatar"),c.alt=`${e} avatar`;const d=i();return d[t].add(this.className),d.appendChild(c),s&&us.applyCustomStyles(d,c,s,e),d}getPosition(t,e){var i,s,n,o,r,a;let l=ue.processPosition(null==(s=null==(i=null==e?void 0:e[t])?void 0:i[pt])?void 0:s.position);return t!==u&&(l??(l=null==(o=null==(n=null==e?void 0:e.ai)?void 0:n[pt])?void 0:o.position)),l??(l=null==(a=null==(r=null==e?void 0:e[rt])?void 0:r[pt])?void 0:a.position),l??(l=t===u?"end":$),l}static errorFallback(t,e){const i=e.target;i.onerror=null,i[y]=t}static applyCustomStylesToElements(t,i,s){Object.assign(t[e],s.container),Object.assign(i[e],s.avatar)}static applyCustomStyles(t,e,i,s){var n,o,r,a;if(null!=(n=i[rt])&&n[pt]&&us.applyCustomStylesToElements(t,e,i[rt][pt]),s===u)null!=(o=i.user)&&o[pt]&&us.applyCustomStylesToElements(t,e,i.user[pt]);else{null!=(r=i.ai)&&r[pt]&&us.applyCustomStylesToElements(t,e,i.ai[pt]);const n=null==(a=i[s])?void 0:a[pt];n&&us.applyCustomStylesToElements(t,e,n)}}}class ds extends hs{constructor(t){super("name"),this._names=t}addBesideBubble(e,i){const s="boolean"==typeof this._names?{}:this._names,n=this.createName(i,s),o=ds.getPosition(i,s);n[t].add(o===$?"start-item-position":"end-item-position"),e.insertAdjacentElement(o===$?"beforebegin":"afterend",n)}createName(e,s){const n=i();return n[t].add(this.className),n.textContent=ds.getNameText(e,s),ds.applyStyle(n,e,s),n}static getPosition(t,e){var i,s,n;let o=ue.processPosition(null==(i=null==e?void 0:e[t])?void 0:i.position);return t!==u&&(o??(o=null==(s=null==e?void 0:e[h])?void 0:s.position)),o??(o=null==(n=null==e?void 0:e[rt])?void 0:n.position),o??(o=t===u?"end":$),o}static applyStyle(t,i,s){var n,o,r,a;Object.assign(t[e],null==(n=s[rt])?void 0:n[e]),i===u?Object.assign(t[e],null==(o=s[u])?void 0:o[e]):(Object.assign(t[e],null==(r=s[h])?void 0:r[e]),Object.assign(t[e],null==(a=s[i])?void 0:a[e]))}static getNameText(t,e){var i,s,n,o,a,l;return t===u?(null==(i=e[u])?void 0:i[r])||(null==(s=e[rt])?void 0:s[r])||"User":t===h?(null==(n=e[h])?void 0:n[r])||(null==(o=e[rt])?void 0:o[r])||"AI":(null==(a=e[t])?void 0:a[r])||(null==(l=e[rt])?void 0:l[r])||t}}const ps=class e{constructor(t){var s,n,o,r;this.messageElementRefs=[],this.htmlClassUtilities={},this.messageToElements=[],this.maxVisibleMessages=4e3,this.autoScrollAllowed=!0,this.elementRef=e.createContainerElement(),this.messageStyles=ue.processMessageStyles(t.messageStyles),this._remarkable=Qi.createNew(t.remarkable),this._applyHTMLToRemarkable=null==(s=t.remarkable)?void 0:s.applyHTML,t.avatars&&(this.avatar=new us(t.avatars)),t.names&&(this.name=new ds(t.names)),t.browserStorage&&(this.browserStorage=new Yi(t.browserStorage)),this._onMessage=is.onMessage.bind(this,t),t.htmlClassUtilities&&(this.htmlClassUtilities=t.htmlClassUtilities),(t.hiddenMessages||t.scrollButton)&&(this.scrollButton=new as(this,t.hiddenMessages,t.scrollButton)),this.focusMode=ue.processFocusMode(t.focusMode),this.focusMode||(this._lastGroupMessagesElement=i(),this.elementRef.appendChild(this._lastGroupMessagesElement),t.upwardsMode&&(this.elementRef=this._lastGroupMessagesElement)),"boolean"!=typeof this.focusMode&&null!=(n=this.focusMode)&&n.fade&&rs.setFade(this.elementRef,this.focusMode.fade),this._customWrappers=t.htmlWrappers||ue.processStreamHTMLWrappers(null==(o=t.connect)?void 0:o.stream),"boolean"!=typeof this.focusMode&&!1===(null==(r=this.focusMode)?void 0:r.streamAutoScroll)&&(this.autoScrollAllowed=!1),t.maxVisibleMessages&&(this.maxVisibleMessages=t.maxVisibleMessages),setTimeout(()=>{this.submitUserMessage=t.submitUserMessage})}static createContainerElement(){const t=i();return t.id=O,t}addNewTextMessage(i,s,n,o=!1){if(null!=n&&n.status){const t=this.overwriteText(s,i,this.messageElementRefs);if(t)return t;n.status=!1}const r=o?this.createAndPrependNewMessageElement(i,s,o):this.createAndAppendNewMessageElement(i,s);return r.bubbleElement[t].add(e.TEXT_BUBBLE_CLASS),this.applyCustomStyles(r,s,!1),vs.fillEmptyMessageElement(r.bubbleElement,i),r}overwriteText(t,i,s){const n=vs.overwriteMessage(this.messageToElements,s,i,t,"text",e.TEXT_BUBBLE_CLASS);return n&&this.renderText(n.bubbleElement,i,t),n}createAndAppendNewMessageElement(t,e){const i=this.createNewMessageElement(t,e);return this.appendOuterContainerElemet(i.outerContainer,this.focusMode?e:void 0),i}createNewGroupElementFocusMode(){var s;null==(s=this._lastGroupMessagesElement)||s[t].remove(e.LAST_GROUP_MESSAGES_ACTIVE);const n=i();(this.messageToElements.length>1||1===this.messageToElements.length&&this.messageToElements[0][0][P]!==u)&&n[t].add(e.LAST_GROUP_MESSAGES_ACTIVE),this._lastGroupMessagesElement=n}appendOuterContainerElemet(t,e){var i;this.focusMode&&(e===u||!this._lastGroupMessagesElement)&&this.createNewGroupElementFocusMode(),null==(i=this._lastGroupMessagesElement)||i.appendChild(t),this._lastGroupMessagesElement&&(this.focusMode||!this.elementRef.contains(this._lastGroupMessagesElement))&&this.elementRef.appendChild(this._lastGroupMessagesElement)}createAndPrependNewMessageElement(i,s,n,o=!1){var r;const a=this.createNewMessageElement(i,s,n,o);if(n&&null!=(r=this.elementRef.firstChild)&&r[t].contains(e.INTRO_CLASS)){this.elementRef.firstChild.insertAdjacentElement("afterend",a.outerContainer);const t=this.messageElementRefs[0];this.messageElementRefs[0]=this.messageElementRefs[1],this.messageElementRefs[1]=t}else this.elementRef.insertBefore(a.outerContainer,this.elementRef.firstChild);return a}createMessageElementsOnOrientation(t,e,i,s=!1){return i?this.createAndPrependNewMessageElement(t,e,i,s):this.createNewMessageElement(t,e,i,s)}getNumberOfContentMessages(){var e,i;const s=this.messageElementRefs.length;return null!=(i=null==(e=this.messageElementRefs[s-1])?void 0:e.bubbleElement)&&i[t].contains(he.BUBBLE_CLASS)?s-1:s}createNewMessageElement(t,i,s=!1,n=!1){var o;!n&&this.getNumberOfContentMessages()>=this.maxVisibleMessages&&setTimeout(()=>this.removeFirstMessage()),n||null==(o=this._introPanel)||o.hide();const r=this.messageElementRefs[this.messageElementRefs.length-1];return ns.changeFullViewToSmall(this),!s&&e.isTemporaryElement(r)&&(this.revealRoleElementsIfTempRemoved(r,i),this.removeLastMessage()),this.createMessageElements(t,i,s)}revealRoleElementsIfTempRemoved(e,i){if((this.avatar||this.name)&&xe.isElementTemporary(e)){const s=this.messageElementRefs[this.messageElementRefs.length-2];s&&this.messageToElements.length>0&&!e.bubbleElement[t].contains(vs.getRoleClass(i))&&vs.revealRoleElements(s.innerContainer,this.avatar,this.name)}}static isTemporaryElement(t){return e.isLoadingMessage(t)||xe.isElementTemporary(t)}createElements(t,i){const s=e.createBaseElements(i),{outerContainer:n,innerContainer:o,bubbleElement:r}=s;return n.appendChild(o),this.addInnerContainerElements(r,t,i),s}createMessageElements(t,e,i=!1){const s=this.createElements(t,e);return vs.updateRefArr(this.messageElementRefs,s,i),vs.classifyRoleMessages(this.messageElementRefs,e),s}static createBaseElements(e){const s=i(),n=i();n[t].add("inner-message-container"),s.appendChild(n),s[t].add("outer-message-container"),s[t].add(vs.buildRoleOuterContainerClass(e));const o=i();return o[t].add("message-bubble"),n.appendChild(o),{outerContainer:s,innerContainer:n,bubbleElement:o}}addInnerContainerElements(e,i,s){const n=this.messageElementRefs[this.messageElementRefs.length-1];return vs.areOuterContainerClassRolesSame(s,n)&&!this.isLastMessageError()&&vs.hideRoleElements(n.innerContainer,this.avatar,this.name),e[t].add("message-bubble",vs.getRoleClass(s),s===u?"user-message-text":"ai-message-text"),this.renderText(e,i,s),vs.addRoleElements(e,s,this.avatar,this.name),{bubbleElement:e}}applyCustomStyles(t,e,i,s){t&&this.messageStyles&&ts.applyCustomStyles(this.messageStyles,t,e,i,s)}static createMessageContent(t){const{text:e,files:i,html:s,custom:n,_sessionId:o,role:l}=t,c={[P]:l||h};return e&&(c[r]=e),i&&(c[k]=i),s&&(c[a]=s),!e&&!i&&!s&&(c[r]=""),n&&(c.custom=n),o&&(c._sessionId=o),c}removeMessage(t){t.outerContainer.remove();const e=this.messageElementRefs.findIndex(e=>e===t);this.messageElementRefs.splice(e,1)}removeFirstMessage(){this.messageElementRefs[0].outerContainer.remove(),this.messageElementRefs.shift()}removeLastMessage(){this.messageElementRefs[this.messageElementRefs.length-1].outerContainer.remove(),this.messageElementRefs.pop()}isLastMessageError(){var e;return null==(e=vs.getLastMessageBubbleElement(this.elementRef))?void 0:e[t].contains(p)}static isLoadingMessage(e){return null==e?void 0:e.bubbleElement[t].contains(he.BUBBLE_CLASS)}sendClientUpdate(t,e=!1){var i;null==(i=this._onMessage)||i.call(this,t,e)}renderText(t,e,i){const{contentEl:s,wrapper:n}=ke.tryAddWrapper(t,e,this._customWrappers,i);n&&ke.apply(this,t),s.innerHTML=this._remarkable.render(e),this._applyHTMLToRemarkable&&ke.apply(this,s),0===s.innerText.trim().length&&s.children.length>0&&"P"!==s.children[0].tagName&&(s.innerText=e)}refreshTextMessages(t){this._remarkable=Qi.createNew(t),this.messageToElements.forEach(t=>{t[1][r]&&t[0][r]&&this.renderText(t[1][r].bubbleElement,t[0][r],t[0][P])})}getFirstMessageContentEl(){const{text:t,html:e,files:i}=this.messageToElements[this.messageToElements.length-1][1];return t||e||(null==i?void 0:i[0])}scrollToFirstElement(t,e){var i;if(t===u){const t="boolean"!=typeof this.focusMode&&(null==(i=this.focusMode)?void 0:i.smoothScroll);re.scrollToBottom(this,t)}else if(e&&this.autoScrollAllowed){const t=this.getFirstMessageContentEl();re.scrollToBottom(this,!1,null==t?void 0:t.outerContainer)}}};ps.TEXT_BUBBLE_CLASS="text-message",ps.INTRO_CLASS="deep-chat-intro",ps.LAST_GROUP_MESSAGES_ACTIVE="deep-chat-last-group-messages-active";let ms=ps;class vs{static getLastElementsByClass(e,i,s){for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(o.bubbleElement[t].contains(i[0])&&!i.slice(1).find(e=>!o.bubbleElement[t].contains(e))){if(!s)return o;if(!s.find(e=>o.bubbleElement[t].contains(e)))return o}}}static getLastMessage(t,e,i){for(let s=t.length-1;s>=0;s-=1)if(t[s][0][P]===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(t,e,i,s,n,o){const r=vs.getLastElementsByClass(e,[vs.getRoleClass(s),o],[he.BUBBLE_CLASS]),a=vs.getLastMessage(t,s,n);return a&&(a[n]=i),r}static getRoleClass(t){return`${t}-message`}static fillEmptyMessageElement(e,i){0===i.trim().length&&(e[t].add(v),e.innerHTML='<div style="color:#00000000">.</div>')}static unfillEmptyMessageElement(e,i){e[t].contains(v)&&i.trim().length>0&&e.replaceChildren()}static getLastMessageBubbleElement(e){var i,s,n;return Array.from((null==(n=null==(s=null==(i=vs.getLastMessageElement(e))?void 0:i.children)?void 0:s[0])?void 0:n.children)||[]).find(e=>e[t].contains("message-bubble"))}static getLastMessageElement(t){var e;const i=null==(e=t.children[t.children.length-1])?void 0:e.children;return null==i?void 0:i[i.length-1]}static addRoleElements(t,e,i,s){null==i||i.addBesideBubble(t,e),null==s||s.addBesideBubble(t,e)}static hideRoleElements(t,e,i){null==e||e.tryHide(t),null==i||i.tryHide(t)}static revealRoleElements(t,e,i){null==e||e.tryReveal(t),null==i||i.tryReveal(t)}static softRemRoleElements(t,e,i){null==e||e.trySoftRem(t),null==i||i.trySoftRem(t)}static updateRefArr(t,e,i){i?t.unshift(e):t.push(e)}static buildRoleOuterContainerClass(t){return`${m}${t}`}static addNewPositionClasses(e,i){e.outerContainer[t].remove(f,g,b),e.outerContainer[t].add(...i)}static getNumberOfElements(t){let e=0;return void 0!==t[r]&&(e+=1),void 0!==t[a]&&(e+=1),t[k]&&(e+=t[k].length),e}static filterdMessageElements(e,i){return e.filter(e=>e.bubbleElement[t].contains(i))}static findMessageElements(e,i){return e.find(e=>e.bubbleElement[t].contains(i))}static generateMessageBodyElements(t,e){const i={};return t[r]&&(i[r]=vs.findMessageElements(e,ms.TEXT_BUBBLE_CLASS)),t[a]&&(i[a]=vs.findMessageElements(e,Ce.HTML_BUBBLE_CLASS)),t[k]&&(i[k]=vs.filterdMessageElements(e,I)),i}static generateMessageBody(t,e,i=!1){const s=vs.getNumberOfElements(t),n=i?e.slice(0,s):e.slice(e.length-s);return vs.generateMessageBodyElements(t,n)}static classifyRoleMessages(e,i){let s=i?vs.buildRoleOuterContainerClass(i):void 0;for(let n=e.length-1;n>=0;n-=1){if(i||(s=Array.from(e[n].outerContainer[t]).find(t=>t.startsWith(m))),!s)continue;const o=e[n],r=o.outerContainer[t].contains(s),a=e[n-1],l=e[n+1],c=null==a?void 0:a.outerContainer[t].contains(s),h=null==l?void 0:l.outerContainer[t].contains(s);if(r)!c&&h?vs.addNewPositionClasses(o,[f]):c&&h?vs.addNewPositionClasses(o,[g]):c&&!h?vs.addNewPositionClasses(o,[b]):!c&&!h&&vs.addNewPositionClasses(o,[f,b]);else if(i)break}}static areOuterContainerClassRolesSame(e,i){return!!i&&Array.from(i.outerContainer[t]).find(t=>t.startsWith(m))===vs.buildRoleOuterContainerClass(e)}static resetAllRoleElements(e,i,s){if(!i&&!s)return;let n="";e.forEach((o,r)=>{o.bubbleElement[t].contains(p)||vs.revealRoleElements(o.innerContainer,i,s);const a=Array.from(o.outerContainer[t]).find(t=>t.startsWith(m));n===a&&vs.hideRoleElements(e[r-1].innerContainer,i,s),n=a})}static deepCloneMessagesWithReferences(t){return t.map(t=>vs.processMessageContent(t))}static processMessageContent(t){if(null==t||typeof t!==Kt)return t;if(Array.isArray(t))return t.map(t=>vs.processMessageContent(t));const e={};return Object.entries(t).forEach(([t,i])=>{"ref"===t&&i instanceof File||"custom"===t?e[t]=i:e[t]=null!==i&&typeof i===Kt?vs.processMessageContent(i):i}),e}}const fs=class e{constructor(t,e){this._fileAdded=!1,this._streamType="",this._hasStreamEnded=!1,this._partialContent="",this._messages=t,"object"==typeof e&&(this._partialRender=e.partialRender)}upsertStreamedMessage(t){if(this._hasStreamEnded)return;if(void 0===(null==t?void 0:t[r])&&void 0===(null==t?void 0:t[a]))return console[l](J);const e=(null==t?void 0:t[r])||(null==t?void 0:t[a])||"",i=re.isScrollbarAtBottomOfElement(this._messages.elementRef),s=void 0!==(null==t?void 0:t[r])?r:a;if(this._elements||this._message){if(this._streamType!==s)return console[l]("Cannot mix {text: string} and {html: string} responses.");null!=t&&t[P]&&(null==t?void 0:t[P])!==this._activeMessageRole?(this.finaliseStreamedMessage(!1),this.setInitialState(s,e,null==t?void 0:t[P])):this.updateBasedOnType(e,s,null==t?void 0:t.overwrite)}else this.setInitialState(s,e,null==t?void 0:t[P]);null!=t&&t._sessionId&&(this._sessionId=null==t?void 0:t._sessionId),null!=t&&t.custom&&this._message&&(this._message.custom=t.custom),i&&this._messages.autoScrollAllowed&&re.scrollToBottom(this._messages)}setInitialState(i,s,n){var o,a,l;this._streamType=i,this._targetWrapper=void 0,this._fileAdded=!1,this._partialContent="",this._partialBubble=void 0,n??(n=h);const c=(null==(o=this._messages._customWrappers)?void 0:o[n])||(null==(a=this._messages._customWrappers)?void 0:a[rt]),u=c?"":s;this._elements=i===r?this._messages.addNewTextMessage(u,n):Ce.add(this._messages,u,n),this._elements&&(this._elements.bubbleElement[t].add(e.MESSAGE_CLASS),this._activeMessageRole=n,this._message={[P]:this._activeMessageRole,[i]:u},this._messages.messageToElements.push([this._message,{[i]:this._elements}]),c&&this.setTargetWrapperIfNeeded(this._elements,s,this._streamType,c),null==(l=this._messages.scrollButton)||l.updateHidden())}setTargetWrapperIfNeeded(t,e,i,s){t.bubbleElement.innerHTML=s,this._targetWrapper=ke.getTargetWrapper(t.bubbleElement),this._elements&&ke.apply(this._messages,this._elements.bubbleElement),this.updateBasedOnType(e,i)}updateBasedOnType(t,e,i=!1){var s;const n=this._targetWrapper||(null==(s=this._elements)?void 0:s.bubbleElement);this._partialRender||vs.unfillEmptyMessageElement(n,t),(e===r?this.updateText:this.updateHTML).bind(this)(t,n,i)}updateText(t,e,i){this._message&&(this._message[r]=i?t:this._message[r]+t,this._partialRender&&this.isNewPartialRenderParagraph(e,i)&&this.partialRenderNewParagraph(e),this._partialBubble?this.updatePartialRenderBubble(t):this._messages.renderText(e,this._message[r]))}containsPartialRenderMark(t){const i=t.indexOf(e.PARTIAL_RENDER_MARK);return-1!==i&&!t.substring(i+e.PARTIAL_RENDER_MARK.length).startsWith("---")}isNewPartialRenderParagraph(t,e){var i;if(e)return t.innerHTML="",!0;const s=this._streamType;if(!this._partialBubble){const t=null==(i=this._message)?void 0:i[s];return!!t&&this.containsPartialRenderMark(t)}return!!this._partialContent&&this.containsPartialRenderMark(this._partialContent)}partialRenderNewParagraph(e){this._partialContent="",this._partialBubble=i(),this._partialBubble[t].add("partial-render-message"),e.appendChild(this._partialBubble)}updatePartialRenderBubble(t){this._partialContent+=t,this._streamType===r?this._messages.renderText(this._partialBubble,this._partialContent):this._partialBubble.innerHTML=this._partialContent}updateHTML(t,e,s){if(this._message)if(this._message[a]=s?t:(this._message[a]||"")+t,this._partialRender&&this.isNewPartialRenderParagraph(e,s)&&this.partialRenderNewParagraph(e),this._partialBubble)this.updatePartialRenderBubble(t);else if(s)e.innerHTML=t;else{const s=i("span");s.innerHTML=t,e.appendChild(s)}}finaliseStreamedMessage(i=!0){var s,n;if(!this._endStreamAfterOperation&&(!this._fileAdded||this._elements)){if(!this._elements)throw Error(X);this._message&&null!=(s=this._elements.bubbleElement)&&s[t].contains(e.MESSAGE_CLASS)&&(this._streamType===r?this._messages.textToSpeech&&le.speak(this._message[r]||"",this._messages.textToSpeech):this._streamType===a&&this._elements&&ke.apply(this._messages,this._elements.outerContainer),this._elements.bubbleElement[t].remove(e.MESSAGE_CLASS),this._message&&(this._sessionId&&(this._message._sessionId=this._sessionId),this._messages.sendClientUpdate(ms.createMessageContent(this._message),!1),null==(n=this._messages.browserStorage)||n.addMessages(this._messages.messageToElements.map(([t])=>t))),this._hasStreamEnded=i)}}markFileAdded(){this._fileAdded=!0}async endStreamAfterFileDownloaded(t,e){this._endStreamAfterOperation=!0;const{text:i,files:s}=await e();i&&this.updateBasedOnType(i,r,!0),this._endStreamAfterOperation=!1,this.finaliseStreamedMessage(),s&&t.addNewMessage({[k]:s})}};fs.MESSAGE_CLASS="streamed-message",fs.PARTIAL_RENDER_MARK="\n\n";let gs=fs;class bs{static async tempRemoveContentHeader(t,e,i){if(null==t||!t.headers)throw new Error(W);const s=t.headers[Wt];let n;delete t.headers[Wt];try{n=await e(i)}catch(e){throw t.headers[Wt]=s,e}return t.headers[Wt]=s,n}static displayError(t,e,i="Service error, please try again."){if(console[l](e),typeof e===Kt)return e instanceof Error?t.addNewErrorMessage(o,e.message):Array.isArray(e)||typeof e[l]===B?t.addNewErrorMessage(o,e):0===Object.keys(e).length?t.addNewErrorMessage(o,i):t.addNewErrorMessage(o,R(e));t.addNewErrorMessage(o,e)}static fetch(t,e,i,s){var n,o;const r={method:(null==(n=t.connectSettings)?void 0:n.method)||Yt,headers:e};return r.method!==Qt&&(r.body=i?R(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(Zt)?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[l]}}static validateResponseFormat(t,e){if(!t)return!1;const i=Array.isArray(t)?t:[t];return e&&i.length>1?(console[l](K),!1):!i.find(t=>"object"!=typeof t||!(typeof t[l]===B||typeof t[r]===B||typeof t[a]===B||Array.isArray(t[k])))}static onInterceptorError(t,e,i){t.addNewErrorMessage(o,e),null==i||i()}static async basicResponseProcessing(t,e,i={}){const{io:s,displayError:n=!0,useRI:o=!0}=i;if(null==s||!s.extractResultData)return e;const r=o?s.deepChat.responseInterceptor:void 0,a=await(null==r?void 0:r(e))||e,l=await s.extractResultData(a);if(l&&("object"==typeof l||Array.isArray(l)))return l;if(n){const i=z(e,"response",!!r,a);bs.displayError(t,i)}}}function ys(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 ws="text/event-stream",xs="last-event-id";function ks(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=ws),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??_s;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,ys(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[xs]=t:delete d[xs]},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 _s(t){const e=t.headers.get("content-type");if(null==e||!e.startsWith(ws))throw new Error(`Expected content-type to be ${ws}, Actual: ${e}`)}class Cs{static async request(t,e,i,s=!0,n=!1){var o,r,a,l,c;const h={body:e,headers:null==(o=t.connectSettings)?void 0:o.headers},{body:u,headers:d,error:p}=await bs.processRequestInterceptor(t.deepChat,h);if(p)return bs.onInterceptorError(i,p,t.streamHandlers.onClose);if(null!=(r=t.connectSettings)&&r.handler)return Ss.stream(t,u,i);if((null==(a=t.connectSettings)?void 0:a.url)===Ms.URL)return Ms.requestStream(i,t);const m=new gs(i,t.stream),v={method:(null==(l=t.connectSettings)?void 0:l.method)||Yt,headers:d,credentials:null==(c=t.connectSettings)?void 0:c.credentials,body:s?R(u):u};return"object"==typeof t.stream&&t.stream.readable?Cs.handleReadableStream(t,i,m,v,n,u):Cs.handleEventStream(t,i,m,v,n,u),m}static handleReadableStream(t,e,i,s,n,o){var a;const{onOpen:l,onClose:c}=t.streamHandlers;let h=!1;fetch((null==(a=t.connectSettings)?void 0:a.url)||t.url||"",s).then(async s=>{var a,u;if(!s.body)throw new Error("Readable Stream connection error.");const d=s.body.getReader(),p=new TextDecoder;l();let m=!1;for(;!m&&!h;){const{value:s,done:l}=await d.read();if(m=l,m)Cs.handleClose(t,i,c,n);else{const n=p.decode(s,{stream:!0}),l=await(null==(u=(a=t.deepChat).responseInterceptor)?void 0:u.call(a,n))||n,c="object"==typeof l?l:{[r]:n};Cs.handleMessage(t,e,i,c,o)}}}).catch(i=>{Cs.handleError(t,e,i)}),t.streamHandlers.onAbort=()=>{i.finaliseStreamedMessage(),t.streamHandlers.onClose(),h=!0}}static handleEventStream(t,e,i,s,n,o){var r;const{onOpen:a,onClose:l}=t.streamHandlers,c=new AbortController;t.streamHandlers.onAbort=()=>{i.finaliseStreamedMessage(),t.streamHandlers.onClose(),c.abort()},ks((null==(r=t.connectSettings)?void 0:r.url)||t.url||"",{...s,openWhenHidden:!0,async onopen(t){if(t.ok)return a();throw await bs.processResponseByType(t)},async onmessage(s){var n,r;if(R(s.data)!==R("[DONE]")){let a;try{a=JSON.parse(s.data)}catch{a={}}const l=await(null==(r=(n=t.deepChat).responseInterceptor)?void 0:r.call(n,a))||a;Cs.handleMessage(t,e,i,l,o)}},onerror(t){throw l(),t},onclose(){Cs.handleClose(t,i,l,n)},signal:c.signal}).catch(i=>{Cs.handleError(t,e,i)})}static handleMessage(t,e,i,s,n){var o;null==(o=t.extractResultData)||o.call(t,s,n).then(t=>{Cs.upsertContent(e,i.upsertStreamedMessage.bind(i),i,t),e.removeError()}).catch(t=>{e.isLastMessageError()||bs.displayError(e,t)})}static handleError(t,e,i){var s;e.isLastMessageError()||null==(s=t.extractResultData)||s.call(t,i).then(()=>{bs.displayError(e,i)}).catch(t=>{bs.displayError(e,t)})}static handleClose(t,e,i,s){if(t.asyncCallInProgress)return e.finaliseStreamedMessage(!1),void(t.asyncCallInProgress=!1);try{e.finaliseStreamedMessage(),i()}catch(t){if(!s)throw t}}static async simulate(t,e,i,s){if(!await bs.basicResponseProcessing(t,i,{io:s,useRI:!1}))return e.onClose();if(Array.isArray(i)&&(i=i[0]),i[a]){e.onOpen();let n=ke.splitHTML(i[a]);0===n.length&&(n=i[a].split(""));const o=new gs(t,null==s?void 0:s.stream);Cs.populateMessages(t,n,o,e,a,0,s)}if(i[k]){const n=await bs.basicResponseProcessing(t,{[k]:i[k]},{io:s});t.addNewMessage({sendUpdate:!1,...n}),!i[a]&&!i[r]&&(new gs(t,null==s?void 0:s.stream).finaliseStreamedMessage(),e.onClose())}if(i[r]){e.onOpen();const n=i[r].split(""),o=new gs(t,null==s?void 0:s.stream);Cs.populateMessages(t,n,o,e,r,0,s)}i[l]&&(bs.displayError(t,i[l]),e.onClose()),e.onAbort=()=>{e.onClose()}}static async populateMessages(t,e,i,s,n,o,r){const a=e[o];if(a){try{const e=await bs.basicResponseProcessing(t,{[n]:a},{io:r});Cs.upsertContent(t,i.upsertStreamedMessage.bind(i),i,e),t.removeError()}catch(e){t.isLastMessageError()||bs.displayError(t,e)}const l=setTimeout(()=>{Cs.populateMessages(t,e,i,s,n,o+1,r)},s.simulationInterim||6);s.onAbort=()=>{Cs.abort(l,i,s.onClose)}}else i.finaliseStreamedMessage(),s.onClose()}static isSimulation(t){return"object"==typeof t&&!!t.simulation}static isSimulatable(t,e){return Cs.isSimulation(t)&&e&&(e[r]||e[a])}static abort(t,e,i){clearTimeout(t),e.finaliseStreamedMessage(),i()}static upsertContent(t,e,i,s){if(s&&Array.isArray(s)&&(s=s[0]),null!=s&&s[r]||null!=s&&s[a]){const t=e(s);i??(i=t||void 0)}if(null!=s&&s[k]&&(t.addNewMessage({[k]:s[k]}),null==i||i.markFileAdded()),null!=s&&s[l])throw s[l]}}const As=class t{static generateResponse(t){const e=t[t.length-1][0];if(e[k]&&e[k].length>0){if(e[k].length>1)return"These are interesting files!";const t=e[k][0];return t[y]&&t[y].startsWith("data:image/gif")?"That is a nice gif!":t[w]===_?"That is a nice image!":t[w]===T?"I like the sound of that!":"That is an interesting file!"}if(e[r]){if("?"===e[r].charAt(e[r].length-1))return"I'm sorry but I can't answer that question...";if(e[r].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]):{[r]:t.generateResponse(i)}}static request(e,i){const s=t.getResponse(i);setTimeout(async()=>{const t=await bs.basicResponseProcessing(i,s,{io:e});if(!t)return e.completionsHandlers.onFinish();const n=Array.isArray(t)?t:[t],r=n.find(t=>typeof t[l]===B);r?(i.addNewErrorMessage(o,r[l]),e.completionsHandlers.onFinish()):Cs.isSimulatable(e.stream,t)?Cs.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);Cs.simulate(e,i.streamHandlers,s,i)},400)}};As.URL="deep-chat-demo";let Ms=As;class Ts{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(!Ts.isElementPresentInDOM(t.deepChat))return;const i=t.connectSettings.websocket;if(i){if(t.connectSettings.handler)return Ss.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&&typeof t.websocket===Kt&&Ts.assignListeners(t,n,e),null==(s=(i=t.deepChat)._validationHandler)||s.call(i)},t.websocket.onerror=i=>{console[l](i),Ts.retryConnection(t,e)}}catch(i){console[l](i),Ts.retryConnection(t,e)}}}static retryConnection(t,e){var i,s;null==(s=(i=t.deepChat)._validationHandler)||s.call(i),Ts.isElementPresentInDOM(t.deepChat)&&(t.websocket="pending",e.isLastMessageError()||e.addNewErrorMessage(o,"Connection error"),setTimeout(()=>{Ts.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 bs.basicResponseProcessing(i,n,{io:t,displayError:!1});if(!o)throw Error(z(n,"server",!!t.deepChat.responseInterceptor,o));if(Cs.isSimulation(t.stream)){const e=Ts.stream.bind(this,t,i,s),r=s[n[P]||h];Cs.upsertContent(i,e,r,o)}else{const t=Array.isArray(o)?o:[o],e=t.find(t=>typeof t[l]===B);if(e)throw e[l];t.forEach(t=>i.addNewMessage(t))}}catch(t){bs.displayError(i,t,"Error in server message")}},e.onclose=()=>{var e,s;console[l]("Connection closed"),i.isLastMessageError()||i.addNewErrorMessage(o,"Connection error"),t.stream&&(null==(s=(e=t.streamHandlers).onAbort)||s.call(e)),Ts.createConnection(t,i)}}static async sendWebsocket(t,e,i,s=!0){var n,r;if((null==(n=t.connectSettings)?void 0:n.url)===Ms.URL)return Ms.request(t,i);const a=t.websocket;if(!a||"pending"===a)return;const c={body:e,headers:null==(r=t.connectSettings)?void 0:r.headers},{body:h,error:u}=await bs.processRequestInterceptor(t.deepChat,c);if(u)return i.addNewErrorMessage(o,u);if(!Ts.isWebSocket(a))return a.newUserMessage.listener(h);const d=s?R(h):h;void 0===a.readyState||a.readyState!==a.OPEN?(console[l]("Connection is not open"),i.isLastMessageError()||i.addNewErrorMessage(o,"Connection error")):(a.send(R(d)),t.completionsHandlers.onFinish())}static canSendMessage(t){return!t||"pending"!==t&&(Ts.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(typeof n===B){const o=s[P]||h,l=i[o];s[r]===n||s[a]===n?(null==l||l.finaliseStreamedMessage(),delete i[o]):(i[o]??(i[o]=new gs(e,t.stream)),i[o].upsertStreamedMessage(s))}else Cs.simulate(e,t.streamHandlers,s)}}class Ss{static async request(t,e,i){var s,n;let r=!0;const a=Ss.generateOptionalSignals();null==(n=(s=t.connectSettings).handler)||n.call(s,e,{...a,onResponse:async e=>{if(!r)return;r=!1;const s=await bs.basicResponseProcessing(i,e,{io:t,displayError:!1});if(s){const e=Array.isArray(s)?s:[s],n=e.find(t=>typeof t[l]===B);n?(console[l](n[l]),i.addNewErrorMessage(o,n[l]),t.completionsHandlers.onFinish()):Cs.isSimulatable(t.stream,s)?Cs.simulate(i,t.streamHandlers,s):(e.forEach(t=>i.addNewMessage(t)),t.completionsHandlers.onFinish())}else console[l](z(e,"server",!!t.deepChat.responseInterceptor,s)),i.addNewErrorMessage(o,"Error in server message"),t.completionsHandlers.onFinish()}})}static attemptToFinaliseStream(t,e){try{const i=e.messageElementRefs[e.messageElementRefs.length-1];ms.isLoadingMessage(i)?e.removeLastMessage():t.finaliseStreamedMessage()}catch(t){console[l](t),e.addNewErrorMessage(o,t)}}static stream(t,e,i){var s,n;let o=!0,r=!1;const a=new gs(i,t.stream);t.streamHandlers.onAbort=()=>{Ss.attemptToFinaliseStream(a,i),t.streamHandlers.onClose(),o=!1};const c=Ss.generateOptionalSignals();null==(n=(s=t.connectSettings).handler)||n.call(s,e,{...c,onOpen:()=>{r||!o||(t.streamHandlers.onOpen(),r=!0)},onResponse:async e=>{if(!o)return;const s=await bs.basicResponseProcessing(i,e,{io:t,displayError:!1});if(s)s[l]?(Ss.streamError(s[l],a,t,i),o=!1):Cs.upsertContent(i,a.upsertStreamedMessage.bind(a),a,s);else{const n=z(e,"server",!!t.deepChat.responseInterceptor,s);Ss.streamError(n,a,t,i),o=!1}},onClose:()=>{o&&(Ss.attemptToFinaliseStream(a,i),t.streamHandlers.onClose(),o=!1)},stopClicked:t.streamHandlers.stopClicked})}static streamError(t,e,i,s){console[l](t),e.finaliseStreamedMessage(),s.addNewErrorMessage(o,t),i.streamHandlers.onClose()}static websocket(t,e){var i,s;const n={isOpen:!1,newUserMessage:{listener:()=>{}},roleToStream:{}};t.websocket=n;const r=Ss.generateOptionalSignals();null==(s=(i=t.connectSettings).handler)||s.call(i,void 0,{...r,onOpen:()=>{e.removeError(),n.isOpen=!0},onResponse:async i=>{const s=await bs.basicResponseProcessing(e,i,{io:t,displayError:!1});if(s){const i=Array.isArray(s)?s:[s],r=i.find(t=>typeof t[l]===B);if(r)console[l](r[l]),e.isLastMessageError()||e.addNewErrorMessage(o,r[l]);else if(Cs.isSimulation(t.stream)){const i=s,o=Ts.stream.bind(this,t,e,n.roleToStream),r=n.roleToStream[i[P]||h];Cs.upsertContent(e,o,r,i)}else i.forEach(t=>e.addNewMessage(t))}else console[l](z(i,"server",!!t.deepChat.responseInterceptor,s)),e.addNewErrorMessage(o,"Error in server message")},onClose:()=>{n.isOpen=!1},newUserMessage:n.newUserMessage})}static generateOptionalSignals(){return{onClose:()=>{},onOpen:()=>{},stopClicked:{listener:()=>{}},newUserMessage:{listener:()=>{}}}}}class js{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:c,headers:h,error:u}=await bs.processRequestInterceptor(t.deepChat,a),{onFinish:d}=t.completionsHandlers;if(u)return bs.onInterceptorError(i,u,d);if(null!=(o=t.connectSettings)&&o.handler)return Ss.request(t,c,i);if((null==(r=t.connectSettings)?void 0:r.url)===Ms.URL)return Ms.request(t,i);let p=!0;bs.fetch(t,h,s,c).then(t=>(p=!!t.ok,t)).then(t=>bs.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,c);if(!p)throw e;if(!r||typeof r!==Kt&&!Array.isArray(r))throw Error(z(e,"response",!!t.deepChat.responseInterceptor,o));if(r[l])throw r[l];t.asyncCallInProgress?t.asyncCallInProgress=!1:Cs.isSimulatable(t.stream,r)?Cs.simulate(i,t.streamHandlers,r):((Array.isArray(r)?r:[r]).forEach(t=>i.addNewMessage(t)),d())}).catch(t=>{bs.displayError(i,t),d()})}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(()=>{js.executePollRequest(t,e,i,s)},l.timeoutMS):Cs.isSimulatable(t.stream,l)?Cs.simulate(s,t.streamHandlers,l):(s.addNewMessage(l),n())}).catch(t=>{bs.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 bs.processRequestInterceptor(t.deepChat,a);if(h)return bs.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)||Yt,body:s?R(l):l,headers:c};t.connectSettings.credentials&&(d.credentials=t.connectSettings.credentials),js.executePollRequest(t,u,d,i)}static verifyKey(t,e,i,s,n,o,r,a,c){if(""===t)return o(H);r(),fetch(e,{method:s,headers:i,body:c||null}).then(t=>bs.processResponseByType(t)).then(e=>{a(e,t,n,o)}).catch(t=>{o(V),console[l](t)})}}class Es{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[r];if(void 0!==o&&(s+=o.length,s>e)){t[n][r]=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=Es.getMaxMessages(t,e)):t=[t[t.length-1]],t=F(t),void 0===i?t:Es.getCharacterLimitMessages(t,i)}}const Is=class i{constructor(t,e,i){this._isLoading=!1,this._isPaginationComplete=!1,this._index=0,this._messages=e,i.fetchHistory&&this.fetchHistory(i.fetchHistory),this.setupInitialHistory(t)}async fetchHistory(t){const e=ns.addMessage(this._messages),s=await t();this._messages.removeMessage(e),i.displayIntroMessages(this._messages.messageElementRefs),s.forEach(t=>this._messages.addAnyMessage(t,!0)),setTimeout(()=>re.scrollToBottom(this._messages),0)}scrollToPreloadFirstEl(t,e){this._messages.elementRef.scrollTop=e+t.offsetTop-40}processLoadedHistory(e){var i;const{messageElementRefs:s,messageToElements:n,elementRef:o}=this._messages,r=null==(i=s.find(e=>!e.outerContainer[t].contains(ms.INTRO_CLASS)))?void 0:i.outerContainer,a=o.scrollTop;null==e||e.reverse().map(t=>{const e=this._messages.addAnyMessage({...t,sendUpdate:!0},!0,!0);if(e){const t=vs.generateMessageBody(e,s,!0);n.unshift([e,t])}return e}).filter(t=>!!t).reverse().forEach(t=>this._messages.sendClientUpdate(t,!0)),r&&(this._messages.messageElementRefs.length>=this._messages.maxVisibleMessages?setTimeout(()=>this.scrollToPreloadFirstEl(r,a)):this.scrollToPreloadFirstEl(r,a))}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,avatar:n,name:o}=this._messages;vs.resetAllRoleElements(s,n,o)}async loadHistoryOnScroll(t){this._messages.elementRef.onscroll=async()=>{if(!this._isLoading&&!this._isPaginationComplete&&0===this._messages.elementRef.scrollTop){this._isLoading=!0;const e=ns.addMessage(this._messages,!1);try{const i=await t(this._index++);this.populateMessages(e,i),this._isLoading=!1}catch(t){this._messages.removeMessage(e),this._isPaginationComplete=!0,this._messages.addNewErrorMessage(o,i.FAILED_ERROR_MESSAGE,!0),console[l](t)}}}}populateInitialHistory(t){t.forEach(t=>{ue.processHistoryFile(t),this._messages.addAnyMessage(t,!0)})}async loadInitialHistory(t){this._isLoading=!0;const e=ns.addMessage(this._messages);try{const i=await t(this._index++),s=this._messages.elementRef.scrollTop;this.populateMessages(e,i),this.restoreScrollOrScrollToBottom(0===s)}catch(t){this._messages.removeMessage(e),this._isPaginationComplete=!0,this._messages.addNewErrorMessage(o,i.FAILED_ERROR_MESSAGE,!0),console[l](t)}i.displayIntroMessages(this._messages.messageElementRefs),this._isLoading=!1}async setupInitialHistory(t){var e;t.loadHistory&&this.loadInitialHistory(t.loadHistory);const i=null==(e=this._messages.browserStorage)?void 0:e.get(),s=t.history||ue.processHistory(t)||(null==i?void 0:i.messages);s&&(this.populateInitialHistory(s),this.restoreScrollOrScrollToBottom(!0),this._index+=1)}restoreScrollOrScrollToBottom(t){var e,i,s;const n=null==(i=null==(e=this._messages.browserStorage)?void 0:e.get())?void 0:i.scrollHeight;void 0!==n&&null!=(s=this._messages.browserStorage)&&s.trackScrollHeight?setTimeout(()=>{this._messages.elementRef.scrollTop=n},0):t&&setTimeout(()=>re.scrollToBottom(this._messages),0)}static addErrorPrefix(t){t.permittedErrorPrefixes??(t.permittedErrorPrefixes=[]),t.permittedErrorPrefixes.push(i.FAILED_ERROR_MESSAGE)}static displayIntroMessages(i){for(let s=0;s<i.length;s+=1){const s=i[0];if(!s.outerContainer[t].contains(ms.INTRO_CLASS))break;s.outerContainer[e].display=""}}};Is.FAILED_ERROR_MESSAGE="Failed to load history";let $s=Is;class Os{static parseConfig(t,e,i){var s;const n={files:t};if("object"==typeof i){ue.processFileConfigConnect(i);const{files:t,connect:o,button:r}=i;t&&(t.infoModal&&(n[k].infoModal=t.infoModal,null!=(s=t.infoModal)&&s.textMarkDown&&(n.infoModalTextMarkUp=e.render(t.infoModal.textMarkDown))),t.acceptedFormats&&(n[k].acceptedFormats=t.acceptedFormats),t.maxNumberOfFiles&&(n[k].maxNumberOfFiles=t.maxNumberOfFiles)),n.button=r,o&&Object.keys(o).length>0&&(n.connect=o)}return n}static processMixedFiles(t,e,i){if(i){const s={acceptedFormats:""};t.fileTypes.mixedFiles=Os.parseConfig(s,e,i)}}static processMicrophone(t,e,i,s){var n,o,r,a,l,c;const h={acceptedFormats:"audio/*",...(null==(n=t.fileTypes[T])?void 0:n[k])||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.recordAudio=Os.parseConfig(h,e,i),"object"==typeof i&&i[k]&&((o=t.recordAudio)[k]??(o[k]={}),t.recordAudio[k].format=null==(r=i[k])?void 0:r.format,t.recordAudio[k].maxDurationSeconds=null==(a=i[k])?void 0:a.maxDurationSeconds,null!=(l=t.fileTypes[T])&&l[k]&&((c=t.fileTypes[T][k]).maxNumberOfFiles??(c.maxNumberOfFiles=i[k].maxNumberOfFiles)))):s||(t.fileTypes[T]=Os.parseConfig(h,e,i)))}static processAudioConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"audio/*",...(null==s?void 0:s[k])||{}};t.fileTypes[T]=Os.parseConfig(n,e,i)}static processGifConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"image/gif",...(null==s?void 0:s[k])||{}};t.fileTypes[M]=Os.parseConfig(n,e,i)}static processCamera(t,e,i,s){var n,o,r,a;const l={acceptedFormats:"image/*",...(null==(n=t.fileTypes[C])?void 0:n[k])||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t[A]=Os.parseConfig(l,e,i),"object"==typeof i&&(t[A].modalContainerStyle=i.modalContainerStyle,i[k]&&((o=t[A])[k]??(o[k]={}),t[A][k].format=null==(r=i[k])?void 0:r.format,t[A][k].dimensions=null==(a=i[k])?void 0:a.dimensions))):s||(t.fileTypes[C]=Os.parseConfig(l,e,i)))}static processImagesConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"image/*",...(null==s?void 0:s[k])||{}};t.fileTypes[C]=Os.parseConfig(n,e,i)}static populateDefaultFileIO(t,e){var i,s;t&&(t[k]??(t[k]={}),(i=t[k]).acceptedFormats??(i.acceptedFormats=e),(s=t[k]).maxNumberOfFiles??(s.maxNumberOfFiles=1))}static set(t,e,i){Os.populateDefaultFileIO(null==i?void 0:i[T],".4a,.mp3,.webm,.mp4,.mpga,.wav,.mpeg,.m4a"),Os.populateDefaultFileIO(null==i?void 0:i[C],".png,.jpg");const s=Qi.createNew(t.remarkable);Os.processImagesConfig(e,s,t[C],null==i?void 0:i[C]),Os.processCamera(e,s,t[A],t[C]),Os.processGifConfig(e,s,t[M],null==i?void 0:i[M]),Os.processAudioConfig(e,s,t[T],null==i?void 0:i[T]),Os.processMicrophone(e,s,t[S],t[T]),Os.processMixedFiles(e,s,t[j])}}class Ps{constructor(t,e,i){var s,n,o,r,a;this.rawBody={},this.validateKeyProperty=!1,this.canSendMessage=Ps.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,Os.set(t,this,e),t.connect&&(this.connectSettings=t.connect),this.demo&&((r=this.connectSettings).url??(r.url=Ms.URL)),this.connectSettings.websocket&&Ts.setup(this),this.stream=(null==(a=this.deepChat.connect)?void 0:a.stream)||ue.checkForStream(this.deepChat),t.loadHistory&&$s.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}`,R(t))});const o=e[e.length-1];return o[r]&&(delete o[k],s.append(`message${n+=1}`,R(o))),s}getServiceIOByType(t){if(t[w].startsWith(T)&&this.fileTypes[T])return this.fileTypes[T];if(t[w].startsWith(_)){if(this.fileTypes[M]&&t[w].endsWith("/gif"))return this.fileTypes[M];if(this.fileTypes[C])return this.fileTypes[C];if(this[A])return this[A]}return this.fileTypes[j]}async request(t,e,i=!0){return this.stream&&!Cs.isSimulation(this.stream)?Cs.request(this,t,e,i):js.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[Wt]||((s=this.connectSettings).headers??(s.headers={}),(n=this.connectSettings.headers)[Wt]??(n[Wt]=Zt),a=!0),await this.request(r,t),a&&(null==(o=this.connectSettings.headers)||delete o[Wt])}async callApiWithFiles(t,e,i){const s=Ps.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){var i;if(!this.connectSettings)throw new Error(W);const s=Es.processMessages(e.messageToElements.map(([t])=>t),this.maxMessages,this.totalMessagesMaxCharLength);if(!this.connectSettings.websocket||this.connectSettings.handler&&this.connectSettings.url===Ms.URL)this.callServiceAPI(e,s,t[k]);else{const n={messages:s,...this.rawBody};t[k]&&null!=(i=this.getServiceIOByType(t[k][0]))&&i.connect?this.callApiWithFiles(e,s,t[k]):Ts.sendWebsocket(this,n,e,!1)}}async extractResultData(t){return t.result?ue.handleResponseProperty(t):bs.validateResponseFormat(t,!!this.stream)?t:void 0}isDirectConnection(){return!1}isWebModel(){return!1}isCustomView(){return!1}}class Bs extends Ps{constructor(t,e,i,s,n){var o;super(t,n),this.insertKeyPlaceholderText="API Key",this.keyHelpUrl="",this.asyncCallInProgress=!1,this.systemMessage="",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}completeConfig(t,e){t.system_prompt&&(this.systemMessage=t.system_prompt),e&&(this.functionHandler=e),delete t.system_prompt,delete t.key,delete t.function_handler,Object.assign(this.rawBody,t)}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,augmentUrl:a}=this._keyVerificationDetails,l=(null==o?void 0:o(t))||this._buildHeadersFunc(t),c=(null==a?void 0:a(t))||i;js.verifyKey(t,c,l,s,this.keyAuthenticated.bind(this,e.onSuccess),e.onFail,e.onLoad,n,r)}isDirectConnection(){return!0}static getRoleViaUser(t){return t===u?u:d}static getRoleViaAI(t){return t===h?d:u}processMessages(t){return Es.getCharacterLimitMessages(t,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this.systemMessage.length:-1)}addSystemMessage(t){this.systemMessage&&t.unshift({[P]:ne,content:this.systemMessage})}async callDirectServiceServiceAPI(t,e,i,s,n){if(!this.connectSettings)throw new Error(W);const o=i(this.rawBody,e),r=!!s&&this.stream;if((!r||typeof r===Kt&&r.simulation)&&!o.stream)return await js.request(this,o,t,n);o.stream=!0,null!=s&&s.readable&&(this.stream={readable:!0}),Cs.request(this,o,t)}async callToolFunction(t,e){var i,s;this.asyncCallInProgress=!0;const n=await t(e);if(!Array.isArray(n)){if(n[r]){const t={[r]:n[r]},e=await(null==(s=(i=this.deepChat).responseInterceptor)?void 0:s.call(i,t))||t;if(Array.isArray(e))throw Error("Function tool response interceptor cannot return an array");return{processedResponse:e}}throw Error(Y)}return{responses:await Promise.all(n)}}makeAnotherRequest(t,e,i){try{return e&&(this.stream?Cs.request(this,t,e):js.request(this,t,e)),{[r]:i||""}}catch(t){throw this.asyncCallInProgress=!1,t}}genereteAPIKeyName(t){return`${t} API Key`}static getImageContent(t){return t.filter(t=>t[w]===_).map(t=>({[w]:se,[se]:{url:t[y]||""}})).filter(t=>t[se].url.length>0)}static getTextWImagesContent(t){if(t[k]&&t[k].length>0){const e=this.getImageContent(t[k]);return t[r]&&t[r].trim().length>0&&e.unshift({[w]:r,[r]:t[r]}),e.length>0?e:t[r]||""}return t[r]||""}static getTextWFilesContent(t,e){if(t[k]&&t[k].length>0){const i=e(t[k]);return t[r]&&t[r].trim().length>0&&i.unshift({[w]:r,[r]:t[r]}),i}return t[r]||""}async extractStreamResultWToolsGeneric(t,e,i,s,n){const{delta:o,finish_reason:a}=e;if("tool_calls"===a){const e={tool_calls:t._streamToolCalls};return t._streamToolCalls=void 0,this.handleToolsGeneric(e,i,t.messages,s,n)}return null!=o&&o.tool_calls&&(t._streamToolCalls?o.tool_calls.forEach((e,i)=>{t._streamToolCalls&&(t._streamToolCalls[i].function.arguments+=e.function.arguments)}):t._streamToolCalls=o.tool_calls),{[r]:(null==o?void 0:o.content)||""}}async handleToolsGeneric(t,e,i,s,n){if(!t.tool_calls||!s||!e)throw Error(Q);const o=F(s),r=t.tool_calls.map(t=>({name:t.function.name,arguments:t.function.arguments})),{responses:a,processedResponse:l}=await this.callToolFunction(e,r);if(l)return l;if(n&&(o.messages=o.messages.slice(o.messages.length-1),n.message&&o.messages.unshift({[P]:ne,content:n.message})),o.messages.push({tool_calls:t.tool_calls,[P]:d,content:null}),!a.find(({response:t})=>typeof t!==B)&&r.length===a.length)return a.forEach((e,i)=>{var s;const n=null==(s=t.tool_calls)?void 0:s[i];null==o||o.messages.push({[P]:"tool",tool_call_id:null==n?void 0:n.id,name:null==n?void 0:n.function.name,content:e.response})}),this.makeAnotherRequest(o,i);throw Error(Y)}updateSessionId(t){this.messages&&this.messages.messageToElements.length>0&&(this.messages.messageToElements[this.messages.messageToElements.length-1][0]._sessionId=t)}}class Rs{static waitForPropertiesToBeUpdatedBeforeRender(t){t._propUpdated_=!1,setTimeout(()=>{t._propUpdated_?Rs.waitForPropertiesToBeUpdatedBeforeRender(t):(t._waitingToRender_=!1,t.onRender())})}static attemptRender(t){t._propUpdated_=!0,t._waitingToRender_||(t._waitingToRender_=!0,Rs.waitForPropertiesToBeUpdatedBeforeRender(t))}}const Fs=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:Rs.attemptRender(this)}})}attributeChangedCallback(e,i,s){if(i===s)return;const n=t._attributes_[e](s);this[t._attributeToProperty_[e]]=n}onRender(){}};Fs._attributes_={},Fs._attributeToProperty_={};let Ls=Fs;class qs{static createSVGElement(t){return(new DOMParser).parseFromString(t,"image/svg+xml").documentElement}}const zs=class s{static changeVisibility(t,i,n,o){o.target.id===s.VISIBLE_ICON_ID?(i[e].display="none",n[e].display="block",t[w]="password"):(i[e].display="block",n[e].display="none",t[w]=r)}static createIconElement(e,i){const s=qs.createSVGElement(e);return s.id=i,s[t].add("visibility-icon"),s}static create(t){const n=i();n.id="visibility-icon-container";const o=s.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',s.VISIBLE_ICON_ID);o[e].display="none",n.appendChild(o);const r=s.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 n.appendChild(r),n.onclick=s.changeVisibility.bind(this,t,o,r),n}};zs.VISIBLE_ICON_ID="visible-icon";let Ds=zs;class Ns{static createCautionText(){const e=i("a");return e[t].add("insert-key-input-help-text"),e.innerText="Please exercise CAUTION when inserting your API key outside of deepchat.dev or localhost!!",e}static createHelpLink(e){const s=i("a");return s[t].add("insert-key-input-help-text"),s.href=e,s.innerText="Find more info here",s.target="_blank",s}static createFailText(){const t=i();return t.id="insert-key-input-invalid-text",t[e].display="none",t}static createHelpTextContainer(t,e=!0){const s=i();s.id="insert-key-help-text-container";const n=i();n.id="insert-key-help-text-contents";const o=Ns.createFailText();if(n.appendChild(o),t){const e=Ns.createHelpLink(t);n.appendChild(e)}if(!0===e){const t=Ns.createCautionText();n.appendChild(t)}return s.appendChild(n),{helpTextContainerElement:s,failTextElement:o}}static onFail(i,s,n,o){i[t].replace("insert-key-input-valid","insert-key-input-invalid"),n.innerText=o,n[e].display="block",s.innerText="Start",i[t].remove(gt)}static onLoad(e,i){e[t].add(gt),i.innerHTML='<div id="loading-key"></div>'}static verifyKey(t,e,i){const s=t.value.trim();i.verifyKey(s,e)}static addVerificationEvents(e,i,s,n,o){const r={onSuccess:n,onFail:Ns.onFail.bind(this,e,i,s),onLoad:Ns.onLoad.bind(this,e,i)},a=Ns.verifyKey.bind(this,e,r,o);i.onclick=a,e.onkeydown=i=>{!e[t].contains(gt)&&i.key===Et.ENTER&&a()}}static createStartButton(){const t=i();return t.id="start-button",t.innerText="Start",t}static onInputFocus(e){e.target[t].replace("insert-key-input-invalid","insert-key-input-valid")}static createInput(e){const s=i();s.id="insert-key-input-container";const n=i("input");return n.id="insert-key-input",n.placeholder=e||"API Key",n[w]="password",n[t].add("insert-key-input-valid"),n.onfocus=Ns.onInputFocus,s.appendChild(n),s}static createContents(t,e){var s;const n=i();n.id="insert-key-contents";const o=Ns.createInput(e.insertKeyPlaceholderText),r=o.children[0],a=Ds.create(r);o.appendChild(a),n.appendChild(o);const l=Ns.createStartButton(),{helpTextContainerElement:c,failTextElement:h}=Ns.createHelpTextContainer(e.keyHelpUrl,null==(s=e.deepChat._insertKeyViewStyles)?void 0:s.displayCautionText);return n.appendChild(l),n.appendChild(c),Ns.addVerificationEvents(r,l,h,t,e),n}static createElements(t,e){const s=i();s.id="insert-key-view";const n=Ns.createContents(t,e);return s.appendChild(n),s}static render(t,e,i){const s=Ns.createElements(e,i);t.replaceChildren(s)}}const Us=class t{static enableButtons(e,i,s=0){window.webLLM?(e&&(e[ht]=!1),i&&(i[ht]=!1)):s<4*Gs.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[k]&&n[k].length>0&&e(n[k])}),l&&(l.onclick=()=>n[lt]()),(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=i("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[lt](),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>`}};Us.DOWNLOAD_BUTTON_CLASS="deep-chat-download-button",Us.UPLOAD_BUTTON_CLASS="deep-chat-upload-button",Us.FILE_INPUT_CLASS="deep-chat-file-input",Us.EXPORT_BUTTON_CLASS="deep-chat-export-button";let Hs=Us;const Vs={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},Ws=class t extends Ps{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[P]===u&&i[r]){const n=e[s+1];null!=n&&n[r]&&n[P]!==u&&t.push([i[r],n[r]])}})}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(o,t.WEB_LLM_NOT_FOUND_ERROR),console[l]("The deep-chat-web-llm module has not been attached to the window object. Please see the following guide:"),console[l]("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&&re.scrollToTop(null==(e=this._messages)?void 0:e.elementRef)},t)}getIntroMessage(t){if(!this.shouldAddIntroMessage(t)||!this._chatEl)return;const e=Hs.setUpInitial(this.init.bind(this),this._webModel.introMessage,this._chatEl,!!this._webModel.worker);return this.scrollToTop(1),{[P]:h,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(o,t.MULTIPLE_MODELS_ERROR),void console[l](t.MULTIPLE_MODELS_ERROR);if(this._isModelLoaded||this._isModelLoading)return;const{worker:i}=this._webModel;return Vs.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=F(Vs);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,a,l,c,h;this.scrollToTop(),t.chat=e,this._isModelLoading=!0;let u=!1===(null==(s=this._webModel.introMessage)?void 0:s.displayed);let d;t.chat.setInitProgressCallback(t=>{var e;null==(e=this._messages)||e.addNewMessage({html:`<div>${t[r]}</div>`,overwrite:!0,sendUpdate:!1}),u&&(setTimeout(()=>re.scrollToBottom(this._messages)),u=!1)});try{const{model:e,appConfig:s}=this.getConfig(),n={};this._webModel.instruction&&(n.conv_config={[ne]:this._webModel.instruction}),this._conversationHistory.length>0&&(n.conversation_history=this._conversationHistory),d=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!=(a=this._webModel.introMessage)&&a.removeAfterLoad)!1===this._webModel.introMessage.displayed?null==(c=this._messages)||c.removeLastMessage():null==(h=this._removeIntro)||h.call(this);else{const t=Hs.setUpAfterLoad(d,this._webModel.introMessage,this._chatEl,!!this._webModel.worker);null==(l=this._messages)||l.addNewMessage({html:t,overwrite:!0,sendUpdate:!1})}this._isModelLoaded=!0,this._isModelLoading=!1}async unloadChat(e){var i;null==(i=this._messages)||i.addNewErrorMessage(o,t.GENERIC_ERROR),console[l](e),this._isModelLoaded=!1,this._isModelLoading=!1,t.chat&&(await t.chat.unload(),t.chat=void 0)}async immediateResp(e,i,s){const n={[r]: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.onAbort=()=>{s.interruptGenerate()},this.streamHandlers.onOpen();const n=new gs(e);await s.generate(i,async(i,s)=>{const o=await t.processResponse(this.deepChat,e,{[r]:s});o&&n.upsertStreamedMessage({[r]:o[0][r],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(o),console.log(t)}}async generateResp(t,e,i){const s=e[e.length-1][r],{body:n,error:o}=await bs.processRequestInterceptor(this.deepChat,{body:{[r]:s}}),a=!!this.stream;try{if(o)bs.displayError(t,new Error(o)),(a?this.streamHandlers.onClose:this.completionsHandlers.onFinish)();else if(n&&n[r])this.generateRespByType(t,n[r],!!this.stream,i);else{const e=D({body:n},!1);console[l](e);const i=a?this.streamHandlers.onClose:this.completionsHandlers.onFinish;bs.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[l](K);const a=Array.isArray(o)?o:[o],c=a.find(t=>typeof t[l]===B);if(!c){if(a.find(t=>!t||!t[r])){const s=N(i,!!t.responseInterceptor,o);return void bs.displayError(e,new Error(s))}return a}bs.displayError(e,new Error(c[l]))}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)})})})}};Ws.GENERIC_ERROR=`Error, please check the [troubleshooting](${c}webModel#troubleshooting) section of documentation for help.`,Ws.MULTIPLE_MODELS_ERROR="Cannot run multiple web models",Ws.WEB_LLM_NOT_FOUND_ERROR="WebLLM module not found",Ws.DEFAULT_MODEL="Llama-2-7b-chat-hf-q4f32_1",Ws.MODULE_SEARCH_LIMIT_S=5;let Gs=Ws;const Zs=(t,e,i,s)=>({url:t,method:e,handleVerificationResult:i,augmentUrl:s}),Ks=t=>({[Lt]:`${Xt}${t}`,[Wt]:Zt}),Js=(t,e,i,s)=>{const n=t;Array.isArray(n[l])&&"Error in `parameters`: field required"===n[l][0]?i(e):s(H)},Xs=class t extends Bs{constructor(e,i,s,n,o,r){super(e,Zs("https://api-inference.huggingface.co/models/gpt2",Yt,Js),Ks,o,r),this.insertKeyPlaceholderText="Hugging Face Token",this.keyHelpUrl="https://huggingface.co/settings/tokens",this.permittedErrorPrefixes=[Dt],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=F(t),n=e[e.length-1][r];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(W);const s=this.preprocessBody(this.rawBody,e,i);js.request(this,s,t)}};Xs.URL_PREFIX="https://api-inference.huggingface.co/models/";let Qs=Xs;class Ys extends Qs{constructor(t,e,i,s,n,o){super(t,e,i,s,n,o),this.isTextInputDisabled=!0,this.canSendMessage=Ys.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(W);if(null==i||!i[0])throw new Error(G);js.poll(this,i[0],t,!1)}}class tn extends Ys{constructor(t){var e,i,s;const n=null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.audioClassification,o=null==(s=t.directConnection)?void 0:s.huggingFace;super(t,`Attach an audio ${x}`,"ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition",n,o,{audio:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t[l])throw t[l];return{[r]:(null==(e=t[0])?void 0:e.label)||""}}}class en extends Ys{constructor(t){var e,i,s;const n=null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.imageClassification,o=null==(s=t.directConnection)?void 0:s.huggingFace;super(t,`Attach an image ${x}`,"google/vit-base-patch16-224",n,o,{images:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t[l])throw t[l];return{[r]:(null==(e=t[0])?void 0:e.label)||""}}}const sn=t=>({[Lt]:`${Xt}${t}`,[Wt]:Zt}),nn=(t,e,i,s)=>{t.message?s(H):i(e)},on=()=>Zs("https://api.stability.ai/v1/engines/list",Qt,nn),rn="data:image/png;base64,";class an extends Bs{constructor(t,e,i,s,n){super(t,e,i,s,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Stability AI"),this.keyHelpUrl="https://platform.stability.ai/docs/getting-started/authentication",this.permittedErrorPrefixes=[Ut,"invalid_"]}}class ln extends an{constructor(t){var e;const i=F(t.directConnection),s=null==i?void 0:i.stabilityAI;super(t,on(),sn,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";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`),ln.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=ln.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(_,e),Object.keys(t).forEach(e=>{i.append(e,String(t[e]))}),i}async callServiceAPI(t,e,i){if(!this.connectSettings)throw new Error(W);if(!i)throw new Error(Z);const s=this.createFormDataBody(this.rawBody,i[0]);bs.tempRemoveContentHeader(this.connectSettings,js.request.bind(this,this,s,t),!1)}async extractResultData(t){if(t.message)throw t.message;const e=t.artifacts.map(t=>({[y]:`${rn}${t.base64}`,[w]:_}));return{[k]:e}}}class cn extends an{constructor(t){var e;const i=F(t.directConnection),s=null==i?void 0:i.stabilityAI,n={[C]:{[k]:{acceptedFormats:".png",maxNumberOfFiles:2}}};super(t,on(),sn,s,n),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";const o=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageMasking;"object"==typeof o&&(o.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${o.engine_id}/image-to-image/masking`),void 0!==o.weight&&null!==o.weight&&(this._imageWeight=o.weight),void 0!==o.mask_source&&null!==o.mask_source&&(this._maskSource=o.mask_source),cn.cleanConfig(o),Object.assign(this.rawBody,o)),this.canSendMessage=cn.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(W);if(!i||!i[0]||!i[1])throw new Error(Z);const o=null==(n=null==(s=e[e.length-1])?void 0:s[r])?void 0:n.trim(),a=this.createFormDataBody(this.rawBody,i[0],i[1],o);bs.tempRemoveContentHeader(this.connectSettings,js.request.bind(this,this,a,t),!1)}async extractResultData(t){if(t.message)throw t.message;const e=t.artifacts.map(t=>({[y]:`${rn}${t.base64}`,[w]:_}));return{[k]:e}}}class hn extends Ys{constructor(t){var e,i,s;const n=null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.audioSpeechRecognition,o=null==(s=t.directConnection)?void 0:s.huggingFace;super(t,`Attach an audio ${x}`,"facebook/wav2vec2-large-960h-lv60-self",n,o,{audio:{}})}async extractPollResultData(t){if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t[l])throw t[l];return{[r]:t[r]||""}}}class un extends Qs{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[l])throw t[l];return{[r]:(null==(e=t[0])?void 0:e.generated_text)||""}}}class dn extends Qs{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=[Dt,"Error in"],this._context=n.context}preprocessBody(t,e){const i=e[e.length-1][r];if(i)return{inputs:{question:i,context:this._context,options:{wait_for_model:!0}}}}async extractResultData(t){if(t[l])throw t[l];return{[r]:t.answer||""}}}class pn extends Qs{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[l])throw t[l];return{[r]:(null==(e=t[0])?void 0:e.summary_text)||""}}}class mn extends Qs{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)}processMessagesI(t){const e=t.filter(t=>t[r]),i=e[e.length-1][r],s=e.slice(0,e.length-1);if(!i)return;return{past_user_inputs:s.filter(t=>t[P]===u).map(t=>t[r]),generated_responses:s.filter(t=>t[P]===h).map(t=>t[r]),mostRecentMessageText:i}}preprocessBody(t,e){const i=F(t),s=this.processMessagesI(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,[r]:s.mostRecentMessageText},...i}}async extractResultData(t){if(t[l])throw t[l];return{[r]:t.generated_text||""}}}class vn extends an{constructor(t){var e;const i=F(t.directConnection),s=i.stabilityAI,n={[C]:{[k]:{acceptedFormats:".png",maxNumberOfFiles:1}}};super(t,on(),sn,s,n),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/image-to-image",this.textInputPlaceholderText="Describe image changes";const o=null==(e=i.stabilityAI)?void 0:e.imageToImage;"object"==typeof o&&(o.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${o.engine_id}/text-to-image`),void 0!==o.weight&&null!==o.weight&&(this._imageWeight=o.weight),vn.cleanConfig(o),Object.assign(this.rawBody,o)),this.canSendMessage=vn.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(W);if(!i)throw new Error(Z);const o=null==(n=null==(s=e[e.length-1])?void 0:s[r])?void 0:n.trim(),a=this.createFormDataBody(this.rawBody,i[0],o);bs.tempRemoveContentHeader(this.connectSettings,js.request.bind(this,this,a,t),!1)}async extractResultData(t){if(t.message)throw t.message;const e=t.artifacts.map(t=>({[y]:`${rn}${t.base64}`,[w]:_}));return{[k]:e}}}class fn extends Qs{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[l])throw t[l];return{[r]:(null==(e=t[0])?void 0:e.translation_text)||""}}}class gn extends an{constructor(t){var e;const i=F(t.directConnection),s=i.stabilityAI;super(t,on(),sn,s),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/text-to-image",this.textInputPlaceholderText="Describe an image";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),gn.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=gn.canSendTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendTextMessage(t){return!(!t||""===t.trim())}preprocessBody(t,e){const i=e[e.length-1][r],s=F(t),n={[r]:i};return this._imageWeight&&(n.weight=this._imageWeight),s.text_prompts=[n],s}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){if(t.message)throw t.message;const e=t.artifacts.map(t=>({[y]:`${rn}${t.base64}`,[w]:_}));return{[k]:e}}}class bn extends Qs{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.permittedErrorPrefixes=[Dt,"No mask_token"]}async extractResultData(t){var e;if(t[l])throw t[l];return{[r]:(null==(e=t[0])?void 0:e.sequence)||""}}}const yn=t=>({[Wt]:Zt,[Lt]:`${Xt}${t}`}),wn=(t,e,i,s)=>{const n=t;n[l]?n[l].message===zt?s(H):s(V):i(e)},xn=()=>Zs("https://open.bigmodel.cn/api/paas/v4/models",Qt,wn);class kn extends Bs{constructor(t){var e,i,s;const n=F(t.directConnection),o=n.bigModel;super(t,xn(),yn,o),this.insertKeyPlaceholderText=this.genereteAPIKeyName("BigModel"),this.keyHelpUrl="https://open.bigmodel.cn/usercenter/apikeys",this.url="https://open.bigmodel.cn/api/paas/v4/audio/speech",this.permittedErrorPrefixes=[Lt,Ht];const r=null==(e=n.bigModel)?void 0:e.textToSpeech;typeof r===Kt&&(this.cleanConfig(r),Object.assign(this.rawBody,r)),(i=this.rawBody).model??(i.model="cogtts"),(s=this.rawBody).voice??(s.voice="tongtong")}cleanConfig(t){delete t.key}preprocessBody(t,e){const i=F(t),s=e[e.length-1];return i.input=(null==s?void 0:s[r])||"",i}async callServiceAPI(t,e){return this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){const e=new Blob([t],{[w]:"audio/mpeg"}),i=URL.createObjectURL(e);return{[k]:[{[y]:i,[w]:T}]}}}const _n=t=>({[Wt]:Zt,[Lt]:`${Xt}${t}`}),Cn=(t,e,i,s)=>{const n=t;n[l]?n[l].message===zt?s(H):s(V):i(e)},An=()=>Zs("https://api.together.xyz/v1/models",Qt,Cn);class Mn extends Bs{constructor(t){var e,i,s;const n=F(t.directConnection),o=n.together;super(t,An(),_n,o),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Together AI"),this.keyHelpUrl="https://api.together.xyz/settings/api-keys",this.url="https://api.together.xyz/v1/audio/speech",this.permittedErrorPrefixes=[Vt,Ht];const r=null==(e=n.together)?void 0:e.textToSpeech;typeof r===Kt&&this.completeConfig(r),(i=this.rawBody).model??(i.model="cartesia/sonic"),(s=this.rawBody).voice??(s.voice="laidback woman")}preprocessBody(t,e){const i=F(t),s=e[e.length-1];return i.input=(null==s?void 0:s[r])||"",i}async callServiceAPI(t,e){return this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){const e=new Blob([t],{[w]:"audio/mpeg"}),i=URL.createObjectURL(e);return{[k]:[{[y]:i,[w]:T}]}}}const Tn="https://api.openai.com/v1/",Sn="https://platform.openai.com/account/api-keys",jn="input_text",En="input_image",In="output_text",$n="image_generation_call",On="function_call_output",Pn="response",Bn=t=>({[Lt]:`${Xt}${t}`,[Wt]:Zt}),Rn=(t,e,i,s)=>{const n=t;n[l]?"invalid_api_key"===n[l].code?s(H):s(V):i(e)},Fn=()=>Zs(`${Tn}models`,Qt,Rn),Ln=async(t,e,i,s=!0)=>{const{connectSettings:n,deepChat:o,completionsHandlers:r,messages:a}=t;n.method=i;const c={body:e,headers:n.headers},{body:h,headers:u,error:d}=await bs.processRequestInterceptor(o,c),{onFinish:p}=r;if(d&&a)return bs.onInterceptorError(a,d,p);const m=await bs.fetch(t,u,s,h).then(t=>bs.processResponseByType(t));if(m[l])throw m[l].message;return m},qn=class t{static async storeFiles(t,e,i,s){const n=t.connectSettings.headers;if(!n)return;t.url=s;const o=n[Wt];delete n[Wt];const r=i.map(async e=>{const i=new FormData;return i.append("purpose","assistants"),i.append("file",e),new Promise(e=>{e(Ln(t,i,Yt,!1))})});try{const t=(await Promise.all(r)).map(t=>({id:t.id,name:t.filename}));return n[Wt]=o,t}catch(i){throw n[Wt]=o,bs.displayError(e,i),t.completionsHandlers.onFinish(),i}}static getType(t,e){const{path:i}=t[e];return!i||i.endsWith("png")?_:E}static async getFiles(e,i,s,n){const o=i.map(({fileId:t})=>(e.url=`${s}${t}${n}`,new Promise(t=>{t(Ln(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({[y]:e.target.result,name:i[s].name,[w]: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 a,l;let c;const{getFilesPrefix:h,getFilesPostfix:u}=s;return i.length>0&&(c=await t.getFiles(e,i,h,u),null!=(a=null==o?void 0:o[r])&&a.value&&c.forEach((t,e)=>{var s;if(!t[y])return;const n=i[e].path;null!=(s=null==o?void 0:o[r])&&s.value&&n&&(o[r].value=o[r].value.replace(n,t[y]))})),null!=(l=null==o?void 0:o[r])&&l.value?{[r]:o[r].value,[P]:n}:{[k]:c,[P]:n}}static getFileDetails(e,i){var s;const n=[];return null!=(s=null==i?void 0:i[r])&&s.value&&e.content.forEach(e=>{var i,s;null==(s=null==(i=e[r])?void 0:i.annotations)||s.forEach(e=>{var i;e[r]&&e[r].startsWith("sandbox:")&&null!=(i=e.file_path)&&i.file_id&&n.push({path:e[r],fileId:e.file_path.file_id,name:t.getFileName(e[r])})})}),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(s.role!==d)break;i.push(s)}return i.reverse()}static parseMessages(e,i,s){const n=[];return i.forEach(async i=>{i.content.filter(t=>!!t[r]||!!t.image_file).sort(t=>t[r]?-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:d}],s)}static async processAPIMessages(e,i,s,n){const o=t.parseResult(i,s);return t.parseMessages(e,o,n)}};qn.FILES_WITH_TEXT_ERROR="content with type `text` must have `text` values",qn.FUNCTION_TOOL_RESP_ERROR=`Response must contain an array of strings for each individual function/tool_call, see ${c}directConnection/OpenAI/#assistant-functions.`;let zn=qn;const Dn=class t extends Bs{constructor(t,e,i,s,n,o){if(super(t,s,n,o),this.insertKeyPlaceholderText=this.genereteAPIKeyName("OpenAI"),this.keyHelpUrl=Sn,this.url="",this.permittedErrorPrefixes=[Ut,"Please send text",$s.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[{[l]:tt}]}}static processImageMessage(t,e){const i=null==e?void 0:e.filter(t=>es.isImageFileExtension(t.name)).map(t=>({[w]:"image_file",image_file:{file_id:t.id}}));if(i&&i.length>0)return t[r]&&t[r].length>0&&i.push({[w]:r,[r]:t[r]}),{content:i,[P]:u}}static processAttachmentsMessage(t,e,i){return{attachments:e.map(t=>({tools:[{[w]:i}],file_id:t.id})),content:[{[w]:r,[r]:t[r]}],[P]:u}}processMessage(e,i){const s=this.totalMessagesMaxCharLength||-1,n=Es.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||t===C?e=t:(console[l](`Tool type "${t}" is not valid`),console[l]('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})=>!es.isImageFileExtension(t)))console[l]("The uploaded files contained a non-image file"),console[l]('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[r]||"",[P]:u}}createNewThreadMessages(t,e,i){const s=F(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);js.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):js.request(this,s,t)}}async callServiceAPI(t,e,i){var s;if(this._waitingForStreamResponse=!1,!this.connectSettings)throw new Error(W);(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 zn.storeFiles(this,t,i,this.urlSegments.storeFiles):void 0;this.connectSettings.method=Yt,this.callService(t,e,n)}async createNewAssistant(){try{this.url=this.urlSegments.newAssistantUrl;const t=await Ln(this,F(this._newAssistantDetails),Yt);return this._config.assistant_id=t.id,this._config.assistant_id}catch(t){console[l](t),console[l]("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[l])throw t[l].message.startsWith(zn.FILES_WITH_TEXT_ERROR)?Error("Please send text with your file(s)"):t[l].message;this.asyncCallInProgress=!0,await this.assignThreadAndRun(t);const i=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs/${this.run_id}${this.urlSegments.threadsPosfix}`,s={method:Qt,headers:null==(e=this.connectSettings)?void 0:e.headers};return js.executePollRequest(this,i,s,this.messages),{[r]:""}}async assignThreadAndRun(t){if(this.sessionId){this.url=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs${this.urlSegments.threadsPosfix}`;const t=await Ln(this,F(this.rawBody),Yt);this.run_id=t.id}else this.sessionId=t.thread_id,this.run_id=t.id,this.updateSessionId(this.sessionId)}async getThreadMessages(t,e=!1){var i,s;this.url=`${this.urlSegments.threadsPrefix}/${t}/messages?${this.urlSegments.listMessagesPostfix}`;let n=await Ln(this,{},Qt);return!e&&this.deepChat.responseInterceptor&&(n=await(null==(s=(i=this.deepChat).responseInterceptor)?void 0:s.call(i,n))),zn.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(s===Jt&&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,[k]: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._functionHandlerI)throw Error(Q);const i=e.map(t=>({name:t.function.name,arguments:t.function.arguments})),s=await this._functionHandlerI(i);if(!Array.isArray(s)||e.length!==s.length)throw Error(zn.FUNCTION_TOOL_RESP_ERROR);const n=await Promise.all(s);if(n.find(t=>typeof t!==B))throw Error(zn.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 Ln(this,{tool_outputs:o},Yt),{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.asyncCallInProgress=!0,this.url=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs${this.urlSegments.threadsPosfix}`;const t=F(this.rawBody);this.createStreamRun(t)}return{[r]:""}}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[r]);if(null!=(e=null==s?void 0:s[r])&&e.annotations&&s[r].annotations.length>0){const e=t.content.find(t=>!!t[r])||t.content[0],s=zn.getFilesAndText.bind(this,this,{[P]:d,content:t.content},this.urlSegments,e);return null==(i=this._messageStream)||i.endStreamAfterFileDownloaded(this.messages,s),{[r]:""}}}if(null!=(s=t.delta)&&s.content){if(t.delta.content.length>1){const e=t.delta.content.find(t=>t[r]);if(null!=(n=null==e?void 0:e[r])&&n.annotations&&0===e[r].annotations.length){const e=await zn.processStreamMessages(this,t.delta.content,this.urlSegments);return{[r]:e[0][r],[k]:e[1][k]}}}return{[r]:null==(o=t.delta.content[0][r])?void 0:o.value}}return!this.sessionId&&t.thread_id&&(this.sessionId=t.thread_id),{[r]:""}}async createStreamRun(t){t.stream=!0,this._waitingForStreamResponse=!0,this._messageStream=await Cs.request(this,t,this.messages,!0,!0)}};Dn.POLLING_TIMEOUT_MS=500;let Nn=Dn;class Un extends Nn{constructor(t){var e,i,s,n,o;const r=F(t.directConnection),a=r.openAI,l=null==(e=r.openAI)?void 0:e.assistant;if(super(t,l,Un.buildUrlSegments(l),Fn(),Bn,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)),typeof l===Kt){const{function_handler:e,files_tool_type:i}=null==(o=null==(n=t.directConnection)?void 0:n.openAI)?void 0:o.assistant;e&&(this._functionHandlerI=e),i&&(this.filesToolType=i)}}static buildUrlSegments(t){const e="object"==typeof t&&t.custom_base_url||Tn;return{threadsPrefix:`${e}/threads`,threadsPosfix:"",newAssistantUrl:`${e}/assistants`,createMessagePostfix:"",listMessagesPostfix:"order=desc",storeFiles:`${e}/${k}`,getFilesPrefix:`${e}/${k}/`,getFilesPostfix:"/content"}}}const Hn=`Please define the Azure URL Details. [More Information](${c}directConnection/Azure)`,Vn=t=>({"api-key":t,[Wt]:Zt}),Wn=t=>Zs(`${t.endpoint}/openai/models?api-version=${t.version}`,Qt,Rn),Gn=t=>{const{endpoint:e,version:i,deploymentId:s}=t;return e&&i&&s},Zn=class t extends Nn{constructor(e){var i,s,n,o,r,a,c,h;const u=F(e.directConnection),d=u.azure,p=null==(i=u.azure)?void 0:i.openAI,m=(null==p?void 0:p.urlDetails)||{},v=`${null==(s=null==p?void 0:p.urlDetails)?void 0:s.endpoint}/openai/`,f=`?api-version=${null==(n=null==p?void 0:p.urlDetails)?void 0:n.version}`,g={threadsPrefix:`${v}${t.THREAD_RESOURCE}`,threadsPosfix:f,newAssistantUrl:`${v}${t.NEW_ASSISTANT_RESOURCE}${f}`,createMessagePostfix:f,listMessagesPostfix:`order=desc&api-version=${null==(o=null==p?void 0:p.urlDetails)?void 0:o.version}`,storeFiles:`${v}${k}${f}`,getFilesPrefix:`${v}${k}/`,getFilesPostfix:`/content${f}`};if(super(e,null==p?void 0:p.assistant,g,Wn(m),Vn,d),this.permittedErrorPrefixes=[Hn],this.insertKeyPlaceholderText=this.genereteAPIKeyName("Azure OpenAI"),this.keyHelpUrl="https://learn.microsoft.com/en-us/answers/questions/1193991/how-to-get-the-value-of-openai-api-key",this.isTextInputDisabled=!1,typeof(null==p?void 0:p.assistant)===Kt){const{function_handler:t,files_tool_type:i}=null==(c=null==(a=null==(r=e.directConnection)?void 0:r.azure)?void 0:a.openAI)?void 0:c.assistant;t&&(this._functionHandlerI=t),i&&(this.filesToolType=i)}Gn(m)?(h=this.connectSettings).headers??(h.headers={}):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout(()=>{e.addMessage({[l]:Hn})}))}};Zn.THREAD_RESOURCE="threads",Zn.NEW_ASSISTANT_RESOURCE="assistants";let Kn=Zn;class Jn{static addAttributes(t){t[P]="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-${ht}`,"true")}static removeAriaDisabled(t){t.removeAttribute(`aria-${ht}`)}static removeAriaAttributes(t){Jn.removeAriaBusy(t),Jn.removeAriaDisabled(t)}}const Xn='<?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',Qn=class e{static createTextElement(s){const n=i();return n[t].add(e.INPUT_BUTTON_INNER_TEXT_CLASS),n.innerText=s,n}static tryAddSVGElement(t,e,i,s){i?t.push(qs.createSVGElement(i)):""!==i&&s&&t.push(e)}static createCustomElements(t,i,s){var n,o;const a=null==s?void 0:s[t],l=null==(n=null==a?void 0:a[r])?void 0:n.content,c=null==(o=null==a?void 0:a[ut])?void 0:o.content,h=[];return e.tryAddSVGElement(h,i,c,l),l&&h.push(e.createTextElement(l)),h.length>0?h:void 0}static reassignClassBasedOnChildren(i,s){i[t].remove(e.INPUT_BUTTON_SVG_CLASS,e.INPUT_BUTTON_SVG_TEXT_CLASS),s.find(i=>i[t].contains(e.INPUT_BUTTON_INNER_TEXT_CLASS))?s.length>1&&i[t].add(e.INPUT_BUTTON_SVG_TEXT_CLASS):i[t].add(e.INPUT_BUTTON_SVG_CLASS)}};Qn.INPUT_BUTTON_SVG_TEXT_CLASS="input-button-svg-text",Qn.INPUT_BUTTON_INNER_TEXT_CLASS="text-button",Qn.INPUT_BUTTON_SVG_CLASS="input-button-svg";let Yn=Qn;class to{static parseSVGTextElements(t){return{[ut]:t.find(t=>t.tagName.toLowerCase()===ut),[r]:t.find(t=>"div"===t.tagName.toLowerCase())}}}class eo{static unsetAllCSS(t,e){var i,s;e.container&&xt.unsetAllCSSMouseStates(t,e.container);const{svg:n,text:o}=to.parseSVGTextElements(Array.from(t.children));null!=(i=e[ut])&&i[pt]&&n&&xt.unsetAllCSSMouseStates(n,e[ut][pt]),null!=(s=e[r])&&s[pt]&&o&&xt.unsetAllCSSMouseStates(o,e[r][pt])}static unsetActionCSS(t,e){var i,s;e.container&&xt.unsetActivityCSSMouseStates(t,e.container);const{svg:n,text:o}=to.parseSVGTextElements(Array.from(t.children));null!=(i=e[ut])&&i[pt]&&n&&xt.unsetActivityCSSMouseStates(n,e[ut][pt]),null!=(s=e[r])&&s[pt]&&o&&xt.unsetActivityCSSMouseStates(o,e[r][pt])}static setElementsCSS(t,i,s){var n,o,a,l,c;Object.assign(t[e],null==(n=i.container)?void 0:n[s]);const{svg:h,text:u}=to.parseSVGTextElements(Array.from(t.children));h&&Object.assign(h[e],null==(a=null==(o=i[ut])?void 0:o[pt])?void 0:a[s]),u&&Object.assign(u[e],null==(c=null==(l=i[r])?void 0:l[pt])?void 0:c[s])}static setElementCssUpToState(t,e,i){eo.setElementsCSS(t,e,rt),i!==rt&&(eo.setElementsCSS(t,e,at),i!==at&&eo.setElementsCSS(t,e,lt))}}class io{constructor(t,e,i,s,n,o){this._mouseState={state:"default"},this.isCustom=!1,Jn.addAttributes(t),this.elementRef=t,this[ut]=qs.createSVGElement(e),this.customStyles=n,this.position=ue.processPosition(i),this._tooltipSettings=s,this.dropupText=o}buttonMouseLeave(t){var i;this._mouseState.state=rt,"visible"===(null==(i=this._activeTooltip)?void 0:i.element[e].visibility)&&this._tooltipSettings&&Tt.hide(this._activeTooltip,this._tooltipSettings),t&&(eo.unsetAllCSS(this.elementRef,t),eo.setElementsCSS(this.elementRef,t,rt))}buttonMouseEnter(t){var e;this._mouseState.state=at,this._tooltipSettings&&(this._activeTooltip=Tt.display(this.elementRef,this._tooltipSettings,null==(e=this._activeTooltip)?void 0:e.element)),t&&eo.setElementsCSS(this.elementRef,t,at)}buttonMouseUp(t){t&&eo.unsetActionCSS(this.elementRef,t),this.buttonMouseEnter(t)}buttonMouseDown(t){this._mouseState.state=lt,t&&eo.setElementsCSS(this.elementRef,t,lt)}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&&eo.unsetActionCSS(this.elementRef,s)}}reapplyStateStyle(t,e){if(!this.customStyles)return;e&&this.unsetCustomStateStyles(e);const i=this.customStyles[t];i&&eo.setElementCssUpToState(this.elementRef,i,this._mouseState.state),this.setEvents(i)}changeElementsByState(t){this.elementRef.replaceChildren(...t),Yn.reassignClassBasedOnChildren(this.elementRef,t)}buildDefaultIconElement(t){const e=this[ut].cloneNode(!0);return e.id=t,[e]}createInnerElements(t,e,i){const s=Yn.createCustomElements(e,this[ut],i);if(s&&s.length>0){if(this.position===ot){const e=s[0].cloneNode(!0);e.id=s[0]===this[ut]?t:"dropup-menu-item-icon-element-custom",s[0]=e}return s}return this.buildDefaultIconElement(t)}}const so=class e extends io{constructor(t){var s,n;const o=(null==(n=null==(s=null==t?void 0:t[rt])?void 0:s[ut])?void 0:n.content)||e.EMPTY_SVG;super(i(),o,void 0,void 0,t),this.isActive=!1,this._innerElements=this.createInnerElementsForStates(this.customStyles),this.changeToDefault()}createInnerElementsForStates(t){return{[rt]:this.createInnerButtonElements(rt,t),[ct]:this.createInnerButtonElements(ct,t),[dt]:this.createInnerButtonElements(dt,t)}}createInnerButtonElements(t,e){return Yn.createCustomElements(t,this[ut],e)||[this[ut]]}changeState(e){this.changeElementsByState(e),this.elementRef[t].replace(Yn.INPUT_BUTTON_SVG_CLASS,"deep-chat-openai-realtime-button")}changeToActive(){this.changeState(this._innerElements[ct]),this.reapplyStateStyle(ct,[dt,rt]),this.isActive=!0}changeToDefault(){var t,e,i,s;this.changeState(this._innerElements[rt]),null!=(t=this.customStyles)&&t[ct]&&eo.unsetAllCSS(this.elementRef,null==(e=this.customStyles)?void 0:e[ct]),null!=(i=this.customStyles)&&i[dt]&&eo.unsetAllCSS(this.elementRef,null==(s=this.customStyles)?void 0:s[dt]),this.reapplyStateStyle(rt,[ct,dt]),this.isActive=!1}changeToUnavailable(){var t,e,i,s;this.changeState(this._innerElements[dt]),null!=(t=this.customStyles)&&t[ct]&&eo.unsetAllCSS(this.elementRef,null==(e=this.customStyles)?void 0:e[ct]),null!=(i=this.customStyles)&&i[rt]&&eo.unsetAllCSS(this.elementRef,null==(s=this.customStyles)?void 0:s[rt]),this.reapplyStateStyle(dt,[rt,ct]),this.isActive=!1}};so.EMPTY_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"></svg>';let no=so;class oo{static setPropertyValueIfDoesNotExist(t,e,i){const s=e[0];1===e.length?t[s]??(t[s]=i):(t[s]??(t[s]={}),e.shift(),oo.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(),oo.setPropertyValue(t[s],e,i))}static getObjectValue(t,e){const i=t[e[0]];return void 0===i||1===e.length?i:oo.getObjectValue(i,e.slice(1))}static overwritePropertyObjectFromAnother(t,e,i){const s=oo.getObjectValue(e,i);if(s){const e={...s,...oo.getObjectValue(t,i)||{}};oo.setPropertyValue(t,i,e)}}static isJson(t){try{return R(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 ro='<?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="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>',ao='<?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="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>',lo=class s extends Bs{constructor(t){var e,i,n,o,r;const a=F(t.directConnection),c=s.getKey(t);super(t,Fn(),Bn,{key:c}),this.insertKeyPlaceholderText=this.genereteAPIKeyName("OpenAI"),this.keyHelpUrl=Sn,this._microphoneButton=null,this._toggleButton=null,this._errorElement=null,this._loadingElement=null,this._pc=null,this._mediaStream=null,this._isMuted=!1;const h=null==(e=a.openAI)?void 0:e.realtime;if(typeof h===Kt){this._avatarConfig=h.avatar,this._ephemeralKey=h.ephemeralKey,this._errorConfig=h[l],this._loadingConfig=h.loading,Object.assign(this.rawBody,h.config);const e=null==(n=null==(i=t.directConnection)?void 0:i.openAI)?void 0:n.realtime,{function_handler:s}=e.config||{};s&&(this._functionHandlerI=s),this._events=h.events,e.methods=this.generateMethods(),this.setInputAudioTranscribe(t,null==(o=e.config)?void 0:o.input_audio_transcription)}(r=this.rawBody).model??(r.model="gpt-4o-realtime-preview-2025-06-03"),this._avatarConfig=s.buildAvatarConfig(h),this._buttonsConfig=s.buildButtonsConfig(h),this._avatarEl=s.createAvatar(this._avatarConfig),this._containerEl=this.createContainer(),this._deepChat=t}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}setInputAudioTranscribe(t,e){if(e){const t="whisper-1";this.rawBody.input_audio_transcription="object"==typeof e?{model:e.model||t,language:e.language,prompt:e.prompt}:{model:t}}else t.onMessage&&(console.warn("To get user audio transcription, set `input_audio_transcription` in the `realtime` config."),console.warn(`See: ${c}directConnection/OpenAI/OpenAIRealtime#OpenAIRealtimeConfig`))}setUpView(t,i){t[e].display="none",i.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(`${Tn}realtime/sessions`,{method:Yt,body:R(this.rawBody),headers:{[Wt]:Zt,[Lt]:`${Xt}${t}`}})).json()).client_secret.value}generateMethods(){return{updateConfig:t=>{var e;null==(e=this._dc)||e.send(R({[w]:"session.update",session:t}))},sendMessage:(t,e)=>{const i=e||ne,s=[{[w]:i===ne||i===u?jn:r,text:t}],n={[P]:i,[w]:"message",content:s};this.sendMessage(n)}}}static buildAvatarConfig(t){const e="object"==typeof t&&t.avatar?F(t.avatar):{};return e.maxScale=e.maxScale&&e.maxScale>=1?e.maxScale:2.5,e}static buildButtonsConfig(t){var e,i,s,n,o,a,l,c,h,u,d,p,m,v,f;const g="object"==typeof t&&t.buttons?F(t.buttons):{};return null!=(s=null==(i=null==(e=g[S])?void 0:e[rt])?void 0:i[r])&&s.content||(g[S]??(g[S]={}),(n=g[S])[rt]??(n[rt]={}),(o=g[S][rt])[ut]??(o[ut]={}),(a=g[S][rt][ut]).content??(a.content=Xn)),null!=(h=null==(c=null==(l=g.toggle)?void 0:l[rt])?void 0:c[r])&&h.content||(g.toggle??(g.toggle={}),(u=g.toggle)[rt]??(u[rt]={}),(d=g.toggle[rt])[ut]??(d[ut]={}),(p=g.toggle[rt][ut]).content??(p.content=ro),(m=g.toggle)[ct]??(m[ct]={}),(v=g.toggle[ct])[ut]??(v[ut]={}),(f=g.toggle[ct][ut]).content??(f.content=ao)),g}createContainer(){const t=i();return t.id="deep-chat-openai-realtime-container",t.appendChild(this.createAvatarContainer()),t.appendChild(this.createButtonsContainer()),t.appendChild(this.createError()),t}createAvatarContainer(){var t,s;const n=i();return n.id="deep-chat-openai-realtime-avatar-container",Object.assign(n[e],null==(s=null==(t=this._avatarConfig)?void 0:t[pt])?void 0:s.container),n.appendChild(this._avatarEl),n}static createAvatar(t){var s;const n=i("img");return n.id="deep-chat-openai-realtime-avatar",Object.assign(n[e],null==(s=null==t?void 0:t[pt])?void 0:s[_]),n[y]=(null==t?void 0:t[y])||cs,n}createButtonsContainer(){var t;const n=i();n.id="deep-chat-openai-realtime-buttons-container",Object.assign(n[e],null==(t=this._buttonsConfig)?void 0:t.container),this._microphoneButton=this.createMicophoneButton();const o=s.createButtonContainer(this._microphoneButton.elementRef);this._toggleButton=this.createToggleButton();const r=s.createButtonContainer(this._toggleButton.elementRef);return n.appendChild(o),n.appendChild(r),n.appendChild(this.createLoading()),n}static createButtonContainer(e){const s=i();return s[t].add("deep-chat-openai-realtime-button-container"),s.appendChild(e),s}createMicophoneButton(){var e;const i=new no(null==(e=this._buttonsConfig)?void 0:e[S]);return i.elementRef[t].add(s.BUTTON_DEFAULT,"deep-chat-openai-realtime-microphone"),re.assignButtonEvents(i.elementRef,()=>{i.isActive?(this.toggleMicorphone(!0),i.elementRef[t].replace(s.MICROPHONE_ACTIVE,s.BUTTON_DEFAULT),i.changeToDefault(),this._isMuted=!1):(this.toggleMicorphone(!1),i.elementRef[t].replace(s.BUTTON_DEFAULT,s.MICROPHONE_ACTIVE),Jn.removeAriaAttributes(i.elementRef),i.changeToActive(),this._isMuted=!0)}),i}toggleMicorphone(t){var e;null==(e=this._mediaStream)||e.getAudioTracks().forEach(e=>e.enabled=t)}createToggleButton(){var e;const i=new no(null==(e=this._buttonsConfig)?void 0:e.toggle);return i.elementRef[t].add(s.BUTTON_DEFAULT,"deep-chat-openai-realtime-toggle"),re.assignButtonEvents(i.elementRef,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[l]("Failed to start conversation:",t),this.displayError(),this.hideLoading()}}),i}async init(t){const e=new RTCPeerConnection;this._pc=e;const s=i(T);s.autoplay=!0;const n=new AudioContext,o=n.createAnalyser();o.fftSize=256;const a=new Uint8Array(o.frequencyBinCount);this._pc.ontrack=async t=>{if(t.streams[0]){s.srcObject=t.streams[0];const e=n.createMediaStreamSource(t.streams[0]);"suspended"===n.state&&await n.resume(),e.connect(o),this.monitorFrequencies(o,a)}else console[l]("No streams found in the ontrack event."),this.displayError()},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.toggleMicorphone(!1))}).catch(t=>{console[l]("Error accessing microphone:",t),this.displayError()}),this._dc=this._pc.createDataChannel("oai-events"),this._dc.addEventListener("message",async t=>{var e,i,s;const n=JSON.parse(t.data);if("session.created"===n[w])this.removeUnavailable(),this._toggleButton&&(Jn.removeAriaAttributes(this._toggleButton.elementRef),this._toggleButton.changeToActive()),null==(i=null==(e=this._events)?void 0:e.started)||i.call(e),this._deepChat.dispatchEvent(new CustomEvent("sts-session-started")),this.hideLoading();else if("response.done"===n[w]){const e=null==(s=JSON.parse(t.data).response.output)?void 0:s[0];if((null==e?void 0:e[w])===ee){const{name:t,call_id:i}=e;try{await this.handleTool(t,e.arguments,i)}catch(t){this.stopOnError(t)}}}else n[w]===l?this.stopOnError(n[l].message):n[w]===Vt?this.stopOnError(n.message):"response.audio_transcript.delta"===n[w]||("response.audio_transcript.done"===n[w]?n.transcript&&is.onMessage(this._deepChat,{[P]:h,[r]:n.transcript},!1):"conversation.item.input_audio_transcription.completed"===n[w]&&n.transcript&&is.onMessage(this._deepChat,{[P]:u,[r]:n.transcript},!1))});try{const i=await this._pc.createOffer();if(e!==this._pc||(await this._pc.setLocalDescription(i),e!==this._pc))return;const s=await fetch(`${Tn}realtime`,{method:Yt,body:i.sdp,headers:{[Lt]:`${Xt}${t}`,[Wt]:"application/sdp"}});if(e!==this._pc)return;const n={[w]:"answer",sdp:await s[r]()};if(e!==this._pc||(await this._pc.setRemoteDescription(n),e!==this._pc))return}catch(t){console[l](t),this.displayError()}}monitorFrequencies(t,i){const s=()=>{var n;t.getByteFrequencyData(i);const o=1+i.reduce((t,e)=>t+e,0)/(255*i.length)*100/100*((null==(n=this._avatarConfig)?void 0:n.maxScale)-1);this._avatarEl[e].transform=`scale(${o})`,requestAnimationFrame(s)};s()}stopOnError(t){this.stop(),console[l](t),this.displayError()}stop(){var t,e,i;null==(t=this._mediaStream)||t.getTracks().forEach(t=>t.stop()),this._mediaStream=null,this._pc&&(this._pc.close(),this._pc=null,null==(i=null==(e=this._events)?void 0:e.stopped)||i.call(e),this._deepChat.dispatchEvent(new CustomEvent("sts-session-stopped")),this._dc=void 0)}changeToUnavailable(){this._microphoneButton&&s.changeButtonToUnavailable(this._microphoneButton),this._toggleButton&&s.changeButtonToUnavailable(this._toggleButton)}static changeButtonToUnavailable(e){e.elementRef[t].add(s.UNAVAILABLE),Jn.removeAriaBusy(e.elementRef),Jn.addAriaDisabled(e.elementRef),e.changeToUnavailable()}changeToAvailable(){this._microphoneButton&&s.changeButtonToAvailable(this._microphoneButton),this._toggleButton&&s.changeButtonToAvailable(this._toggleButton)}static changeButtonToAvailable(t){s.removeButtonUnavailable(t),t.changeToDefault()}removeUnavailable(){this._microphoneButton&&s.removeButtonUnavailable(this._microphoneButton),this._toggleButton&&s.removeButtonUnavailable(this._toggleButton)}static removeButtonUnavailable(e){Jn.removeAriaDisabled(e.elementRef),e.elementRef[t].remove(s.UNAVAILABLE)}createError(){var t;const s=i();return s.id="deep-chat-openai-realtime-error",Object.assign(s[e],null==(t=this._errorConfig)?void 0:t[e]),this._errorElement=s,s}displayFailedToRetrieveEphemeralKey(t){console[l]("Failed to retrieve ephemeral key"),console[l](t),this.displayError()}displayError(){var t;this._errorElement&&(this._errorElement[e].display="block",this._errorElement.textContent=(null==(t=this._errorConfig)?void 0:t[r])||"Error",this.changeToUnavailable()),this.hideLoading()}createLoading(){var t,s;const n=i();return n.id="deep-chat-openai-realtime-loading",this._loadingElement=n,null!=(t=this._loadingConfig)&&t[a]&&(this._loadingElement.innerHTML=this._loadingConfig[a]),Object.assign(n[e],null==(s=this._loadingConfig)?void 0:s[e]),n[e].display="none",n}displayLoading(){var i,n,o;this._toggleButton&&(this._toggleButton.changeToActive(),this._toggleButton.elementRef[t].add(s.BUTTON_LOADING),Jn.removeAriaDisabled(this._toggleButton.elementRef),Jn.addAriaBusy(this._toggleButton.elementRef)),("boolean"!=typeof(null==(i=this._loadingConfig)?void 0:i.display)||this._loadingConfig.display)&&this._loadingElement&&(this._loadingElement[e].display="block",null!=(n=this._loadingConfig)&&n[a]||(this._loadingElement.textContent=(null==(o=this._loadingConfig)?void 0:o[r])||"Loading"))}hideLoading(){this._toggleButton&&(this._toggleButton.elementRef[t].remove(s.BUTTON_LOADING),Jn.removeAriaBusy(this._toggleButton.elementRef)),this._loadingElement&&(this._loadingElement[e].display="none")}async handleTool(t,e,i){if(!this._functionHandlerI)throw Error(Q);const s=await this._functionHandlerI({name:t,arguments:e});if("object"!=typeof s||!oo.isJson(s))throw Error('The `function_handler` response must be a JSON object, e.g. {response: "My response"}');const n={[w]:On,call_id:i,output:R(s)};this.sendMessage(n)}sendMessage(t){if(!this._dc)return;const e=R({[w]:"conversation.item.create",item:t});this._dc.send(e);const i={[w]:"response.create"};this._dc.send(R(i))}isCustomView(){return!0}};lo.BUTTON_DEFAULT="deep-chat-openai-realtime-button-default",lo.BUTTON_LOADING="deep-chat-openai-realtime-button-loading",lo.MICROPHONE_ACTIVE="deep-chat-openai-realtime-microphone-active",lo.UNAVAILABLE="deep-chat-openai-realtime-button-unavailable";let co=lo;const ho=class t extends Bs{constructor(e){var i,s,n;const o=F(e.directConnection),r=null==o?void 0:o.openAI;super(e,Fn(),Bn,r),this.insertKeyPlaceholderText=this.genereteAPIKeyName("OpenAI"),this.keyHelpUrl=Sn,this.url=`${Tn}audio/speech`,this.permittedErrorPrefixes=[Nt];const a=null==(i=null==o?void 0:o.openAI)?void 0:i.textToSpeech;typeof a===Kt&&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=F(t),o=null==(s=null==(i=e[e.length-1])?void 0:i[r])?void 0:s.trim();return o&&""!==o&&(n.input=o),n}async callServiceAPI(t,e){this.url=this.connectSettings.url||this.url,this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){if(t instanceof Blob)return new Promise(e=>{const i=new FileReader;i.readAsDataURL(t),i.onload=t=>{e({[k]:[{[y]:t.target.result,[w]:T}]})}});if(t[l])throw t[l].message;return{[l]:l}}};ho.DEFAULT_MODEL="tts-1",ho.DEFAULT_VOIDE="alloy";let uo=ho;const po=class t extends Bs{constructor(e){var i,s;const n=F(e.directConnection),o=null==n?void 0:n.openAI;super(e,Fn(),Bn,o,{audio:{}}),this.insertKeyPlaceholderText=this.genereteAPIKeyName("OpenAI"),this.keyHelpUrl=Sn,this.url="",this.permittedErrorPrefixes=[Nt],this.textInputPlaceholderText=te,this._service_url=t.AUDIO_TRANSCRIPTIONS_URL;const r=null==(i=null==n?void 0:n.openAI)?void 0:i[T];"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[w]&&"translation"===e[w]&&(this._service_url=t.AUDIO_TRANSLATIONS_URL,delete e.language)}static cleanConfig(t){delete t[w]}static createFormDataBody(t,e){const i=new FormData;return i.append(x,e),Object.keys(t).forEach(e=>{i.append(e,String(t[e]))}),i}preprocessBody(t,e){var i,s;const n=F(t),o=null==(s=null==(i=e[e.length-1])?void 0:i[r])?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(W);if(null==s||!s[0])throw new Error(G);this.url=this.connectSettings.url||this._service_url;const o=this.preprocessBody(this.rawBody,i),r=t.createFormDataBody(o,s[0]);bs.tempRemoveContentHeader(this.connectSettings,js.request.bind(this,this,r,e),!1)}async extractResultData(t){if(t[l])throw t[l].message;return{[r]:t[r]}}};po.AUDIO_TRANSCRIPTIONS_URL=`${Tn}audio/transcriptions`,po.AUDIO_TRANSLATIONS_URL=`${Tn}audio/translations`,po.DEFAULT_MODEL="whisper-1";let mo=po;const vo="Ocp-Apim-Subscription-Key",fo="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",go=(t,e)=>({[vo]:e,[Wt]:"application/ssml+xml","X-Microsoft-OutputFormat":t}),bo=t=>({[vo]:t,Accept:Zt}),yo=(t,e,i,s)=>{t[l]?s(H):i(e)},wo=t=>({[vo]:t,[Wt]:Zt}),xo=(t,e,i,s)=>{var n;"401"===(null==(n=t[l])?void 0:n.code)?s(H):i(e)},ko=(t,e,i,s)=>{t.json().then(t=>{Array.isArray(t)||401e3!==t[l].code?i(e):s(H)})},_o=(t,e)=>{const i={[vo]:e,[Wt]:Zt};return t&&(i["Ocp-Apim-Subscription-Region"]=t),i};class Co extends Bs{constructor(t,e,i,s,n){super(t,{url:`${i}/language/analyze-text/jobs?api-version=2022-10-01-preview`,method:Yt,createHeaders:t=>({[vo]:`${t}`}),handleVerificationResult:xo},e,s,n),this.insertKeyPlaceholderText="Azure Language Subscription Key",this.keyHelpUrl=fo,this.permittedErrorPrefixes=["Access"]}}const Ao=class t extends Co{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,wo,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({[l]:t.ENDPOINT_ERROR_MESSAGE})}))}preprocessBody(t,e){const i=e[e.length-1][r];if(i)return{analysisInput:{documents:[{id:"1",language:t.language,[r]:i}]},tasks:[{kind:"ExtractiveSummarization"}]}}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this)),this.messages=t}async extractResultData(t){var e;if(t[l])throw t[l].message;if(this.messages&&this.completionsHandlers){this.asyncCallInProgress=!0;const i=t.headers.get("operation-location"),s={method:Qt,headers:null==(e=this.connectSettings)?void 0:e.headers};js.executePollRequest(this,i,s,this.messages)}return{[r]:""}}async extractPollResultData(t){if(t[l])throw t[l];if("running"===t.status||"notStarted"===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[r];return{[r]:e||""}}};Ao.ENDPOINT_ERROR_MESSAGE=`Please define the azure endpoint. [More Information](${c}directConnection/Azure#Summarization)`;let Mo=Ao;const To=t=>({[Lt]:t,[Wt]:"application/octet-stream"}),So=(t,e,i,s)=>{const n=t;n[l]?"invalid_api_key"===n[l].code?s(H):s(V):i(e)};class jo extends Bs{constructor(t){var e;const i=null==(e=t.directConnection)?void 0:e.assemblyAI;super(t,Zs("https://api.assemblyai.com/v2/upload",Yt,So),To,i,{audio:{}}),this.insertKeyPlaceholderText=this.genereteAPIKeyName("AssemblyAI"),this.keyHelpUrl="https://www.assemblyai.com/app/account",this.url="https://api.assemblyai.com/v2/upload",this.isTextInputDisabled=!0,this.textInputPlaceholderText=te,this.permittedErrorPrefixes=[Ft,Nt],this.canSendMessage=jo.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(W);if(null==i||!i[0])throw new Error(G);js.request(this,i[0],t,!1)}async extractResultData(t){var e,i;if(t[l])throw t[l];const s=null==(i=null==(e=this.connectSettings)?void 0:e.headers)?void 0:i[Lt],n=await(async(t,e)=>{const i={[qt]:t,[Gt]:Zt},s=`https://api.assemblyai.com/v2/transcript/${(await(await fetch("https://api.assemblyai.com/v2/transcript",{method:Yt,body:R({audio_url:e}),headers:i})).json()).id}`;let n;for(;!n;){const t=await(await fetch(s,{headers:i})).json();if(t.status===Jt)n=t;else{if(t.status===l)throw new Error(`Transcription failed: ${t[l]}`);await new Promise(t=>setTimeout(t,3e3))}}return n})(s,t.upload_url);return{[r]:n[r]}}}class Eo extends Bs{constructor(t,e,i,s,n){var o,r;const a=F(t.directConnection);super(t,e||Fn(),i||Bn,s||a.openAI),this.insertKeyPlaceholderText=this.genereteAPIKeyName("OpenAI"),this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.permittedErrorPrefixes=[Ut,"Invalid value"];const l=n||(null==(o=a.openAI)?void 0:o.chat);typeof l===Kt&&this.processConfig(l,t),this.maxMessages??(this.maxMessages=-1),(r=this.rawBody).model??(r.model="gpt-4o")}processConfig(t,e){var i,s,n;this.completeConfig(t,null==(n=null==(s=null==(i=e.directConnection)?void 0:i.openAI)?void 0:s.chat)?void 0:n.function_handler)}static getBaseFileContent(t){return t.map(t=>{var e,i,s;if(t[w]===T){const n=null==(e=t[y])?void 0:e.split(",")[1],o=(null==(s=null==(i=t.name)?void 0:i.split(".").pop())?void 0:s.toLowerCase())||"wav";return{[w]:ie,[ie]:{data:n,format:o}}}return t})}static getBaseContent(t,e=!0){if(e&&t[k]&&t[k].length>0){const e=this.getBaseFileContent(t[k]);return t[r]&&t[r].trim().length>0&&e.unshift({[w]:r,[r]:t[r]}),e}return t[r]}}class Io extends Eo{constructor(){super(...arguments),this.url=`${Tn}chat/completions`}static getFileContent(t){return Eo.getBaseFileContent(t).map(t=>t[w]===ie?t:{[w]:se,[se]:{url:t[y]}})}static getContent(t){if(t[k]&&t[k].length>0){const e=Io.getFileContent(t[k]);return t[r]&&t[r].trim().length>0&&e.unshift({[w]:r,[r]:t[r]}),e}return t[r]}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>({content:Io.getContent(t),[P]:Bs.getRoleViaUser(t[P])}));return this.addSystemMessage(s),i.messages=s,i}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){var i,s,n,o,a,c;if(t[l])throw t[l].message;if(null!=(s=null==(i=t.choices)?void 0:i[0])&&s.delta)return this.extractStreamResult(t.choices[0],e);if(null!=(o=null==(n=t.choices)?void 0:n[0])&&o.message){if(t.choices[0].message.tool_calls)return this.handleToolsGeneric(t.choices[0].message,this.functionHandler,this.messages,e);if(null!=(a=t.choices[0].message)&&a[T]){const e=this.deepChat.textToSpeech,i="object"==typeof e&&"boolean"==typeof(null==(c=null==e?void 0:e[T])?void 0:c.displayText);return{[k]:[{[y]:`data:audio/wav;base64,${t.choices[0].message[T].data}`,[w]:T}],[r]:i?t.choices[0].message[T].transcript:void 0}}return{[r]:t.choices[0].message.content}}return{[r]:""}}async extractStreamResult(t,e){return this.extractStreamResultWToolsGeneric(this,t,this.functionHandler,e)}}const $o=class extends Bs{constructor(t,e,i,s,n){super(t,{url:`https://${i}.api.cognitive.microsoft.com/sts/v1.0/issuetoken`,method:Yt,createHeaders:t=>({[vo]:`${t}`}),handleVerificationResult:yo},e,s,n),this.insertKeyPlaceholderText="Azure Speech Subscription Key",this.keyHelpUrl=fo}};$o.REGION_ERROR_PREFIX=`Please define a region config property. [More Information](${c}directConnection/Azure#`;let Oo=$o;const Po=class t extends Oo{constructor(e){var i,s,n,o,r,a;const c=null==(s=null==(i=e.directConnection)?void 0:i.azure)?void 0:s.textToSpeech,h=null==(n=e.directConnection)?void 0:n.azure;super(e,go.bind({},(null==c?void 0:c.outputFormat)||"audio-16khz-128kbitrate-mono-mp3"),c.region,h),this.permittedErrorPrefixes=[t.REGION_ERROR_MESSAGE],this.isTextInputDisabled=!1,this.url="",c.region?(Object.assign(this.rawBody,c),(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://${c.region}.tts.speech.microsoft.com/cognitiveservices/v1`):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout(()=>{e.addMessage({[l]:t.REGION_ERROR_MESSAGE})}))}preprocessBody(t,e){const i=e[e.length-1][r];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){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),void 0,!1)}async extractResultData(t){return new Promise(e=>{const i=new FileReader;i.readAsDataURL(t),i.onload=t=>{e({[k]:[{[y]:t.target.result,[w]:T}]})}})}};Po.REGION_ERROR_MESSAGE=`${Oo.REGION_ERROR_PREFIX}TextToSpeech)`;let Bo=Po;const Ro=class t extends Oo{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,a={audio:{[k]:{acceptedFormats:".wav,.ogg"}}};if(super(e,bo,o.region,r,a),this.permittedErrorPrefixes=[t.REGION_ERROR_MESSAGE],this.url="",this.isTextInputDisabled=!0,this.textInputPlaceholderText=te,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({[l]: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(W);if(null==i||!i[0])throw new Error(G);null!=(n=this.connectSettings)&&n.headers&&(this.connectSettings.headers[Wt]=i[0].name.toLocaleLowerCase().endsWith(".wav")?"audio/wav; codecs=audio/pcm; samplerate=16000":"audio/ogg; codecs=opus"),js.request(this,i[0],t,!1)}async extractResultData(t){if(t[l])throw t[l];return{[r]:t.DisplayText||""}}};Ro.REGION_ERROR_MESSAGE=`${Oo.REGION_ERROR_PREFIX}SpeechToText)`;let Fo=Ro;class Lo extends Bs{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;var r;super(t,(r=n.region,{url:"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es",method:Yt,createHeaders:t=>_o(r,t),handleVerificationResult:ko}),_o.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][r];if(e)return[{Text:e}]}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){var e;if(Array.isArray(t))return{[r]:(null==(e=t[0].translations)?void 0:e[0][r])||""};throw t[l]}}class qo extends Bs{constructor(t){var e,i;const s=F(t.directConnection),n=s.bigModel;super(t,xn(),yn,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("BigModel"),this.keyHelpUrl="https://open.bigmodel.cn/usercenter/apikeys",this.url="https://open.bigmodel.cn/api/paas/v4/images/generations",this.permittedErrorPrefixes=[Lt,Ht];const o=null==(e=s.bigModel)?void 0:e[C];typeof o===Kt&&(this.cleanConfig(o),Object.assign(this.rawBody,o)),(i=this.rawBody).model??(i.model="cogview-4-250304")}cleanConfig(t){delete t.key}preprocessBody(t,e){const i=F(t),s=e[e.length-1];return i.prompt=(null==s?void 0:s[r])||"",i}async callServiceAPI(t,e){return this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){const e=t.data.map(t=>null!=t&&t.url?{[y]:t.url,[w]:_}:{[y]:"",[w]:_});return{[k]:e}}}const zo=t=>({[Wt]:Zt,[Lt]:`${Xt}${t}`}),Do=(t,e,i,s)=>{const n=t;n[l]?n[l].message===zt?s(H):s(V):i(e)},No=()=>Zs("https://api.groq.com/openai/v1/models",Qt,Do);class Uo extends Bs{constructor(t){var e,i,s,n;const o=F(t.directConnection),r=o.groq;super(t,No(),zo,r),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Groq"),this.keyHelpUrl="https://console.groq.com/keys",this.url="https://api.groq.com/openai/v1/audio/speech",this.permittedErrorPrefixes=[Nt,"property"];const a=null==(e=o.groq)?void 0:e.textToSpeech;typeof a===Kt&&this.completeConfig(a),(i=this.rawBody).model??(i.model="playai-tts"),(s=this.rawBody).voice??(s.voice="Fritz-PlayAI"),(n=this.rawBody).response_format??(n.response_format="mp3")}preprocessBody(t,e){const i=F(t),s=e[e.length-1];return i.input=(null==s?void 0:s[r])||"",i}async callServiceAPI(t,e){return this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){const e=this.rawBody.response_format||"mp3",i=new Blob([t],{[w]:`audio/${e}`}),s=URL.createObjectURL(i);return{[k]:[{[y]:s,[w]:T}]}}}class Ho extends Bs{constructor(t){var e,i;const s=F(t.directConnection),n=s.together;super(t,An(),_n,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Together AI"),this.keyHelpUrl="https://api.together.xyz/settings/api-keys",this.url="https://api.together.xyz/v1/images/generations",this.permittedErrorPrefixes=[Vt,Ht];const o=null==(e=s.together)?void 0:e[C];typeof o===Kt&&this.completeConfig(o),(i=this.rawBody).model??(i.model="black-forest-labs/FLUX.1-schnell-Free")}preprocessBody(t,e){const i=F(t),s=e[e.length-1];return i.prompt=(null==s?void 0:s[r])||"",i}async callServiceAPI(t,e){return this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){const e=t.data.map(t=>null!=t&&t.url?{[y]:t.url,[w]:_}:null!=t&&t.b64_json?{[y]:`data:image/png;base64,${t.b64_json}`,[w]:_}:{[y]:"",[w]:_});return{[k]:e}}}const Vo=class t extends Eo{constructor(e,i,s,n,o){var r,a;super(e,i,s,n,o),this.keyHelpUrl=Sn,this.url=`${Tn}responses`,this._functionStreamInProgress=!1,this._useConversation=!1,this._conversationLoadLimit=50;const l=o||(null==(a=null==(r=e.directConnection)?void 0:r.openAI)?void 0:a.chat);this._urlSegments=t.buildUrlSegments(l),this.url=this._urlSegments.responsesUrl,typeof l===Kt&&!0!==l&&l&&(l.conversation&&(this._useConversation=!0,"string"==typeof l.conversation&&(this._conversationId=l.conversation)),"number"==typeof l.conversationLoadLimit&&(this._conversationLoadLimit=l.conversationLoadLimit),this.cleanConfig(l)),this._conversationId&&(this.fetchHistory=this.fetchHistoryFunc.bind(this))}processConfig(t,e){super.processConfig(t,e)}static buildUrlSegments(t){const e="object"==typeof t&&(null==t?void 0:t.custom_base_url)||Tn;return{responsesUrl:`${e}responses`,conversationsUrl:`${e}conversations`}}cleanConfig(t){delete t.conversation,delete t.conversationLoadLimit,delete t.custom_base_url}static getFileContent(t){return Eo.getBaseFileContent(t).map(t=>t[w]===ie?t:{detail:"auto",[w]:En,[se]:t[y]})}static getContent(e){if(e[P]===u&&e[k]&&e[k].length>0){const i=t.getFileContent(e[k]);return e[r]&&e[r].trim().length>0&&i.unshift({[w]:jn,[r]:e[r]}),i}return e[r]}async fetchHistoryFunc(){setTimeout(()=>this.deepChat.disableSubmitButton(),2);try{const t=this.url,{conversationsUrl:e}=this._urlSegments;this.url=`${e}/${this._conversationId}/items?limit=${this._conversationLoadLimit}`;const i=await Ln(this,{},Qt);return this.connectSettings.method=Yt,this.url=t,this.deepChat.disableSubmitButton(!1),this.processConversationHistory(i)}catch{return this.deepChat.disableSubmitButton(!1),[{[l]:tt}]}}static filterCompleted(t){return(null==t?void 0:t.filter(t=>t.status===Jt))||[]}processConversationHistory(e){if(!e.data||!Array.isArray(e.data))return[];const i=[];for(const s of t.filterCompleted(e.data.reverse()))if("message"===s[w]&&s.content&&Array.isArray(s.content))for(const e of s.content)e[w]!==jn&&e[w]!==In||!e[r]?e[w]===En&&i.push({[P]:s[P],[k]:t.generateImageFile(e[se]||"")}):i.push({[P]:s[P],[r]:e[r]});else s[w]===$n&&i.push({[P]:h,[k]:t.generateImageFile(s.result)});return i}preprocessBody(e,i){const s=F(e);i=this.processMessages(i);const n=(i=this._useConversation?[i[i.length-1]]:i).map(e=>({content:t.getContent(e),[P]:Bs.getRoleViaUser(e[P])}));return s.input=n,this._conversationId&&(s.conversation=this._conversationId),s}async createConversation(){try{const t=this.url;this.url=this._urlSegments.conversationsUrl;const e=await Ln(this,{},Yt);return this.url=t,e.id}catch(t){throw console[l]("Failed to create conversation:",t),t}}async callServiceAPI(t,e){this.messages??(this.messages=t),this._useConversation&&!this._conversationId&&(this._conversationId=await this.createConversation()),this._conversationId&&this.updateSessionId(this._conversationId),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){const i=await this.extractResult(t,e);return this._conversationId&&(i._sessionId=this._conversationId),i}async extractResult(e,i){var s,n,o,a;if(e[l])throw e[l].message;if(e.status){const a=t.filterCompleted(e.output);if(a.length>0){const t=null==(o=null==(n=null==(s=a.find(t=>{var e,i;return typeof(null==(i=null==(e=t.content)?void 0:e[0])?void 0:i[r])===B}))?void 0:s.content)?void 0:n[0])?void 0:o[r],e=await this.handleResponsesFunctionCalls(a,i,t);if(e)return e;return this.handleFileGenerationResponse(a,t)||{[r]:t}}return{[r]:""}}return(null==(a=e.item)?void 0:a[w])===ee&&e[w]?this.handleStreamedResponsesFunctionCall(e,i):e[w]===`${Pn}.${$n}.partial_image`&&e.partial_image_b64?{[k]:[{[y]:`${t.IMAGE_BASE64_PREFIX}${e.partial_image_b64}`,[w]:_}]}:e.delta&&!this._functionStreamInProgress&&e[w]===`${Pn}.${In}.delta`?{[r]:e.delta}:{[r]:""}}async handleStreamedResponsesFunctionCall(t,e){var i;if(t[w]===`${Pn}.output_item.done`){if(this._functionStreamInProgress=!1,(null==(i=t.item)?void 0:i[w])===ee)return this.handleResponsesFunctionCalls([t.item],e)}else t[w]===`${Pn}.output_item.added`&&(this._functionStreamInProgress=!0);return{[r]:""}}handleFileGenerationResponse(e,i){const s=e.find(t=>t[w]===$n);return s?{[k]:t.generateImageFile(s.result),[r]:i}:null}static generateImageFile(e){return[{[y]:`${t.IMAGE_BASE64_PREFIX}${e}`,[w]:_}]}async handleResponsesFunctionCalls(t,e,i){const s=t.filter(t=>t[w]===ee);if(0===s.length)return null;if(!e||!this.functionHandler)throw Error(Q);const n=s.map(t=>({name:t.name,arguments:t.arguments})),{responses:o,processedResponse:r}=await this.callToolFunction(this.functionHandler,n);if(r)return r;const a=F(e);if(a.input&&(s.forEach(t=>a.input.push(t)),!o.find(({response:t})=>typeof t!==B)&&n.length===o.length))return o.forEach((t,e)=>{const i=s[e];a.input.push({[w]:On,call_id:i.call_id,output:t[Pn]})}),this.makeAnotherRequest(a,this.messages,i);throw Error(Y)}};Vo.IMAGE_BASE64_PREFIX="data:image/png;base64,";let Wo=Vo;class Go extends Wo{constructor(t){var e,i,s,n,o,r,a;const c=F(t.directConnection),h=c.azure,u=(null==(i=null==(e=c.azure)?void 0:e.openAI)?void 0:i.urlDetails)||{},d=null==(n=null==(s=c.azure)?void 0:s.openAI)?void 0:n.chat;if(super(t,Wn(u),Vn,h,d),this.permittedErrorPrefixes=[Hn],this.isTextInputDisabled=!1,typeof d===Kt){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)}Gn(u)?this.url=Go.buildURL(u):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout(()=>{t.addMessage({[l]:Hn})}))}static buildURL(t){const{endpoint:e,deploymentId:i,version:s}=t;return`${e}/openai/deployments/${i}/chat/completions?api-version=${s}`}}class Zo extends Bs{constructor(t){var e,i,s,n,o;const r=F(t.directConnection),a=r.bigModel;super(t,xn(),yn,a),this.insertKeyPlaceholderText=this.genereteAPIKeyName("BigModel"),this.keyHelpUrl="https://open.bigmodel.cn/usercenter/apikeys",this.url="https://open.bigmodel.cn/api/paas/v4/chat/completions",this.permittedErrorPrefixes=[Lt,Ht];const l=null==(e=r.bigModel)?void 0:e.chat;typeof l===Kt&&this.completeConfig(l,null==(n=null==(s=null==(i=t.directConnection)?void 0:i.bigModel)?void 0:s.chat)?void 0:n.function_handler),this.maxMessages??(this.maxMessages=-1),(o=this.rawBody).model??(o.model="glm-4.5")}static getFileContent(t){return t.map(t=>t[w]===_?{[w]:se,[se]:{url:t[y]||""}}:{[w]:x,file_url:{url:t[y]||""}})}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>({content:Zo.getTextWFilesContent(t,Zo.getFileContent),[P]:Bs.getRoleViaAI(t[P])}));return this.addSystemMessage(s),i.messages=s,i}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){if(t[l])throw t[l].message;if(t.choices.length>0){if(void 0!==t.choices[0].delta)return this.extractStreamResult(t.choices[0],e);if(void 0!==t.choices[0].message){const i=t.choices[0].message;return i.tool_calls?this.handleToolsGeneric({tool_calls:i.tool_calls},this.functionHandler,this.messages,e):{[r]:i.content}}}return{[r]:""}}async extractStreamResult(t,e){var i,s,n,o;const{delta:a,finish_reason:l}=t,c=null==(i=this.messages)?void 0:i.messageToElements[this.messages.messageToElements.length-2];if((null==c?void 0:c[0][P])===h&&0===(null==(s=null==c?void 0:c[0][r])?void 0:s.replace(/\n/g,"").trim().length)&&(null==(n=this.messages)||n.removeMessage(c[1][r]),null==(o=this.messages)||o.messageToElements.splice(this.messages.messageToElements.length-2,1)),"tool_calls"===l){if(a.tool_calls){const t={tool_calls:a.tool_calls};return this.handleToolsGeneric(t,this.functionHandler,this.messages,e)}return{[r]:(null==a?void 0:a.content)||""}}return{[r]:(null==a?void 0:a.content)||""}}}class Ko extends Bs{constructor(t){var e,i;const s=F(t.directConnection),n=s.together;super(t,An(),_n,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Together AI"),this.keyHelpUrl="https://api.together.xyz/settings/api-keys",this.url="https://api.together.xyz/v1/chat/completions",this.permittedErrorPrefixes=[Vt,Ht];const o=null==(e=s.together)?void 0:e.chat;typeof o===Kt&&this.completeConfig(o),this.maxMessages??(this.maxMessages=-1),(i=this.rawBody).model??(i.model="meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo")}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>({content:t[r]||"",[P]:t[P]===h?d:t[P]}));return this.addSystemMessage(s),i.messages=s,i}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t){if(t[l])throw t[l].message;if(t.choices.length>0){if(void 0!==t.choices[0].message)return{[r]:t.choices[0].message.content};if(void 0!==t.choices[0].delta)return{[r]:t.choices[0].delta.content}}return{[r]:""}}}const Jo=class t extends Bs{constructor(e){var i;const{directConnection:s}=e,n=null==s?void 0:s.openAI,o={images:{[k]:{acceptedFormats:".png",maxNumberOfFiles:2}}};super(e,Fn(),Bn,n,o),this.insertKeyPlaceholderText=this.genereteAPIKeyName("OpenAI"),this.keyHelpUrl=Sn,this.url="",this.permittedErrorPrefixes=[Ut,"Invalid input image"];const r=null==(i=null==s?void 0:s.openAI)?void 0:i[C];if(this[A]){const t="object"==typeof r&&r.size?Number.parseInt(r.size):1024;this[A][k]={dimensions:{width:t,height:t}}}typeof r===Kt&&Object.assign(this.rawBody,r),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(_,e),i&&s.append("mask",i),Object.keys(t).forEach(e=>{s.append(e,String(t[e]))}),s}preprocessBody(t,e){const i=F(t);return e&&""!==e&&(i.prompt=e),i}callApiWithImage(e,i,s){var n,o;let a;const l=null==(o=null==(n=i[i.length-1])?void 0:n[r])?void 0:o.trim();if(s[1]||l&&""!==l){this.url=t.IMAGE_EDIT_URL;const e=this.preprocessBody(this.rawBody,l);a=t.createFormDataBody(e,s[0],s[1])}else this.url=t.IMAGE_VARIATIONS_URL,a=t.createFormDataBody(this.rawBody,s[0]);bs.tempRemoveContentHeader(this.connectSettings,js.request.bind(this,this,a,e),!1)}async callServiceAPI(e,i,s){var n;if(null==(n=this.connectSettings)||!n.headers)throw new Error(W);if(null!=s&&s[0])this.callApiWithImage(e,i,s);else{if(!this.connectSettings)throw new Error(W);this.url=t.IMAGE_GENERATION_URL;const s=this.preprocessBody(this.rawBody,i[i.length-1][r]);js.request(this,s,e)}}async extractResultData(t){if(t[l])throw t[l].message;const e=t.data.map(t=>t.url?{[y]:t.url,[w]:_}:{[y]:`${rn}${t.b64_json}`,[w]:_});return{[k]:e}}};Jo.IMAGE_GENERATION_URL=`${Tn}images/generations`,Jo.IMAGE_VARIATIONS_URL=`${Tn}images/variations`,Jo.IMAGE_EDIT_URL=`${Tn}images/edits`;let Xo=Jo;const Qo=t=>({[Lt]:`${Xt}${t}`,[Wt]:Zt}),Yo=(t,e,i,s)=>{const n=t;n[l]?n[l][w]===Ht?s(H):s(V):i(e)};class tr extends Bs{constructor(t){var e,i,s,n;const o=F(t.directConnection).openRouter;super(t,Zs("https://openrouter.ai/api/v1/key",Qt,Yo),Qo,o),this.insertKeyPlaceholderText=this.genereteAPIKeyName("OpenRouter"),this.keyHelpUrl="https://openrouter.ai/keys",this.url="https://openrouter.ai/api/v1/chat/completions",this.permittedErrorPrefixes=[Vt,Ht],typeof o===Kt&&this.completeConfig(o,null==(i=null==(e=t.directConnection)?void 0:e.openRouter)?void 0:i.function_handler),this.maxMessages??(this.maxMessages=-1),(s=this.rawBody).model??(s.model="openai/gpt-4o"),(n=this.rawBody).max_tokens??(n.max_tokens=1e3)}static getAudioContent(t){return t.filter(t=>t[w]===T).map(t=>{var e,i,s;const n=null==(e=t[y])?void 0:e.split(",")[1],o=null==(s=null==(i=t[y])?void 0:i.match(/data:audio\/([^;]+)/))?void 0:s[1];return{[w]:ie,[ie]:{data:n||"",format:"wav"===o||"mp3"===o?o:"mp3"}}}).filter(t=>t[ie].data.length>0)}static getContent(t){if(t[k]&&t[k].length>0){const e=[...tr.getImageContent(t[k]),...tr.getAudioContent(t[k])];return t[r]&&t[r].trim().length>0&&e.unshift({[w]:r,[r]:t[r]}),e.length>0?e:t[r]||""}return t[r]||""}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>({content:tr.getContent(t),[P]:Bs.getRoleViaUser(t[P])})),n=[];return this.systemMessage&&n.push({[P]:ne,content:this.systemMessage}),n.push(...s),i.messages=n,i}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){var i,s,n,o;if(t[l])throw t[l].message;if("chat.completion.chunk"===t.object){const n=null==(i=t.choices)?void 0:i[0];if(null!=n&&n.delta)return this.extractStreamResult(n,e);if(null!=(s=t.message)&&s[C]){const e=t.message[C].map(t=>({[y]:t[se].url}));return{[r]:t.message.content||"",[k]:e}}return{[r]:""}}if("chat.completion"===t.object){const i=null==(n=t.choices)?void 0:n[0];if(null!=i&&i.message){if(i.message.tool_calls)return this.handleToolsGeneric({tool_calls:i.message.tool_calls},this.functionHandler,this.messages,e);const t=(null==(o=i.message[C])?void 0:o.map(t=>({[y]:t[se].url})))||[];return{[r]:i.message.content||"",files:t}}}return{[r]:""}}async extractStreamResult(t,e){const{delta:i}=t;if(null!=i&&i[C]){const t=i[C].map(t=>({[y]:t[se].url}));return{[r]:i.content||"",[k]:t}}return this.extractStreamResultWToolsGeneric(this,t,this.functionHandler,e)}}const er=t=>({[Lt]:`${Xt}${t}`,[Wt]:Zt}),ir=(t,e,i,s)=>{t[l]?s(H):i(e)};class sr extends Bs{constructor(t){var e;const i=F(t.directConnection).perplexity;super(t,Zs("https://api.perplexity.ai/chat/completions",Yt,ir),er,i),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Perplexity"),this.keyHelpUrl="https://www.perplexity.ai/settings/api",this.url="https://api.perplexity.ai/chat/completions",this.permittedErrorPrefixes=[Nt,Ft,"Permission denied"],typeof i===Kt&&this.completeConfig(i),this.maxMessages??(this.maxMessages=-1),(e=this.rawBody).model??(e.model="sonar")}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>({content:t[r]||"",[P]:Bs.getRoleViaUser(t[P])}));return this.addSystemMessage(s),i.messages=s,i}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t){if(t[l])throw t[l].message;if(t.choices&&t.choices.length>0){const e=t.choices[0];if(e.delta&&e.delta.content)return{[r]:e.delta.content};if(e.message&&e.message.content)return{[r]:e.message.content}}return{[r]:""}}}const nr=t=>({[Lt]:`Bearer ${t}`,[Wt]:Zt}),or=(t,e,i,s)=>{const n=t;n.detail?s(n.detail):i(e)};class rr extends Bs{constructor(t){var e,i,s,n;const o=F(t.directConnection).openWebUI;super(t,Zs("http://localhost:3000/api/v1/models",Qt,or),nr,o),this.insertKeyPlaceholderText="Open WebUI API Key",this.keyHelpUrl="https://docs.openwebui.com/getting-started/api-endpoints/",this.url="http://localhost:3000/api/chat/completions",this.permittedErrorPrefixes=["Error"],typeof o===Kt&&(this.completeConfig(o,null==(i=null==(e=t.directConnection)?void 0:e.openWebUI)?void 0:i.function_handler),o[k]&&o[k].length>0&&(this.rawBody[k]=o[k])),this.maxMessages??(this.maxMessages=-1),(s=this.rawBody).model??(s.model="llama3.2"),(n=this.rawBody).stream??(n.stream=!1)}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>({content:Bs.getTextWImagesContent(t),[P]:Bs.getRoleViaUser(t[P])}));return this.addSystemMessage(s),i.messages=s,i}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{readable:!0})}async extractResultData(t,e){var i;if(t[l])throw t[l].message;if(t[r]){const i=t[r].trim();return this.processStreamingResponse(i,e)}if(t.choices&&null!=(i=t.choices[0])&&i.message){const i=t.choices[0].message;return i.tool_calls?this.handleTools({tool_calls:i.tool_calls},e):{[r]:i.content||""}}return{[r]:""}}async processStreamingResponse(t,e){var i;const s=t.split("\n").filter(t=>""!==t.trim());let n="";for(const t of s){let s=t.trim();if(s.startsWith("data: ")&&(s=s.substring(6)),"[DONE]"!==s)try{const t=JSON.parse(s);if(t.choices&&null!=(i=t.choices[0])&&i.delta){const i=t.choices[0].delta;if(i.tool_calls)return this.handleTools({tool_calls:i.tool_calls},e);i.content&&(n+=i.content)}}catch{continue}}return{[r]:n}}async handleTools(t,e){if(!t.tool_calls||!e||!this.functionHandler)throw Error(Q);const i=F(e),s=t.tool_calls.map(t=>({name:t.function.name,arguments:t.function.arguments})),{responses:n,processedResponse:o}=await this.callToolFunction(this.functionHandler,s);if(o)return o;if(i.messages.push({tool_calls:t.tool_calls,[P]:d,content:""}),!n.find(({response:t})=>typeof t!==B)&&s.length===n.length)return n.forEach((e,s)=>{var n;const o=null==(n=t.tool_calls)?void 0:n[s];null==i||i.messages.push({[P]:"tool",tool_name:null==o?void 0:o.function.name,content:e.response})}),this.makeAnotherRequest(i,this.messages);throw Error(Y)}}const ar=t=>({[Lt]:`${Xt}${t}`,[Wt]:Zt}),lr=(t,e,i,s)=>{const n=t;n[l]?n[l][w]===Ht?s(H):s(V):i(e)};class cr extends Bs{constructor(t){var e,i,s;const n=F(t.directConnection).deepSeek;super(t,Zs("https://api.deepseek.com/models",Qt,lr),ar,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("DeepSeek"),this.keyHelpUrl="https://platform.deepseek.com/api_keys",this.url="https://api.deepseek.com/v1/chat/completions",this.permittedErrorPrefixes=[Vt,Ht],typeof n===Kt&&this.completeConfig(n),this.maxMessages??(this.maxMessages=-1),(e=this.rawBody).model??(e.model="deepseek-chat"),(i=this.rawBody).temperature??(i.temperature=1),(s=this.rawBody).max_tokens??(s.max_tokens=4096)}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>({content:t[r]||"",[P]:Bs.getRoleViaUser(t[P])}));return this.addSystemMessage(s),i.messages=s,i}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t){if(t[l])throw t[l].message;if(t.choices&&t.choices.length>0){const e=t.choices[0];if(e.delta&&e.delta.content)return{[r]:e.delta.content};if(e.message&&e.message.content)return{[r]:e.message.content}}return{[r]:""}}}const hr=t=>({[Lt]:`${Xt}${t}`,[Wt]:Zt}),ur=(t,e,i,s)=>{var n;1004===(null==(n=t.base_resp)?void 0:n.status_code)?s(H):i(e)};class dr extends Bs{constructor(t){var e;const i=F(t.directConnection).miniMax;super(t,Zs("https://api.minimax.io/v1/files/delete",Yt,ur),hr,i),this.insertKeyPlaceholderText=this.genereteAPIKeyName("MiniMax"),this.keyHelpUrl="https://www.minimaxi.com",this.url="https://api.minimax.io/v1/text/chatcompletion_v2",this.permittedErrorPrefixes=[Vt,Ht,"insufficient balance"],typeof i===Kt&&this.completeConfig(i),this.maxMessages??(this.maxMessages=-1),(e=this.rawBody).model??(e.model="MiniMax-M1")}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>({content:t[r]||"",[P]:Bs.getRoleViaUser(t[P])}));return this.addSystemMessage(s),i.messages=s,i}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t){var e;if(t[l])throw t[l].message;if(t.choices&&t.choices.length>0){const e=t.choices[0];if(e.delta&&e.delta.content)return{[r]:e.delta.content};if(e.message&&e.message.content)return{[r]:e.message.content}}if("number"==typeof(null==(e=t.base_resp)?void 0:e.status_code)&&t.base_resp.status_code>0)throw t.base_resp.status_msg;return{[r]:""}}}const pr=t=>({[Lt]:`${Xt}${t}`,[Wt]:Zt,accept:Zt}),mr=(t,e,i,s)=>{t.detail?s(H):i(e)};class vr extends Bs{constructor(t){var e,i,s;const n=F(t.directConnection).mistral;super(t,Zs("https://api.mistral.ai/v1/models",Qt,mr),pr,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Mistral"),this.keyHelpUrl="https://console.mistral.ai/api-keys/",this.url="https://api.mistral.ai/v1/chat/completions",this.permittedErrorPrefixes=[Nt],typeof n===Kt&&this.completeConfig(n,null==(i=null==(e=t.directConnection)?void 0:e.mistral)?void 0:i.function_handler),this.maxMessages??(this.maxMessages=-1),(s=this.rawBody).model??(s.model="mistral-small-latest")}static getFileContent(t){return t.map(t=>t[w]===_?{[w]:se,[se]:t[y]||""}:{[w]:r,[r]:`[Unsupported ${x} ${w}: ${t[w]}]`})}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>({[P]:Bs.getRoleViaAI(t[P]),content:Bs.getTextWFilesContent(t,vr.getFileContent)}));return this.addSystemMessage(s),i.messages=s,i}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){if(t.message)throw t.message;if(t[l])throw t[l].message;if(t.choices&&t.choices.length>0){const i=t.choices[0];if(i.delta)return this.extractStreamResult(i,e);if(i.message)return i.message.tool_calls?this.handleToolsGeneric({tool_calls:i.message.tool_calls},this.functionHandler,this.messages,e):{[r]:i.message.content||""}}return{[r]:""}}async extractStreamResult(t,e){const{delta:i,finish_reason:s}=t;if("tool_calls"===s&&null!=i&&i.tool_calls){const t={tool_calls:i.tool_calls};return this.handleToolsGeneric(t,this.functionHandler,this.messages,e)}return{[r]:(null==i?void 0:i.content)||""}}}class fr extends Bs{constructor(t){var e,i,s,n,o;const r=F(t.directConnection),a=r.groq;super(t,No(),zo,a),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Groq"),this.keyHelpUrl="https://console.groq.com/keys",this.url="https://api.groq.com/openai/v1/chat/completions",this.permittedErrorPrefixes=[Nt,"property"];const l=null==(e=r.groq)?void 0:e.chat;typeof l===Kt&&this.completeConfig(l,null==(n=null==(s=null==(i=t.directConnection)?void 0:i.groq)?void 0:s.chat)?void 0:n.function_handler),this.maxMessages??(this.maxMessages=-1),(o=this.rawBody).model??(o.model="llama-3.3-70b-versatile")}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>({content:fr.getTextWImagesContent(t),[P]:t[P]===h?d:t[P]}));return this.addSystemMessage(s),i.messages=s,i}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){var i,s,n,o;if(t[l])throw t[l].message;return null!=(s=null==(i=t.choices)?void 0:i[0])&&s.delta?this.extractStreamResult(t.choices[0],e):null!=(o=null==(n=t.choices)?void 0:n[0])&&o.message?t.choices[0].message.tool_calls?this.handleToolsGeneric(t.choices[0].message,this.functionHandler,this.messages,e,{message:this.systemMessage}):{[r]:t.choices[0].message.content||""}:{[r]:""}}async extractStreamResult(t,e){return this.extractStreamResultWToolsGeneric(this,t,this.functionHandler,e)}}const gr=t=>({[Lt]:`${Xt}${t}`,[Wt]:Zt,accept:Zt}),br=(t,e,i,s)=>{typeof t.message===B?s(H):i(e)};class yr extends Bs{constructor(t){var e;const i=F(t.directConnection).cohere;if(super(t,Zs("https://api.cohere.ai/v1/models",Qt,br),gr,i),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Cohere"),this.keyHelpUrl="https://dashboard.cohere.ai/api-keys",this.permittedErrorPrefixes=["invalid"],this.url="https://api.cohere.com/v2/chat",typeof i===Kt){const t=ue.processCohere(i);this.canSendMessage=()=>t,this.cleanConfig(i),Object.assign(this.rawBody,i)}this.maxMessages??(this.maxMessages=-1),(e=this.rawBody).model??(e.model="command-a-03-2025")}cleanConfig(t){delete t.key}preprocessBody(t,e){const i=F(t),s=e.filter(t=>t[r]);return i.messages=s.map(t=>({[P]:Bs.getRoleViaAI(t[P]),content:t[r]})),i}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{readable:!0})}async extractResultData(t){var e,i,s;if("string"==typeof t.message)throw t.message;if(this.stream&&t[r]){const e=yr.parseBundledEvents(t[r]);return{text:yr.aggregateBundledEventsText(e)}}if("message"in t&&null!=(s=null==(i=null==(e=t.message)?void 0:e.content)?void 0:i[0])&&s[r])return{[r]:t.message.content[0][r]};throw new Error("Invalid response format from Cohere API")}static parseBundledEvents(t){const e=t.trim().split("\n"),i=[];for(const t of e)if(t.trim())try{const e=JSON.parse(t);i.push(e)}catch(e){console[l]("Failed to parse line:",t,e)}return i}static aggregateBundledEventsText(t){return t.filter(t=>{var e,i,s;return"content-delta"===t[w]&&(null==(s=null==(i=null==(e=t.delta)?void 0:e.message)?void 0:i.content)?void 0:s[r])}).map(t=>{var e,i,s;return null==(s=null==(i=null==(e=t.delta)?void 0:e.message)?void 0:i.content)?void 0:s[r]}).join("")}}const wr=()=>({[Wt]:Zt}),xr=(t,e,i,s)=>{var n;const o=t;o[l]?403===o[l].code||null!=(n=o[l].message)&&n.includes("API key")?s(H):s(V):i(e)};class kr extends Bs{constructor(t){var e,i;const s=F(t.directConnection).gemini;if(super(t,(()=>{const t="https://generativelanguage.googleapis.com/v1beta/models?key=";return Zs(t,Qt,xr,e=>`${t}${e}`)})(),wr,s),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Gemini"),this.keyHelpUrl="https://aistudio.google.com/app/apikey",this.urlPrefix="https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent",this.url="",this.permittedErrorPrefixes=["API_KEY_INVALID"],typeof s===Kt){const n=s;n.model&&(this.urlPrefix=`https://generativelanguage.googleapis.com/v1beta/models/${n.model}:generateContent`),this.cleanConfig(n),this.completeConfig(n,null==(i=null==(e=t.directConnection)?void 0:e.gemini)?void 0:i.function_handler)}this.maxMessages??(this.maxMessages=-1)}cleanConfig(t){delete t.model}static getContent(t){const e=[];return t[r]&&t[r].trim().length>0&&e.push({[r]:t[r]}),t[k]&&t[k].length>0&&t[k].forEach(t=>{if(t[y]&&t[y].includes("data:")){const[i,s]=t[y].split(",");e.push({inlineData:{mimeType:i.replace("data:","").replace(";base64",""),data:s}})}}),{parts:e,[P]:t[P]===u?u:"model"}}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>kr.getContent(t));return i.contents=s,this.systemMessage&&(i.systemInstruction={parts:[{[r]:this.systemMessage}]}),i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error(W);this.messages??(this.messages=t);const i=this.preprocessBody(this.rawBody,e),s=this.stream;s&&(typeof s!==Kt||!s.simulation)||i.stream?(this.url=`${this.urlPrefix.replace(":generateContent",":streamGenerateContent")}?alt=sse&key=${this.key}`,Cs.request(this,i,t)):(this.url=`${this.urlPrefix}?key=${this.key}`,js.request(this,i,t))}async extractResultData(t,e){var i,s,n,o;if(t[l])throw t[l].message||"Gemini API Error";if(null!=(n=null==(s=null==(i=t.candidates)?void 0:i[0])?void 0:s.content)&&n.parts){const i=t.candidates[0].content.parts,s=i.find(t=>t.functionCall);if(null!=s&&s.functionCall)return this.handleTools([s.functionCall],e);const n=i.find(t=>t[r]),a=i.find(t=>{var e;return"image/png"===(null==(e=t.inlineData)?void 0:e.mimeType)});return{[r]:(null==n?void 0:n[r])||"",[k]:null!=(o=null==a?void 0:a.inlineData)&&o.data?[{[y]:`data:image/png;base64,${a.inlineData.data}`}]:[]}}return{[r]:""}}async handleTools(t,e){if(!t||!e||!this.functionHandler)throw Error(Q);const i=F(e),s=t.map(t=>({name:t.name,arguments:R(t.args)})),{responses:n,processedResponse:o}=await this.callToolFunction(this.functionHandler,s);if(o)return o;const r={parts:t.map(t=>({functionCall:{name:t.name,args:t.args}})),[P]:"model"};if(i.contents.push(r),!n.find(({response:t})=>typeof t!==B)&&s.length===n.length){const e={parts:n.map((e,i)=>({functionResponse:{name:t[i].name,response:{result:e.response}}})),[P]:u};return i.contents.push(e),this.makeAnotherRequest(i,this.messages)}throw Error(Y)}}const _r=t=>({"x-api-key":t,[Wt]:Zt,"anthropic-version":"2023-06-01","anthropic-dangerous-direct-browser-access":"true"}),Cr=(t,e,i,s)=>{const n=t;n[l]?n[l][w]===Ht?s(H):s(V):i(e)};class Ar extends Bs{constructor(t){var e,i,s,n;const o=F(t.directConnection).claude;super(t,Zs("https://api.anthropic.com/v1/models",Qt,Cr),_r,o),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Claude"),this.keyHelpUrl="https://console.anthropic.com/settings/keys",this.url="https://api.anthropic.com/v1/messages",this.permittedErrorPrefixes=[Ht,Vt],this._streamToolCalls={[w]:"tool_use",id:"",name:"",input:""},typeof o===Kt&&this.completeConfig(o,null==(i=null==(e=t.directConnection)?void 0:e.claude)?void 0:i.function_handler),this.maxMessages??(this.maxMessages=-1),(s=this.rawBody).model??(s.model="claude-sonnet-4-5-20250929"),(n=this.rawBody).max_tokens??(n.max_tokens=4096)}static getFileContent(t){return t.map(t=>{var e,i,s;if(t[w]===_){const n=null==(e=t[y])?void 0:e.split(",")[1],o=(null==(s=null==(i=t[y])?void 0:i.match(/data:([^;]+)/))?void 0:s[1])||"image/jpeg";return{[w]:_,source:{[w]:"base64",media_type:o,data:n||""}}}return{[w]:r,[r]:`[Unsupported ${x} ${w}: ${t[w]}]`}})}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>({content:Ar.getTextWFilesContent(t,Ar.getFileContent),[P]:Bs.getRoleViaUser(t[P])}));return i.messages=s,this.systemMessage&&(i.system=this.systemMessage),i}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){var i,s,n;if(t[l])throw t[l].message;if(t.content&&t.content.length>0){const i=t.content.find(t=>"tool_use"===t[w]);if(i)return this.handleTools([i],e);const s=t.content.find(t=>t[w]===r);if(s)return{[r]:s[r]}}if("content_block_delta"===t[w]&&t.delta&&"text_delta"===t.delta[w])return{[r]:t.delta[r]||""};if("content_block_start"===t[w]&&"tool_use"===(null==(i=t.content_block)?void 0:i[w]))this._streamToolCalls=t.content_block,this._streamToolCalls.input="";else if("content_block_delta"===t[w]&&"input_json_delta"===(null==(s=t.delta)?void 0:s[w]))this._streamToolCalls.input+=t.delta.partial_json||"";else if("message_delta"===t[w]&&"tool_use"===(null==(n=t.delta)?void 0:n.stop_reason))return this._streamToolCalls.input=this._streamToolCalls.input?JSON.parse(this._streamToolCalls.input):{},this.handleTools([this._streamToolCalls],e);return{[r]:""}}async handleTools(t,e){if(!t||!e||!this.functionHandler)throw Error(Q);const i=F(e),s=t.map(t=>({name:t.name,arguments:R(t.input)})),{responses:n,processedResponse:o}=await this.callToolFunction(this.functionHandler,s);if(o)return o;const r=t.map(t=>({[w]:"tool_use",id:t.id,name:t.name,input:t.input}));if(i.messages.push({[P]:"assistant",content:r}),!n.find(({response:t})=>typeof t!==B)&&s.length===n.length){const e=n.map((e,i)=>({[w]:"tool_result",tool_use_id:t[i].id,content:e.response}));return i.messages.push({[P]:u,content:e}),this.makeAnotherRequest(i,this.messages)}throw Error(Y)}}const Mr=()=>({}),Tr=()=>{},Sr=class t extends Bs{constructor(t){var e,i,s,n;const o=F(t.directConnection);super(t,Zs("",Qt,Tr),Mr,{key:"placeholder"}),this.insertKeyPlaceholderText="",this.keyHelpUrl="",this.validateKeyProperty=!1,this.url="http://localhost:11434/api/chat",this.permittedErrorPrefixes=["Error"];const r=o.ollama;typeof r===Kt&&this.completeConfig(r,null==(i=null==(e=t.directConnection)?void 0:e.ollama)?void 0:i.function_handler),this.maxMessages??(this.maxMessages=-1),(s=this.rawBody).model??(s.model="llama3.2"),(n=this.rawBody).stream??(n.stream=!1)}static getImageData(t){return t.filter(t=>t[w]===_).map(t=>{var e;return(null==(e=t[y])?void 0:e.split(",")[1])||""}).filter(t=>t.length>0)}preprocessBody(e,i){const s=F(e),n=this.processMessages(i).map(e=>{const i={content:e[r]||"",[P]:Bs.getRoleViaUser(e[P])};if(e[k]&&e[k].length>0){const s=t.getImageData(e[k]);s.length>0&&(i[C]=s)}return i});return this.addSystemMessage(n),s.messages=n,s}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{readable:!0})}parseMessage(t){return t.split("\n").filter(t=>t.trim()).map(t=>JSON.parse(t))}async extractResultData(e,i){var s,n;if(e[l])throw e[l].message;if(e[r]){const o=this.parseMessage(e[r]),a=[];for(const t of o)null!=(s=t.message)&&s.tool_calls&&a.push(await this.handleTools({tool_calls:t.message.tool_calls},i)),a.push({[r]:(null==(n=t.message)?void 0:n.content)||""});const l=a.map(t=>t[r]),c=l.lastIndexOf(t.THINK_END);return-1===c||null!=i&&i.think?{[r]:l.join("")}:{[r]:l.slice(c+1).join(""),overwrite:!0}}return e.message?e.message.tool_calls?this.handleTools({tool_calls:e.message.tool_calls},i):{[r]:e.message.content||""}:{[r]:""}}async handleTools(t,e){if(!t.tool_calls||!e||!this.functionHandler)throw Error(Q);const i=F(e),s=t.tool_calls.map(t=>({name:t.function.name,arguments:R(t.function.arguments)})),{responses:n,processedResponse:o}=await this.callToolFunction(this.functionHandler,s);if(o)return o;if(i.messages.push({tool_calls:t.tool_calls,[P]:d,content:""}),!n.find(({response:t})=>typeof t!==B)&&s.length===n.length)return n.forEach((e,s)=>{var n;const o=null==(n=t.tool_calls)?void 0:n[s];null==i||i.messages.push({[P]:"tool",tool_name:null==o?void 0:o.function.name,content:e.response})}),this.makeAnotherRequest(i,this.messages);throw Error(Y)}};Sr.THINK_END="</think>";let jr=Sr;const Er=t=>({Authorization:`${Xt}${t}`,[Wt]:Zt}),Ir=(t,e,i,s)=>{const n=t;n[l]?n[l][w]===Ht||n[l][w]===Vt?s(H):s(V):i(e)},$r=()=>Zs("https://api.x.ai/v1/models",Qt,Ir),Or=class t extends Bs{constructor(e){var i,s;const{directConnection:n}=e,o=null==n?void 0:n.x;super(e,$r(),Er,o),this.insertKeyPlaceholderText=this.genereteAPIKeyName("X"),this.keyHelpUrl="https://console.x.ai/team/default/api-keys",this.url=t.IMAGE_GENERATION_URL,this.permittedErrorPrefixes=[Vt,Ht];const r=null==(i=null==n?void 0:n.x)?void 0:i[C];typeof r===Kt&&Object.assign(this.rawBody,r),(s=this.rawBody).model??(s.model="grok-2-image")}preprocessBody(t,e){const i=e[e.length-1][r],s=F(t);return i&&""!==i&&(s.prompt=i),s}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this))}async extractResultData(t){if(t[l])throw t[l].message;const e=t.data.map(t=>t.url?{[y]:t.url,[w]:_}:{[y]:`${rn}${t.b64_json}`,[w]:_});return{[k]:e}}};Or.IMAGE_GENERATION_URL="https://api.x.ai/v1/images/generations";let Pr=Or;const Br=t=>({[Lt]:`${Xt}${t}`,[Wt]:Zt}),Rr=(t,e,i,s)=>{const n=t;n[l]?n[l][w]===Vt?s(H):s(V):i(e)};class Fr extends Bs{constructor(t){var e,i,s;const n=F(t.directConnection).qwen;super(t,Zs("https://dashscope-intl.aliyuncs.com/compatible-mode/v1/models",Qt,Rr),Br,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Qwen"),this.keyHelpUrl="https://www.alibabacloud.com/help/en/model-studio/get-api-key",this.url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions",this.permittedErrorPrefixes=["No static","The model",Ut],typeof n===Kt&&this.completeConfig(n,null==(i=null==(e=t.directConnection)?void 0:e.qwen)?void 0:i.function_handler),this.maxMessages??(this.maxMessages=-1),(s=this.rawBody).model??(s.model="qwen-plus")}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>({content:Fr.getTextWImagesContent(t),[P]:Bs.getRoleViaUser(t[P])}));return this.addSystemMessage(s),i.messages=s,i}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){if(t[l])throw t[l].message;if(t.choices&&t.choices.length>0){const i=t.choices[0];if(i.delta)return this.extractStreamResult(i,e);if(i.message)return i.message.tool_calls?this.handleToolsGeneric({tool_calls:i.message.tool_calls},this.functionHandler,this.messages,e):{[r]:i.message.content||""}}return{[r]:""}}async extractStreamResult(t,e){return this.extractStreamResultWToolsGeneric(this,t,this.functionHandler,e)}}const Lr=t=>({[Lt]:`${Xt}${t}`,[Wt]:Zt}),qr=(t,e,i,s)=>{const n=t;n[l]?n[l][w]===Ht?s(H):s(V):i(e)};class zr extends Bs{constructor(t){var e,i,s;const n=F(t.directConnection).kimi;super(t,Zs("https://api.moonshot.ai/v1/models",Qt,qr),Lr,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Kimi"),this.keyHelpUrl="https://platform.moonshot.ai/console/api-keys",this.url="https://api.moonshot.ai/v1/chat/completions",this.permittedErrorPrefixes=[Nt,"Not found"],typeof n===Kt&&this.completeConfig(n,null==(i=null==(e=t.directConnection)?void 0:e.kimi)?void 0:i.function_handler),this.maxMessages??(this.maxMessages=-1),(s=this.rawBody).model??(s.model="moonshot-v1-8k")}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>({content:zr.getTextWImagesContent(t),[P]:Bs.getRoleViaUser(t[P])}));return this.addSystemMessage(s),i.messages=s,i}async callServiceAPI(t,e){this.messages??(this.messages=t),this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t,e){if(t[l])throw t[l].message;if(t.choices&&t.choices.length>0){const i=t.choices[0];if(i.delta)return this.extractStreamResult(i,e);if(i.message)return i.message.tool_calls?this.handleToolsGeneric({tool_calls:i.message.tool_calls},this.functionHandler,this.messages,e):{[r]:i.message.content||""}}return{[r]:""}}async extractStreamResult(t,e){return this.extractStreamResultWToolsGeneric(this,t,this.functionHandler,e)}}class Dr extends Bs{constructor(t){var e,i;const s=F(t.directConnection),n=s.x;super(t,$r(),Er,n),this.insertKeyPlaceholderText=this.genereteAPIKeyName("X"),this.keyHelpUrl="https://console.x.ai/team/default/api-keys",this.url="https://api.x.ai/v1/chat/completions",this.permittedErrorPrefixes=[Vt,Ht];const o=null==(e=s.x)?void 0:e.chat;typeof o===Kt&&this.completeConfig(o),this.maxMessages??(this.maxMessages=-1),(i=this.rawBody).model??(i.model="grok-3-latest")}preprocessBody(t,e){const i=F(t),s=this.processMessages(e).map(t=>({content:t[r]||"",[P]:Bs.getRoleViaUser(t[P])}));return this.addSystemMessage(s),i.messages=s,i}async callServiceAPI(t,e){this.callDirectServiceServiceAPI(t,e,this.preprocessBody.bind(this),{})}async extractResultData(t){var e,i,s,n;if(t[l])throw t[l].message;if("chat.completion.chunk"===t.object){const s=null==(e=t.choices)?void 0:e[0];return null!=(i=null==s?void 0:s.delta)&&i.content?{[r]:s.delta.content}:{[r]:""}}return"chat.completion"===t.object&&null!=(n=null==(s=t.choices)?void 0:s[0])&&n.message?{[r]:t.choices[0].message.content||""}:{[r]:""}}}var Nr=(t=>(t.BLOCKING="blocking",t.STREAMING="streaming",t))(Nr||{}),Ur=(t=>(t.MESSAGE="message",t.AGENT_MESSAGE="agent_message",t.WORKFLOW_FINISHED="workflow_finished",t.ERROR="error",t))(Ur||{});const Hr=t=>{const e=t.trim();if(!e.startsWith("data:"))return null;const i=e.replace(/^data:\s*/,"").trim();return i?JSON.parse(i):null};async function Vr(t,e){if(0===t.length)return[];const i=t.map(async t=>{const i=await async function(t,e){const i=new FormData;i.append(x,t),i.append(u,e[u]);const{[Wt]:s,...n}=e.headers,o=await fetch(e.url,{method:Yt,headers:n,body:i});if(!o.ok){const t=await o.text();throw new Error(t)}const r=await o.json();if(!r.id)throw new Error("Upload response missing file ID");return r.id}(t,e);return((t,e)=>({type:e,transfer_method:"local_file",upload_file_id:t}))(i,t[w].startsWith("image/")?_:x)});return(await Promise.all(i)).filter(t=>null!==t)}const Wr=(t,e,i)=>{var s,n;switch(!e.conversationIdSet&&t.conversation_id&&(i(t.conversation_id),e.conversationIdSet=!0),t.event){case Ur.MESSAGE:case Ur.AGENT_MESSAGE:e.fullAnswer+=t.answer||"";break;case Ur.WORKFLOW_FINISHED:!e.fullAnswer&&null!=(n=null==(s=t.data)?void 0:s.outputs)&&n.answer&&(e.fullAnswer=t.data.outputs.answer);break;case Ur.ERROR:e.errorMessage=t.message||Ur.ERROR}};const Gr=t=>({[Wt]:Zt,[Lt]:`${Xt}${t}`}),Zr=(t,e,i,s)=>{const n=t;n[l]?n[l].message===zt?s(H):s(V):"user_input_form"in t||"opening_statement"in t||"file_upload"in t?i(e):s(V)};class Kr extends Bs{constructor(t){var e;const i=F(t.directConnection),s=null==i?void 0:i.dify,n=(null==(e=t.connect)?void 0:e.url)??"https://api.dify.ai/v1";super(t,Zs(`${n}/parameters`,Qt,Zr),Gr,s),this.insertKeyPlaceholderText=this.genereteAPIKeyName("Dify"),this.keyHelpUrl="https://docs.dify.ai/en/use-dify/publish/developing-with-apis",this.permittedErrorPrefixes=[Ht],this._conversationId="",this._user=u,this._inputs={},this.url=`${n}/chat-messages`,this._uploadUrl=`${n}/${k}/upload`,typeof s===Kt&&(s[u]&&(this._user=s[u]),s.inputs&&(this._inputs=s.inputs),this.completeConfig(s)),this.maxMessages??(this.maxMessages=-1),this._mode=this.stream?Nr.STREAMING:Nr.BLOCKING}preprocessBody(t,e,i){const s=this.processMessages(e),n=s[s.length-1],o=(null==n?void 0:n[r])||" ",a={inputs:this._inputs,query:o,response_mode:this._mode,[u]:this._user};return this._conversationId&&(a.conversation_id=this._conversationId),i&&i.length>0&&(a[k]=i),a}async callServiceAPI(t,e,i){this.messages??(this.messages=t);let s=[];i&&i.length>0&&(s=await Vr(i,{url:this._uploadUrl,[u]:this._user,headers:this.connectSettings.headers})),this.callDirectServiceServiceAPI(t,e,(t,e)=>this.preprocessBody(t,e,s))}async extractResultData(t){const e=t=>{this._conversationId=t};return this._mode!==Nr.BLOCKING||this.stream?async function(t,e){const i={fullAnswer:"",conversationIdSet:!1,errorMessage:""},s=(await t.text()).split(/\r?\n\r?\n/);for(const t of s){const s=Hr(t);s&&Wr(s,i,e)}return i.errorMessage?{[l]:i.errorMessage}:{[r]:i.fullAnswer}}(t,e):function(t,e){return t.conversation_id&&e(t.conversation_id),t.code&&t.message&&!t.answer?{[l]:t.message}:{[r]:t.answer||""}}(t,e)}}class Jr{static create(t){const{directConnection:e,connect:i,demo:s,webModel:n}=t;if(n)return new Gs(t);if(e){if(e.openAI)return e.openAI[C]?new Xo(t):e.openAI.speechToText?new mo(t):e.openAI.textToSpeech?new uo(t):e.openAI.assistant?new Un(t):e.openAI.realtime?new co(t):e.openAI.completions?new Io(t):new Wo(t);if(e.assemblyAI)return new jo(t);if(e.cohere)return new yr(t);if(e.huggingFace)return e.huggingFace.textGeneration?new un(t):e.huggingFace.summarization?new pn(t):e.huggingFace.translation?new fn(t):e.huggingFace.fillMask?new bn(t):e.huggingFace.questionAnswer?new dn(t):e.huggingFace.audioSpeechRecognition?new hn(t):e.huggingFace.audioClassification?new tn(t):e.huggingFace.imageClassification?new en(t):new mn(t);if(e.azure){if(e.azure.openAI){if(e.azure.openAI.chat)return new Go(t);if(e.azure.openAI.assistant)return new Kn(t)}if(e.azure.speechToText)return new Fo(t);if(e.azure.textToSpeech)return new Bo(t);if(e.azure.summarization)return new Mo(t);if(e.azure.translation)return new Lo(t)}if(e.stabilityAI)return e.stabilityAI.imageToImage?new vn(t):e.stabilityAI.imageToImageUpscale?new ln(t):e.stabilityAI.imageToImageMasking?new cn(t):new gn(t);if(e.mistral)return new vr(t);if(e.gemini)return new kr(t);if(e.claude)return new Ar(t);if(e.deepSeek)return new cr(t);if(e.miniMax)return new dr(t);if(e.openRouter)return new tr(t);if(e.kimi)return new zr(t);if(e.x)return e.x[C]?new Pr(t):new Dr(t);if(e.qwen)return new Fr(t);if(e.together)return e.together[C]?new Ho(t):e.together.textToSpeech?new Mn(t):new Ko(t);if(e.bigModel)return e.bigModel[C]?new qo(t):e.bigModel.textToSpeech?new kn(t):new Zo(t);if(e.groq)return e.groq.textToSpeech?new Uo(t):new fr(t);if(e.perplexity)return new sr(t);if(e.ollama)return new jr(t);if(e.openWebUI)return new rr(t);if(e.dify)return new Kr(t)}return i&&Object.keys(i).length>0&&!s?new Ps(t):new Ps(t,void 0,s||!0)}}const Xr=class{};Xr.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 Qr=Xr;function Yr(t){return function(e,i){Object.defineProperty(e,i,{});const s=e.constructor,n=i.toLocaleLowerCase();s._attributes_[n]=Qr.attibutes[t],s._attributeToProperty_[n]=i}}const ta="submit-button",ea="loading-button",ia="disabled-button",sa="text-input-container-start-adjustment",na="text-input-container-end-adjustment",oa="text-input-container-start-small-adjustment",ra="text-input-container-end-small-adjustment";class aa{constructor(t){this._isDisplayed=!1,this._elementRef=this.createIntroPanelWithChild(t),this._isDisplayed=!0}static createIntroPanel(){const s=i();return s[t].add("intro-panel"),Object.assign(s[e]),s}createIntroPanelWithChild(t){const i=aa.createIntroPanel();return"none"===t[e].display&&(t[e].display="block"),i.appendChild(t),i}hide(){this._isDisplayed&&(this._elementRef[e].display="none",this._isDisplayed=!1)}display(){this._isDisplayed||(this._elementRef[e].display="",this._isDisplayed=!0)}}const la=class e{static createImage(t,e){const i=new Image;return i[y]=t[y],e&&es.scrollDownOnImageLoad(i[y],e),es.processContent(_,i,i[y],t.name)}static createImageMessage(i,s,n,o,r){const a=i.createNewMessageElement("",n,o),l=!o&&r?i.scrollToFirstElement.bind(i,n,r):void 0,c=e.createImage(s,l);return a.bubbleElement.appendChild(c),a.bubbleElement[t].add(e.IMAGE_BUBBLE_CLASS),{[w]:_,elements:a}}static createAudioElement(e,s){const n=i(T);return n[y]=e[y],n[t].add("audio-player"),n.controls=!0,jt.IS_SAFARI&&(n[t].add("audio-player-safari"),n[t].add(s===u?"audio-player-safari-end":"audio-player-safari-start")),n}static autoPlayAudio(t){t.addEventListener("loadeddata",()=>{t.play().catch(t=>{console.warn("Auto-play failed:",t)})})}static createNewAudioMessage(i,s,n,o){const r=e.createAudioElement(s,n),a=i.createMessageElementsOnOrientation("",n,o);return a.bubbleElement.appendChild(r),a.bubbleElement[t].add(e.AUDIO_BUBBLE_CLASS),{[w]:T,elements:a,audioElement:r}}static createAnyFile(e){const s=i();s[t].add("any-file-message-contents");const n=i();n[t].add("any-file-message-icon-container");const o=qs.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>');o[t].add("any-file-message-icon"),n.appendChild(o);const r=i();return r[t].add("any-file-message-text"),r.textContent=e.name||x,s.appendChild(n),s.appendChild(r),es.processContent(E,s,e[y],r.textContent)}static createNewAnyFileMessage(i,s,n,o){const r=i.createMessageElementsOnOrientation("",n,o),a=e.createAnyFile(s);return r.bubbleElement[t].add(e.ANY_FILE_BUBBLE_CLASS),r.bubbleElement.appendChild(a),{[w]:x,elements:r}}static createMessages(t,i,s,n,o=!1){return i.map((i,r)=>{var a;if(i.ref&&(i=es.removeFileRef(i)),es.isAudioFile(i)){const n=e.createNewAudioMessage(t,i,s,o),r=null==(a=t.textToSpeech)?void 0:a.audio;return r&&(r.autoPlay&&e.autoPlayAudio(n.audioElement),"boolean"==typeof r.displayAudio&&!r.displayAudio)?void 0:n}return es.isImageFile(i)?e.createImageMessage(t,i,s,o,n&&0===r):e.createNewAnyFileMessage(t,i,s,o)}).filter(t=>void 0!==t)}static addMessages(t,i,s,n,o){e.createMessages(t,i,s,n,o).filter(t=>void 0!==t).forEach(({[w]:e,elements:i})=>{es.addMessage(t,i,e,s,o)})}};la.IMAGE_BUBBLE_CLASS="image-message",la.AUDIO_BUBBLE_CLASS="audio-message",la.ANY_FILE_BUBBLE_CLASS="any-file-message";let ca=la;class ha{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][k])||i.forEach(e=>{ha.removeElements(t.messageElementRefs,e)}),delete e[0][k],delete e[1][k]}static removeTextHTMLMessage(t,e,i){const s=e[1][i];ha.removeElements(t.messageElementRefs,s),delete e[0][i],delete e[1][i]}static updateHTMLMessage(t,e,i){var s,n,o;if(e[1][a])Ce.overwriteElements(t,i,e[1][a]);else{const l=Ce.create(t,i,e[0][P]),c=(null==(n=e[1][k])?void 0:n[(null==(s=e[1][k])?void 0:s.length)-1])||e[1][r],{nextSibling:h}=c.outerContainer;null==(o=null==h?void 0:h.parentElement)||o.insertBefore(l.outerContainer,h),t.messageElementRefs.splice(t.messageElementRefs.length-1,1);const u=t.messageElementRefs.findIndex(t=>t===c);t.messageElementRefs.splice(u+1,0,l),e[1][a]=l}e[0][a]=i}static updateFileMessages(t,e,i){var s,n;const o=e[0][P],l=ca.createMessages(t,i,o,!1),c=e[1][a],h=(null==(n=e[1][k])?void 0:n[(null==(s=e[1][k])?void 0:s.length)-1])||e[1][r],u=c||h;let d=t.messageElementRefs.findIndex(t=>t===u);h&&(d+=1);const p=(null==c?void 0:c.outerContainer)||(null==h?void 0:h.outerContainer.nextSibling);l.forEach(({type:e,elements:i},s)=>{var n;es.setElementProps(t,i,e,o),null==(n=p.parentElement)||n.insertBefore(i.outerContainer,p),t.messageElementRefs.splice(t.messageElementRefs.length-1,1),t.messageElementRefs.splice(d+s,0,i)}),ha.removeFilesMessages(t,e),e[1][k]=l.map(({elements:t})=>t),e[0][k]=i}static updateTextMessage(t,e,i){var s,n;if(e[1][r])t.renderText(e[1][r].bubbleElement,i,e[0][P]);else{const o=t.createElements(i,e[0][P]),l=(null==(s=e[1][k])?void 0:s[0])||e[1][a];null==(n=l.outerContainer.parentElement)||n.insertBefore(o.outerContainer,l.outerContainer);const c=t.messageElementRefs.findIndex(t=>t===l);t.messageElementRefs.splice(c,0,o),e[1][r]=o}e[0][r]=i}static isElementActive(e){var i,s;return da.isActiveElement(null==(i=e[r])?void 0:i.bubbleElement[t])||da.isActiveElement(null==(s=e[a])?void 0:s.bubbleElement[t])}static update(t,e,i){const s=t.messageToElements[i];if(s){if(ha.isElementActive(s[1]))return console[l]("Cannot update a message that is being streamed");e[r]&&ha.updateTextMessage(t,s,e[r]),e[k]?ha.updateFileMessages(t,s,e[k]):ha.removeFilesMessages(t,s),e[a]&&ha.updateHTMLMessage(t,s,e[a]),!e[r]&&s[1][r]&&ha.removeTextHTMLMessage(t,s,r),!e[a]&&s[1][a]&&ha.removeTextHTMLMessage(t,s,a);const{messageElementRefs:i,avatar:n,name:o}=t;vs.classifyRoleMessages(i),vs.resetAllRoleElements(i,n,o)}else console[l]("Message index not found. Please use the `getMessages` method to find the correct index")}}class ua{static getText(t,e){var i,s;if(!(t.directConnection||t.connect||t.webModel||t.demo))return`Connect to any API using the [connect](${c}connect#connect-1) property or a popular service via [directConnection](${c}directConnection/#directConnection).\n Host AI entirely on your browser via a [webModel](${c}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](${c}modes#demo) property to true.`;if(t.directConnection){if(!e.isDirectConnection())return`Please define a valid service inside\n the [directConnection](${c}directConnection/#directConnection) object.`;const n=null==(i=t.directConnection.openAI)?void 0:i.chat;if("object"==typeof n&&null!=(s=n.tools)&&s.find(t=>"function"===t[w])&&!n.function_handler)return`Please define the \`function_handler\` property inside the openAI [chat](${c}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](${c}connect#connect-1) object.`;return null}}class da extends ms{constructor(t,e,i){var s,n;super(t);const{permittedErrorPrefixes:o,demo:r}=e;this._errorMessageOverrides=null==(s=t.errorMessages)?void 0:s.overrides,this._onClearMessages=is.onClearMessages.bind(this,t),this._onError=is.onError.bind(this,t),this._isLoadingMessageAllowed=da.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&&this.prepareDemo(ue.processDemo(r),t.loadHistory),this.addIntroductoryMessages(t,e);const a=new $s(t,this,e);this._displayServiceErrorMessages=null==(n=t.errorMessages)?void 0:n.displayServiceErrorMessages,t.getMessages=()=>vs.deepCloneMessagesWithReferences(this.messageToElements.map(([t])=>t)),t.clearMessages=this.clearMessages.bind(this,e),t.refreshMessages=this.refreshTextMessages.bind(this,t.remarkable),t.scrollToBottom=re.scrollToBottom.bind(this,this),t.addMessage=(t,e)=>{this.addAnyMessage({...t,sendUpdate:!!e},!e)},t.updateMessage=(t,e)=>ha.update(this,t,e),e.isWebModel()&&e.setUpMessages(this),t.textToSpeech&&le.processConfig(t.textToSpeech,t=>{this.textToSpeech=t}),this.elementRef.onscroll=async()=>{var e,i;t.loadHistory&&a.loadHistoryOnScroll(t.loadHistory),null==(e=this.scrollButton)||e.updateScroll(),null!=(i=this.browserStorage)&&i.trackScrollHeight&&this.browserStorage.addScrollHeight(this.elementRef.scrollTop)}}static getDefaultDisplayLoadingMessage(t,e){return("object"!=typeof t.displayLoadingBubble||!t.displayLoadingBubble.toggle)&&(e.websocket?typeof t.displayLoadingBubble!==Kt&&!!t.displayLoadingBubble:(typeof t.displayLoadingBubble===Kt||t.displayLoadingBubble)??!0)}setLoadingToggle(t){const e=this.messageElementRefs[this.messageElementRefs.length-1],i=ms.isLoadingMessage(e);if(!t&&i)this.removeLastMessage(),delete this._activeLoadingConfig;else{if(this._activeLoadingConfig&&i){const i=ke.getTargetWrapper(e.bubbleElement);if(i)return this._activeLoadingConfig=t||{},this.updateLoadingMessage(i);this.removeLastMessage()}this._activeLoadingConfig=t||{},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&&ns.addMessage(this,!1),null!=e&&e.full&&ns.addMessage(this)}t.displayErrors&&(t.displayErrors[rt]&&this.addNewErrorMessage("",""),t.displayErrors.service&&this.addNewErrorMessage(o,""),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=ua.getText(t,e);if(i){const t=this.createAndAppendNewMessageElement(i,h);this.applyCustomStyles(t,h,!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;vs.hideRoleElements(t,this.avatar,this.name)}this.addIntroductoryMessage(t,s)}):this.addIntroductoryMessage(i,s))}addIntroductoryMessage(i,s){var n;let o;return null!=i&&i[r]?o=this.createAndAppendNewMessageElement(i[r],h):null!=i&&i[a]&&(o=Ce.add(this,i[a],h)),o&&(this.applyCustomStyles(o,h,!1,null==(n=this.messageStyles)?void 0:n.intro),o.outerContainer[t].add(ms.INTRO_CLASS),s&&(o.outerContainer[e].display="none")),o}removeIntroductoryMessage(){const e=this.messageElementRefs[0];e.outerContainer[t].contains(ms.INTRO_CLASS)&&(e.outerContainer.remove(),this.messageElementRefs.shift())}addAnyMessage(t,e=!1,i=!1){return t[l]?this.addNewErrorMessage(o,t[l],i):this.addNewMessage(t,e,i)}tryAddTextMessage(t,e,i,s=!1,n=!1){void 0!==t[r]&&null!==i[r]&&(this.addNewTextMessage(t[r],t[P],e,n),!s&&this.textToSpeech&&t[P]!==u&&le.speak(t[r],this.textToSpeech))}tryAddFileMessages(t,e,i=!1){t[k]&&Array.isArray(t[k])&&ca.addMessages(this,t[k],t[P],e,i)}tryAddHTMLMessage(t,e,i=!1){if(void 0!==t[a]&&null!==t[a]){const s=Ce.add(this,t[a],t[P],e,i);!i&&xe.isElementTemporary(s)&&delete t[a]}}addNewMessage(t,e=!1,i=!1){var s,n,o,a;t[P]!==u&&(null==(s=this._hiddenAttachments)||s.removeHiddenFiles());const l=da.createMessageContent(t),c=null==(o=null==(n=this.textToSpeech)?void 0:n.audio)?void 0:o.displayText;"boolean"==typeof c&&!c&&delete l[r];const h=re.isScrollbarAtBottomOfElement(this.elementRef),d={status:t.overwrite};return i?(this.tryAddFileMessages(l,h,i),this.tryAddHTMLMessage(l,d,i),this.tryAddTextMessage(l,d,t,e,i)):(this.tryAddTextMessage(l,d,t,e,i),this.tryAddHTMLMessage(l,d,i),this.tryAddFileMessages(l,h,i)),this.isValidMessageContent(l)&&!i&&(this.updateStateOnMessage(l,t.overwrite,t.sendUpdate,e),d.status||setTimeout(()=>this.scrollToFirstElement(l[P],h)),e||null==(a=this.browserStorage)||a.addMessages(this.messageToElements.map(([t])=>t)),this.scrollButton&&l[P]!==u&&this.tryUpdateHiddenMessageCount(e,t)),this._activeLoadingConfig&&this.addLoadingMessage(!1),l}tryUpdateHiddenMessageCount(t,e){(!t||void 0!==e.sendUpdate)&&setTimeout(()=>{var t,e;return null==(e=null==(t=this.scrollButton)?void 0:t.updateHidden)?void 0:e.call(t)})}isValidMessageContent(t){return t[r]||t[a]||t[k]&&t[k].length>0}updateStateOnMessage(t,e,i=!0,s=!1){if(!e){const e=vs.generateMessageBody(t,this.messageElementRefs);this.messageToElements.push([t,e])}i&&this.sendClientUpdate(t,s)}removeMessageOnError(){const e=this.messageElementRefs[this.messageElementRefs.length-1],i=null==e?void 0:e.bubbleElement;(null!=i&&i[t].contains(gs.MESSAGE_CLASS)&&""===i.textContent||da.isTemporaryElement(e))&&this.removeLastMessage()}addNewErrorMessage(e,i,s=!1){var n,o,r,a,c,h;null==(n=this._hiddenAttachments)||n.readdHiddenFiles(),this.removeMessageOnError();const u=this.getPermittedMessage(i)||(null==(o=this._errorMessageOverrides)?void 0:o[e])||(null==(r=this._errorMessageOverrides)?void 0:r[rt])||"Error, please try again.",d=this.createMessageElementsOnOrientation(u,l,s);vs.hideRoleElements(d.innerContainer,this.avatar,this.name);const{bubbleElement:m,outerContainer:v}=d;m[t].add(p),this.renderText(m,u);const f=ts.extractParticularSharedStyles(["fontSize","fontFamily"],null==(a=this.messageStyles)?void 0:a[rt]);ts.applyCustomStylesToElements(d,!1,f),ts.applyCustomStylesToElements(d,!1,null==(c=this.messageStyles)?void 0:c[l]),s||this.appendOuterContainerElemet(v),this.textToSpeech&&le.speak(u,this.textToSpeech),null==(h=this._onError)||h.call(this,u),setTimeout(()=>re.scrollToBottom(this))}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[l]?[t[l]]:[]}getPermittedMessage(t){if(t){const e=da.extractErrorMessages(t);for(let t=0;t<e.length;t+=1){const i=e[t];if(typeof i===B){if(this._displayServiceErrorMessages)return i;if(this._permittedErrorPrefixes){const t=da.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,i);if(t)return t}}}}}removeError(){this.isLastMessageError()&&vs.getLastMessageElement(this.elementRef).remove()}addDefaultLoadingMessage(e,s=h){const n=this.createMessageElements("",s),{bubbleElement:o}=n;n.bubbleElement[t].add(he.DOTS_CONTAINER_CLASS);const r=i();return r[t].add("loading-message-dots"),o.appendChild(r),he.setDots(o,e),n}addLoadingMessage(i=!1){var s,n,o,r,l,c;if(ms.isLoadingMessage(this.messageElementRefs[this.messageElementRefs.length-1])||!this._activeLoadingConfig&&!i&&!this._isLoadingMessageAllowed)return;const u=(null==(s=this._activeLoadingConfig)?void 0:s[P])||h,d=(null==(n=this._activeLoadingConfig)?void 0:n[e])||(null==(r=null==(o=this.messageStyles)?void 0:o.loading)?void 0:r.message),p=null==d?void 0:d[a],m=p?Ce.createElements(this,p,u,!1):this.addDefaultLoadingMessage(d,u);this.appendOuterContainerElemet(m.outerContainer),m.bubbleElement[t].add(he.BUBBLE_CLASS),this.applyCustomStyles(m,u,!1,null==d?void 0:d[pt]),null==(c=null==(l=this.avatar)?void 0:l.getAvatarContainer(m.innerContainer))||c[t].add("loading-avatar-container"),!this.focusMode&&re.isScrollbarAtBottomOfElement(this.elementRef)&&re.scrollToBottom(this)}updateLoadingMessage(t){var i;const s=null==(i=this._activeLoadingConfig)?void 0:i[e],n=null==s?void 0:s[a];t.innerHTML=n||""}populateIntroPanel(t){t&&(this._introPanel=new aa(t),ke.apply(this,this._introPanel._elementRef),this.elementRef.appendChild(this._introPanel._elementRef))}async addMultipleFiles(t,e){return this._hiddenAttachments=e,Promise.all((t||[]).map(t=>new Promise(e=>{if(t[w]&&t[w]!==E){const i=new FileReader;i.readAsDataURL(t[x]),i.onload=()=>{const s=t[x].name;e({[y]:i.result,name:s,[w]:t[w],ref:t[x]})}}else{const i=t[x].name||x;e({name:i,[w]:E,ref:t[x]})}})))}static isActiveElement(t){return!!t&&(t.contains(he.BUBBLE_CLASS)||t.contains(ns.CLASS)||t.contains(gs.MESSAGE_CLASS))}clearMessages(e,i){var s,n,o,l;const c=[];this.messageElementRefs.forEach(e=>{da.isActiveElement(e.bubbleElement[t])?c.push(e):e.outerContainer.remove()}),Array.from(this.elementRef.children).forEach(e=>{var i;const s=null==(i=e.children[0])?void 0:i.children[0];null!=s&&s[t].contains(p)&&e.remove()}),this.messageElementRefs=c;const h=this.messageToElements.filter(e=>e[1][r]&&da.isActiveElement(e[1][r].bubbleElement[t])||e[1][a]&&da.isActiveElement(e[1][a].bubbleElement[t]));this.messageToElements.splice(0,this.messageToElements.length,...h),!1!==i&&(null!=(s=this._introPanel)&&s._elementRef&&this._introPanel.display(),this.addIntroductoryMessages()),null==(n=this.browserStorage)||n.clear(),null==(o=this.scrollButton)||o.clearHidden(),null==(l=this._onClearMessages)||l.call(this),delete e.sessionId}}class pa{static adjustInputPadding(e,i){i[et].length>0&&e[t].add("text-input-inner-start-adjustment"),i[it].length>0&&e[t].add("text-input-inner-end-adjustment")}static adjustForOutsideButton(e,i,s){0===s[nt].length&&s[st].length>0?(e[0][t].add(oa),i[t].add(oa)):0===s[st].length&&s[nt].length>0&&(e[3][t].add(ra),i[t].add(ra))}static adjustOutsideSubmit(e,i,s){if(!(s[et].length>0||s[it].length>0)){if(0===s[nt].length&&s[st].length>0)return e[0][t].add(sa),i[t].add(sa),s[st].map(e=>e.button.elementRef[t].add("submit-button-enlarged"));if(0===s[st].length&&s[nt].length>0)return e[3][t].add(na),i[t].add(na),s[nt].map(e=>e.button.elementRef[t].add("submit-button-enlarged"))}}static set(t,e,i,s){!!pa.adjustOutsideSubmit(e,i,s)||pa.adjustForOutsideButton(e,i,s),pa.adjustInputPadding(t,s)}}class ma{static create(){return Array.from({length:4}).map((e,s)=>{const n=i();return n[t].add("input-button-container"),(0===s||3===s)&&n[t].add("outer-button-container"),(1===s||2===s)&&n[t].add("inner-button-container"),n})}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 t===st?0:t===et?1:t===it?2:3}static addButton(e,i,s){i[t].add(s);const n=ma.getContainerIndex(s);e[n].appendChild(i),3===n&&i[t].add(nt)}}const va=["camera","gifs","images","audio","mixedFiles",ft,"microphone"],fa=class s{static addHighlightEvents(t,e){e.addEventListener(mt,e=>{t.highlightedItem=e.target}),e.addEventListener(vt,()=>{t.highlightedItem=void 0})}static addItemEvents(t,e,i,n){be.add(e,n),e.addEventListener(lt,()=>{i[lt]()}),s.addHighlightEvents(t,e)}static createItemText(n,o){const r=i();return Object.assign(r[e],o),r[t].add(s.TEXT_CLASS),r.textContent=n||"File",r}static createItemIcon(n,o){const r=i();return Object.assign(r[e],o),r[t].add(s.ICON_CLASS),r.appendChild(n),r}static populateItem(e,i,n){const{elementRef:o,dropupText:a,svg:l,customStyles:c}=e,h=o.children[0],u=c&&Object.values(c).find(t=>{var e;return""===(null==(e=t[ut])?void 0:e.content)});h[t].contains(Yn.INPUT_BUTTON_INNER_TEXT_CLASS)?(u||i.appendChild(s.createItemIcon(l,null==n?void 0:n.iconContainer)),i.appendChild(s.createItemText(h.textContent,null==n?void 0:n[r]))):(u||i.appendChild(s.createItemIcon(o.children[0],null==n?void 0:n.iconContainer)),i.appendChild(s.createItemText(a,null==n?void 0:n[r])))}static createItem(n,o,r){var a;const l=i();Object.assign(l[e],null==(a=null==r?void 0:r.item)?void 0:a[rt]),s.populateItem(o,l,r),l[t].add(s.MENU_ITEM_CLASS),l.tabIndex=0;const{elementRef:c}=o;if(o.isCustom)o.setDropupItem(n,l);else{const t=xt.processStateful((null==r?void 0:r.item)||{});s.addItemEvents(n,l,c,t)}return l}};fa.MENU_ITEM_CLASS="dropup-menu-item",fa.CUSTOM_BUTTON_ITEM_CLASS="dropup-menu-item-custom-button",fa.TEXT_CLASS="dropup-menu-item-text",fa.ICON_CLASS="dropup-menu-item-icon";let ga=fa;const ba=class s extends io{constructor(t,e,i,n){var o,a,l,c,h,u;const d=(null==(c=null==(l=null==(a=null==(o=null==t?void 0:t[pt])?void 0:o.button)?void 0:a[rt])?void 0:l[r])?void 0:c.content)||`Custom ${e}`,p=Tt.tryCreateConfig(`Custom ${e}`,null==t?void 0:t.tooltip);super(s.createButtonElement(),'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 22" fill="none">\n <rect x="2.5" y="2.5" width="17" height="17" rx="2" stroke="#000000" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>\n',null==t?void 0:t.position,p,(null==(h=null==t?void 0:t[pt])?void 0:h.button)||p&&{},d),this._state=rt,this.isCustom=!0,this._innerElements=this.createInnerElementsForStates(this.customStyles),this._menuStyles=n,this._onClick=t.onClick,this._dropupStyles=null==(u=t[pt])?void 0:u.dropup,this.setSetState(t),this.addClickListener(i),this.changeState(t.initialState,!0)}static createButtonElement(){const e=i();return e[t].add("input-button",s.BUTTON_CLASS),e}createInnerElementsForStates(t){const e="custom-icon",i=this.createInnerElements(e,rt,t);return{[rt]:i,[ct]:this.genStateInnerElements(e,ct,i,t),[ht]:this.genStateInnerElements(e,ht,i,t)}}setSetState(t){t.setState=t=>{t===rt&&this.changeToDefault(),t===ct&&this.changeToActive(),t===ht&&this.changeToDisabled()}}addClickListener(t){re.assignButtonEvents(this.elementRef,()=>{var e;const i=null==(e=this._onClick)?void 0:e.call(this,this._state);null==t||t(),(i===rt||i===ct||i===ht)&&this.changeState(i)})}changeState(t,e){t===ht?this.changeToDisabled(e):t===ct?this.changeToActive(e):this.changeToDefault(e)}applyDropupContentStyles(i){const s=Array.from(this.elementRef.children);if(null!=i&&i[r]){const n=s.find(e=>e[t].contains(ga.TEXT_CLASS));n&&Object.assign(n[e],i[r])}if(null!=i&&i.iconContainer){const n=s.find(e=>e[t].contains(ga.ICON_CLASS));n&&Object.assign(n[e],i.iconContainer)}}resetDropupItem(t){var e,i,s;this.elementRef=ke.replaceElementWithNewClone(this.elementRef,this._originalElementRef),this.elementRef.innerHTML="",""===(null==(e=null==t?void 0:t[ut])?void 0:e.content)||this.elementRef.appendChild(ga.createItemIcon(this[ut],null==(i=this._menuStyles)?void 0:i.iconContainer)),this.elementRef.appendChild(ga.createItemText(this.dropupText,null==(s=this._menuStyles)?void 0:s[r]))}assignDropupItemStyle(t,i){var s;this.elementRef.parentElement&&this._originalElementRef&&this.resetDropupItem(i),ga.addHighlightEvents(this._menu,this.elementRef),this.applyDropupContentStyles(t),Object.assign(this.elementRef[e],null==(s=null==t?void 0:t.item)?void 0:s[rt]);const n=xt.processStateful((null==t?void 0:t.item)||{});be.add(this.elementRef,n),this.addClickListener()}changeToDefault(e){var i,n,o,r,a,l;!e&&this._state===rt||(this.elementRef[t].contains(ga.MENU_ITEM_CLASS)?this.assignDropupItemStyle(null==(i=this._dropupStyles)?void 0:i[rt],null==(n=this.customStyles)?void 0:n[rt]):(this.changeElementsByState(this._innerElements[rt]),null!=(o=this.customStyles)&&o[ct]&&eo.unsetAllCSS(this.elementRef,null==(r=this.customStyles)?void 0:r[ct]),null!=(a=this.customStyles)&&a[ht]&&eo.unsetAllCSS(this.elementRef,null==(l=this.customStyles)?void 0:l[ht]),this.reapplyStateStyle(rt,[ct,ht])),this.elementRef[t].remove(s.DISABLED_CONTAINER_CLASS,s.ACTIVE_CONTAINER_CLASS),this.elementRef[t].add(s.DEFAULT_CONTAINER_CLASS),Jn.removeAriaDisabled(this.elementRef),this._state=rt)}changeToActive(e){var i,n;!e&&this._state===ct||(this.elementRef[t].contains(ga.MENU_ITEM_CLASS)?this.assignDropupItemStyle(null==(i=this._dropupStyles)?void 0:i[ct],null==(n=this.customStyles)?void 0:n[ct]):(this.changeElementsByState(this._innerElements[ct]),this.reapplyStateStyle(ct,[ht,rt])),this.elementRef[t].remove(s.DISABLED_CONTAINER_CLASS,s.DEFAULT_CONTAINER_CLASS),this.elementRef[t].add(s.ACTIVE_CONTAINER_CLASS),Jn.removeAriaDisabled(this.elementRef),this._state=ct)}changeToDisabled(e){var i,n,o,r,a,l;!e&&this._state===ht||(this.elementRef[t].contains(ga.MENU_ITEM_CLASS)?this.assignDropupItemStyle(null==(i=this._dropupStyles)?void 0:i[ht],null==(n=this.customStyles)?void 0:n[ht]):(this.changeElementsByState(this._innerElements[ht]),null!=(o=this.customStyles)&&o[ct]&&eo.unsetAllCSS(this.elementRef,null==(r=this.customStyles)?void 0:r[ct]),null!=(a=this.customStyles)&&a[rt]&&eo.unsetAllCSS(this.elementRef,null==(l=this.customStyles)?void 0:l[rt]),this.reapplyStateStyle(ht,[rt,ct])),this.elementRef[t].remove(s.ACTIVE_CONTAINER_CLASS,s.DEFAULT_CONTAINER_CLASS),this.elementRef[t].add(s.DISABLED_CONTAINER_CLASS),Jn.addAriaDisabled(this.elementRef),this._state=ht)}setDropupItem(t,e){this._menu=t,this.elementRef=e,this._originalElementRef=e.cloneNode(!0),this.changeState(this._state,!0)}genStateInnerElements(t,e,i,n){var o,a,l,c;let h=this.createInnerElements(t,e,n);const u=null==(a=null==(o=null==n?void 0:n[e])?void 0:o[ut])?void 0:a.content,d=null==(c=null==(l=null==n?void 0:n[e])?void 0:l[r])?void 0:c.content;if(void 0===u||void 0===d){const{svg:t,[r]:e}=to.parseSVGTextElements(i),{svg:n,[r]:o}=to.parseSVGTextElements(h),a=[];s.addToInnerElements(a,u,t,n),s.addToInnerElements(a,d,e,o),h=a}return h}static addToInnerElements(t,e,i,s){void 0===e&&i?t.push(i.cloneNode(!0)):s&&t.push(s)}static add(t,e){const{customButtons:i,focusInput:n,dropupStyles:o}=t;null==i||i.forEach((t,i)=>{const r={button:new s(t,i+1,n,null==o?void 0:o.menu)};e[`${s.INDICATOR_PREFIX}${i+1}`]=r})}};ba.INDICATOR_PREFIX="custom",ba.BUTTON_CLASS="custom-button",ba.DISABLED_CONTAINER_CLASS="custom-button-container-disabled",ba.DEFAULT_CONTAINER_CLASS="custom-button-container-default",ba.ACTIVE_CONTAINER_CLASS="custom-button-container-active";let ya=ba;class wa{static focusItemWhenOnEdge(t,e){const i=t.elementRef,s=e?i.children[0]:i.children[i.children.length-1];wa.focusSiblingItem(t,s,e,!0)}static focusSiblingItem(t,e,i,s=!1){const n=s?e:e[i?"nextSibling":"previousSibling"];n?(e.dispatchEvent(new MouseEvent(vt)),n.dispatchEvent(new MouseEvent(mt)),n.focus()):(e.dispatchEvent(new MouseEvent(vt)),wa.focusItemWhenOnEdge(t,i))}}class xa{constructor(t,e){var i;this._isOpen=!0,this._styles=e,this.elementRef=xa.createElement(null==(i=this._styles)?void 0:i.container),this.close(),setTimeout(()=>this.addWindowEvents(t))}static createElement(t){const s=i();return s.id=ot,Object.assign(s[e],t),s}open(){this.elementRef[e].display="block",this._isOpen=!0}close(){this._isOpen&&(this.elementRef[e].display="none",this._isOpen=!1)}toggle(){this._isOpen?this.close():this.open()}addItem(t){const e=ga.createItem(this,t,this._styles);this.elementRef.appendChild(e)}addWindowEvents(t){this.clickEvent=this.windowClick.bind(this,t),window.addEventListener(lt,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(lt,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===Et.ESCAPE?(this.close(),null==(i=this.highlightedItem)||i.dispatchEvent(new MouseEvent(vt))):e.key===Et.ENTER?(null==(s=this.highlightedItem)||s[lt](),null==(n=this.highlightedItem)||n.dispatchEvent(new MouseEvent(vt))):e.key===Et.ARROW_DOWN?wa.focusSiblingItem(this,this.highlightedItem||this.elementRef.children[this.elementRef.children.length-1],!0):e.key===Et.ARROW_UP&&wa.focusSiblingItem(this,this.highlightedItem||this.elementRef.children[0],!1))}}const ka=class e extends io{constructor(i,s){var n,o;const r=Tt.tryCreateConfig("Options",null==(n=null==s?void 0:s.button)?void 0:n.tooltip);super(e.createButtonElement(),'<?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>',void 0,r,{[pt]:null==(o=null==s?void 0:s.button)?void 0:o[pt]});const a=this.createInnerElementsForStates(this.customStyles);this._menu=new xa(i,null==s?void 0:s.menu),this.addClickEvent(),this.buttonContainer=e.createButtonContainer(),this.changeElementsByState(a[pt]),this.buttonContainer.appendChild(this.elementRef),this.elementRef[t].add(e.BUTTON_ICON_CLASS),this.buttonContainer.appendChild(this._menu.elementRef),this.reapplyStateStyle(pt),this.addContainerEvents(i)}static createButtonElement(){const e=i();return e[t].add("input-button"),e}createInnerElementsForStates(t){return{[pt]:this.createInnerElements("dropup-icon",pt,t)}}addClickEvent(){this.elementRef.onclick=this._menu.toggle.bind(this._menu),this.elementRef.onkeydown=t=>{t.key===Et.ENTER&&setTimeout(()=>{this._menu.toggle();const t=this._menu.elementRef.children[0];t.focus(),t.dispatchEvent(new MouseEvent(mt))})}}static createButtonContainer(){const t=i();return t.id="dropup-container",t}addItem(t){this._menu.addItem(t)}addContainerEvents(i){i.addEventListener(lt,i=>{const s=i.target[t];!s.contains(e.BUTTON_ICON_CLASS)&&!s.contains(ya.DISABLED_CONTAINER_CLASS)&&this._menu.close()})}static getPosition(t,e){var i,s;return null!=(i=null==e?void 0:e.button)&&i.position?ue.processPosition(null==(s=null==e?void 0:e.button)?void 0:s.position):t[st].length>0&&0===t[nt].length?nt:st}};ka.BUTTON_ICON_CLASS="dropup-button";let _a=ka;class Ca{static addToDropup(t,e,i,s){const n=new _a(i,s);va.forEach(t=>{const i=e[ot].findIndex(e=>e.buttonType===t),s=e[ot][i];s&&(n.addItem(s.button),e[ot].splice(i,1))}),e[ot].forEach(({button:t})=>n.addItem(t));const o=_a.getPosition(e,s);ma.addButton(t,n.buttonContainer,o),e[o].push({})}static addToSideContainer(t,e){[et,it,st,nt].forEach(i=>{const s=i;e[s].forEach(e=>{ma.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{[ot]:[],[st]:[],[et]:[],[it]:[],[nt]:[]}}static generatePositionToButtons(t){const e=Ca.createPositionsToButtonsObj();Object.keys(t).forEach(i=>{var s;const n=null==(s=t[i])?void 0:s.button.position;n&&Ca.setPosition(t,i,e[n])}),0===e[it].length&&t.submit&&Ca.setPosition(t,ft,e[it]),0===e[nt].length&&(t.submit?Ca.setPosition(t,ft,e[nt]):t.microphone?Ca.setPosition(t,S,e[nt]):t.camera?Ca.setPosition(t,A,e[nt]):t[`${ya.INDICATOR_PREFIX}1`]&&Ca.setPosition(t,`${ya.INDICATOR_PREFIX}1`,e[nt])),t.submit&&Ca.setPosition(t,ft,0===e[st].length?e[st]:e[it]),t.microphone&&Ca.setPosition(t,S,0===e[st].length?e[st]:e[it]);const i=Object.keys(t);return i.length>1||e[ot].length>0?(va.forEach(i=>{t[i]&&e[ot].push({...t[i],buttonType:i})}),i.forEach(i=>{const s=i;s.startsWith(ya.INDICATOR_PREFIX)&&t[s]&&e[ot].push({...t[s],customType:s})})):1===i.length&&Ca.setPosition(t,i[0],0===e[nt].length?e[nt]:e[st]),e}static addButtons(t,e,i,s){const n=Ca.generatePositionToButtons(e);return Ca.addToSideContainer(t,n),n[ot].length>0&&Ca.addToDropup(t,n,i,s),n}}const Aa={[C]:{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"},[M]:{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"},[T]:{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<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 Ma extends io{constructor(t){(null==t?void 0:t.position)===ot&&(t.position=nt);const e=Tt.tryCreateConfig("Microphone",null==t?void 0:t.tooltip);super(Ma.createMicrophoneElement(),Xn,null==t?void 0:t.position,e,t),this.isActive=!1,this._innerElements=this.createInnerElementsForStates(this.customStyles),this.changeToDefault()}createInnerElementsForStates(t){const e="microphone-icon";return{[rt]:this.createInnerElements(e,rt,t),[ct]:this.createInnerElements(e,ct,t),[yt]:this.createInnerElements(e,yt,t),[wt]:this.createInnerElements(e,wt,t)}}static createMicrophoneElement(){const e=i();return e.id="microphone-button",e[t].add("input-button"),e}changeToActive(){this.changeElementsByState(this._innerElements[ct]),this.toggleIconFilter(ct),this.reapplyStateStyle(ct,[rt,wt]),this.isActive=!0}changeToDefault(){this.changeElementsByState(this._innerElements[rt]),this.toggleIconFilter(rt),this.reapplyStateStyle(rt,[ct,wt]),this.isActive=!1}changeToCommandMode(){this.changeElementsByState(this._innerElements[wt]),this.toggleIconFilter("command"),this.reapplyStateStyle(wt,[ct])}changeToUnsupported(){this.changeElementsByState(this._innerElements[yt]),this.elementRef[t].add(`${yt}-microphone`),this.reapplyStateStyle(yt,[ct])}toggleIconFilter(e){const i=this.elementRef.children[0];if(i.tagName.toLocaleLowerCase()===ut)switch(e){case rt:i[t].remove("active-microphone-icon","command-microphone-icon"),i[t].add("default-microphone-icon");break;case ct:i[t].remove("default-microphone-icon","command-microphone-icon"),i[t].add("active-microphone-icon");break;case"command":i[t].remove("active-microphone-icon","default-microphone-icon"),i[t].add("command-microphone-icon")}}}function Ta(t){return t&&t.h&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Sa,ja,Ea,Ia={},$a={},Oa={},Pa={},Ba={};function Ra(){if(Sa)return Ba;Sa=1,Object.defineProperty(Ba,"h",{value:!0}),Ba.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 Ba.Text=t,t.FIRST_CHAR_REGEX=/\S/,t.DOUBLE_LINE=/\n\n/g,t.ONE_LINE=/\n/g,Ba}function Fa(){if(ja)return Pa;ja=1,Object.defineProperty(Pa,"h",{value:!0}),Pa.Translate=void 0;const t=Ra();return Pa.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("")}},Pa}var La,qa={};function za(){if(La)return qa;La=1,Object.defineProperty(qa,"h",{value:!0}),qa.Browser=void 0;class t{}return qa.Browser=t,t.IS_SAFARI=()=>(void 0===t._IS_SAFARI&&(t._IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),t._IS_SAFARI),qa}var Da,Na={},Ua={};var Ha,Va={};var Wa,Ga={},Za={};function Ka(){if(Wa)return Za;Wa=1,Object.defineProperty(Za,"h",{value:!0}),Za.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 Za.AutoScroll=t,Za}var Ja,Xa={};function Qa(){if(Ja)return Xa;Ja=1,Object.defineProperty(Xa,"h",{value:!0}),Xa.Elements=void 0;return Xa.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}},Xa}var Ya,tl,el={};function il(){if(Ya)return el;Ya=1,Object.defineProperty(el,"h",{value:!0}),el.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 el.Cursor=t,el}function sl(){if(tl)return Ga;tl=1,Object.defineProperty(Ga,"h",{value:!0}),Ga.CommandUtils=void 0;const t=Ka(),e=Qa(),i=za(),s=il(),n=Ra();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 Ga.CommandUtils=o,Ga}var nl,ol={};var rl,al,ll,cl={};function hl(){if(al)return Na;al=1,Object.defineProperty(Na,"h",{value:!0}),Na.Speech=void 0;const t=function(){if(Da)return Ua;Da=1,Object.defineProperty(Ua,"h",{value:!0}),Ua.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 Ua.EventListeners=t,t.KEY_DOWN_TIMEOUT=null,Ua}(),e=(Ha||(Ha=1,Object.defineProperty(Va,"h",{value:!0}),Va.PreResultUtils=void 0,Va.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)}}),Va),i=sl(),s=Ka(),n=function(){if(nl)return ol;nl=1,Object.defineProperty(ol,"h",{value:!0}),ol.Highlight=void 0;const t=Qa(),e=il();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 ol.Highlight=i,ol}(),o=Qa(),r=function(){if(rl)return cl;rl=1,Object.defineProperty(cl,"h",{value:!0}),cl.Padding=void 0;const t=Qa(),e=il(),i=Ra();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 cl.Padding=s,cl}(),a=za(),l=il(),c=Ra();return Na.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}},Na}function ul(){if(ll)return $a;ll=1,Object.defineProperty($a,"h",{value:!0}),$a.WebSpeech=void 0;const t=function(){if(Ea)return Oa;Ea=1,Object.defineProperty(Oa,"h",{value:!0}),Oa.WebSpeechTranscript=void 0;const t=Fa();return Oa.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}}},Oa}(),e=za(),i=hl();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 $a.WebSpeech=s,$a}var dl,pl={};var ml,vl={},fl={};var gl,bl,yl={},wl={};function xl(){if(bl)return yl;bl=1,Object.defineProperty(yl,"h",{value:!0}),yl.AzureSpeechConfig=void 0;const t=(gl||(gl=1,Object.defineProperty(wl,"h",{value:!0}),wl.README_URL=void 0,wl.README_URL="https://github.com/OvidijusParsiunas/speech-to-element"),wl);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 yl.AzureSpeechConfig=e,yl}var kl,_l={};var Cl,Al={};var Ml,Tl,Sl,jl={};function El(){if(Tl)return vl;Tl=1,Object.defineProperty(vl,"h",{value:!0}),vl.Azure=void 0;const t=(ml||(ml=1,Object.defineProperty(fl,"h",{value:!0}),fl.PreventConnectionStop=void 0,fl.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}}),fl),e=xl(),i=function(){if(kl)return _l;kl=1,Object.defineProperty(_l,"h",{value:!0}),_l.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 _l.StopTimeout=t,t.DEFAULT_MS=2e4,_l}(),s=(Cl||(Cl=1,Object.defineProperty(Al,"h",{value:!0}),Al.AzureAudioConfig=void 0,Al.AzureAudioConfig=class{static get(t,e){return e?t.fromMicrophoneInput(e):t.fromDefaultMicrophoneInput()}}),Al),n=function(){if(Ml)return jl;Ml=1,Object.defineProperty(jl,"h",{value:!0}),jl.AzureTranscript=void 0;const t=Fa();return jl.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}}},jl}(),o=hl();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 vl.Azure=r,vl}const Il=Ta(function(){if(Sl)return Ia;Sl=1,Object.defineProperty(Ia,"h",{value:!0});const t=ul(),e=sl(),i=function(){if(dl)return pl;dl=1,Object.defineProperty(pl,"h",{value:!0}),pl.GlobalState=void 0;class t{static doubleClickDetector(){return!!t.doubleClickPending||(t.doubleClickPending=!0,setTimeout(()=>{t.doubleClickPending=!1},300),!1)}}return pl.GlobalState=t,t.doubleClickPending=!1,pl}(),s=El();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 Ia.default=n,Ia}());class $l{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),Il.stop(),this._stop||setTimeout(e,Pl.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 Ol=class t extends Ma{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||Il.isWebSpeechSupported()){const i=!t.textInput||!t.textInput[ht];re.assignButtonEvents(this.elementRef,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)}),Il.endCommandMode(),{restart:!0,removeNewText:!0}):null),n.submitAfterSilence&&(this._silenceSubmit=new $l(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(),Il.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[lt](),i||setTimeout(()=>e[lt](),t.MICROPHONE_RESET_TIMEOUT_MS)}};Ol.MICROPHONE_RESET_TIMEOUT_MS=300;let Pl=Ol;class Bl{constructor(t,e,i,s,n){this._attachments=[],this._fileCountLimit=99,this._acceptedFormat="",this._hiddenAttachments=new Set,i.maxNumberOfFiles&&(this._fileCountLimit=i.maxNumberOfFiles),this._toggleContainerDisplay=s,this._fileAttachmentsContainerRef=n,i.acceptedFormats&&(this._acceptedFormat=i.acceptedFormats),setTimeout(()=>{this._validationHandler=t._validationHandler,this._onInput=e.onInput})}attemptAddFile(t,e){var i;return!!Bl.isFileTypeValid(t,this._acceptedFormat)&&(this.addAttachmentBasedOnType(t,e,!0),null==(i=this._onInput)||i.call(this,!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[w]===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[w].startsWith(s.slice(0,-2)))return!0}}return!1}static getTypeFromBlob(t){const{type:e}=t;return e.startsWith(_)?_:e.startsWith(T)?T:E}addAttachmentBasedOnType(t,e,i){const s=Bl.getTypeFromBlob(t);if(s===_){const s=Bl.createImageAttachment(e);this.addFileAttachment(t,_,s,i)}else if(s===T){const s=Fl.createAudioAttachment(e);this.addFileAttachment(t,T,s,i)}else{const e=Bl.createAnyFileAttachment(t.name);this.addFileAttachment(t,E,e,i)}}static createImageAttachment(e){const i=new Image;return i[y]=e,i[t].add("image-attachment"),i}static createAnyFileAttachment(e){const s=i();s[t].add("border-bound-attachment"),jt.IS_SAFARI&&s[t].add("border-bound-attachment-safari");const n=i();n[t].add("any-file-attachment-text");const o=i();return o[t].add("file-attachment-text-container"),o.appendChild(n),n.textContent=e,s.appendChild(o),s}addFileAttachment(t,e,i,s){var n;const o=Bl.createContainer(i);if(this._attachments.length>=this._fileCountLimit){const t=this._attachments[this._attachments.length-1].removeButton;null==t||t[lt]();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(e){const s=i();return s[t].add("file-attachment"),s.appendChild(e),s}createRemoveAttachmentButton(e){const s=i();s[t].add("remove-file-attachment-button"),s.onclick=this.removeAttachment.bind(this,e);const n=i();return n[t].add("x-icon"),n.innerText="×",s.appendChild(n),s}removeAttachment(t,e){var i,s;const n=this._attachments.findIndex(e=>e===t);if(n<0)return;null==(i=this._onInput)||i.call(this,!(null==e||!e.isTrusted));const o=this._attachments[n].attachmentContainerElement;this._attachments.splice(n,1),Fl.stopAttachmentPlayback(o),o.remove(),this._toggleContainerDisplay(!1),null==(s=this._validationHandler)||s.call(this)}getFiles(){return Array.from(this._attachments).map(t=>({[x]:t[x],[w]:t.fileType}))}hideAttachments(){this._hiddenAttachments.clear(),this._attachments.forEach(t=>{setTimeout(()=>{var e;return null==(e=t.removeButton)?void 0:e[lt]()}),this._hiddenAttachments.add(t)})}removeAttachments(){this._attachments.forEach(t=>{setTimeout(()=>{var e;return null==(e=t.removeButton)?void 0:e[lt]()})}),this._hiddenAttachments.clear()}readdAttachments(){var t;Array.from(this._hiddenAttachments).forEach(t=>{this._fileAttachmentsContainerRef.appendChild(t.attachmentContainerElement),this._attachments.push(t)}),null==(t=this._onInput)||t.call(this,!1),this._hiddenAttachments.clear()}}const Rl=class e extends Bl{constructor(t,e,i,s,n){super(t,e,i,s,n)}static createAudioContainer(){const e=i();return e[t].add("border-bound-attachment","audio-attachment-icon-container"),jt.IS_SAFARI&&e[t].add("border-bound-attachment-safari"),e}static addAudioElements(e,s){const n=e.parentElement?re.cloneElement(e):e,o=i(T);o[y]=s;const r=qs.createSVGElement(ro);r[t].add("attachment-icon","play-icon");const a=qs.createSVGElement(ao);a[t].add("attachment-icon","stop-icon"),n.replaceChildren(r),o.onplay=()=>{n.replaceChildren(a)},o.onpause=()=>{n.replaceChildren(r),o.currentTime=0},o.onended=()=>{n.replaceChildren(r)},re.assignButtonEvents(n,()=>{o.paused?o.play():o.pause()})}static createAudioAttachment(t){const i=e.createAudioContainer();return e.addAudioElements(i,t),i}createTimer(i,s){let n=0;const o=void 0!==s&&s<e.TIMER_LIMIT_S?s:e.TIMER_LIMIT_S;return setInterval(()=>{var e;n+=1,n===o&&(null==(e=this.stopPlaceholderCallback)||e.call(this),this.clearTimer()),600===n&&i[t].add("audio-placeholder-text-4-digits");const s=Math.floor(n/60),r=(n%60).toString().padStart(2,"0");i.textContent=`${s}:${r}`},1e3)}createPlaceholderAudioAttachment(s){const n=e.createAudioContainer(),o=i();o[t].add("audio-placeholder-text-3-digits");const r=i();r[t].add("file-attachment-text-container","audio-placeholder-text-3-digits-container"),r.appendChild(o);const a=qs.createSVGElement(ao);return a[t].add("attachment-icon","stop-icon","not-removable-attachment-icon"),o.textContent="0:00",this._activePlaceholderTimer=this.createTimer(o,s),n.appendChild(r),this.addPlaceholderAudioAttachmentEvents(n,a,r),n}addPlaceholderAudioAttachmentEvents(t,e,i){t.addEventListener(mt,()=>t.replaceChildren(e));t.addEventListener(vt,()=>t.replaceChildren(i));t.addEventListener(lt,()=>{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([],""),T,i,!1),this.stopPlaceholderCallback=t}completePlaceholderAttachment(t,i){const s=this._activePlaceholderAttachment;s&&(s[x]=t,e.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(e){var i,s,n;null!=(n=null==(s=null==(i=e.children[0])?void 0:i.children)?void 0:s[0])&&n[t].contains("stop-icon")&&e.children[0][lt]()}};Rl.TIMER_LIMIT_S=5999;let Fl=Rl;class Ll{static create(t,e,i,s,n,o){return o===T?new Fl(t,e,i,s,n):new Bl(t,e,i,s,n)}}class ql{constructor(t,i,s){this._fileAttachmentsTypes=[],this.elementRef=this.createAttachmentContainer();const n="object"==typeof s&&!!s.displayFileAttachmentContainer;this.toggleContainerDisplay(n),t.appendChild(this.elementRef),i&&Object.assign(this.elementRef[e],i)}addType(t,e,i,s){const n=Ll.create(t,e,i,this.toggleContainerDisplay.bind(this),this.elementRef,s);return this._fileAttachmentsTypes.push(n),n}createAttachmentContainer(){const t=i();return t.id="file-attachment-container",t}toggleContainerDisplay(t){t?this.elementRef[e].display="block":0===this.elementRef.children.length&&(this.elementRef[e].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){ql.addFilesToType(t,this._fileAttachmentsTypes)}hideFiles(){this._fileAttachmentsTypes.forEach(t=>t.hideAttachments()),this.elementRef.replaceChildren(),this.toggleContainerDisplay(!1)}removeHiddenFiles(){this._fileAttachmentsTypes.forEach(t=>t.removeAttachments())}readdHiddenFiles(){this._fileAttachmentsTypes.forEach(t=>t.readdAttachments()),this.toggleContainerDisplay(!0)}getNumberOfTypes(){return this._fileAttachmentsTypes.length}}const zl=class s{constructor(t,e,i){this._isOpen=!1,this._contentRef=s.createModalContent(e,null==i?void 0:i.backgroundColor),this._buttonPanel=s.createButtonPanel(null==i?void 0:i.backgroundColor),this._elementRef=s.createContainer(this._contentRef,i),this._elementRef.appendChild(this._buttonPanel),t.appendChild(this._elementRef),this._backgroundPanelRef=s.createDarkBackgroundPanel(),t.appendChild(this._backgroundPanelRef),this.addWindowEvents(t)}isOpen(){return this._isOpen}static createContainer(s,n){const o=i();return o[t].add("modal"),o.appendChild(s),n&&delete n.backgroundColor,Object.assign(o[e],n),o}static createModalContent(s,n){const o=i();return o[t].add(...s),n&&(o[e].backgroundColor=n),i().appendChild(o),o}static createButtonPanel(s){const n=i();return n[t].add("modal-button-panel"),s&&(n[e].backgroundColor=s),n}static createDarkBackgroundPanel(){const t=i();return t.id="modal-background-panel",t}addButtons(...t){t.forEach(t=>{Jn.addAttributes(t),this._buttonPanel.appendChild(t)})}static createTextButton(e){const s=i();return s[t].add("modal-button"),s.textContent=e,s}static createSVGButton(e){const s=i();s[t].add("modal-button","modal-svg-button");const n=qs.createSVGElement(e);return n[t].add("modal-svg-button-icon"),s.appendChild(n),s}close(){this._elementRef[t].remove("show-modal"),this._elementRef[t].add("hide-modal"),this._backgroundPanelRef[t].remove("show-modal-background"),this._backgroundPanelRef[t].add("hide-modal-background"),this._isOpen=!1,setTimeout(()=>{this._elementRef[e].display="none",this._backgroundPanelRef[e].display="none"},s.MODAL_CLOSE_TIMEOUT_MS)}displayModalElements(){this._elementRef[e].display="flex",this._elementRef[t].remove("hide-modal"),this._elementRef[t].add("show-modal"),this._backgroundPanelRef[e].display="block",this._backgroundPanelRef[t].remove("hide-modal-background"),this._backgroundPanelRef[t].add("show-modal-background"),this._isOpen=!0}openTextModal(t){this._contentRef.innerHTML=t,this.displayModalElements()}addCloseButton(t,e,i){const n=e?s.createSVGButton(t):s.createTextButton(t);return this.addButtons(n),re.assignButtonEvents(n,()=>{this.close(),setTimeout(()=>{null==i||i()},140)}),n}static createTextModalFunc(t,e,i){var n;if("object"==typeof e&&null!=(n=e[k])&&n.infoModal){const n=new s(t,["modal-content"],e[k].infoModal.containerStyle);return n.addCloseButton("OK",!1,i),n.openTextModal.bind(n,e.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===Et.ESCAPE?(this.close(),null==(i=this.extensionCloseCallback)||i.call(this)):e.key===Et.ENTER&&(this.close(),null==(s=this.extensionCloseCallback)||s.call(this)))}};zl.MODAL_CLOSE_TIMEOUT_MS=190;let Dl=zl;class Nl extends io{constructor(t,e,i,s,n,o){var a,l,c,h,u,d,p,m,v,f;const g=ue.processPosition(null==(a=null==i?void 0:i.button)?void 0:a.position),b=(null==(h=null==(c=null==(l=null==i?void 0:i.button)?void 0:l[pt])?void 0:c[r])?void 0:h.content)||o,y=Tt.tryCreateConfig("Upload File",null==(u=null==i?void 0:i.button)?void 0:u.tooltip);super(Nl.createButtonElement(),n,g,y,i.button,b);const w=this.createInnerElementsForStates(s,this.customStyles);this._inputElement=Nl.createInputElement(null==(d=null==i?void 0:i[k])?void 0:d.acceptedFormats),this.addClickEvent(t,i),this.changeElementsByState(w[pt]),this.reapplyStateStyle(pt),this._fileAttachmentsType=e,this._openModalOnce=!1===(null==(m=null==(p=i[k])?void 0:p.infoModal)?void 0:m.openModalOnce)||null==(f=null==(v=i[k])?void 0:v.infoModal)?void 0:f.openModalOnce}createInnerElementsForStates(t,e){return{[pt]:this.createInnerElements(t,pt,e)}}triggerImportPrompt(t){t.onchange=this.import.bind(this,t),t[lt]()}import(t){ql.addFilesToType(Array.from(t[k]||[]),[this._fileAttachmentsType]),t.value=""}static createInputElement(t){const e=i("input");return e[w]=x,e.accept=t||"",e.hidden=!0,e.multiple=!0,e}static createButtonElement(){const e=i();return e[t].add("input-button"),e}addClickEvent(t,e){const i=this.triggerImportPrompt.bind(this,this._inputElement),s=Dl.createTextModalFunc(t,e,i);this.elementRef.onclick=this[lt].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 Ul{static create(t,e,i){const s=Ul.createElement(i);Ul.addEvents(s,t,e),t.appendChild(s)}static createElement(t){const s=i();return s.id="drag-and-drop",typeof t===Kt&&Object.assign(s[e],t),s}static addEvents(t,e,i){e.ondragenter=e=>{e.preventDefault(),Ul.display(t)},t.ondragleave=e=>{e.preventDefault(),Ul.hide(t)},t.ondragover=t=>{t.preventDefault()},t.ondrop=e=>{e.preventDefault(),Ul.uploadFile(i,e),Ul.hide(t)}}static uploadFile(t,e){var i;const s=null==(i=e.dataTransfer)?void 0:i[k];s&&t.addFilesToAnyType(Array.from(s))}static display(t){t[e].display="block"}static hide(t){t[e].display="none"}static isEnabled(t,e){return(void 0===e||!1!==e)&&(!!e||t.getNumberOfTypes()>0)}}class Hl{static validate(t,e,i,s,n,o,r){const a=!i.isSubmitProgrammaticallyDisabled&&t(s,n,r);return a?e.changeToSubmitIcon():e.changeToDisabledIcon(),null==o||o.addInputText(s||""),a}static async useValidationFunc(t,e,i,s,n,o){const r=e.isTextInputEmpty()?"":e.inputElementRef.textContent;await i.completePlaceholders();const a=i.getAllFileData(),l=null==a?void 0:a.map(t=>t[x]);return Hl.validate(t,s,n,r,l,o)}static async useValidationFuncProgrammatic(t,e,i,s,n){var o;const a=null==(o=e[k])?void 0:o.map(t=>t[x]);return Hl.validate(t,i,s,e[r],a,n,!0)}static validateWebsocket(t,e){const{websocket:i,connectSettings:s}=t;return!(i&&s.url!==Ms.URL&&!Ts.canSendMessage(i))||(e.changeToDisabledIcon(),!1)}static attach(t,e,i,s,n,o){const r=t.validateInput||ue.processValidateInput(t);t._validationHandler=async t=>{if(n.status.loadingActive||n.status.requestInProgress||!Hl.validateWebsocket(e,n))return!1;const a=r||e.canSendMessage;return a?t?Hl.useValidationFuncProgrammatic(a,t,n,e,o):Hl.useValidationFunc(a,i,s,n,e,o):null}}}class Vl{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 Wl extends Ma{constructor(t,e){var i,s;super(e.button),this._waitingForBrowserApproval=!1,this._audioType=t,this._extension=(null==(i=e[k])?void 0:i.format)||"mp3",this._maxDurationSeconds=null==(s=e[k])?void 0:s.maxDurationSeconds,re.assignButtonEvents(this.elementRef,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[$]()}).catch(t=>{console[l](t),this.stop()}).finally(()=>{this._waitingForBrowserApproval=!1})}createFile(t){const e=new Blob([t.data],{type:`audio/${this._extension}`}),i=Vl.getFileName(this._newFilePrefix||T,this._extension),s=new File([e],i,{type:e[w]}),n=new FileReader;n.readAsDataURL(s),n.onload=t=>{this._audioType.completePlaceholderAttachment(s,t.target.result)}}}class Gl{static resetSubmit(t,e){e?t.unsetCustomStateStyles([gt,ft]):t.unsetCustomStateStyles([bt,gt,ft]),t.reapplyStateStyle(ft)}static overwriteDefaultStyleWithSubmit(t,e){if(!t.submit)return;const i=F(t[e]||{});oo.overwritePropertyObjectFromAnother(i,t.submit,["container",rt]),oo.overwritePropertyObjectFromAnother(i,t.submit,[r,"styles",rt]),oo.overwritePropertyObjectFromAnother(i,t.submit,[ut,"styles",rt]),t[e]=i}static setUpDisabledButton(t){oo.setPropertyValueIfDoesNotExist(t,[ft,"container",rt,"backgroundColor"],""),oo.setPropertyValueIfDoesNotExist(t,[ht,"container",rt,"backgroundColor"],"unset"),oo.setPropertyValueIfDoesNotExist(t.submit,[ut,"styles",rt,"filter"],""),oo.setPropertyValueIfDoesNotExist(t[ht],[ut,"styles",rt,"filter"],"brightness(0) saturate(100%) invert(70%) sepia(0%) saturate(5564%) hue-rotate(207deg) brightness(100%) contrast(97%)"),oo.setPropertyValueIfDoesNotExist(t[ht],[r,"styles",rt,"color"],"grey"),Gl.overwriteDefaultStyleWithSubmit(t,ht)}static process(t){const e=F(t||{});return Gl.overwriteDefaultStyleWithSubmit(e,gt),Gl.overwriteDefaultStyleWithSubmit(e,bt),null!=t&&t.alwaysEnabled||Gl.setUpDisabledButton(e),e}}class Zl extends io{constructor(t,e,i,s,n,o){const r=Gl.process(t.submitButtonStyles),a=Tt.tryCreateConfig("Submit",null==r?void 0:r.tooltip);super(Zl.createButtonContainerElement(),'<?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',null==r?void 0:r.position,a,r),this._isSVGLoadingIconOverriden=!1,this.status={requestInProgress:!1,loadingActive:!1},this._messages=i,this._textInput=e,this._fileAttachments=n,this._innerElements=this.createInnerElementsForStates(),this._stopClicked={listener:()=>{}},this._serviceIO=s,this._alwaysEnabled=!(null==r||!r.alwaysEnabled),t.disableSubmitButton=this.disableSubmitButton.bind(this,s),this.attemptOverwriteLoadingStyle(t),o.microphone&&this.setUpSpeechToText(o.microphone.button,t.speechToText),setTimeout(()=>{var e;this._validationHandler=t._validationHandler,this.assignHandlers(this._validationHandler),null==(e=this._validationHandler)||e.call(this)})}createInnerElementsForStates(){const{submit:t,loading:e,stop:i}=this.createCustomElements();return{submit:t,loading:e||[Zl.createLoadingIconElement()],stop:i||[Zl.createStopIconElement()],[ht]:this.createDisabledIconElement(t)}}createCustomElements(){const t=Yn.createCustomElements(ft,this[ut],this.customStyles),e={loading:void 0,stop:void 0};return Object.keys(e).forEach(t=>{const i=t,s=Yn.createCustomElements(i,this[ut],this.customStyles);s&&(e[i]=s)}),e.submit=t||this.buildDefaultIconElement("submit-icon"),e}static createButtonContainerElement(){const e=i();return e[t].add("input-button"),e}static createLoadingIconElement(){const e=i();return e[t].add("loading-submit-button"),e}static createStopIconElement(){const t=i();return t.id="stop-icon",t}createDisabledIconElement(t){return Yn.createCustomElements(ht,this[ut],this.customStyles)||[t[0].cloneNode(!0)]}attemptOverwriteLoadingStyle(t){var e,s,n,o,a,l,c,h,u;if(!(null!=(s=null==(e=this.customStyles)?void 0:e.submit)&&s[ut]||null!=(a=null==(o=null==(n=this.customStyles)?void 0:n.loading)?void 0:o[ut])&&a.content||null!=(h=null==(c=null==(l=this.customStyles)?void 0:l.loading)?void 0:c[r])&&h.content||void 0!==t.displayLoadingBubble&&!0!==t.displayLoadingBubble)){const e=i("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==(u=t.shadowRoot)||u.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),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({[r]:"",[k]:t});else{const e=this._textInput.inputElementRef.innerText.trim();this.attemptSubmit({[r]:e,[k]:t})}(jt.IS_SAFARI||jt.IS_MOBILE)&&setTimeout(()=>Rt.focusEndOfInput(this._textInput.inputElementRef))}async programmaticSubmit(t){"string"==typeof t&&(t=ue.processSubmitUserMessage(t));const e={[r]:t[r]};t[k]&&(e[k]=Array.from(t[k]).map(t=>({file:t,[w]:Bl.getTypeFromBlob(t)}))),t.custom&&(e.custom=t.custom),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(),jt.IS_MOBILE&&setTimeout(()=>this._textInput.inputElementRef.focus()),"boolean"!=typeof this._messages.focusMode&&null!=(s=this._messages.focusMode)&&s.fade&&await rs.fadeAnimation(this._messages.elementRef,this._messages.focusMode.fade),await this.addNewMessage(t),this._serviceIO.isWebModel()||this._messages.addLoadingMessage();const a=null==(n=t[k])?void 0:n.map(t=>t[x]),l={[r]:""===t[r]?void 0:t[r],[k]:a};await this._serviceIO.callAPI(l,this._messages),null==(o=this._fileAttachments)||o.hideFiles()}async addNewMessage({text:t,files:e,custom:i}){const s={[P]:u,custom:i};t&&(s[r]=t),e&&(s[k]=await this._messages.addMultipleFiles(e,this._fileAttachments)),this._serviceIO.sessionId&&(s._sessionId=this._serviceIO.sessionId),Object.keys(s).length>0&&this._messages.addNewMessage(s)}stopStream(){var t,e,i;null==(e=(t=this._serviceIO.streamHandlers).onAbort)||e.call(t),null==(i=this._stopClicked)||i.listener(),this._validationHandler&&this.resetSubmit(this._validationHandler)}changeToStopIcon(){this._serviceIO.websocket||(this.elementRef[t].remove(ea,ia,ta),Jn.removeAriaAttributes(this.elementRef),this.changeElementsByState(this._innerElements.stop),this.reapplyStateStyle(bt,[gt,ft]),re.assignButtonEvents(this.elementRef,this.stopStream.bind(this)),this.status.loadingActive=!1)}changeToLoadingIcon(){this._serviceIO.websocket||(this._isSVGLoadingIconOverriden||this.changeElementsByState(this._innerElements.loading),this.elementRef[t].remove(ta,ia),Jn.removeAriaDisabled(this.elementRef),this.elementRef[t].add(ea),Jn.addAriaBusy(this.elementRef),this.reapplyStateStyle(gt,[ft]),re.assignButtonEvents(this.elementRef,()=>{}),this.status.requestInProgress=!0,this.status.loadingActive=!0)}changeToSubmitIcon(){this.elementRef[t].contains(ta)||(this.elementRef[t].remove(ea,ia),Jn.removeAriaAttributes(this.elementRef),this.elementRef[t].add(ta),this.changeElementsByState(this._innerElements.submit),Gl.resetSubmit(this,this.status.loadingActive),re.assignButtonEvents(this.elementRef,()=>{var t;this.submitFromInput(),null!=(t=this._microphoneButton)&&t.isActive&&Pl.toggleSpeechAfterSubmit(this._microphoneButton.elementRef,!!this._stopSTTAfterSubmit),setTimeout(()=>Rt.focusEndOfInput(this._textInput.inputElementRef))}))}changeToDisabledIcon(e=!1){this._alwaysEnabled&&!e?this.changeToSubmitIcon():this.elementRef[t].contains(ia)||(this.elementRef[t].remove(ea,ta),Jn.removeAriaBusy(this.elementRef),this.elementRef[t].add(ia),Jn.addAriaDisabled(this.elementRef),this.changeElementsByState(this._innerElements[ht]),this.reapplyStateStyle(ht,[ft]),re.assignButtonEvents(this.elementRef,()=>{}))}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))}}class Kl extends Dl{constructor(e,s,n,o){super(e,["modal-content","modal-camera-content"],n),this._stopped=!1,this._format="image/png",this._canvas=i("canvas"),this._canvas[t].add("camera-modal-canvas");const{captureButton:r,submitButton:a}=this.addButtonsAndTheirEvents(s);this._captureButton=r,this._submitButton=a,this._captureIcon=this._captureButton.children[0],this._refreshIcon=qs.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[t].add("modal-svg-button-icon","modal-svg-refresh-icon"),"jpeg"===(null==o?void 0:o.format)&&(this._format="image/jpeg"),null!=o&&o.dimensions&&(this._dimensions=o.dimensions),this._contentRef.appendChild(this._canvas),this.extensionCloseCallback=this.stop}addButtonsAndTheirEvents(e){const i=Dl.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 <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');i[t].add("modal-svg-camera-button"),i.children[0][t].add("modal-svg-camera-icon");const s=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);s[t].add("modal-svg-close-button"),s.children[0][t].add("modal-svg-close-icon");const n=Dl.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 n[t].add("modal-svg-submit-button"),this.addButtons(i,n),this.addButtonEvents(i,s,n,e),{captureButton:i,submitButton:n}}addButtonEvents(t,e,i,s){re.assignButtonEvents(t,this.capture.bind(this)),re.assignButtonEvents(e,this.stop.bind(this)),re.assignButtonEvents(i,()=>{const t=this.getFile();t&&ql.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[t].replace("modal-svg-refresh-button","modal-svg-camera-button");const e=this._canvas.getContext("2d");null==e||e.clearRect(0,0,this._canvas.width,this._canvas.height)},Dl.MODAL_CLOSE_TIMEOUT_MS)}start(){this._dataURL=void 0,this._submitButton[t].add(`modal-svg-submit-${ht}`),this._stopped=!1,navigator.mediaDevices.getUserMedia({video:this._dimensions||!0}).then(t=>{if(this._mediaStream=t,!this.isOpen())return this.stop();const e=i("video");e.srcObject=t,e.play(),requestAnimationFrame(this.updateCanvas.bind(this,e,this._canvas))}).catch(t=>{console[l](t),this.stop(),this.close()})}capture(){this._dataURL?(this._captureButton.replaceChildren(this._captureIcon),this._captureButton[t].replace("modal-svg-refresh-button","modal-svg-camera-button"),this._submitButton[t].add(`modal-svg-submit-${ht}`),this._dataURL=void 0):(this._captureButton.replaceChildren(this._refreshIcon),this._captureButton[t].replace("modal-svg-camera-button","modal-svg-refresh-button"),this._submitButton[t].remove(`modal-svg-submit-${ht}`),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=Vl.getFileName(this._newFilePrefix||"photo",n);return new File([s],o,{type:s[w]})}}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[$]()}static createCameraModalFunc(t,e,i,s){const n=new Kl(t,e,i,s);return n.openCameraModal.bind(n,n)}}class Jl extends io{constructor(t,e,i){var s,n,o,a,l,c;const h=ue.processPosition(null==(s=null==i?void 0:i.button)?void 0:s.position),u=(null==(a=null==(o=null==(n=null==i?void 0:i.button)?void 0:n[pt])?void 0:o[r])?void 0:a.content)||"Photo",d=Tt.tryCreateConfig("Camera",null==(l=null==i?void 0:i.button)?void 0:l.tooltip),p=(null==(c=null==i?void 0:i.button)?void 0:c[pt])||{};super(Jl.createButtonElement(),'<?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>',h,d,p,u);const m=this.createInnerElementsForStates(this.customStyles);i&&this.addClickEvent(t,e,i.modalContainerStyle,i[k]),this.changeElementsByState(m[pt]),this.reapplyStateStyle(pt)}createInnerElementsForStates(t){return{[pt]:this.createInnerElements("camera-icon",pt,t)}}static createButtonElement(){const e=i();return e[t].add("input-button"),e}addClickEvent(t,e,i,s){const n=Kl.createCameraModalFunc(t,e,i,s);re.assignButtonEvents(this.elementRef,n)}}class Xl{constructor(t,e,i,s){this.elementRef=Xl.createPanelElement(t.inputAreaStyle);const n={},o=this.createFileUploadComponents(t,i,s,n),r=new Bt(t,i,o,e.browserStorage);t.speechToText&&!n.microphone&&(n.microphone={button:new Pl(t,r,e.addNewErrorMessage.bind(e))});const a=new Zl(t,r,e,i,o,n);r.submit=a.submitFromInput.bind(a),Hl.attach(t,i,r,o,a,e.browserStorage),t.submitUserMessage=a.programmaticSubmit.bind(a),n.submit={button:a},t.customButtons&&ya.add(t,n),Xl.addElements(this.elementRef,r,n,s,o,t.dropupStyles),Xl.assignOnInput(t,i,o,r)}static createPanelElement(t){const s=i();return s.id="input",Object.assign(s[e],t),s}createFileUploadComponents(t,e,i,s){var n,o,r,a;const l=new ql(this.elementRef,t.attachmentContainerStyle,e.demo);if(Xl.createUploadButtons(t,e,e.fileTypes||{},l,i,s),null!=(n=e[A])&&n[k]){const n=(null==(o=s[C])?void 0:o.fileType)||l.addType(t,e,e[A][k],C);s[A]={button:new Jl(i,n,e[A])}}if(null!=(r=e.recordAudio)&&r[k]){const i=(null==(a=s[T])?void 0:a.fileType)||l.addType(t,e,e.recordAudio[k],T);s.microphone={button:new Wl(i,e.recordAudio)}}return Ul.isEnabled(l,t.dragAndDrop)&&Ul.create(i,l,t.dragAndDrop),l}static createUploadButtons(t,e,i,s,n,o){Object.keys(i).forEach(r=>{const a=r,l=i[a];if(l[k]){const i=s.addType(t,e,l[k],a),{id:r,svgString:c,dropupText:h}=Aa[a],u=new Nl(n,i,l,r,c,h);o[a]={button:u,fileType:i}}})}static addElements(t,e,i,s,n,o){re.addElements(t,e.elementRef);const r=ma.create(),a=Ca.addButtons(r,i,s,o);pa.set(e.inputElementRef,r,n.elementRef,a),ma.add(t,r)}static assignOnInput(t,e,i,s){e.onInput=e=>{setTimeout(()=>{const n=i.getAllFileData(),o=s.inputElementRef.innerText.trim(),a={[r]:o};n&&(a[k]=n.map(t=>t[x])),is.onInput(t,a,e)})}}}class Ql{static createElements(t,e,s){const n=i();n.id="chat-view";const o=!t.focusMode&&t.upwardsMode;n.classList.add(o?"deep-chat-upwards-mode":"deep-chat-downwards-mode");const r=new da(t,e,s);e.websocket&&Ts.createConnection(e,r);const a=new Xl(t,r,e,n),l=o?r.elementRef.parentElement:r.elementRef;return re.addElements(n,l,a.elementRef),n}static render(t,e,i,s){const n=Ql.createElements(t,i,s);e.replaceChildren(n),i.isCustomView()&&i.setUpView(n,e)}}var Yl=Object.defineProperty,tc=(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&&Yl(e,i,o),o};class ec extends Ls{constructor(){var t;super(),this.getMessages=()=>[],this.submitUserMessage=()=>console.warn(U("submitUserMessage")),this.addMessage=()=>console.warn(U("addMessage")),this.updateMessage=()=>{},this.clearMessages=()=>{},this.focusInput=()=>Rt.focusFromParentElement(this._elementRef),this.refreshMessages=()=>{},this.scrollToBottom=()=>{},this.disableSubmitButton=()=>{},this.setPlaceholderText=()=>{},this._hasBeenRendered=!1,this._auxiliaryStyleApplied=!1,this._elementRef=i(),this._elementRef.id="container",this.attachShadow({mode:"open"}).appendChild(this._elementRef),null==(t=this.shadowRoot)||t.appendChild(Tt.buildElement()),At.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-microphone-active{background-color:#ffe7e7}.deep-chat-openai-realtime-microphone-active:hover{background-color:#ffdede}.deep-chat-openai-realtime-microphone-active:active{background-color:#ffd2d2}.deep-chat-openai-realtime-microphone>*{height:30px;width:30px}.deep-chat-openai-realtime-microphone-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-inline-start: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);inset-inline-start:50%;transform:translate(-50%,-50%);font-size:17px}#deep-chat-openai-realtime-loading{position:absolute;font-size:15px;top:50%;inset-inline-start:50%;transform:translate(-50%,-50%)}#insert-key-view{height:100%;position:relative}#insert-key-contents{text-align:center;position:absolute;inset-block-start:44%;inset-inline-start:50%;transform:translate(-50%,-50%);width:82%;display:flex;max-width:700px}#insert-key-title{margin-bottom:15px}#insert-key-input-container{margin-inline-end: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:inline-end;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;inset-inline-end:-1.7em;inset-block-start:-1.43em}#visible-icon{inset-block-start:-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-inline: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}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,.deep-chat-upwards-mode #messages>div{overflow:auto;overflow-anchor:none}.deep-chat-upwards-mode #messages{height:100%;display:flex;flex-direction:column;justify-content:flex-end}.outer-message-container:last-child{margin-bottom:5px}.inner-message-container{display:flex;margin-inline: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.26}.user-message-text{color:#fff;background-color:#0084ff;margin-inline-end:0px;margin-inline-start:auto}.ai-message-text{color:#000;background-color:#e4e6eb;margin-inline-start:0px;margin-inline-end:auto}.deep-chat-last-group-messages-active{height:100%}#scroll-button{position:absolute;top:75%;left:50%;right:50%;transform:translate(-50%,-50%);transition:opacity .1s ease;display:flex;opacity:0;padding:8px;background-color:#fff;border:.5px solid #000000;justify-content:center;align-items:center;white-space:nowrap;cursor:pointer}#scroll-button:hover{background-color:#fafafa}.loading-history-message-full-view{position:absolute;height:70%;width:100%;display:flex;align-items:center}.deep-chat-upwards-mode #messages .loading-history-message-full-view{height:100%}.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-inline:auto;background-color:#f4c0c0;color:#474747;text-align:center;max-width:95%;margin-top:14px;margin-bottom:10px}.deep-chat-loading-message-dots-container{width:1em;padding-top:.6em;padding-bottom:.6em;padding-inline-start:1.3em;padding-inline-end:.75em}.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{inset-inline-start:-.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{inset-inline-start:.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,.message-bubble>.partial-render-message>p:first-child,.html-wrapper>p:first-child{margin-top:0}.message-bubble>p:last-child,.message-bubble>.partial-render-message:last-child>p,.html-wrapper>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-start{float:inline-start}.audio-player-safari-end{float:inline-end}.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-inline-start:6px;margin-inline-end: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-inline-end:7px}.message-bubble>a{color:inherit}.start-item-position{margin-inline-end:10px}.end-item-position{margin-inline-start:10px}.role-hidden{display:none}.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:start;background-color:#d7d7d73b;padding-inline-start:4px}.file-attachment{width:2.85em;height:2.85em;display:inline-flex;margin-inline-end:.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{inset-inline: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-inline-start:.26rem}.audio-placeholder-text-4-digits{padding-inline-start:.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-inline-start:.13em;margin-inline:auto}.remove-file-attachment-button{height:1.25em;width:1.25em;border:1px solid #cfcfcf;border-radius:25px;background-color:#fff;top:-4px;inset-inline-end:-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:3}.modal-content{border-top:1px solid rgb(217,217,217);border-inline:1px solid rgb(217,217,217);border-start-start-radius:inherit;border-start-end-radius:inherit;background-color:#fff;overflow-y:auto;height:fit-content;max-height:calc(100% - 3.3em);width:100%}.modal-content>p{margin-inline:1em}.modal-content>ul{margin-inline-end: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-end-start-radius:inherit;border-end-end-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;inset-block:0;margin-top:auto;margin-bottom:auto;cursor:pointer;-webkit-user-select:none;user-select:none;margin-inline:.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:2;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-end{position:absolute;inset-inline-end:calc(10% + .35em);inset-block-end:.85em}.inside-start{position:absolute;inset-inline-start:calc(10% + .35em);inset-block-end:.85em}.outside-start{position:absolute;inset-inline-end:calc(11px - .55em);inset-block-end:.88em}.outside-end{position:absolute;inset-inline-start:calc(11px - .55em);inset-block-end:.88em}#upload-images-icon{position:absolute;pointer-events:none;width:1.45em;height:1.45em;inset-inline-start:.11em;inset-block-end:.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;inset-inline-start:.07em;inset-block-end:.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;inset-inline-start:.17em;inset-block-end:.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;inset-inline-start:.23em;inset-block-end:.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;inset-inline-start:.25em;inset-block-end:.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;inset-inline-start:.25em;inset-block-end:.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;inset-inline-start:.35em;inset-block-end:.35em;border-radius:2px}.submit-button-enlarged{scale:1.1;margin-inline:.3em}.loading-submit-button{position:relative;inset-inline-start: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;inset-block-end:-.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}}.tooltip{position:absolute;visibility:hidden;z-index:1;pointer-events:none;padding:5px;padding-inline:7px;background-color:#333;border-radius:5px;width:max-content}.tooltip-text{color:#fff;font-size:13px}.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-svg-text{padding:1px;height:1.65em;display:flex}.input-button-svg-text>svg{padding:.22rem}.input-button-svg-text>div{margin-inline-start:2px}.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-inline:4px;height:1.6em;width:max-content}#custom-icon{height:100%;width:1.2em}.custom-button-container-default{color:#505050}.custom-button-container-default>.dropup-menu-item-icon{color:unset}.custom-button-container-default>svg{filter:brightness(0) saturate(100%) invert(39%) sepia(1%) saturate(0%) hue-rotate(83deg) brightness(93%) contrast(90%)}.custom-button-container-default>.dropup-menu-item-icon>svg{position:absolute;inset-inline-start:.2em}.custom-button-container-active{background-color:#edf7ff;color:#0285ff}.custom-button-container-active:hover,.custom-button-container-active:focus-visible{background-color:#def0ff}.custom-button-container-active:active{background-color:#d2eaff}.custom-button-container-active>svg{filter:brightness(0) saturate(100%) invert(32%) sepia(34%) saturate(4196%) hue-rotate(196deg) brightness(107%) contrast(104%)}.custom-button-container-disabled{color:#aeaeae;cursor:auto}.custom-button-container-disabled>div{pointer-events:none}.custom-button-container-disabled:hover,.custom-button-container-disabled:focus-visible{background-color:transparent}.custom-button-container-disabled:active{background-color:transparent}.custom-button-container-disabled>svg{filter:brightness(0) saturate(100%) invert(67%) sepia(0%) saturate(818%) hue-rotate(28deg) brightness(102%) contrast(100%)}#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-start-adjustment{margin-inline-start:1.5em}.text-input-container-end-adjustment{margin-inline-end:1.5em}.text-input-container-start-small-adjustment{margin-inline-start:1.1em}.text-input-container-start-small-adjustment>.outside-start{inset-inline-end:calc(14px - .55em)}.text-input-container-end-small-adjustment{margin-inline-end:1.1em}.text-input-container-end-small-adjustment>.outside-end{inset-inline-start:calc(14px - .55em)}#text-input{text-align:start;outline:none;word-wrap:break-word;line-break:auto}.text-input-styling{padding:.4em .5em;overflow:overlay;width:100%}.text-input-inner-start-adjustment{padding-inline-start:2.2em}.text-input-inner-end-adjustment{padding-inline-end: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-end>#dropup-menu,.inside-end>#dropup-menu{inset-inline-end:0px}#dropup-icon{position:absolute;pointer-events:none;width:1.16em;height:1.2em;inset-inline-start:.265em;bottom:.43em;filter:brightness(0) saturate(100%) invert(54%) sepia(0%) saturate(724%) hue-rotate(6deg) brightness(92%) contrast(90%)}.dropup-button>*{pointer-events:none}#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-inline-start:.35em;padding-inline-end:.84em;padding-top:.28em;padding-bottom:.28em;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-start-start-radius:inherit;border-start-end-radius:inherit}.dropup-menu-item:last-child{padding-bottom:.45em;border-end-start-radius:inherit;border-end-end-radius:inherit}.dropup-menu-item-icon{width:1.39em;position:relative}.dropup-menu-item-icon>svg{bottom:0!important;top:0!important;margin-bottom:auto;margin-top:auto}#dropup-menu-item-icon-element-custom{position:absolute;pointer-events:none;width:1.21em;height:1.21em;inset-inline-start:.28em;filter:brightness(0) saturate(100%) invert(15%) sepia(0%) saturate(337%) hue-rotate(125deg) brightness(91%) contrast(94%)}.dropup-menu-item-text{margin-inline-start:.56em;margin-top:.08em;width:max-content}#input{width:100%;display:inline-flex;text-align:center;margin-inline:auto;margin-top:auto;position:relative;justify-content:center}#chat-view{height:100%;grid-template-columns:100%}.deep-chat-downwards-mode{display:grid}.deep-chat-upwards-mode{display:flex;flex-direction:column}::-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-inline-start: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(){_t.attemptAppendStyleSheetToHead(this.style),ue.processConnect(this),(!this._activeService||this._activeService.demo)&&(this._activeService=Jr.create(this)),this.auxiliaryStyle&&!this._auxiliaryStyleApplied&&(At.apply(this.auxiliaryStyle,this.shadowRoot),this._auxiliaryStyleApplied=!0),At.applyDefaultStyleToComponent(this.style,this.chatStyle),ue.checkForContainerStyles(this,this._elementRef),this._activeService.key&&this._activeService.validateKeyProperty?n.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):this._activeService instanceof Bs&&!this._activeService.key?this._activeService instanceof Bs&&Ns.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):(this._childElement??(this._childElement=this.children[0]),Ql.render(this,this._elementRef,this._activeService,this._childElement)),this._hasBeenRendered||is.onRender(this),this._hasBeenRendered=!0}disconnectedCallback(){Gs.chat=void 0}}tc([Yr("object")],ec.prototype,"connect"),tc([Yr("object")],ec.prototype,"directConnection"),tc([Yr("object")],ec.prototype,"webModel"),tc([Yr("object")],ec.prototype,"requestBodyLimits"),tc([Yr("function")],ec.prototype,"requestInterceptor"),tc([Yr("function")],ec.prototype,"responseInterceptor"),tc([Yr("function")],ec.prototype,"validateInput"),tc([Yr("function")],ec.prototype,"loadHistory"),tc([Yr("object")],ec.prototype,"chatStyle"),tc([Yr("object")],ec.prototype,"attachmentContainerStyle"),tc([Yr("object")],ec.prototype,"dropupStyles"),tc([Yr("object")],ec.prototype,"inputAreaStyle"),tc([Yr("object")],ec.prototype,"textInput"),tc([Yr("object")],ec.prototype,"defaultInput"),tc([Yr("object")],ec.prototype,"submitButtonStyles"),tc([Yr("object")],ec.prototype,"customButtons"),tc([Yr("string")],ec.prototype,"auxiliaryStyle"),tc([Yr("array")],ec.prototype,"history"),tc([Yr("object")],ec.prototype,"browserStorage"),tc([Yr("object")],ec.prototype,"introMessage"),tc([Yr("object")],ec.prototype,"avatars"),tc([Yr("object")],ec.prototype,"names"),tc([Yr("object")],ec.prototype,"displayLoadingBubble"),tc([Yr("object")],ec.prototype,"errorMessages"),tc([Yr("object")],ec.prototype,"messageStyles"),tc([Yr("object")],ec.prototype,"textToSpeech"),tc([Yr("object")],ec.prototype,"speechToText"),tc([Yr("object")],ec.prototype,"images"),tc([Yr("object")],ec.prototype,"gifs"),tc([Yr("object")],ec.prototype,"camera"),tc([Yr("object")],ec.prototype,"audio"),tc([Yr("object")],ec.prototype,"microphone"),tc([Yr("object")],ec.prototype,"mixedFiles"),tc([Yr("object")],ec.prototype,"dragAndDrop"),tc([Yr("object")],ec.prototype,"htmlWrappers"),tc([Yr("object")],ec.prototype,"htmlClassUtilities"),tc([Yr("object")],ec.prototype,"remarkable"),tc([Yr("object")],ec.prototype,"focusMode"),tc([Yr("boolean")],ec.prototype,"upwardsMode"),tc([Yr("object")],ec.prototype,"scrollButton"),tc([Yr("object")],ec.prototype,"hiddenMessages"),tc([Yr("number")],ec.prototype,"maxVisibleMessages"),tc([Yr("function")],ec.prototype,"onMessage"),tc([Yr("function")],ec.prototype,"onClearMessages"),tc([Yr("function")],ec.prototype,"onComponentRender"),tc([Yr("function")],ec.prototype,"onInput"),tc([Yr("function")],ec.prototype,"onError"),tc([Yr("object")],ec.prototype,"demo"),tc([Yr("object")],ec.prototype,"_insertKeyViewStyles"),customElements.define("deep-chat",ec);export{ec as DeepChat};