deep-chat-dev 9.0.194 → 9.0.196

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.
Files changed (41) hide show
  1. package/custom-elements.json +13927 -10730
  2. package/dist/deepChat.bundle.js +1 -1
  3. package/dist/deepChat.js +3707 -3581
  4. package/dist/services/azure/azureOpenAIAssistantIO.d.ts +10 -0
  5. package/dist/services/azure/azureOpenAIAssistantIO.d.ts.map +1 -0
  6. package/dist/services/azure/azureOpenAIChatIO.d.ts +9 -0
  7. package/dist/services/azure/azureOpenAIChatIO.d.ts.map +1 -0
  8. package/dist/services/azure/utils/azureOpenAIUtils.d.ts +12 -0
  9. package/dist/services/azure/utils/azureOpenAIUtils.d.ts.map +1 -0
  10. package/dist/services/openAI/assistant/openAIAssistantIO.d.ts +9 -0
  11. package/dist/services/openAI/assistant/openAIAssistantIO.d.ts.map +1 -0
  12. package/dist/services/openAI/{openAIAssistantIO.d.ts → assistant/openAIAssistantIOI.d.ts} +30 -15
  13. package/dist/services/openAI/assistant/openAIAssistantIOI.d.ts.map +1 -0
  14. package/dist/services/openAI/{utils → assistant/utils}/openAIAssistantUtils.d.ts +10 -9
  15. package/dist/services/openAI/assistant/utils/openAIAssistantUtils.d.ts.map +1 -0
  16. package/dist/services/openAI/openAIChatIO.d.ts +4 -1
  17. package/dist/services/openAI/openAIChatIO.d.ts.map +1 -1
  18. package/dist/services/openAI/utils/openAIUtils.d.ts +1 -1
  19. package/dist/services/openAI/utils/openAIUtils.d.ts.map +1 -1
  20. package/dist/services/serviceIO.d.ts +2 -2
  21. package/dist/services/serviceIO.d.ts.map +1 -1
  22. package/dist/services/serviceIOFactory.d.ts.map +1 -1
  23. package/dist/types/azure.d.ts +13 -0
  24. package/dist/types/azure.d.ts.map +1 -1
  25. package/dist/types/buttonTypes.d.ts +2 -2
  26. package/dist/types/buttonTypes.d.ts.map +1 -1
  27. package/dist/types/fileTypes.d.ts +1 -1
  28. package/dist/types/fileTypes.d.ts.map +1 -1
  29. package/dist/types/openAI.d.ts +2 -2
  30. package/dist/types/openAI.d.ts.map +1 -1
  31. package/dist/utils/buttons/inputButtons.d.ts +2 -2
  32. package/dist/utils/buttons/inputButtons.d.ts.map +1 -1
  33. package/dist/utils/files/fileTypeButtonIcons.d.ts +2 -2
  34. package/dist/utils/files/fileTypeButtonIcons.d.ts.map +1 -1
  35. package/dist/views/chat/input/buttons/styleAdjustments/inputButtonPositions.d.ts +3 -3
  36. package/dist/views/chat/input/buttons/styleAdjustments/inputButtonPositions.d.ts.map +1 -1
  37. package/dist/views/chat/input/input.d.ts +2 -2
  38. package/dist/views/chat/input/input.d.ts.map +1 -1
  39. package/package.json +1 -1
  40. package/dist/services/openAI/openAIAssistantIO.d.ts.map +0 -1
  41. package/dist/services/openAI/utils/openAIAssistantUtils.d.ts.map +0 -1
@@ -1 +1 @@
1
- class t{static render(t,e){const i=document.createElement("div");i.id="error-view",i.innerText=e,t.replaceChildren(i)}}class e{static onLoad(t){t.innerHTML='<div id="loading-validate-key-property"></div>'}static createElements(){const t=document.createElement("div");return t.id="validate-property-key-view",t}static render(i,s,n){const o=e.createElements(),r={onSuccess:s,onFail:t.render.bind(this,i,"Your 'key' has failed authentication"),onLoad:e.onLoad.bind(this,o)};n.key&&n.verifyKey(n.key,r),i.replaceChildren(o)}}class i{static unsetStyle(t,e){const i=Object.keys(e).reduce(((t,e)=>(t[e]="",t)),{});Object.assign(t.style,i)}static unsetActivityCSSMouseStates(t,e){e.click&&i.unsetStyle(t,e.click),e.hover&&i.unsetStyle(t,e.hover)}static unsetAllCSSMouseStates(t,e){i.unsetActivityCSSMouseStates(t,e),e.default&&i.unsetStyle(t,e.default)}static processStateful(t,e,i){const s=t.default||{},n=Object.assign(JSON.parse(JSON.stringify({...s,...e})),null==t?void 0:t.hover);return{default:s,hover:n,click:Object.assign(JSON.parse(JSON.stringify({...n,...i})),null==t?void 0:t.click)}}static mergeStatefulStyles(t){const e={default:{},hover:{},click:{}};return t.forEach((t=>{e.default=Object.assign(e.default,t.default),e.hover=Object.assign(e.hover,t.hover),e.click=Object.assign(e.click,t.click)})),e}static overwriteDefaultWithAlreadyApplied(t,e){Object.keys(t.default||[]).forEach((i=>{var s;const n=i;e.style[n]&&null!=(s=t.default)&&s[n]&&(t.default[i]=e.style[n])}))}static applyToStyleIfNotDefined(t,e){for(const i in e){const s=e[i];""===t[i]&&s&&(t[i]=s)}}}const s=class t{static attemptAppendStyleSheetToHead(e){if(e.fontFamily&&e.fontFamily!==t.DEFAULT_FONT_FAMILY)return;const i=document.getElementsByTagName("head")[0];if(!Array.from(i.getElementsByTagName("link")).some((e=>e.getAttribute("href")===t.FONT_URL))){const e=document.createElement("link");e.rel="stylesheet",e.href=t.FONT_URL,i.appendChild(e)}}};s.FONT_URL="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap",s.DEFAULT_FONT_FAMILY="'Inter', sans-serif, Avenir, Helvetica, Arial";let n=s;const o=class t{static apply(e,i){if(i)try{t.applyStyleSheet(e,i)}catch{t.addStyleElement(e,i)}}static applyStyleSheet(t,e){const i=new CSSStyleSheet;i.replaceSync(t),e.adoptedStyleSheets.push(i)}static addStyleElement(t,e){const i=document.createElement("style");i.innerHTML=t,e.appendChild(i)}static applyDefaultStyleToComponent(e,s){s&&i.applyToStyleIfNotDefined(e,s),i.applyToStyleIfNotDefined(e,t.DEFAULT_COMPONENT_STYLE)}};o.DEFAULT_COMPONENT_STYLE={height:"350px",width:"320px",border:"1px solid #cacaca",fontFamily:n.DEFAULT_FONT_FAMILY,fontSize:"0.9rem",backgroundColor:"white",position:"relative",overflow:"hidden"};let r=o;var a;let l=((a=class{}).IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),a.IS_CHROMIUM=window.chrome,a);var c=(t=>(t.ESCAPE="Escape",t.ENTER="Enter",t.TAB="Tab",t.ARROW_UP="ArrowUp",t.ARROW_DOWN="ArrowDown",t.ARROW_RIGHT="ArrowRight",t.ARROW_LEFT="ArrowLeft",t.BACKSPACE="Backspace",t.DELETE="Delete",t.META="Meta",t.CONTROL="Control",t))(c||{});const h=class t{static add(e,i,s,n){void 0!==s&&e.addEventListener("keydown",t.onKeyDown.bind(this,s)),e.oninput=t.onInput.bind(this,s,n),e.addEventListener("paste",(t=>{var e;t.preventDefault(),null!=(e=t.clipboardData)&&e.files.length&&i.addFilesToAnyType(Array.from(t.clipboardData.files))}))}static onKeyDown(e,i){const s=i.target.textContent;s&&s.length>=e&&!t.PERMITTED_KEYS.has(i.key)&&!t.isKeyCombinationPermitted(i)&&i.preventDefault()}static isKeyCombinationPermitted(t){return"a"===t.key&&(t.ctrlKey||t.metaKey)}static onInput(t,e,i){const s=i.target,n=s.textContent||"";void 0!==t&&n.length>t&&(s.textContent=n.substring(0,t),v.focusEndOfInput(s)),null==e||e()}};h.PERMITTED_KEYS=new Set([c.BACKSPACE,c.DELETE,c.ARROW_RIGHT,c.ARROW_LEFT,c.ARROW_DOWN,c.ARROW_UP,c.META,c.CONTROL,c.ENTER]);let u=h;class d{static sanitizePastedTextContent(t){var e,i;t.preventDefault();const s=null==(e=t.clipboardData)?void 0:e.getData("text/plain");s&&(null==(i=document.execCommand)||i.call(document,"insertText",!1,s))}}const p=class t{constructor(e,i,s){var n,o;const r=t.processConfig(i,e.textInput);this.elementRef=t.createContainerElement(null==(n=null==r?void 0:r.styles)?void 0:n.container),this._config=r,this.inputElementRef=this.createInputElement(),this.elementRef.appendChild(this.inputElementRef),e.setPlaceholderText=this.setPlaceholderText.bind(this),e.setPlaceholderText((null==(o=this._config.placeholder)?void 0:o.text)||"Ask me anything!"),setTimeout((()=>{u.add(this.inputElementRef,s,this._config.characterLimit,e._validationHandler)}))}static processConfig(t,e){var i;return e??(e={}),e.disabled??(e.disabled=t.isTextInputDisabled),e.placeholder??(e.placeholder={}),(i=e.placeholder).text??(i.text=t.textInputPlaceholderText),e}static createContainerElement(t){const e=document.createElement("div");return e.id="text-input-container",Object.assign(e.style,t),e}static preventAutomaticScrollUpOnNewLine(t){let e;t.addEventListener("keydown",(()=>{e=window.scrollY})),t.addEventListener("input",(()=>{e!==window.scrollY&&window.scrollTo({top:e})}))}clear(){var t;const e=window.scrollY;this.inputElementRef.classList.contains("text-input-disabled")||(Object.assign(this.inputElementRef.style,null==(t=this._config.placeholder)?void 0:t.style),this.inputElementRef.textContent="",v.focusEndOfInput(this.inputElementRef)),l.IS_CHROMIUM&&window.scrollTo({top:e})}createInputElement(){var e,i,s,n;const o=document.createElement("div");return o.id=t.TEXT_INPUT_ID,o.classList.add("text-input-styling"),l.IS_CHROMIUM&&t.preventAutomaticScrollUpOnNewLine(o),"boolean"==typeof this._config.disabled&&!0===this._config.disabled?(o.contentEditable="false",o.classList.add("text-input-disabled")):(o.contentEditable="true",this.addEventListeners(o)),Object.assign(o.style,null==(e=this._config.styles)?void 0:e.text),Object.assign(o.style,null==(i=this._config.placeholder)?void 0:i.style),null!=(n=null==(s=this._config.placeholder)?void 0:s.style)&&n.color||o.setAttribute("textcolor",""),o}removePlaceholderStyle(){var t,e,s,n;!this.inputElementRef.classList.contains("text-input-disabled")&&null!=(t=this._config.placeholder)&&t.style&&(i.unsetStyle(this.inputElementRef,null==(e=this._config.placeholder)?void 0:e.style),Object.assign(this.inputElementRef.style,null==(n=null==(s=this._config)?void 0:s.styles)?void 0:n.text))}addEventListeners(t){var e,i;null!=(e=this._config.styles)&&e.focus&&(t.onfocus=()=>{var t;return Object.assign(this.elementRef.style,null==(t=this._config.styles)?void 0:t.focus)},t.onblur=this.onBlur.bind(this,this._config.styles.focus,null==(i=this._config.styles)?void 0:i.container)),t.addEventListener("keydown",this.onKeydown.bind(this)),t.addEventListener("input",this.onInput.bind(this)),t.addEventListener("paste",d.sanitizePastedTextContent)}onBlur(t,e){i.unsetStyle(this.elementRef,t),e&&Object.assign(this.elementRef.style,e)}onKeydown(t){var e;t.key===c.ENTER&&!t.ctrlKey&&!t.shiftKey&&(t.preventDefault(),null==(e=this.submit)||e.call(this))}onInput(){var t;this.isTextInputEmpty()?Object.assign(this.inputElementRef.style,null==(t=this._config.placeholder)?void 0:t.style):this.removePlaceholderStyle()}setPlaceholderText(t){this.inputElementRef.setAttribute("deep-chat-placeholder-text",t)}isTextInputEmpty(){return""===this.inputElementRef.textContent}};p.TEXT_INPUT_ID="text-input";let m=p;class v{static focusEndOfInput(t){const e=document.createRange();e.selectNodeContents(t),e.collapse(!1);const i=window.getSelection();null==i||i.removeAllRanges(),null==i||i.addRange(e)}static focusFromParentElement(t){const e=t.querySelector(`#${m.TEXT_INPUT_ID}`);e&&(l.IS_SAFARI&&e.focus(),v.focusEndOfInput(e))}}function f(t){return t.charAt(0).toUpperCase()+t.slice(1)}function g(t,e,i,s){const n=`\n${f(e)} message: ${JSON.stringify(t)} \n`,o=i?`${f(e)} message after interceptor: ${function(t){return t&&JSON.stringify(t)}(s)} \n`:"";return n+o}const b="Make sure the events are using {text: string} or {html: string} format.\nYou can also augment them using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor",y={INVALID_KEY:"Invalid API Key",CONNECTION_FAILED:"Failed to connect",INVALID_RESPONSE:function(t,e,i,s){return`${g(t,e,i,s)}Make sure the ${e} message is using the Response format: https://deepchat.dev/docs/connect/#Response \nYou can also augment it using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor`},INVALID_MODEL_REQUEST:function(t,e){const i="request";return`${g(t,i,e)}Make sure the ${i} message is using the {body: {text: string}} format, e.g: {body: {text: "Model Response"}}`},INVALID_MODEL_RESPONSE:function(t,e,i){const s="response";return`${g(t,s,e,i)}Make sure the ${s} message is using the {text: string} format, e.g: {text: "Model Response"}`},INVALID_STREAM_EVENT:b,INVALID_STREAM_EVENT_MIX:"Cannot mix {text: string} and {html: string} responses.",NO_VALID_STREAM_EVENTS_SENT:`No valid stream events were sent.\n${b}`},w=class t{static addElements(t,...e){e.forEach((e=>t.appendChild(e)))}static isScrollbarAtBottomOfElement(e){const i=e.scrollHeight,s=e.clientHeight;return e.scrollTop>=i-s-t.CODE_SNIPPET_GENERATION_JUMP}static cloneElement(t){const e=t.cloneNode(!0);return t.parentNode.replaceChild(e,t),e}static scrollToBottom(t){t.scrollTop=t.scrollHeight}static scrollToTop(t){t.scrollTop=0}};w.CODE_SNIPPET_GENERATION_JUMP=.5;let x=w;const k=class t{static speak(t,e){if(window.SpeechSynthesisUtterance){const i=new SpeechSynthesisUtterance(t);Object.assign(i,e),speechSynthesis.speak(i)}}static processConfig(e,i){const s={};setTimeout((()=>{if("object"==typeof e&&(e.lang&&(s.lang=e.lang),e.pitch&&(s.pitch=e.pitch),e.rate&&(s.rate=e.rate),e.volume&&(s.volume=e.volume),e.voiceName)){const t=window.speechSynthesis.getVoices().find((t=>{var i;return t.name.toLocaleLowerCase()===(null==(i=e.voiceName)?void 0:i.toLocaleLowerCase())}));t&&(s.voice=t)}i(s)}),t.LOAD_VOICES_MS)}};k.LOAD_VOICES_MS=200;let _=k;class S{static checkForContainerStyles(t,e){const i=t.containerStyle;i&&(Object.assign(e.style,i),console.error("The containerStyle property is deprecated since version 1.3.14."),console.error("Please change to using the style property instead: https://deepchat.dev/docs/styles#style"))}static handleResponseProperty(t){return console.error("The {result: ....} response object type is deprecated since version 1.3.0."),console.error("Please change to using the new response object: https://deepchat.dev/docs/connect#Response"),t.result}static processHistory(t){const e=t.initialMessages;if(e)return console.error("The initialMessages property is deprecated since version 2.0.0."),console.error("Please change to using the history property instead: https://deepchat.dev/docs/messages/#history"),e}static processHistoryFile(t){const e=t.file;e&&(console.error("The file property in MessageContent is deprecated since version 1.3.17."),console.error("Please change to using the files array property: https://deepchat.dev/docs/messages/#MessageContent"),t.files=[e])}static processValidateInput(t){const e=t.validateMessageBeforeSending;if(e)return console.error("The validateMessageBeforeSending property is deprecated since version 1.3.24."),console.error("Please change to using validateInput: https://deepchat.dev/docs/interceptors#validateInput"),e}static processSubmitUserMessage(t){return console.error("The submitUserMessage(text: string) argument string type is deprecated since version 1.4.4."),console.error("Please change to using the new argument type: https://deepchat.dev/docs/methods#submitUserMessage"),{text:t}}static flagHTMLUpdateClass(t){var e;null!=(e=t.children[0])&&e.classList.contains("deep-chat-update-message")&&(console.error('The "deep-chat-update-message" html class is deprecated since version 1.4.4.'),console.error("Please change to using {..., overwrite: true} object: https://deepchat.dev/docs/connect#Response"))}static processConnect(t){const e=t;e.request&&(e.connect?Object.assign(e.connect,e.request):e.connect=e.request,console.error("The request property is deprecated since version 2.0.0."),console.error("Please see the connect object: https://deepchat.dev/docs/connect#connect-1"))}static checkForStream(t){const e=t.stream;if(e)return console.error("The stream property has been moved to the connect object in version 2.0.0."),console.error("Please see the connect object: https://deepchat.dev/docs/connect#connect-1"),e}static fireOnNewMessage(t,e){var i;const s=t;s.onNewMessage&&(console.error("The onNewMessage event has been deprecated since version 2.0.0."),console.error("Please see the onMessage event: https://deepchat.dev/docs/events#onMessage"),null==(i=s.onNewMessage)||i.call(s,e)),t.dispatchEvent(new CustomEvent("new-message",{detail:e}))}static processFileConfigConnect(t){const e=t;e.request&&(console.error("The request property in file configuration is deprecated since version 2.0.0."),console.error("Please use the connect property instead: https://deepchat.dev/docs/files"),e.connect||(e.connect=e.request))}}const T=class t{static colorToHex(t){const e=document.createElement("div");return e.style.color=t,document.body.appendChild(e),`#${window.getComputedStyle(e).color.match(/\d+/g).map((t=>parseInt(t).toString(16).padStart(2,"0"))).join("")}`}static setDots(e,i){var s,n,o,r;if(null!=(r=null==(o=null==(n=null==(s=null==i?void 0:i.loading)?void 0:s.message)?void 0:n.styles)?void 0:o.bubble)&&r.color){const s=t.colorToHex(i.loading.message.styles.bubble.color);e.style.setProperty("--loading-message-color",s),e.style.setProperty("--loading-message-color-fade",`${s}33`)}else e.style.setProperty("--loading-message-color","#848484"),e.style.setProperty("--loading-message-color-fade","#55555533")}static setRing(e,i){const{color:s,width:n,height:o,margin:r,border:a}=i||{};if(s){const i=t.colorToHex(s);e.style.setProperty("--loading-history-color",i)}else e.style.setProperty("--loading-history-color","#dbdbdb");e.style.setProperty("--loading-history-height",o||"57px"),e.style.setProperty("--loading-history-width",n||"57px"),e.style.setProperty("--loading-history-margin",r||"7px"),e.style.setProperty("--loading-history-border",a||"6px")}};T.BUBBLE_CLASS="deep-chat-loading-message-bubble",T.DOTS_CONTAINER_CLASS="deep-chat-loading-message-dots-container";let A=T;const j=class t{static hide(e){var i;(i=e.getElementsByClassName(t.CONTAINER_CLASS)[0].style).visibility||(i.visibility="hidden")}static reveal(e){e.getElementsByClassName(t.CONTAINER_CLASS)[0].style.visibility=""}static applyCustomStylesToElements(t,e,i){Object.assign(t.style,i.container),Object.assign(e.style,i.avatar)}static applyCustomStyles(e,i,s,n){var o,r,a,l;if(null!=(o=s.default)&&o.styles&&t.applyCustomStylesToElements(e,i,s.default.styles),n===I.USER_ROLE)null!=(r=s.user)&&r.styles&&t.applyCustomStylesToElements(e,i,s.user.styles);else{null!=(a=s.ai)&&a.styles&&t.applyCustomStylesToElements(e,i,s.ai.styles);const o=null==(l=s[n])?void 0:l.styles;o&&t.applyCustomStylesToElements(e,i,o)}}static createAvatar(e,i){var s,n,o,r,a;const l=document.createElement("img");e===I.USER_ROLE?l.src=(null==(s=null==i?void 0:i.user)?void 0:s.src)||(null==(n=null==i?void 0:i.default)?void 0:n.src)||"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==":l.src=(null==(o=null==i?void 0:i[e])?void 0:o.src)||(null==(r=null==i?void 0:i.ai)?void 0:r.src)||(null==(a=null==i?void 0:i.default)?void 0:a.src)||"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",l.classList.add("avatar");const c=document.createElement("div");return c.classList.add(t.CONTAINER_CLASS),c.appendChild(l),i&&t.applyCustomStyles(c,l,i,e),c}static getPosition(t,e){var i,s,n,o,r,a;let l=null==(s=null==(i=null==e?void 0:e[t])?void 0:i.styles)?void 0:s.position;return t!==I.USER_ROLE&&(l??(l=null==(o=null==(n=null==e?void 0:e.ai)?void 0:n.styles)?void 0:o.position)),l??(l=null==(a=null==(r=null==e?void 0:e.default)?void 0:r.styles)?void 0:a.position),l??(l=t===I.USER_ROLE?"right":"left"),l}static add(e,i,s){const n="boolean"==typeof s?void 0:s,o=t.createAvatar(i,n),r=t.getPosition(i,n);o.classList.add("left"===r?"left-item-position":"right-item-position"),e.insertAdjacentElement("left"===r?"beforebegin":"afterend",o)}};j.CONTAINER_CLASS="avatar-container";let M=j;const C=class t{static hide(e){var i;(i=e.getElementsByClassName(t.NAME_CLASS)[0].style).visibility||(i.visibility="hidden")}static reveal(e){e.getElementsByClassName(t.NAME_CLASS)[0].style.visibility=""}static getPosition(t,e){var i,s,n;let o=null==(i=null==e?void 0:e[t])?void 0:i.position;return t!==I.USER_ROLE&&(o??(o=null==(s=null==e?void 0:e.ai)?void 0:s.position)),o??(o=null==(n=null==e?void 0:e.default)?void 0:n.position),o??(o=t===I.USER_ROLE?"right":"left"),o}static applyStyle(t,e,i){var s,n,o,r;Object.assign(t.style,null==(s=i.default)?void 0:s.style),e===I.USER_ROLE?Object.assign(t.style,null==(n=i.user)?void 0:n.style):(Object.assign(t.style,null==(o=i.ai)?void 0:o.style),Object.assign(t.style,null==(r=i[e])?void 0:r.style))}static getNameText(t,e){var i,s,n,o,r,a;return t===I.USER_ROLE?(null==(i=e.user)?void 0:i.text)||(null==(s=e.default)?void 0:s.text)||"User":t===I.AI_ROLE?(null==(n=e.ai)?void 0:n.text)||(null==(o=e.default)?void 0:o.text)||"AI":(null==(r=e[t])?void 0:r.text)||(null==(a=e.default)?void 0:a.text)||t}static createName(e,i){const s=document.createElement("div");return s.classList.add(t.NAME_CLASS),s.textContent=t.getNameText(e,i),t.applyStyle(s,e,i),s}static add(e,i,s){const n="boolean"==typeof s?{}:s,o=t.createName(i,n),r=t.getPosition(i,n);o.classList.add("left"===r?"left-item-position":"right-item-position"),e.insertAdjacentElement("left"===r?"beforebegin":"afterend",o)}};C.NAME_CLASS="name";let O=C;const E=class t{static getLastElementsByClass(t,e,i){for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n.bubbleElement.classList.contains(e[0])&&!e.slice(1).find((t=>!n.bubbleElement.classList.contains(t)))){if(!i)return n;if(!i.find((t=>n.bubbleElement.classList.contains(t))))return n}}}static getLastMessage(t,e,i){for(let s=t.length-1;s>=0;s-=1)if(t[s].role===e){if(!i)return t[s];if(t[s][i])return t[s]}}static getLastTextToElement(t,e){for(let i=t.length-1;i>=0;i-=1)if(t[i][0]===e)return t[i]}static overwriteMessage(e,i,s,n,o,r){const a=t.getLastElementsByClass(i,[t.getRoleClass(n),r],[A.BUBBLE_CLASS]),l=t.getLastMessage(e,n,o);return l&&(l[o]=s),a}static getRoleClass(t){return`${t}-message`}static fillEmptyMessageElement(e,i){0===i.trim().length&&(e.classList.add(t.EMPTY_MESSAGE_CLASS),e.innerHTML='<div style="color:#00000000">.</div>')}static unfillEmptyMessageElement(e,i){e.classList.contains(t.EMPTY_MESSAGE_CLASS)&&i.trim().length>0&&e.replaceChildren()}static getLastMessageBubbleElement(e){var i,s,n;return Array.from((null==(n=null==(s=null==(i=t.getLastMessageElement(e))?void 0:i.children)?void 0:s[0])?void 0:n.children)||[]).find((t=>t.classList.contains("message-bubble")))}static getLastMessageElement(t){return t.children[t.children.length-1]}static addRoleElements(t,e,i,s){i&&M.add(t,e,i),s&&O.add(t,e,s)}static hideRoleElements(t,e,i){const s=t[t.length-1].innerContainer;e&&M.hide(s),i&&O.hide(s)}static revealRoleElements(t,e,i){e&&M.reveal(t),i&&O.reveal(t)}static updateRefArr(t,e,i){i?t.unshift(e):t.push(e)}};E.AI_ROLE="ai",E.USER_ROLE="user",E.EMPTY_MESSAGE_CLASS="empty-message";let I=E;class P{static mouseUp(t,e){i.unsetAllCSSMouseStates(t,e),Object.assign(t.style,e.default),Object.assign(t.style,e.hover)}static mouseDown(t,e){Object.assign(t.style,e.click)}static mouseLeave(t,e){i.unsetAllCSSMouseStates(t,e),Object.assign(t.style,e.default)}static mouseEnter(t,e){Object.assign(t.style,e.hover)}static add(t,e){t.addEventListener("mouseenter",P.mouseEnter.bind(this,t,e)),t.addEventListener("mouseleave",P.mouseLeave.bind(this,t,e)),t.addEventListener("mousedown",P.mouseDown.bind(this,t,e)),t.addEventListener("mouseup",P.mouseUp.bind(this,t,e))}}const N={"deep-chat-button":{styles:{default:{backgroundColor:"white",padding:"5px",paddingLeft:"7px",paddingRight:"7px",border:"1px solid #c2c2c2",borderRadius:"6px",cursor:"pointer"},hover:{backgroundColor:"#fafafa"},click:{backgroundColor:"#f1f1f1"}}}},q=Object.keys(N);class R{static applySuggestionEvent(t,e){setTimeout((()=>{e.addEventListener("click",(()=>{var i,s;null==(s=t.submitUserMessage)||s.call(t,{text:(null==(i=e.textContent)?void 0:i.trim())||""})}))}))}static isElementTemporary(t){var e;return!!t&&(null==(e=t.bubbleElement.children[0])?void 0:e.classList.contains("deep-chat-temporary-message"))}static doesElementContainDeepChatClass(t){return q.find((e=>t.classList.contains(e)))}static applyEvents(t,e){const i=N[e].events;Object.keys(i||[]).forEach((e=>{t.addEventListener(e,null==i?void 0:i[e])}))}static getProcessedStyles(t,e,s){const n=Array.from(e.classList).reduce(((e,i)=>{var s;const n=null==(s=t[i])?void 0:s.styles;return n&&t[i].styles&&e.push(n),e}),[]),o=N[s].styles;if(o){const t=JSON.parse(JSON.stringify(o));t.default&&i.overwriteDefaultWithAlreadyApplied(t,e),n.unshift(t)}const r=i.mergeStatefulStyles(n);return i.processStateful(r,{},{})}static applyDeepChatUtilities(t,e,i){q.forEach((t=>{const s=i.getElementsByClassName(t);Array.from(s||[]).forEach((i=>{const s=R.getProcessedStyles(e,i,t);L.applyStylesToElement(i,s),R.applyEvents(i,t)}))}));const s=i.getElementsByClassName("deep-chat-suggestion-button");Array.from(s).forEach((e=>R.applySuggestionEvent(t,e)))}}class L{static applyStylesToElement(t,e){const s=i.processStateful(e,{},{});P.add(t,s),Object.assign(t.style,s.default)}static applyEventsToElement(t,e){Object.keys(e).forEach((i=>{const s=e[i];s&&t.addEventListener(i,s)}))}static applyClassUtilitiesToElement(t,e){const{events:i,styles:s}=e;i&&L.applyEventsToElement(t,i),s&&!R.doesElementContainDeepChatClass(t)&&L.applyStylesToElement(t,s)}static applyCustomClassUtilities(t,e){Object.keys(t).forEach((i=>{const s=e.getElementsByClassName(i);Array.from(s).forEach((e=>{t[i]&&L.applyClassUtilitiesToElement(e,t[i])}))}))}static apply(t,e){R.applyDeepChatUtilities(t,t.htmlClassUtilities,e),L.applyCustomClassUtilities(t.htmlClassUtilities,e)}static traverseNodes(t,e){t.nodeType===Node.ELEMENT_NODE&&e.push(t.outerHTML),t.childNodes.forEach((t=>{L.traverseNodes(t,e)}))}static splitHTML(t){const e=(new DOMParser).parseFromString(t,"text/html"),i=[];return e.body.childNodes.forEach((t=>{L.traverseNodes(t,i)})),i}}class B{static addElement(t,e){t.elementRef.appendChild(e),t.elementRef.scrollTop=t.elementRef.scrollHeight}static createElements(t,e,i,s){const n=t.createMessageElementsOnOrientation("",i,s);return n.bubbleElement.classList.add("html-message"),n.bubbleElement.innerHTML=e,n}static overwrite(t,e,i,s){const{messages:n}=t,o=I.overwriteMessage(n,s,e,i,"html","html-message");return o&&(o.bubbleElement.innerHTML=e,L.apply(t,o.outerContainer),S.flagHTMLUpdateClass(o.bubbleElement)),o}static add(t,e,i,s,n,o=!1){var r;if(null!=n&&n.status){const o=this.overwrite(t,e,i,s);if(o)return o;n.status=!1}const a=B.createElements(t,e,i,o);return I.fillEmptyMessageElement(a.bubbleElement,e),L.apply(t,a.outerContainer),S.flagHTMLUpdateClass(a.bubbleElement),t.applyCustomStyles(a,i,!1,null==(r=t.messageStyles)?void 0:r.html),o||B.addElement(t,a.outerContainer),a}}var F;function z(t){return(F=F||document.createElement("textarea")).innerHTML="&"+t+";",F.value}var D=Object.prototype.hasOwnProperty;function $(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 J=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function V(t){return t.indexOf("\\")<0?t:t.replace(J,"$1")}function U(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 H(t){if(t>65535){var e=55296+((t-=65536)>>10),i=56320+(1023&t);return String.fromCharCode(e,i)}return String.fromCharCode(t)}var K=/&([a-z#][a-z0-9]{1,31});/gi,G=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;function Z(t,e){var i=0,s=z(e);return e!==s?s:35===e.charCodeAt(0)&&G.test(e)&&U(i="x"===e[1].toLowerCase()?parseInt(e.slice(2),16):parseInt(e.slice(1),10))?H(i):t}function W(t){return t.indexOf("&")<0?t:t.replace(K,Z)}var X=/[&<>"]/,Q=/[&<>"]/g,Y={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function tt(t){return Y[t]}function et(t){return X.test(t)?t.replace(Q,tt):t}var it={};function st(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?st(t,e+2):e}it.blockquote_open=function(){return"<blockquote>\n"},it.blockquote_close=function(t,e){return"</blockquote>"+nt(t,e)},it.code=function(t,e){return t[e].block?"<pre><code>"+et(t[e].content)+"</code></pre>"+nt(t,e):"<code>"+et(t[e].content)+"</code>"},it.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&&D.call(t,e)}(n.rules.fence_custom,o[0]))return n.rules.fence_custom[o[0]](t,e,i,s,n);l=' class="'+c+et(W(V(r)))+'"'}return"<pre><code"+l+">"+(i.highlight&&i.highlight.apply(i.highlight,[a.content].concat(o))||et(a.content))+"</code></pre>"+nt(t,e)},it.fence_custom={},it.heading_open=function(t,e){return"<h"+t[e].hLevel+">"},it.heading_close=function(t,e){return"</h"+t[e].hLevel+">\n"},it.hr=function(t,e,i){return(i.xhtmlOut?"<hr />":"<hr>")+nt(t,e)},it.bullet_list_open=function(){return"<ul>\n"},it.bullet_list_close=function(t,e){return"</ul>"+nt(t,e)},it.list_item_open=function(){return"<li>"},it.list_item_close=function(){return"</li>\n"},it.ordered_list_open=function(t,e){var i=t[e];return"<ol"+(i.order>1?' start="'+i.order+'"':"")+">\n"},it.ordered_list_close=function(t,e){return"</ol>"+nt(t,e)},it.paragraph_open=function(t,e){return t[e].tight?"":"<p>"},it.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?nt(t,e):"")},it.link_open=function(t,e,i){var s=t[e].title?' title="'+et(W(t[e].title))+'"':"",n=i.linkTarget?' target="'+i.linkTarget+'"':"";return'<a href="'+et(t[e].href)+'"'+s+n+">"},it.link_close=function(){return"</a>"},it.image=function(t,e,i){var s=' src="'+et(t[e].src)+'"',n=t[e].title?' title="'+et(W(t[e].title))+'"':"";return"<img"+s+(' alt="'+(t[e].alt?et(W(V(t[e].alt))):"")+'"')+n+(i.xhtmlOut?" /":"")+">"},it.table_open=function(){return"<table>\n"},it.table_close=function(){return"</table>\n"},it.thead_open=function(){return"<thead>\n"},it.thead_close=function(){return"</thead>\n"},it.tbody_open=function(){return"<tbody>\n"},it.tbody_close=function(){return"</tbody>\n"},it.tr_open=function(){return"<tr>"},it.tr_close=function(){return"</tr>\n"},it.th_open=function(t,e){var i=t[e];return"<th"+(i.align?' style="text-align:'+i.align+'"':"")+">"},it.th_close=function(){return"</th>"},it.td_open=function(t,e){var i=t[e];return"<td"+(i.align?' style="text-align:'+i.align+'"':"")+">"},it.td_close=function(){return"</td>"},it.strong_open=function(){return"<strong>"},it.strong_close=function(){return"</strong>"},it.em_open=function(){return"<em>"},it.em_close=function(){return"</em>"},it.del_open=function(){return"<del>"},it.del_close=function(){return"</del>"},it.ins_open=function(){return"<ins>"},it.ins_close=function(){return"</ins>"},it.mark_open=function(){return"<mark>"},it.mark_close=function(){return"</mark>"},it.sub=function(t,e){return"<sub>"+et(t[e].content)+"</sub>"},it.sup=function(t,e){return"<sup>"+et(t[e].content)+"</sup>"},it.hardbreak=function(t,e,i){return i.xhtmlOut?"<br />\n":"<br>\n"},it.softbreak=function(t,e,i){return i.breaks?i.xhtmlOut?"<br />\n":"<br>\n":"\n"},it.text=function(t,e){return et(t[e].content)},it.htmlblock=function(t,e){return t[e].content},it.htmltag=function(t,e){return t[e].content},it.abbr_open=function(t,e){return'<abbr title="'+et(W(t[e].title))+'">'},it.abbr_close=function(){return"</abbr>"},it.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>"},it.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'},it.footnote_block_close=function(){return"</ol>\n</section>\n"},it.footnote_open=function(t,e){return'<li id="fn'+Number(t[e].id+1).toString()+'" class="footnote-item">'},it.footnote_close=function(){return"</li>\n"},it.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>'},it.dl_open=function(){return"<dl>\n"},it.dt_open=function(){return"<dt>"},it.dd_open=function(){return"<dd>"},it.dl_close=function(){return"</dl>\n"},it.dt_close=function(){return"</dt>\n"},it.dd_close=function(){return"</dd>\n"};var nt=it.getBreak=function(t,e){return(e=st(t,e))<t.length&&"list_item_close"===t[e].type?"":"\n"};function ot(){this.rules=$({},it),this.getBreak=it.getBreak}function rt(){this.t=[],this.i=null}function at(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 lt(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 ct(t,e,i,s){var n,o,r,a,l,c;if(42!==t.charCodeAt(0)||91!==t.charCodeAt(1)||-1===t.indexOf("]:")||((o=lt(n=new at(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 ht(t){var e=W(t);try{e=decodeURI(e)}catch{}return encodeURI(e)}function ut(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=ht(V(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=V(t.src.slice(o,e)),!t.parser.validateLink(n)))&&(t.linkContent=n,t.pos=e,!0)}function dt(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=V(t.src.slice(s+1,e)),!0;92===i&&e+1<n?e+=2:e++}return!1}function pt(t){return t.trim().replace(/\s+/g," ").toUpperCase()}function mt(t,e,i,s){var n,o,r,a,l,c,h,u,d;if(91!==t.charCodeAt(0)||-1===t.indexOf("]:")||((o=lt(n=new at(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(!ut(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&&dt(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=pt(t.slice(1,o)),typeof s.references[d]>"u"&&(s.references[d]={title:u,href:h}),r)}ot.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},ot.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},rt.prototype.o=function(t){for(var e=this.t.length,i=-1;e--;)if(this.t[++i].name===t)return i;return-1},rt.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))}))}))},rt.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},rt.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},rt.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},rt.prototype.push=function(t,e,i){var s=i||{};this.t.push({name:t,enabled:!0,fn:e,alt:s.alt||[]}),this.i=null},rt.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},rt.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},rt.prototype.getRules=function(t){return null===this.i&&this.l(),this.i[t]||[]},at.prototype.pushPending=function(){this.tokens.push({type:"text",content:this.pending,level:this.pendingLevel}),this.pending=""},at.prototype.push=function(t){this.pending&&this.pushPending(),this.tokens.push(t),this.pendingLevel=this.level},at.prototype.cacheSet=function(t,e){for(var i=this.cache.length;i<=t;i++)this.cache.push(0);this.cache[t]=e},at.prototype.cacheGet=function(t){return t<this.cache.length?this.cache[t]:0};var vt=" \n()[]'\".,!?-";function ft(t){return t.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1")}var gt=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,bt=/\((c|tm|r|p)\)/gi,yt={c:"©",r:"®",p:"§",tm:"™"};function wt(t){return t.indexOf("(")<0?t:t.replace(bt,(function(t,e){return yt[e.toLowerCase()]}))}var xt=/['"]/,kt=/['"]/g,_t=/[-\s()\[\]]/;function St(t,e){return!(e<0||e>=t.length)&&!_t.test(t[e])}function Tt(t,e,i){return t.substr(0,e)+i+t.substr(e+1)}var At=[["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=ct(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=mt(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="(^|["+vt.split("").map(ft).join("")+"])("+Object.keys(t.env.abbreviations).map((function(t){return t.substr(1)})).sort((function(t,e){return e.length-t.length})).map(ft).join("|")+")($|["+vt.split("").map(ft).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=wt(s=i.content),gt.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&&!xt.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&&(kt.lastIndex=o,n=kt.exec(s),n);)if(l=!St(s,n.index-1),o=n.index+1,m="'"===n[0],(c=!St(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=Tt(f[h.token].content,h.pos,t.options.quotes[2]),i.content=Tt(i.content,n.index,t.options.quotes[3])):(f[h.token].content=Tt(f[h.token].content,h.pos,t.options.quotes[0]),i.content=Tt(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=Tt(i.content,n.index,"’"))}else m&&(i.content=Tt(i.content,n.index,"’"))}}]];function jt(){this.options={},this.ruler=new rt;for(var t=0;t<At.length;t++)this.ruler.push(At[t][0],At[t][1])}function Mt(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 Ct(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 Ot(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}jt.prototype.process=function(t){var e,i,s;for(e=0,i=(s=this.ruler.getRules("")).length;e<i;e++)s[e](t)},Mt.prototype.isEmpty=function(t){return this.bMarks[t]+this.tShift[t]>=this.eMarks[t]},Mt.prototype.skipEmptyLines=function(t){for(var e=this.lineMax;t<e&&!(this.bMarks[t]+this.tShift[t]<this.eMarks[t]);t++);return t},Mt.prototype.skipSpaces=function(t){for(var e=this.src.length;t<e&&32===this.src.charCodeAt(t);t++);return t},Mt.prototype.skipChars=function(t,e){for(var i=this.src.length;t<i&&this.src.charCodeAt(t)===e;t++);return t},Mt.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},Mt.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 Et={};["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){Et[t]=!0}));var It=/^<([a-zA-Z]{1,15})[\s\/>]/,Pt=/^<\/([a-zA-Z]{1,15})[\s>]/;function Nt(t,e){var i=t.bMarks[e]+t.blkIndent,s=t.eMarks[e];return t.src.substr(i,s-i)}function qt(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 Rt=[["code",function(t,e,i){var s,n;if(t.tShift[e]-t.blkIndent<4)return!1;for(n=s=e+1;s<i;)if(t.isEmpty(s))s++;else{if(!(t.tShift[s]-t.blkIndent>=4))break;n=++s}return t.line=s,t.tokens.push({type:"code",content:t.getLines(e,n,4+t.blkIndent,!0),block:!0,lines:[e,t.line],level:t.level}),!0}],["fences",function(t,e,i,s){var n,o,r,a,l,c=!1,h=t.bMarks[e]+t.tShift[e],u=t.eMarks[e];if(h+3>u||126!==(n=t.src.charCodeAt(h))&&96!==n||(l=h,(o=(h=t.skipChars(h,n))-l)<3)||(r=t.src.slice(h,u).trim()).indexOf("`")>=0)return!1;if(s)return!0;for(a=e;!(++a>=i||(h=l=t.bMarks[a]+t.tShift[a],u=t.eMarks[a],h<u&&t.tShift[a]<t.blkIndent));)if(!(t.src.charCodeAt(h)!==n||t.tShift[a]-t.blkIndent>=4||(h=t.skipChars(h,n),h-l<o||(h=t.skipSpaces(h),h<u)))){c=!0;break}return o=t.tShift[e],t.line=a+(c?1:0),t.tokens.push({type:"fence",params:r,content:t.getLines(e+1,a,o,!0),lines:[e,t.line],level:t.level}),!0},["paragraph","blockquote","list"]],["blockquote",function(t,e,i,s){var n,o,r,a,l,c,h,u,d,p,m,v=t.bMarks[e]+t.tShift[e],f=t.eMarks[e];if(v>f||62!==t.src.charCodeAt(v++)||t.level>=t.options.maxNesting)return!1;if(s)return!0;for(32===t.src.charCodeAt(v)&&v++,l=t.blkIndent,t.blkIndent=0,a=[t.bMarks[e]],t.bMarks[e]=v,o=(v=v<f?t.skipSpaces(v):v)>=f,r=[t.tShift[e]],t.tShift[e]=v-t.bMarks[e],u=t.parser.ruler.getRules("blockquote"),n=e+1;n<i&&!((v=t.bMarks[n]+t.tShift[n])>=(f=t.eMarks[n]));n++)if(62!==t.src.charCodeAt(v++)){if(o)break;for(m=!1,d=0,p=u.length;d<p;d++)if(u[d](t,n,i,!0)){m=!0;break}if(m)break;a.push(t.bMarks[n]),r.push(t.tShift[n]),t.tShift[n]=-1337}else 32===t.src.charCodeAt(v)&&v++,a.push(t.bMarks[n]),t.bMarks[n]=v,o=(v=v<f?t.skipSpaces(v):v)>=f,r.push(t.tShift[n]),t.tShift[n]=v-t.bMarks[n];for(c=t.parentType,t.parentType="blockquote",t.tokens.push({type:"blockquote_open",lines:h=[e,0],level:t.level++}),t.parser.tokenize(t,e,n),t.tokens.push({type:"blockquote_close",level:--t.level}),t.parentType=c,h[1]=t.line,d=0;d<r.length;d++)t.bMarks[d+e]=a[d],t.tShift[d+e]=r[d];return t.blkIndent=l,!0},["paragraph","blockquote","list"]],["hr",function(t,e,i,s){var n,o,r,a=t.bMarks[e],l=t.eMarks[e];if((a+=t.tShift[e])>l||42!==(n=t.src.charCodeAt(a++))&&45!==n&&95!==n)return!1;for(o=1;a<l;){if((r=t.src.charCodeAt(a++))!==n&&32!==r)return!1;r===n&&o++}return!(o<3)&&(s||(t.line=e+1,t.tokens.push({type:"hr",lines:[e,t.line],level:t.level})),!0)},["paragraph","blockquote","list"]],["list",function(t,e,i,s){var n,o,r,a,l,c,h,u,d,p,m,v,f,g,b,y,w,x,k,_,S,T=!0;if((u=Ot(t,e))>=0)v=!0;else{if(!((u=Ct(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)&&(T=!1),b=t.line-e>1&&t.isEmpty(t.line-1),t.blkIndent=a,t.tShift[e]=r,t.tight=l,t.parentType=c,t.tokens.push({type:"list_item_close",level:--t.level}),n=e=t.line,w[1]=n,f=t.bMarks[e],!(n>=i||t.isEmpty(n)||t.tShift[n]<t.blkIndent));){for(S=!1,k=0,_=x.length;k<_;k++)if(x[k](t,n,i,!0)){S=!0;break}if(S)break;if(v){if((u=Ot(t,n))<0)break}else if((u=Ct(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,T&&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(Pt)))return!1}else if(!(o=t.src.slice(a,l).match(It)))return!1;if(!0!==Et[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=Nt(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=Nt(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=Nt(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)&&qt(t,e)>=0;if(h=e+1,t.isEmpty(h)&&++h>i||t.tShift[h]<t.blkIndent||(n=qt(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=qt(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=qt(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 Lt(){this.ruler=new rt;for(var t=0;t<Rt.length;t++)this.ruler.push(Rt[t][0],Rt[t][1],{alt:(Rt[t][2]||[]).slice()})}Lt.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 Bt=/[\n\t]/g,Ft=/\r[\n\u0085]|[\u2424\u2028\u0085]/g,zt=/\u00a0/g;function Dt(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}}Lt.prototype.parse=function(t,e,i,s){var n,o=0,r=0;if(!t)return[];(t=(t=t.replace(zt," ")).replace(Ft,"\n")).indexOf("\t")>=0&&(t=t.replace(Bt,(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 Mt(t,this,e,i,s),this.tokenize(n,n.line,n.lineMax)};for(var $t=[],Jt=0;Jt<256;Jt++)$t.push(0);function Vt(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}function Ut(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&&(Vt(i)&&(r=!1),Vt(s)&&(a=!1))),{can_open:r,can_close:a,delims:n}}"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach((function(t){$t[t.charCodeAt(0)]=1}));var Ht=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Kt=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Gt=["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"],Zt=/^<([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])?)*)>/,Wt=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;function Xt(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 Qt=Xt(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",/[^"'=<>`\x00-\x20]+/)("single_quoted",/'[^']*'/)("double_quoted",/"[^"]*"/)(),Yt=Xt(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",/[a-zA-Z_:][a-zA-Z0-9:._-]*/)("attr_value",Qt)(),te=Xt(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",Yt)(),ee=Xt(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",te)("close_tag",/<\/[A-Za-z][A-Za-z0-9]*\s*>/)("comment",/<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->/)("processing",/<[?].*?[?]>/)("declaration",/<![A-Z]+\s+[^>]*>/)("cdata",/<!\[CDATA\[[\s\S]*?\]\]>/)();var ie=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,se=/^&([a-z][a-z0-9]{1,31});/i;var ne=[["text",function(t,e){for(var i=t.pos;i<t.posMax&&!Dt(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!==$t[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=Ut(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=Ut(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(Ht,"$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(Kt,"$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=lt(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,ut(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&&dt(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=lt(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[pt(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=lt(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(Wt))?!(Gt.indexOf(s[1].toLowerCase())<0||(o=s[0].slice(1,-1),r=ht(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(Zt))&&(r=ht("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(ee),!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(ie))return e||(i="x"===s[1][0].toLowerCase()?parseInt(s[1].slice(1),16):parseInt(s[1],10),t.pending+=U(i)?H(i):H(65533)),t.pos+=s[0].length,!0}else if(s=t.src.slice(n).match(se)){var r=z(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 oe(){this.ruler=new rt;for(var t=0;t<ne.length;t++)this.ruler.push(ne[t][0],ne[t][1]);this.validateLink=re}function re(t){var e=t.trim().toLowerCase();return!(-1!==(e=W(e)).indexOf(":")&&-1!==["vbscript","javascript","file","data"].indexOf(e.split(":")[0]))}oe.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)}},oe.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()},oe.prototype.parse=function(t,e,i,s){var n=new at(t,this,e,i,s);this.tokenize(n)};var ae={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 le(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 ce(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 oe,this.block=new Lt,this.core=new jt,this.renderer=new ot,this.ruler=new rt,this.options={},this.configure(ae[t]),this.set(e||{})}ce.prototype.set=function(t){$(this.options,t)},ce.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)}))},ce.prototype.use=function(t,e){return t(this,e),this},ce.prototype.parse=function(t,e){var i=new le(this,t,e);return this.core.process(i),i.tokens},ce.prototype.render=function(t,e){return e=e||{},this.renderer.render(this.parse(t,e),this.options,e)},ce.prototype.parseInline=function(t,e){var i=new le(this,t,e);return i.inlineMode=!0,this.core.process(i),i.tokens},ce.prototype.renderInline=function(t,e){return e=e||{},this.renderer.render(this.parseInline(t,e),this.options,e)};class he{static instantiate(){const t=window.hljs;return new ce(t?{highlight:function(e,i){if(i&&t.getLanguage(i))try{return t.highlight(i,e).value}catch{console.error("failed to setup the highlight dependency")}try{return t.highlightAuto(e).value}catch{console.error("failed to automatically highlight messages")}return""},html:!1,xhtmlOut:!1,breaks:!0,langPrefix:"language-",linkTarget:"_blank",typographer:!0}:{breaks:!0,linkTarget:"_blank"})}static createNew(){const t=he.instantiate();return t.inline.validateLink=()=>!0,t}}const ue=class t{static addMessage(t,e,i,s,n){var o;"loading"!==i&&(t.applyCustomStyles(e,s,!0,null==(o=t.messageStyles)?void 0:o[i]),n||(t.elementRef.appendChild(e.outerContainer),t.elementRef.scrollTop=t.elementRef.scrollHeight))}static wrapInLink(e,i,s){const n=document.createElement("a");return n.href=i,n.download=s||t.DEFAULT_FILE_NAME,n.target="_blank",n.appendChild(e),n}static isNonLinkableDataUrl(t,e){return!(!e.startsWith("data")||"image"===t)&&("any"===t&&e.startsWith("data:text/javascript")||!e.startsWith("data:image")&&!e.startsWith("data:application"))}static processContent(e,i,s,n){return!s||t.isNonLinkableDataUrl(e,s)?i:t.wrapInLink(i,s,n)}static waitToLoadThenScroll(t){setTimeout((()=>{t.scrollTop=t.scrollHeight}),60)}static scrollDownOnImageLoad(e,i){if(e.startsWith("data"))t.waitToLoadThenScroll(i);else try{fetch(e,{mode:"no-cors"}).catch((()=>{})).finally((()=>{t.waitToLoadThenScroll(i)}))}catch{i.scrollTop=i.scrollHeight}}static reAddFileRefToObject(t,e){var i;null==(i=t.files)||i.forEach(((t,i)=>{var s;t.ref&&null!=(s=e.message.files)&&s[i]&&(e.message.files[i].ref=t.ref)}))}static removeFileRef(t){const e={...t};return delete e.ref,e}static isAudioFile(t){const{type:e,src:i}=t;return"audio"===e||(null==i?void 0:i.startsWith("data:audio"))||i&&/\.(mp3|ogg|wav|aac|webm|4a)$/i.test(i)}static isImageFile(e){const{type:i,src:s}=e;return"image"===i||(null==s?void 0:s.startsWith("data:image"))||s&&t.isImageFileExtension(s)}static isImageFileExtension(t){return/\.(jpg|jpeg|png|gif|bmp)$/i.test(t)}};ue.DEFAULT_FILE_NAME="file";let de=ue;class pe{static onMessage(t,e,i){var s;const n=JSON.parse(JSON.stringify({message:e,isHistory:i,isInitial:i}));de.reAddFileRefToObject(e,n),null==(s=t.onMessage)||s.call(t,n),t.dispatchEvent(new CustomEvent("message",{detail:n})),S.fireOnNewMessage(t,n)}static onClearMessages(t){var e;null==(e=t.onClearMessages)||e.call(t),t.dispatchEvent(new CustomEvent("clear-messages"))}static onRender(t){var e;null==(e=t.onComponentRender)||e.call(t,t),t.dispatchEvent(new CustomEvent("render",{detail:t}))}static onError(t,e){var i;null==(i=t.onError)||i.call(t,e),t.dispatchEvent(new CustomEvent("error",{detail:e}))}}const me=class t{static generateLoadingRingElement(){const t=document.createElement("div");return t.classList.add("loading-history"),t.appendChild(document.createElement("div")),t.appendChild(document.createElement("div")),t.appendChild(document.createElement("div")),t.appendChild(document.createElement("div")),t}static apply(t,e,i){A.setRing(e.bubbleElement,null==i?void 0:i.bubble),null!=i&&i.bubble&&delete(i=JSON.parse(JSON.stringify(i))).bubble,t.applyCustomStyles(e,"history",!1,i)}static addLoadHistoryMessage(e,i,s=!0){var n,o,r,a,l,c,h,u;e.bubbleElement.classList.add(t.CLASS);const d=s?t.FULL_VIEW_CLASS:t.SMALL_CLASS;e.outerContainer.classList.add(d);const p=s?null==(a=null==(r=null==(o=null==(n=i.messageStyles)?void 0:n.loading)?void 0:o.history)?void 0:r.full)?void 0:a.styles:null==(u=null==(h=null==(c=null==(l=i.messageStyles)?void 0:l.loading)?void 0:c.history)?void 0:h.small)?void 0:u.styles;t.apply(i,e,p),i.elementRef.prepend(e.outerContainer)}static createDefaultElements(e){const i=e.createMessageElements("",I.AI_ROLE),{bubbleElement:s}=i,n=t.generateLoadingRingElement();return s.appendChild(n),i}static addMessage(e,i=!0){var s,n,o,r;const a=null==(r=null==(o=null==(n=null==(s=e.messageStyles)?void 0:s.loading)?void 0:n.history)?void 0:o.full)?void 0:r.html,l=a?B.createElements(e,a,I.AI_ROLE,!0):t.createDefaultElements(e);return t.addLoadHistoryMessage(l,e,i),l}static changeFullViewToSmall(e,i){var s,n,o,r,a,l,c,h;if(null!=i&&i.outerContainer.classList.contains(t.FULL_VIEW_CLASS)){i.outerContainer.classList.replace(t.FULL_VIEW_CLASS,t.SMALL_CLASS);const u=null==(r=null==(o=null==(n=null==(s=e.messageStyles)?void 0:s.loading)?void 0:n.history)?void 0:o.small)?void 0:r.styles;u&&t.apply(e,i,u);const d=null==(h=null==(c=null==(l=null==(a=e.messageStyles)?void 0:a.loading)?void 0:l.history)?void 0:c.small)?void 0:h.html;d&&(i.bubbleElement.innerHTML=d)}}};me.CLASS="loading-history-message",me.FULL_VIEW_CLASS="loading-history-message-full-view",me.SMALL_CLASS="loading-history-message-small";let ve=me;class fe{static applyCustomStylesToElements(t,e,i){if(i&&(Object.assign(t.outerContainer.style,i.outerContainer),Object.assign(t.innerContainer.style,i.innerContainer),Object.assign(t.bubbleElement.style,i.bubble),e)){const e=t.bubbleElement.children[0],s="a"!==e.tagName.toLocaleLowerCase()?e:e.children[0];Object.assign(s.style,i.media)}}static applySideStyles(t,e,i,s){s&&(fe.applyCustomStylesToElements(t,i,s.shared),e===I.USER_ROLE?fe.applyCustomStylesToElements(t,i,s.user):(fe.applyCustomStylesToElements(t,i,s.ai),fe.applyCustomStylesToElements(t,i,s[e])))}static isElementsStyles(t){return!!(t.outerContainer||t.innerContainer||t.bubble||t.media)}static applyCustomStyles(t,e,i,s,n){var o;n&&t.default!==n?fe.isElementsStyles(n)?(fe.applyCustomStylesToElements(e,s,null==(o=t.default)?void 0:o.shared),fe.applyCustomStylesToElements(e,s,n)):(fe.applySideStyles(e,i,s,t.default),fe.applySideStyles(e,i,s,n)):fe.applySideStyles(e,i,s,t.default)}static extractParticularSharedStyles(t,e){if(null==e||!e.shared)return;const i=e.shared,s={outerContainer:{},innerContainer:{},bubble:{},media:{}};return t.forEach((t=>{var e,n,o,r;s.outerContainer[t]=(null==(e=i.outerContainer)?void 0:e[t])||"",s.innerContainer[t]=(null==(n=i.innerContainer)?void 0:n[t])||"",s.bubble[t]=(null==(o=i.bubble)?void 0:o[t])||"",s.media[t]=(null==(r=i.media)?void 0:r[t])||""})),s}}class ge{constructor(t){this.messageElementRefs=[],this.messages=[],this.htmlClassUtilities={},this.textElementsToText=[],this.elementRef=ge.createContainerElement(),this.messageStyles=t.messageStyles,this._remarkable=he.createNew(),this._avatars=t.avatars,this._names=t.names,this._onMessage=pe.onMessage.bind(this,t),t.htmlClassUtilities&&(this.htmlClassUtilities=t.htmlClassUtilities),setTimeout((()=>{this.submitUserMessage=t.submitUserMessage}))}static createContainerElement(){const t=document.createElement("div");return t.id="messages",t}addNewTextMessage(t,e,i,s=!1){if(null!=i&&i.status){const s=this.overwriteText(e,t,this.messageElementRefs);if(s)return s;i.status=!1}const n=s?this.createAndPrependNewMessageElement(t,e,s):this.createAndAppendNewMessageElement(t,e);n.bubbleElement.classList.add("text-message"),this.applyCustomStyles(n,e,!1),I.fillEmptyMessageElement(n.bubbleElement,t);const o=[n,t];return I.updateRefArr(this.textElementsToText,o,s),n}overwriteText(t,e,i){const s=I.overwriteMessage(this.messages,i,e,t,"text","text-message");if(s){this.renderText(s.bubbleElement,e);const t=I.getLastTextToElement(this.textElementsToText,s);t&&(t[1]=e)}return s}createAndAppendNewMessageElement(t,e){const i=this.createNewMessageElement(t,e);return this.elementRef.appendChild(i.outerContainer),setTimeout((()=>x.scrollToBottom(this.elementRef))),i}createAndPrependNewMessageElement(t,e,i){var s;const n=this.createNewMessageElement(t,e,i);if(i&&null!=(s=this.elementRef.firstChild)&&s.classList.contains("deep-chat-intro")){this.elementRef.firstChild.insertAdjacentElement("afterend",n.outerContainer);const t=this.messageElementRefs[0];this.messageElementRefs[0]=this.messageElementRefs[1],this.messageElementRefs[1]=t}else this.elementRef.insertBefore(n.outerContainer,this.elementRef.firstChild);return n}createMessageElementsOnOrientation(t,e,i){return i?this.createAndPrependNewMessageElement(t,e,!0):this.createNewMessageElement(t,e)}createNewMessageElement(t,e,i=!1){var s;null==(s=this._introPanel)||s.hide();const n=this.messageElementRefs[this.messageElementRefs.length-1];return ve.changeFullViewToSmall(this,n),ge.isTemporaryElement(n)&&(this.revealRoleElementsIfTempRemoved(n,e),n.outerContainer.remove(),this.messageElementRefs.pop()),this.createMessageElements(t,e,i)}revealRoleElementsIfTempRemoved(t,e){if((this._avatars||this._names)&&R.isElementTemporary(t)){const i=this.messageElementRefs[this.messageElementRefs.length-2];i&&this.messages[this.messages.length-1]&&!t.bubbleElement.classList.contains(I.getRoleClass(e))&&I.revealRoleElements(i.innerContainer,this._avatars,this._names)}}static isTemporaryElement(t){return ge.isLoadingMessage(t)||R.isElementTemporary(t)}createMessageElements(t,e,i=!1){const s=ge.createBaseElements(),{outerContainer:n,innerContainer:o,bubbleElement:r}=s;return n.appendChild(o),this.addInnerContainerElements(r,t,e),I.updateRefArr(this.messageElementRefs,s,i),s}static createBaseElements(){const t=document.createElement("div"),e=document.createElement("div");e.classList.add("inner-message-container"),t.appendChild(e),t.classList.add("outer-message-container");const i=document.createElement("div");return i.classList.add("message-bubble"),e.appendChild(i),{outerContainer:t,innerContainer:e,bubbleElement:i}}addInnerContainerElements(t,e,i){var s;return(null==(s=this.messages[this.messages.length-1])?void 0:s.role)===i&&!this.isLastMessageError()&&I.hideRoleElements(this.messageElementRefs,!!this._avatars,!!this._names),t.classList.add("message-bubble",I.getRoleClass(i),i===I.USER_ROLE?"user-message-text":"ai-message-text"),this.renderText(t,e),I.addRoleElements(t,i,this._avatars,this._names),{bubbleElement:t}}applyCustomStyles(t,e,i,s){t&&this.messageStyles&&fe.applyCustomStyles(this.messageStyles,t,e,i,s)}static createMessageContent(t){const{text:e,files:i,html:s,_sessionId:n,role:o}=t,r={role:o||I.AI_ROLE};return e&&(r.text=e),i&&(r.files=i),s&&(r.html=s),!e&&!i&&!s&&(r.text=""),n&&(r._sessionId=n),r}removeMessage(t){t.outerContainer.remove();const e=this.messageElementRefs.findIndex((e=>e===t));this.messageElementRefs.splice(e,1)}removeLastMessage(){this.messageElementRefs[this.messageElementRefs.length-1].outerContainer.remove(),this.messageElementRefs.pop()}isLastMessageError(){var t;return null==(t=I.getLastMessageBubbleElement(this.elementRef))?void 0:t.classList.contains("error-message-text")}static isLoadingMessage(t){return null==t?void 0:t.bubbleElement.classList.contains(A.BUBBLE_CLASS)}sendClientUpdate(t,e=!1){var i;null==(i=this._onMessage)||i.call(this,t,e)}renderText(t,e){t.innerHTML=this._remarkable.render(e),0===t.innerText.trim().length&&(t.innerText=e)}refreshTextMessages(){this._remarkable=he.createNew(),this.textElementsToText.forEach((t=>{this.renderText(t[0].bubbleElement,t[1])}))}}const be=class t{constructor(t){this._fileAdded=!1,this._streamedContent="",this._streamType="",this._hasStreamEnded=!1,this._messages=t}upsertStreamedMessage(t){var e;if(this._hasStreamEnded)return;if(void 0===(null==t?void 0:t.text)&&void 0===(null==t?void 0:t.html))return console.error(y.INVALID_STREAM_EVENT);const i=(null==t?void 0:t.text)||(null==t?void 0:t.html)||"",s=x.isScrollbarAtBottomOfElement(this._messages.elementRef),n=void 0!==(null==t?void 0:t.text)?"text":"html";if(this._elements||""!==this._streamedContent){if(this._streamType!==n)return console.error(y.INVALID_STREAM_EVENT_MIX);this.updateBasedOnType(i,n,null==(e=this._elements)?void 0:e.bubbleElement,null==t?void 0:t.overwrite)}else this.setInitialState(n,i,null==t?void 0:t.role);s&&x.scrollToBottom(this._messages.elementRef)}setInitialState(e,i,s){this._streamType=e,s??(s=I.AI_ROLE),this._elements="text"===e?this._messages.addNewTextMessage(i,s):B.add(this._messages,i,s,this._messages.messageElementRefs),this._elements.bubbleElement.classList.add(t.MESSAGE_CLASS),this._streamedContent=i,this._activeMessageRole=s,this._message={role:this._activeMessageRole,[e]:this._streamedContent},this._messages.messages.push(this._message)}updateBasedOnType(t,e,i,s=!1){I.unfillEmptyMessageElement(i,t),("text"===e?this.updateText:this.updateHTML).bind(this)(t,i,s)}updateText(t,e,i){this._streamedContent=i?t:this._streamedContent+t,this._messages.textElementsToText[this._messages.textElementsToText.length-1][1]=this._streamedContent,this._messages.renderText(e,this._streamedContent)}updateHTML(e,i,s){if(s)this._streamedContent=e,i.innerHTML=e;else{const s=document.createElement("span");s.innerHTML=e,i.appendChild(s),this._streamedContent=t.HTML_CONTENT_PLACEHOLDER}}finaliseStreamedMessage(){var e,i;const{textElementsToText:s}=this._messages;if(!this._endStreamAfterOperation&&(!this._fileAdded||this._elements)){if(!this._elements)throw Error(y.NO_VALID_STREAM_EVENTS_SENT);null!=(e=this._elements.bubbleElement)&&e.classList.contains(t.MESSAGE_CLASS)&&("text"===this._streamType?(s[s.length-1][1]=this._streamedContent,this._message&&(this._message.text=this._streamedContent),this._messages.textToSpeech&&_.speak(this._streamedContent,this._messages.textToSpeech)):"html"===this._streamType&&(this._streamedContent===t.HTML_CONTENT_PLACEHOLDER&&(this._streamedContent=(null==(i=this._elements.bubbleElement)?void 0:i.innerHTML)||""),this._elements&&L.apply(this._messages,this._elements.outerContainer),this._message&&(this._message.html=this._streamedContent)),this._elements.bubbleElement.classList.remove(t.MESSAGE_CLASS),this._message&&this._messages.sendClientUpdate(ge.createMessageContent(this._message),!1),this._hasStreamEnded=!0)}}markFileAdded(){this._fileAdded=!0}newMessage(){this.finaliseStreamedMessage(),this._elements=void 0,this._streamedContent="",this._fileAdded=!1,this._hasStreamEnded=!1,this._activeMessageRole=void 0}async endStreamAfterFileDownloaded(t,e){var i;this._endStreamAfterOperation=!0;const{text:s,files:n}=await e();s&&this.updateBasedOnType(s,"text",null==(i=this._elements)?void 0:i.bubbleElement,!0),this._endStreamAfterOperation=!1,this.finaliseStreamedMessage(),n&&t.addNewMessage({files:n})}};be.MESSAGE_CLASS="streamed-message",be.HTML_CONTENT_PLACEHOLDER="htmlplaceholder";let ye=be;const we=class t{static async tempRemoveContentHeader(e,i,s){if(null==e||!e.headers)throw new Error("Request settings have not been set up");const n=e.headers[t.CONTENT_TYPE];let o;delete e.headers[t.CONTENT_TYPE];try{o=await i(s)}catch(i){throw e.headers[t.CONTENT_TYPE]=n,i}return e.headers[t.CONTENT_TYPE]=n,o}static displayError(t,e,i="Service error, please try again."){if(console.error(e),"object"==typeof e)return e instanceof Error?t.addNewErrorMessage("service",e.message):Array.isArray(e)||"string"==typeof e.error?t.addNewErrorMessage("service",e):0===Object.keys(e).length?t.addNewErrorMessage("service",i):t.addNewErrorMessage("service",JSON.stringify(e));t.addNewErrorMessage("service",e)}static fetch(t,e,i,s){var n,o;const r={method:(null==(n=t.connectSettings)?void 0:n.method)||"POST",headers:e};return"GET"!==r.method&&(r.body=i?JSON.stringify(s):s),t.connectSettings.credentials&&(r.credentials=t.connectSettings.credentials),fetch((null==(o=t.connectSettings)?void 0:o.url)||t.url||"",r)}static processResponseByType(t){const e=t.headers.get("content-type");return null!=e&&e.includes("application/json")?t.json():null!=e&&e.includes("text/plain")||!e?t:t.blob()}static async processRequestInterceptor(t,e){var i;const s=await(null==(i=t.requestInterceptor)?void 0:i.call(t,e))||e,n=s,o=s;return{body:n.body,headers:n.headers,error:o.error}}static validateResponseFormat(t){return t&&"object"==typeof t&&("string"==typeof t.error||"string"==typeof t.text||"string"==typeof t.html||Array.isArray(t.files))}static onInterceptorError(t,e,i){t.addNewErrorMessage("service",e),null==i||i()}};we.CONTENT_TYPE="Content-Type";let xe=we;function ke(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 _e="text/event-stream",Se="last-event-id";function Te(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=_e),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??Ae;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,ke(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[Se]=t:delete d[Se]}),(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 Ae(t){const e=t.headers.get("content-type");if(null==e||!e.startsWith(_e))throw new Error(`Expected content-type to be ${_e}, Actual: ${e}`)}class je{static async request(t,e,i,s=!0,n=!1){var o,r,a,l,c,h;const u={body:e,headers:null==(o=t.connectSettings)?void 0:o.headers},{body:d,headers:p,error:m}=await xe.processRequestInterceptor(t.deepChat,u),{onOpen:v,onClose:f,abortStream:g}=t.streamHandlers;if(m)return xe.onInterceptorError(i,m,f);if(null!=(r=t.connectSettings)&&r.handler)return Ee.stream(t,d,i);if((null==(a=t.connectSettings)?void 0:a.url)===Ce.URL)return Ce.requestStream(i,t.streamHandlers);const b=new ye(i),y=xe.fetch.bind(this,t,p,s);return Te((null==(l=t.connectSettings)?void 0:l.url)||t.url||"",{method:(null==(c=t.connectSettings)?void 0:c.method)||"POST",headers:p,credentials:null==(h=t.connectSettings)?void 0:h.credentials,body:s?JSON.stringify(d):d,openWhenHidden:!0,async onopen(t){if(t.ok)return v();throw await xe.processResponseByType(t)},async onmessage(e){var s,n,o;if(JSON.stringify(e.data)!==JSON.stringify("[DONE]")){let r;try{r=JSON.parse(e.data)}catch{r={}}const a=await(null==(n=(s=t.deepChat).responseInterceptor)?void 0:n.call(s,r))||r;null==(o=t.extractResultData)||o.call(t,a,y,d).then((e=>{t.asyncCallInProgress&&e&&""!==e.text?(je.simulate(i,t.streamHandlers,e),f(),t.asyncCallInProgress=!1):je.upsertWFiles(i,b.upsertStreamedMessage.bind(b),b,e)})).catch((t=>xe.displayError(i,t)))}},onerror(t){throw f(),t},onclose(){if(!t.asyncCallInProgress)try{b.finaliseStreamedMessage(),f()}catch(t){if(!n)throw t}},signal:g.signal}).catch((e=>{var s;i.isLastMessageError()||null==(s=t.extractResultData)||s.call(t,e).then((()=>{xe.displayError(i,e)})).catch((t=>{xe.displayError(i,t)}))})),b}static simulate(t,e,i){const s=e;if(i.files&&t.addNewMessage({sendUpdate:!1,ignoreText:!0,...i},!1),i.text){e.onOpen();const n=i.text.split("");je.populateMessages(n,new ye(t),s,"text")}if(i.html){e.onOpen();const n=L.splitHTML(i.html);je.populateMessages(n,new ye(t),s,"html")}}static populateMessages(t,e,i,s,n=0){const o=t[n];if(o){e.upsertStreamedMessage({[s]:o});const r=setTimeout((()=>{je.populateMessages(t,e,i,s,n+1)}),i.simulationInterim||6);i.abortStream.abort=()=>{je.abort(r,e,i.onClose)}}else e.finaliseStreamedMessage(),i.onClose()}static isSimulation(t){return"object"==typeof t&&!!t.simulation}static isSimulatable(t,e){return je.isSimulation(t)&&e&&(e.text||e.html)}static abort(t,e,i){clearTimeout(t),e.finaliseStreamedMessage(),i()}static upsertWFiles(t,e,i,s){if(null!=s&&s.text||null!=s&&s.html){const t=e(s);i??(i=t||void 0)}null!=s&&s.files&&(t.addNewMessage({files:s.files}),null==i||i.markFileAdded())}}const Me=class t{static generateResponse(t){const e=t.messages[t.messages.length-1];if(e.files&&e.files.length>0){if(e.files.length>1)return"These are interesting files!";const t=e.files[0];return t.src&&t.src.startsWith("data:image/gif")?"That is a nice gif!":"image"===t.type?"That is a nice image!":"audio"===t.type?"I like the sound of that!":"That is an interesting file!"}if(e.text){if("?"===e.text.charAt(e.text.length-1))return"I'm sorry but I can't answer that question...";if(e.text.includes("updog"))return"What's updog?"}return"Hi there! This is a demo response!"}static getCustomResponse(t,e){return"function"==typeof t?t(e):t}static getResponse(e){return e.customDemoResponse?t.getCustomResponse(e.customDemoResponse,e.messages[e.messages.length-1]):{text:t.generateResponse(e)}}static request(e,i){const s=t.getResponse(i);setTimeout((async()=>{var t,n;const o=await(null==(n=(t=e.deepChat).responseInterceptor)?void 0:n.call(t,s))||s;o.error?(i.addNewErrorMessage("service",o.error),e.completionsHandlers.onFinish()):je.isSimulatable(e.stream,o)?je.simulate(i,e.streamHandlers,o):(i.addNewMessage(o),e.completionsHandlers.onFinish())}),400)}static requestStream(e,i){setTimeout((()=>{const s=t.getResponse(e);je.simulate(e,i,s)}),400)}};Me.URL="deep-chat-demo";let Ce=Me;class Oe{static setup(t){t.connectSettings.url!==Ce.URL&&(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(!Oe.isElementPresentInDOM(t.deepChat))return;const i=t.connectSettings.websocket;if(i){if(t.connectSettings.handler)return Ee.websocket(t,e);try{const s="boolean"!=typeof i?i:void 0,n=new WebSocket(t.connectSettings.url||"",s);t.websocket=n,t.websocket.onopen=()=>{var i,s;e.removeError(),t.websocket&&"object"==typeof t.websocket&&Oe.assignListeners(t,n,e),null==(s=(i=t.deepChat)._validationHandler)||s.call(i)},t.websocket.onerror=i=>{console.error(i),Oe.retryConnection(t,e)}}catch(i){console.error(i),Oe.retryConnection(t,e)}}}static retryConnection(t,e){var i,s;null==(s=(i=t.deepChat)._validationHandler)||s.call(i),Oe.isElementPresentInDOM(t.deepChat)&&(t.websocket="pending",e.isLastMessageError()||e.addNewErrorMessage("service","Connection error"),setTimeout((()=>{Oe.createConnection(t,e)}),5e3))}static assignListeners(t,e,i){const s={};e.onmessage=async e=>{var n,o;if(t.extractResultData)try{const r=JSON.parse(e.data),a=await(null==(o=(n=t.deepChat).responseInterceptor)?void 0:o.call(n,r))||r,l=await t.extractResultData(a);if(!l||"object"!=typeof l)throw Error(y.INVALID_RESPONSE(r,"server",!!t.deepChat.responseInterceptor,a));if(je.isSimulation(t.stream)){const e=Oe.stream.bind(this,t,i,s),n=s[r.role||I.AI_ROLE];je.upsertWFiles(i,e,n,l)}else i.addNewMessage(l)}catch(t){xe.displayError(i,t,"Error in server message")}},e.onclose=()=>{console.error("Connection closed"),i.isLastMessageError()||i.addNewErrorMessage("service","Connection error"),t.stream&&t.streamHandlers.abortStream.abort(),Oe.createConnection(t,i)}}static async sendWebsocket(t,e,i,s=!0){var n,o;const r=t.websocket;if(!r||"pending"===r)return;const a={body:e,headers:null==(n=t.connectSettings)?void 0:n.headers},{body:l,error:c}=await xe.processRequestInterceptor(t.deepChat,a);if(c)return i.addNewErrorMessage("service",c);if(!Oe.isWebSocket(r))return r.newUserMessage.listener(l);const h=s?JSON.stringify(l):l;if((null==(o=t.connectSettings)?void 0:o.url)===Ce.URL)return Ce.request(t,i);void 0===r.readyState||r.readyState!==r.OPEN?(console.error("Connection is not open"),i.isLastMessageError()||i.addNewErrorMessage("service","Connection error")):(r.send(JSON.stringify(h)),t.completionsHandlers.onFinish())}static canSendMessage(t){return!t||"pending"!==t&&(Oe.isWebSocket(t)?void 0!==t.readyState&&t.readyState===t.OPEN:t.isOpen)}static isWebSocket(t){return void 0!==t.send}static stream(t,e,i,s){if(!s)return;const n=t.stream.simulation;if("string"==typeof n){const t=s.role||I.AI_ROLE,o=i[t];s.text===n||s.html===n?(null==o||o.finaliseStreamedMessage(),delete i[t]):(i[t]??(i[t]=new ye(e)),i[t].upsertStreamedMessage(s))}else je.simulate(e,t.streamHandlers,s)}}class Ee{static async request(t,e,i){var s,n;let o=!0;const r=Ee.generateOptionalSignals();null==(n=(s=t.connectSettings).handler)||n.call(s,e,{...r,onResponse:async e=>{var s,n;if(!o)return;o=!1;const r=await(null==(n=(s=t.deepChat).responseInterceptor)?void 0:n.call(s,e))||e;xe.validateResponseFormat(r)?"string"==typeof r.error?(console.error(r.error),i.addNewErrorMessage("service",r.error),t.completionsHandlers.onFinish()):je.isSimulatable(t.stream,r)?je.simulate(i,t.streamHandlers,r):(i.addNewMessage(r),t.completionsHandlers.onFinish()):(console.error(y.INVALID_RESPONSE(e,"server",!!t.deepChat.responseInterceptor,r)),i.addNewErrorMessage("service","Error in server message"),t.completionsHandlers.onFinish())}})}static attemptToFinaliseStream(t,e){try{const i=e.messageElementRefs[e.messageElementRefs.length-1];ge.isLoadingMessage(i)?e.removeLastMessage():t.finaliseStreamedMessage()}catch(t){console.error(t),e.addNewErrorMessage("service",t)}}static stream(t,e,i){var s,n;let o=!0,r=!1;const a=new ye(i);t.streamHandlers.abortStream.abort=()=>{Ee.attemptToFinaliseStream(a,i),t.streamHandlers.onClose(),o=!1};const l=Ee.generateOptionalSignals();null==(n=(s=t.connectSettings).handler)||n.call(s,e,{...l,onOpen:()=>{r||!o||(t.streamHandlers.onOpen(),r=!0)},onResponse:async e=>{var s,n;if(!o)return;const r=await(null==(n=(s=t.deepChat).responseInterceptor)?void 0:n.call(s,e))||e;xe.validateResponseFormat(r)?r.error?(console.error(r.error),a.finaliseStreamedMessage(),i.addNewErrorMessage("service",r.error),t.streamHandlers.onClose(),o=!1):je.upsertWFiles(i,a.upsertStreamedMessage.bind(a),a,r):console.error(y.INVALID_RESPONSE(e,"server",!!t.deepChat.responseInterceptor,r))},onClose:()=>{o&&(Ee.attemptToFinaliseStream(a,i),t.streamHandlers.onClose(),o=!1)},stopClicked:t.streamHandlers.stopClicked})}static websocket(t,e){var i,s;const n={isOpen:!1,newUserMessage:{listener:()=>{}},roleToStream:{}};t.websocket=n;const o=Ee.generateOptionalSignals();null==(s=(i=t.connectSettings).handler)||s.call(i,void 0,{...o,onOpen:()=>{e.removeError(),n.isOpen=!0},onResponse:async i=>{var s,o;if(!n.isOpen)return;const r=await(null==(o=(s=t.deepChat).responseInterceptor)?void 0:o.call(s,i))||i;if(xe.validateResponseFormat(r))if("string"==typeof r.error)console.error(r.error),e.isLastMessageError()||e.addNewErrorMessage("service",r.error);else if(je.isSimulation(t.stream)){const s=Oe.stream.bind(this,t,e,n.roleToStream),o=n.roleToStream[i.role||I.AI_ROLE];je.upsertWFiles(e,s,o,i)}else e.addNewMessage(r);else console.error(y.INVALID_RESPONSE(i,"server",!!t.deepChat.responseInterceptor,r)),e.addNewErrorMessage("service","Error in server message")},onClose:()=>{n.isOpen=!1},newUserMessage:n.newUserMessage})}static generateOptionalSignals(){return{onClose:()=>{},onOpen:()=>{},stopClicked:{listener:()=>{}},newUserMessage:{listener:()=>{}}}}}class Ie{static async request(t,e,i,s=!0){var n,o,r;const a={body:e,headers:null==(n=t.connectSettings)?void 0:n.headers},{body:l,headers:c,error:h}=await xe.processRequestInterceptor(t.deepChat,a),{onFinish:u}=t.completionsHandlers;if(h)return xe.onInterceptorError(i,h,u);if(null!=(o=t.connectSettings)&&o.handler)return Ee.request(t,l,i);if((null==(r=t.connectSettings)?void 0:r.url)===Ce.URL)return Ce.request(t,i);let d=!0;const p=xe.fetch.bind(this,t,c,s);p(l).then((t=>(d=!!t.ok,t))).then((t=>xe.processResponseByType(t))).then((async e=>{var s,n;if(!t.extractResultData)return;const o=await(null==(n=(s=t.deepChat).responseInterceptor)?void 0:n.call(s,e))||e,r=await t.extractResultData(o,p,l);if(!d)throw e;if(!r||"object"!=typeof r)throw Error(y.INVALID_RESPONSE(e,"response",!!t.deepChat.responseInterceptor,o));r.makingAnotherRequest||(je.isSimulatable(t.stream,r)?je.simulate(i,t.streamHandlers,r):(i.addNewMessage(r),u()))})).catch((t=>{xe.displayError(i,t),u()}))}static executePollRequest(t,e,i,s){const{onFinish:n}=t.completionsHandlers;fetch(e,i).then((t=>t.json())).then((async o=>{var r,a;if(!t.extractPollResultData)return;const l=await t.extractPollResultData(await(null==(a=(r=t.deepChat).responseInterceptor)?void 0:a.call(r,o))||o);l.timeoutMS?setTimeout((()=>{Ie.executePollRequest(t,e,i,s)}),l.timeoutMS):je.isSimulatable(t.stream,l)?je.simulate(s,t.streamHandlers,l):(s.addNewMessage(l),n())})).catch((t=>{xe.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 xe.processRequestInterceptor(t.deepChat,a);if(h)return xe.onInterceptorError(i,h);const u=(null==(o=t.connectSettings)?void 0:o.url)||t.url||"",d={method:(null==(r=t.connectSettings)?void 0:r.method)||"POST",body:s?JSON.stringify(l):l,headers:c};t.connectSettings.credentials&&(d.credentials=t.connectSettings.credentials),Ie.executePollRequest(t,u,d,i)}static verifyKey(t,e,i,s,n,o,r,a,l){if(""===t)return o(y.INVALID_KEY);r(),fetch(e,{method:s,headers:i,body:l||null}).then((t=>xe.processResponseByType(t))).then((e=>{a(e,t,n,o)})).catch((t=>{o(y.CONNECTION_FAILED),console.error(t)}))}}const Pe=class t{constructor(t,e,i){this._isLoading=!1,this._isPaginationComplete=!1,this._index=0,this._messages=e,i.fetchHistory&&this.fetchHistory(i.fetchHistory),t.loadHistory&&this.setupLoadHistoryOnScroll(t.loadHistory),this.setupInitialHistory(t)}async fetchHistory(t){const e=ve.addMessage(this._messages),i=await t();this._messages.removeMessage(e),i.forEach((t=>this._messages.addAnyMessage(t,!0))),setTimeout((()=>x.scrollToBottom(this._messages.elementRef)),0)}processLoadedHistory(t){var e;const i=null==(e=this._messages.messageElementRefs[0])?void 0:e.outerContainer,s=this._messages.elementRef.scrollTop;null==t||t.reverse().map((t=>{if(t){const e=this._messages.addAnyMessage({...t,sendUpdate:!0},!0,!0);return e&&this._messages.messages.unshift(e),e}this._isPaginationComplete=!0})).filter((t=>!!t)).reverse().forEach((t=>this._messages.sendClientUpdate(t,!0))),i&&(this._messages.elementRef.scrollTop=s+i.offsetTop)}async setupLoadHistoryOnScroll(e){this._messages.elementRef.onscroll=async()=>{if(!this._isLoading&&!this._isPaginationComplete&&0===this._messages.elementRef.scrollTop){this._isLoading=!0;const i=ve.addMessage(this._messages,!1);try{const t=await e(this._index++);this._messages.removeMessage(i),this.processLoadedHistory(t),this._isLoading=!1}catch(e){this._messages.removeMessage(i),this._isPaginationComplete=!0,this._messages.addNewErrorMessage("service",t.FAILED_ERROR_MESSAGE,!0),console.error(e)}}}}populateInitialHistory(t){t.forEach((t=>{S.processHistoryFile(t),this._messages.addNewMessage(t,!0)}))}async loadInitialHistory(e){this._isLoading=!0;const i=ve.addMessage(this._messages);try{const t=await e(this._index++),s=this._messages.elementRef.scrollTop;this._messages.removeMessage(i),this._isPaginationComplete=!!t.find((t=>!t));const n=t.filter((t=>!!t));this.processLoadedHistory(n),0===s&&setTimeout((()=>x.scrollToBottom(this._messages.elementRef)),0)}catch(e){this._messages.removeMessage(i),this._isPaginationComplete=!0,this._messages.addNewErrorMessage("service",t.FAILED_ERROR_MESSAGE,!0),console.error(e)}this._isLoading=!1}async setupInitialHistory(t){t.loadHistory&&this.loadInitialHistory(t.loadHistory);const e=t.history||S.processHistory(t);e&&(this.populateInitialHistory(e),this._index+=1)}static addErrorPrefix(e){e.permittedErrorPrefixes??(e.permittedErrorPrefixes=[]),e.permittedErrorPrefixes.push(t.FAILED_ERROR_MESSAGE)}};Pe.FAILED_ERROR_MESSAGE="Failed to load history";let Ne=Pe;class qe{static getCharacterLimitMessages(t,e){var i;if(-1===e)return t;let s=0,n=t.length-1;for(;n>=0;n-=1){const o=null==(i=t[n])?void 0:i.text;if(void 0!==o&&(s+=o.length,s>e)){t[n].text=o.substring(0,o.length-(s-e));break}}return t.slice(Math.max(n,0))}static getMaxMessages(t,e){return t.slice(Math.max(t.length-e,0))}static processMessages(t,e,i){return void 0!==e?e>0&&(t=qe.getMaxMessages(t,e)):t=[t[t.length-1]],t=JSON.parse(JSON.stringify(t)),void 0===i?t:qe.getCharacterLimitMessages(t,i)}}class Re{static parseConfig(t,e,i,s){var n;const o={files:e};if("object"==typeof s){S.processFileConfigConnect(s);const{files:e,connect:r,button:a}=s;e&&(e.infoModal&&(o.files.infoModal=e.infoModal,null!=(n=e.infoModal)&&n.textMarkDown&&(o.infoModalTextMarkUp=i.render(e.infoModal.textMarkDown))),e.acceptedFormats&&(o.files.acceptedFormats=e.acceptedFormats),e.maxNumberOfFiles&&(o.files.maxNumberOfFiles=e.maxNumberOfFiles)),o.button=a,r&&(r.headers||r.method||r.url||r.credentials||t.headers||t.method||t.url||t.credentials)&&(o.connect={url:(null==r?void 0:r.url)||t.url,method:(null==r?void 0:r.method)||t.method,headers:(null==r?void 0:r.headers)||t.headers,credentials:(null==r?void 0:r.credentials)||t.credentials})}return o}static processMixedFiles(t,e,i){if(i){const s={acceptedFormats:""};t.fileTypes.mixedFiles=Re.parseConfig(t.connectSettings,s,e,i)}}static processMicrophone(t,e,i,s){var n,o,r,a,l,c;const h={acceptedFormats:"audio/*",...(null==(n=t.fileTypes.audio)?void 0:n.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.recordAudio=Re.parseConfig(t.connectSettings,h,e,i),"object"==typeof i&&i.files&&((o=t.recordAudio).files??(o.files={}),t.recordAudio.files.format=null==(r=i.files)?void 0:r.format,t.recordAudio.files.maxDurationSeconds=null==(a=i.files)?void 0:a.maxDurationSeconds,null!=(l=t.fileTypes.audio)&&l.files&&((c=t.fileTypes.audio.files).maxNumberOfFiles??(c.maxNumberOfFiles=i.files.maxNumberOfFiles)))):s||(t.fileTypes.audio=Re.parseConfig(t.connectSettings,h,e,i)))}static processAudioConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"audio/*",...(null==s?void 0:s.files)||{}};t.fileTypes.audio=Re.parseConfig(t.connectSettings,n,e,i)}static processGifConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"image/gif",...(null==s?void 0:s.files)||{}};t.fileTypes.gifs=Re.parseConfig(t.connectSettings,n,e,i)}static processCamera(t,e,i,s){var n,o,r,a;const l={acceptedFormats:"image/*",...(null==(n=t.fileTypes.images)?void 0:n.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.camera=Re.parseConfig(t.connectSettings,l,e,i),"object"==typeof i&&(t.camera.modalContainerStyle=i.modalContainerStyle,i.files&&((o=t.camera).files??(o.files={}),t.camera.files.format=null==(r=i.files)?void 0:r.format,t.camera.files.dimensions=null==(a=i.files)?void 0:a.dimensions))):s||(t.fileTypes.images=Re.parseConfig(t.connectSettings,l,e,i)))}static processImagesConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"image/*",...(null==s?void 0:s.files)||{}};t.fileTypes.images=Re.parseConfig(t.connectSettings,n,e,i)}static populateDefaultFileIO(t,e){var i,s;t&&(t.files??(t.files={}),(i=t.files).acceptedFormats??(i.acceptedFormats=e),(s=t.files).maxNumberOfFiles??(s.maxNumberOfFiles=1))}static set(t,e,i){Re.populateDefaultFileIO(null==i?void 0:i.audio,".4a,.mp3,.webm,.mp4,.mpga,.wav,.mpeg,.m4a"),Re.populateDefaultFileIO(null==i?void 0:i.images,".png,.jpg");const s=he.createNew();Re.processImagesConfig(e,s,t.images,null==i?void 0:i.images),Re.processCamera(e,s,t.camera,t.images),Re.processGifConfig(e,s,t.gifs,null==i?void 0:i.gifs),Re.processAudioConfig(e,s,t.audio,null==i?void 0:i.audio),Re.processMicrophone(e,s,t.microphone,t.audio),Re.processMixedFiles(e,s,t.mixedFiles)}}class Le{constructor(t,e,i){var s,n,o,r,a;this.rawBody={},this.validateKeyProperty=!1,this.canSendMessage=Le.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,Re.set(t,this,e),t.connect&&(this.connectSettings=t.connect),this.demo&&((r=this.connectSettings).url??(r.url=Ce.URL)),this.connectSettings.websocket&&Oe.setup(this),this.stream=(null==(a=this.deepChat.connect)?void 0:a.stream)||S.checkForStream(this.deepChat),t.loadHistory&&Ne.addErrorPrefix(this)}static canSendMessage(t,e,i){return!!i||(!(!t||""===t.trim())||!!(e&&e.length>0))}verifyKey(t,e){}static createCustomFormDataBody(t,e,i){const s=new FormData;i.forEach((t=>s.append("files",t))),Object.keys(t).forEach((e=>s.append(e,String(t[e]))));let n=0;e.slice(0,e.length-1).forEach((t=>{s.append(`message${n+=1}`,JSON.stringify(t))}));const o=e[e.length-1];return o.text&&(delete o.files,s.append(`message${n+=1}`,JSON.stringify(o))),s}getServiceIOByType(t){if(t.type.startsWith("audio")&&this.fileTypes.audio)return this.fileTypes.audio;if(t.type.startsWith("image")){if(this.fileTypes.gifs&&t.type.endsWith("/gif"))return this.fileTypes.gifs;if(this.fileTypes.images)return this.fileTypes.images;if(this.camera)return this.camera}return this.fileTypes.mixedFiles}async request(t,e,i=!0){return this.stream&&!je.isSimulation(this.stream)?je.request(this,t,e,i):Ie.request(this,t,e,i)}async callAPIWithText(t,e){var i,s,n,o;const r={messages:e,...this.rawBody};let a=!1;null!=(i=this.connectSettings.headers)&&i["Content-Type"]||((s=this.connectSettings).headers??(s.headers={}),(n=this.connectSettings.headers)["Content-Type"]??(n["Content-Type"]="application/json"),a=!0),await this.request(r,t),a&&(null==(o=this.connectSettings.headers)||delete o["Content-Type"])}async callApiWithFiles(t,e,i){const s=Le.createCustomFormDataBody(this.rawBody,e,i),n=this.connectSettings,o=this.getServiceIOByType(i[0]);this.connectSettings=(null==o?void 0:o.connect)||this.connectSettings,await this.request(s,t,!1),this.connectSettings=n}async callServiceAPI(t,e,i){i?this.callApiWithFiles(t,e,i):this.callAPIWithText(t,e)}async callAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=qe.processMessages(e.messages,this.maxMessages,this.totalMessagesMaxCharLength);if(this.connectSettings.websocket){const t={messages:i,...this.rawBody};Oe.sendWebsocket(this,t,e,!1)}else this.callServiceAPI(e,i,t.files)}async extractResultData(t){if(t.error)throw t.error;return t.result?S.handleResponseProperty(t):xe.validateResponseFormat(t)?t:void 0}isDirectConnection(){return!1}isWebModel(){return!1}}class Be extends Le{constructor(t,e,i,s,n){var o;super(t,n),this.insertKeyPlaceholderText="API Key",this.keyHelpUrl="",Object.assign(this.rawBody,null==(o=t.connect)?void 0:o.additionalBodyProps),this.keyVerificationDetails=e,this.buildHeadersFunc=i,s&&this.setApiKeyProperties(s),this.connectSettings=this.buildConnectSettings(this.key||"",t.connect)}setApiKeyProperties(t){this.key=t.key,t.validateKeyProperty&&(this.validateKeyProperty=t.validateKeyProperty)}buildConnectSettings(t,e){const i=e??{};return i.headers??(i.headers={}),Object.assign(i.headers,this.buildHeadersFunc(t)),i}keyAuthenticated(t,e){this.connectSettings=this.buildConnectSettings(e,this.connectSettings),this.key=e,t()}verifyKey(t,e){const{url:i,method:s,handleVerificationResult:n,createHeaders:o,body:r}=this.keyVerificationDetails,a=(null==o?void 0:o(t))||this.buildHeadersFunc(t);Ie.verifyKey(t,i,a,s,this.keyAuthenticated.bind(this,e.onSuccess),e.onFail,e.onLoad,n,r)}isDirectConnection(){return!0}}class Fe{static waitForPropertiesToBeUpdatedBeforeRender(t){t._propUpdated_=!1,setTimeout((()=>{t._propUpdated_?Fe.waitForPropertiesToBeUpdatedBeforeRender(t):(t._waitingToRender_=!1,t.onRender())}))}static attemptRender(t){t._propUpdated_=!0,t._waitingToRender_||(t._waitingToRender_=!0,Fe.waitForPropertiesToBeUpdatedBeforeRender(t))}}const ze=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:Fe.attemptRender(this)}})}attributeChangedCallback(e,i,s){if(i===s)return;const n=t._attributes_[e](s);this[t._attributeToProperty_[e]]=n}onRender(){}};ze._attributes_={},ze._attributeToProperty_={};let De=ze;class $e{static createSVGElement(t){return(new DOMParser).parseFromString(t,"image/svg+xml").documentElement}}const Je=class t{static changeVisibility(e,i,s,n){n.target.id===t.VISIBLE_ICON_ID?(i.style.display="none",s.style.display="block",e.type="password"):(i.style.display="block",s.style.display="none",e.type="text")}static createIconElement(t,e){const i=$e.createSVGElement(t);return i.id=e,i.classList.add("visibility-icon"),i}static create(e){const i=document.createElement("div");i.id="visibility-icon-container";const s=t.createIconElement('<?xml version="1.0" standalone="no"?>\n<svg version="1.1"\n\txmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n\txmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0.9em" height="0.9em"\n\tviewBox="0 0 1200 1200" enable-background="new 0 0 1200 1200">\n\t\t<path id="path6686" inkscape:connector-curvature="0" d="M779.843,599.925c0,95.331-80.664,172.612-180.169,172.612\n\t\t\tc-99.504,0-180.168-77.281-180.168-172.612c0-95.332,80.664-172.612,180.168-172.612\n\t\t\tC699.179,427.312,779.843,504.594,779.843,599.925z M600,240.521c-103.025,0.457-209.814,25.538-310.904,73.557\n\t\t\tc-75.058,37.122-148.206,89.496-211.702,154.141C46.208,501.218,6.431,549,0,599.981c0.76,44.161,48.13,98.669,77.394,131.763\n\t\t\tc59.543,62.106,130.786,113.018,211.702,154.179c94.271,45.751,198.616,72.092,310.904,73.557\n\t\t\tc103.123-0.464,209.888-25.834,310.866-73.557c75.058-37.122,148.243-89.534,211.74-154.179\n\t\t\tc31.185-32.999,70.962-80.782,77.394-131.763c-0.76-44.161-48.13-98.671-77.394-131.764\n\t\t\tc-59.543-62.106-130.824-112.979-211.74-154.141C816.644,268.36,712.042,242.2,600,240.521z M599.924,329.769\n\t\t\tc156.119,0,282.675,120.994,282.675,270.251c0,149.256-126.556,270.25-282.675,270.25S317.249,749.275,317.249,600.02\n\t\t\tC317.249,450.763,443.805,329.769,599.924,329.769L599.924,329.769z"/>\n</svg>\n',t.VISIBLE_ICON_ID);s.style.display="none",i.appendChild(s);const n=t.createIconElement('<?xml version="1.0" standalone="no"?>\n<svg version="1.1"\n\txmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n\txmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0.9em" height="0.9em"\n\tviewBox="0 0 1200 1200" enable-background="new 0 0 1200 1200">\n\t\t<path d="\n\t\t\tM669.727,273.516c-22.891-2.476-46.15-3.895-69.727-4.248c-103.025,0.457-209.823,25.517-310.913,73.536\n\t\t\tc-75.058,37.122-148.173,89.529-211.67,154.174C46.232,529.978,6.431,577.76,0,628.74c0.76,44.162,48.153,98.67,77.417,131.764\n\t\t\tc59.543,62.106,130.754,113.013,211.67,154.174c2.75,1.335,5.51,2.654,8.276,3.955l-75.072,131.102l102.005,60.286l551.416-960.033\n\t\t\tl-98.186-60.008L669.727,273.516z M902.563,338.995l-74.927,129.857c34.47,44.782,54.932,100.006,54.932,159.888\n\t\t\tc0,149.257-126.522,270.264-282.642,270.264c-6.749,0-13.29-0.728-19.922-1.172l-49.585,85.84c22.868,2.449,45.99,4.233,69.58,4.541\n\t\t\tc103.123-0.463,209.861-25.812,310.84-73.535c75.058-37.122,148.246-89.529,211.743-154.174\n\t\t\tc31.186-32.999,70.985-80.782,77.417-131.764c-0.76-44.161-48.153-98.669-77.417-131.763\n\t\t\tc-59.543-62.106-130.827-113.013-211.743-154.175C908.108,341.478,905.312,340.287,902.563,338.995L902.563,338.995z\n\t\t\tM599.927,358.478c6.846,0,13.638,0.274,20.361,0.732l-58.081,100.561c-81.514,16.526-142.676,85.88-142.676,168.897\n\t\t\tc0,20.854,3.841,40.819,10.913,59.325c0.008,0.021-0.008,0.053,0,0.074l-58.228,100.854\n\t\t\tc-34.551-44.823-54.932-100.229-54.932-160.182C317.285,479.484,443.808,358.477,599.927,358.478L599.927,358.478z M768.896,570.513\n\t\t\tL638.013,797.271c81.076-16.837,141.797-85.875,141.797-168.603C779.81,608.194,775.724,588.729,768.896,570.513L768.896,570.513z"\n\t\t\t/>\n</svg>\n',"not-visible-icon");return i.appendChild(n),i.onclick=t.changeVisibility.bind(this,e,s,n),i}};Je.VISIBLE_ICON_ID="visible-icon";let Ve=Je;class Ue{static createCautionText(){const t=document.createElement("a");return t.classList.add("insert-key-input-help-text"),t.innerText="Please exercise CAUTION when inserting your API key outside of deepchat.dev or localhost!!",t}static createHelpLink(t){const e=document.createElement("a");return e.classList.add("insert-key-input-help-text"),e.href=t,e.innerText="Find more info here",e.target="_blank",e}static createFailText(){const t=document.createElement("div");return t.id="insert-key-input-invalid-text",t.style.display="none",t}static createHelpTextContainer(t,e=!0){const i=document.createElement("div");i.id="insert-key-help-text-container";const s=document.createElement("div");s.id="insert-key-help-text-contents";const n=Ue.createFailText();if(s.appendChild(n),t){const e=Ue.createHelpLink(t);s.appendChild(e)}if(!0===e){const t=Ue.createCautionText();s.appendChild(t)}return i.appendChild(s),{helpTextContainerElement:i,failTextElement:n}}static onFail(t,e,i,s){t.classList.replace("insert-key-input-valid","insert-key-input-invalid"),i.innerText=s,i.style.display="block",e.innerText="Start",t.classList.remove("loading")}static onLoad(t,e){t.classList.add("loading"),e.innerHTML='<div id="loading-key"></div>'}static verifyKey(t,e,i){const s=t.value.trim();i.verifyKey(s,e)}static addVerificationEvents(t,e,i,s,n){const o={onSuccess:s,onFail:Ue.onFail.bind(this,t,e,i),onLoad:Ue.onLoad.bind(this,t,e)},r=Ue.verifyKey.bind(this,t,o,n);e.onclick=r,t.onkeydown=e=>{!t.classList.contains("loading")&&e.key===c.ENTER&&r()}}static createStartButton(){const t=document.createElement("div");return t.id="start-button",t.innerText="Start",t}static onInputFocus(t){t.target.classList.replace("insert-key-input-invalid","insert-key-input-valid")}static createInput(t){const e=document.createElement("div");e.id="insert-key-input-container";const i=document.createElement("input");return i.id="insert-key-input",i.placeholder=t||"API Key",i.type="password",i.classList.add("insert-key-input-valid"),i.onfocus=Ue.onInputFocus,e.appendChild(i),e}static createContents(t,e){var i;const s=document.createElement("div");s.id="insert-key-contents";const n=Ue.createInput(e.insertKeyPlaceholderText),o=n.children[0],r=Ve.create(o);n.appendChild(r),s.appendChild(n);const a=Ue.createStartButton(),{helpTextContainerElement:l,failTextElement:c}=Ue.createHelpTextContainer(e.keyHelpUrl,null==(i=e.deepChat._insertKeyViewStyles)?void 0:i.displayCautionText);return s.appendChild(a),s.appendChild(l),Ue.addVerificationEvents(o,a,c,t,e),s}static createElements(t,e){const i=document.createElement("div");i.id="insert-key-view";const s=Ue.createContents(t,e);return i.appendChild(s),i}static render(t,e,i){const s=Ue.createElements(e,i);t.replaceChildren(s)}}const He=class t{static enableButtons(e,i,s=0){window.webLLM?(e&&(e.disabled=!1),i&&(i.disabled=!1)):s<4*We.MODULE_SEARCH_LIMIT_S&&setTimeout((()=>t.enableButtons(e,i,s+1)),250)}static setUpInitial(e,i,s,n){const o=(null==i?void 0:i.downloadClass)||t.DOWNLOAD_BUTTON_CLASS,r=(null==i?void 0:i.uploadClass)||t.UPLOAD_BUTTON_CLASS,a=(null==i?void 0:i.fileInputClass)||t.FILE_INPUT_CLASS;return setTimeout((()=>{const i=null==s?void 0:s.getElementsByClassName(o)[0],n=null==s?void 0:s.getElementsByClassName(a)[0],l=null==s?void 0:s.getElementsByClassName(r)[0];i&&(i.onclick=()=>e()),n&&(n.onchange=()=>{n.files&&n.files.length>0&&e(n.files)}),l&&(l.onclick=()=>n.click()),(i||l)&&t.enableButtons(i,l)})),(null==i?void 0:i.initialHtml)||`<div>\n Download or upload a web model that will run entirely on your browser: <br/> \n <button disabled class="${o} deep-chat-button deep-chat-web-model-button">Download</button>\n ${n?"":`<input type="file" class="${a}" hidden multiple />\n <button disabled class="${r} deep-chat-button deep-chat-web-model-button">Upload</button>`}\n </div>`}static exportFile(t){const e=document.createElement("a");for(let i=0;i<t.length/4;i+=1)setTimeout((()=>{const s=4*i;for(let i=s;i<Math.min(s+4,t.length);i+=1){const s=URL.createObjectURL(t[i]);e.href=s,e.download=t[i].name,document.body.appendChild(e),e.click(),URL.revokeObjectURL(s)}}),500*i)}static setUpAfterLoad(e,i,s,n){const o=(null==i?void 0:i.exportFilesClass)||t.EXPORT_BUTTON_CLASS;return setTimeout((()=>{const i=null==s?void 0:s.getElementsByClassName(o)[0];i&&(i.onclick=()=>t.exportFile(e))})),(null==i?void 0:i.afterLoadHtml)||`<div>\n Model loaded successfully and has been cached for future requests.\n ${n?"":`<br/> <button style="margin-top: 5px" class="${o} deep-chat-button">Export</button>`}\n </div>`}};He.DOWNLOAD_BUTTON_CLASS="deep-chat-download-button",He.UPLOAD_BUTTON_CLASS="deep-chat-upload-button",He.FILE_INPUT_CLASS="deep-chat-file-input",He.EXPORT_BUTTON_CLASS="deep-chat-export-button";let Ke=He;const Ge={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},Ze=class t extends Le{constructor(e){var i,s;super(e),this._isModelLoaded=!1,this._isModelLoading=!1,this._loadOnFirstMessage=!1,this._webModel={},this.permittedErrorPrefixes=[t.MULTIPLE_MODELS_ERROR,t.WEB_LLM_NOT_FOUND_ERROR,t.GENERIC_ERROR],this._conversationHistory=[],"object"==typeof e.webModel&&(this._webModel=e.webModel),null!=(i=this._webModel.load)&&i.clearCache&&t.clearAllCache(),this.findModelInWindow(e),this.canSendMessage=this.canSubmit.bind(this),this._chatEl=null==(s=e.shadowRoot)?void 0:s.children[0],e.history&&t.setUpHistory(this._conversationHistory,e.history)}setUpMessages(t){this._messages=t,this._removeIntro=()=>{t.removeIntroductoryMessage(),this._removeIntro=void 0}}static setUpHistory(t,e){e.forEach(((i,s)=>{if(i.role===I.USER_ROLE&&i.text){const n=e[s+1];null!=n&&n.text&&n.role!==I.USER_ROLE&&t.push([i.text,n.text])}}))}findModelInWindow(e,i=0){var s;window.webLLM?this.configureInit(this.shouldAddIntroMessage(e.introMessage)):i>t.MODULE_SEARCH_LIMIT_S?(null==(s=this._messages)||s.addNewErrorMessage("service",t.WEB_LLM_NOT_FOUND_ERROR),console.error("The deep-chat-web-llm module has not been attached to the window object. Please see the following guide:"),console.error("https://deepchat.dev/examples/externalModules")):setTimeout((()=>this.findModelInWindow(e,i+1)),1e3)}shouldAddIntroMessage(t){var e;return!t&&this._webModel&&!1!==(null==(e=this._webModel.introMessage)?void 0:e.displayed)}scrollToTop(t){var e;!1!==(null==(e=this._webModel.introMessage)?void 0:e.autoScroll)&&setTimeout((()=>{var t,e;null!=(t=this._messages)&&t.elementRef&&x.scrollToTop(null==(e=this._messages)?void 0:e.elementRef)}),t)}getIntroMessage(t){if(!this.shouldAddIntroMessage(t)||!this._chatEl)return;const e=Ke.setUpInitial(this.init.bind(this),this._webModel.introMessage,this._chatEl,!!this._webModel.worker);return this.scrollToTop(1),{role:I.AI_ROLE,html:e,sendUpdate:!1}}async configureInit(t){const{load:e}=this._webModel;if(e){if(e.onInit)return void this.init();if(e.onMessage)return void(this._loadOnFirstMessage=!0)}t||this.init()}async init(t){var e;null==(e=this._messages)||e.removeError();const i=this.attemptToCreateChat();i&&await this.loadModel(i,t)}attemptToCreateChat(){var e;if(t.chat)return null==(e=this._messages)||e.addNewErrorMessage("service",t.MULTIPLE_MODELS_ERROR),void console.error(t.MULTIPLE_MODELS_ERROR);if(this._isModelLoaded||this._isModelLoading)return;const{worker:i}=this._webModel;return Ge.use_web_worker&&i?new window.webLLM.ChatWorkerClient(i):new window.webLLM.ChatModule}getConfig(){var e;let i=t.DEFAULT_MODEL;this._webModel.model&&(i=this._webModel.model);const s=JSON.parse(JSON.stringify(Ge));if(this._webModel.urls){const t=s.model_list.find((t=>t.local_id=i));t&&(this._webModel.urls.model&&(t.model_url=this._webModel.urls.model),this._webModel.urls.wasm&&(t.model_lib_url=this._webModel.urls.wasm))}return null!=(e=this._webModel.load)&&e.skipCache&&(s.use_cache=!1),{model:i,appConfig:s}}async loadModel(e,i){var s,n,o,r,a,l,c;this.scrollToTop(),t.chat=e,this._isModelLoading=!0;let h=!1===(null==(s=this._webModel.introMessage)?void 0:s.displayed);let u;t.chat.setInitProgressCallback((t=>{var e;null==(e=this._messages)||e.addNewMessage({html:`<div>${t.text}</div>`,overwrite:!0,sendUpdate:!1}),h&&(setTimeout((()=>{var t;return x.scrollToBottom(null==(t=this._messages)?void 0:t.elementRef)})),h=!1)}));try{const{model:e,appConfig:s}=this.getConfig(),n={};this._webModel.instruction&&(n.conv_config={system:this._webModel.instruction}),this._conversationHistory.length>0&&(n.conversation_history=this._conversationHistory),u=await t.chat.reload(e,n,s,i)}catch(t){return this.unloadChat(t)}if(null==(o=(n=this.deepChat)._validationHandler)||o.call(n),null!=(r=this._webModel.introMessage)&&r.removeAfterLoad)!1===this._webModel.introMessage.displayed?null==(l=this._messages)||l.removeLastMessage():null==(c=this._removeIntro)||c.call(this);else{const t=Ke.setUpAfterLoad(u,this._webModel.introMessage,this._chatEl,!!this._webModel.worker);null==(a=this._messages)||a.addNewMessage({html:t,overwrite:!0,sendUpdate:!1})}this._isModelLoaded=!0,this._isModelLoading=!1}async unloadChat(e){var i;null==(i=this._messages)||i.addNewErrorMessage("service",t.GENERIC_ERROR),console.error(e),this._isModelLoaded=!1,this._isModelLoading=!1,t.chat&&(await t.chat.unload(),t.chat=void 0)}async immediateResp(e,i,s){const n={text:await s.generate(i,void 0,0)},o=await t.processResponse(this.deepChat,e,n);o&&e.addNewMessage(o),this.completionsHandlers.onFinish()}async streamResp(e,i,s){this.streamHandlers.abortStream.abort=()=>{s.interruptGenerate()},this.streamHandlers.onOpen();const n=new ye(e);await s.generate(i,(async(i,s)=>{const o=await t.processResponse(this.deepChat,e,{text:s});o&&n.upsertStreamedMessage({text:o.text,overwrite:!0})})),n.finaliseStreamedMessage(),this.streamHandlers.onClose()}async generateRespByType(t,e,i,s){var n;try{i?await this.streamResp(t,e,s):await this.immediateResp(t,e,s)}catch(t){null==(n=this._messages)||n.addNewErrorMessage("service"),console.log(t)}}async generateResp(t,e,i){const s=e[e.length-1].text,{body:n,error:o}=await xe.processRequestInterceptor(this.deepChat,{body:{text:s}}),r=!!this.stream;try{if(o)xe.displayError(t,new Error(o)),(r?this.streamHandlers.onClose:this.completionsHandlers.onFinish)();else if(n&&n.text)this.generateRespByType(t,n.text,!!this.stream,i);else{const e=y.INVALID_MODEL_REQUEST({body:n},!1);console.error(e);const i=r?this.streamHandlers.onClose:this.completionsHandlers.onFinish;xe.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;const n=await(null==(s=t.responseInterceptor)?void 0:s.call(t,i))||i;if(n.error)xe.displayError(e,new Error(n.error));else{if(n&&n.text)return n;{const s=y.INVALID_MODEL_RESPONSE(i,!!t.responseInterceptor,n);xe.displayError(e,new Error(s))}}}isWebModel(){return!0}static clearAllCache(){t.clearCache("webllm/model"),t.clearCache("webllm/wasm")}static clearCache(t){caches.open(t).then((t=>{t.keys().then((e=>{e.forEach((e=>{t.delete(e)}))}))}))}};Ze.GENERIC_ERROR="Error, please check the [troubleshooting](https://deepchat.dev/docs/webModel#troubleshooting) section of documentation for help.",Ze.MULTIPLE_MODELS_ERROR="Cannot run multiple web models",Ze.WEB_LLM_NOT_FOUND_ERROR="WebLLM module not found",Ze.DEFAULT_MODEL="Llama-2-7b-chat-hf-q4f32_1",Ze.MODULE_SEARCH_LIMIT_S=5;let We=Ze;class Xe{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,s){const n=t;Array.isArray(n.error)&&"Error in `parameters`: field required"===n.error[0]?i(e):s(y.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api-inference.huggingface.co/models/gpt2",method:"POST",handleVerificationResult:Xe.handleVerificationResult}}}const Qe=class t extends Be{constructor(e,i,s,n,o,r){super(e,Xe.buildKeyVerificationDetails(),Xe.buildHeaders,o,r),this.insertKeyPlaceholderText="Hugging Face Token",this.keyHelpUrl="https://huggingface.co/settings/tokens",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Hugging Face</b></div>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>',this.permittedErrorPrefixes=["Authorization header"],this.url=`${t.URL_PREFIX}${s}`,this.textInputPlaceholderText=i,"object"==typeof n&&(n.model&&(this.url=`${t.URL_PREFIX}${n.model}`),n.options&&(this.rawBody.options=n.options),n.parameters&&(this.rawBody.parameters=n.parameters))}preprocessBody(t,e,i){const s=JSON.parse(JSON.stringify(t)),n=e[e.length-1].text;if(n)return s.options??(s.options={}),s.options.wait_for_model=!0,{inputs:n,...s}}async callServiceAPI(t,e,i){if(!this.connectSettings)throw new Error("Request settings have not been set up");const s=this.preprocessBody(this.rawBody,e,i);Ie.request(this,s,t)}};Qe.URL_PREFIX="https://api-inference.huggingface.co/models/";let Ye=Qe;class ti extends Ye{constructor(t,e,i,s,n,o){super(t,e,i,s,n,o),this.isTextInputDisabled=!0,this.canSendMessage=ti.canSendFile}static canSendFile(t,e){return!(null==e||!e[0])}preprocessBody(t,e,i){return i[0]}async callServiceAPI(t,e,i){if(!this.connectSettings)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");Ie.poll(this,i[0],t,!1)}}class ei extends ti{constructor(t){var e,i,s;super(t,"Attach an audio file","ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.audioClassification,null==(s=t.directConnection)?void 0:s.huggingFace,{audio:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.label)||""}}}class ii extends ti{constructor(t){var e,i,s;super(t,"Attach an image file","google/vit-base-patch16-224",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.imageClassification,null==(s=t.directConnection)?void 0:s.huggingFace,{images:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.label)||""}}}const si="data:image/png;base64,";class ni{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,s){t.message?s(y.INVALID_KEY):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.stability.ai/v1/engines/list",method:"GET",handleVerificationResult:ni.handleVerificationResult}}}class oi extends Be{constructor(t,e,i,s,n){super(t,e,i,s,n),this.insertKeyPlaceholderText="Stability AI API Key",this.keyHelpUrl="https://platform.stability.ai/docs/getting-started/authentication",this.permittedErrorPrefixes=["Incorrect","invalid_"]}}class ri extends oi{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=null==i?void 0:i.stabilityAI;super(t,ni.buildKeyVerificationDetails(),ni.buildHeaders,s,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}),this.url="https://api.stability.ai/v1/generation/esrgan-v1-x2plus/image-to-image/upscale",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI</b></div>\n <div style="width: 100%; text-align: center; margin-left: -10px; margin-top: 5px"><b>Image to Image Upscale</b></div>\n <p>Upload an image to generate a new one with higher resolution.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageUpscale;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/image-to-image/upscale`),ri.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=ri.canSendFileMessage}static cleanConfig(t){delete t.engine_id}static canSendFileMessage(t,e){return!(null==e||!e[0])}createFormDataBody(t,e){const i=new FormData;return i.append("image",e),Object.keys(t).forEach((e=>{i.append(e,String(t[e]))})),i}async callServiceAPI(t,e,i){if(!this.connectSettings)throw new Error("Request settings have not been set up");if(!i)throw new Error("Image was not found");const s=this.createFormDataBody(this.rawBody,i[0]);xe.tempRemoveContentHeader(this.connectSettings,Ie.request.bind(this,this,s,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${si}${t.base64}`,type:"image"})))}}}class ai extends oi{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=null==i?void 0:i.stabilityAI;super(t,ni.buildKeyVerificationDetails(),ni.buildHeaders,s,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.url="https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/image-to-image/masking",this._maskSource="MASK_IMAGE_WHITE",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI</b></div>\n <div style="width: 100%; text-align: center; margin-left: -10px; margin-top: 5px"><b>Image to Image Masking</b></div>\n <p>Upload an image, its mask image to create a new one based on the changes you have described for the mask area.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageMasking;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/image-to-image/masking`),void 0!==n.weight&&null!==n.weight&&(this._imageWeight=n.weight),void 0!==n.mask_source&&null!==n.mask_source&&(this._maskSource=n.mask_source),ai.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=ai.canSendFileTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendFileTextMessage(t,e){return!(null==e||!e[0]||!t||""===t.trim())}createFormDataBody(t,e,i,s){const n=new FormData;return n.append("init_image",e),n.append("mask_source",String(this._maskSource)),n.append("mask_image",i),s&&""!==s&&n.append("text_prompts[0][text]",s),void 0!==this._imageWeight&&null!==this._imageWeight&&n.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach((e=>{n.append(e,String(t[e]))})),void 0===n.get("weight")&&n.append("weight",String(1)),n}async callServiceAPI(t,e,i){var s,n;if(!this.connectSettings)throw new Error("Request settings have not been set up");if(!i||!i[0]||!i[1])throw new Error("Image was not found");const o=null==(n=null==(s=e[e.length-1])?void 0:s.text)?void 0:n.trim(),r=this.createFormDataBody(this.rawBody,i[0],i[1],o);xe.tempRemoveContentHeader(this.connectSettings,Ie.request.bind(this,this,r,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${si}${t.base64}`,type:"image"})))}}}class li extends ti{constructor(t){var e,i,s;super(t,"Attach an audio file","facebook/wav2vec2-large-960h-lv60-self",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.audioSpeechRecognition,null==(s=t.directConnection)?void 0:s.huggingFace,{audio:{}})}async extractPollResultData(t){if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:t.text||""}}}class ci extends Ye{constructor(t){var e,i,s;super(t,"Once upon a time","gpt2",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.textGeneration,null==(s=t.directConnection)?void 0:s.huggingFace)}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.generated_text)||""}}}class hi extends Ye{constructor(t){var e,i,s;const n=null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.questionAnswer;super(t,"Ask a question","bert-large-uncased-whole-word-masking-finetuned-squad",n,null==(s=t.directConnection)?void 0:s.huggingFace),this.permittedErrorPrefixes=["Authorization header","Error in"],this.context=n.context}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return{inputs:{question:i,context:this.context,options:{wait_for_model:!0}}}}async extractResultData(t){if(t.error)throw t.error;return{text:t.answer||""}}}class ui extends Ye{constructor(t){var e,i,s;super(t,"Insert text to summarize","facebook/bart-large-cnn",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.summarization,null==(s=t.directConnection)?void 0:s.huggingFace)}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.summary_text)||""}}}class di extends Ye{constructor(t){var e,i,s;super(t,"Ask me anything!","facebook/blenderbot-400M-distill",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.conversation,null==(s=t.directConnection)?void 0:s.huggingFace),this.maxMessages??(this.maxMessages=-1)}processMessages(t){const e=t.filter((t=>t.text)),i=e[e.length-1].text,s=e.slice(0,e.length-1);if(!i)return;return{past_user_inputs:s.filter((t=>"user"===t.role)).map((t=>t.text)),generated_responses:s.filter((t=>"ai"===t.role)).map((t=>t.text)),mostRecentMessageText:i}}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=this.processMessages(e);if(s)return i.options??(i.options={}),i.options.wait_for_model=!0,{inputs:{past_user_inputs:s.past_user_inputs,generated_responses:s.generated_responses,text:s.mostRecentMessageText},...i}}async extractResultData(t){if(t.error)throw t.error;return{text:t.generated_text||""}}}class pi extends oi{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=i.stabilityAI;super(t,ni.buildKeyVerificationDetails(),ni.buildHeaders,s,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/image-to-image",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI: Image to Image</b></div>\n <p>Upload an image to create a new one with the changes you have described.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=i.stabilityAI)?void 0:e.imageToImage;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/text-to-image`),void 0!==n.weight&&null!==n.weight&&(this._imageWeight=n.weight),pi.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=pi.canSendFileTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendFileTextMessage(t,e){return!(null==e||!e[0]||!t||""===t.trim())}createFormDataBody(t,e,i){const s=new FormData;return s.append("init_image",e),i&&""!==i&&s.append("text_prompts[0][text]",i),void 0!==this._imageWeight&&null!==this._imageWeight&&s.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach((e=>{s.append(e,String(t[e]))})),void 0===s.get("weight")&&s.append("weight",String(1)),s}async callServiceAPI(t,e,i){var s,n;if(!this.connectSettings)throw new Error("Request settings have not been set up");if(!i)throw new Error("Image was not found");const o=null==(n=null==(s=e[e.length-1])?void 0:s.text)?void 0:n.trim(),r=this.createFormDataBody(this.rawBody,i[0],o);xe.tempRemoveContentHeader(this.connectSettings,Ie.request.bind(this,this,r,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${si}${t.base64}`,type:"image"})))}}}class mi extends Ye{constructor(t){var e,i,s;super(t,"Insert text to translate","Helsinki-NLP/opus-tatoeba-en-ja",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.translation,null==(s=t.directConnection)?void 0:s.huggingFace)}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.translation_text)||""}}}class vi extends oi{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=i.stabilityAI;super(t,ni.buildKeyVerificationDetails(),ni.buildHeaders,s),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/text-to-image",this.textInputPlaceholderText="Describe an image",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI: Text to Image</b></div>\n <p>Insert text to generate an image.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=i.stabilityAI)?void 0:e.textToImage;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/text-to-image`),void 0!==n.weight&&null!==n.weight&&(this._imageWeight=n.weight),vi.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=vi.canSendTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendTextMessage(t){return!(!t||""===t.trim())}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s={text:e};return this._imageWeight&&(s.weight=this._imageWeight),i.text_prompts=[s],i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e[e.length-1].text);Ie.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${si}${t.base64}`,type:"image"})))}}}class fi extends Ye{constructor(t){var e,i,s;super(t,"The goal of life is [MASK].","bert-base-uncased",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.fillMask,null==(s=t.directConnection)?void 0:s.huggingFace),this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Hugging Face</b></div>\n <p>Insert a sentence with the word [MASK] and the model will try to fill it for you. E.g. I want [MASK].</p>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>',this.permittedErrorPrefixes=["Authorization header","No mask_token"]}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.sequence)||""}}}class gi{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json",accept:"application/json"}}static handleVerificationResult(t,e,i,s){var n;null!=(n=t.message)&&n.includes("invalid request: prompt must be at least 1 token long")?i(e):s(y.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api.cohere.ai/v1/generate",method:"POST",handleVerificationResult:gi.handleVerificationResult,body:JSON.stringify({prompt:""})}}}class bi extends Be{constructor(t,e,i,s,n){super(t,gi.buildKeyVerificationDetails(),gi.buildHeaders,n),this.insertKeyPlaceholderText="Cohere API Key",this.keyHelpUrl="https://dashboard.cohere.ai/api-keys",this.permittedErrorPrefixes=["invalid"],this.url=e,this.textInputPlaceholderText=i,s&&"object"==typeof s&&Object.assign(this.rawBody,s)}}class yi extends bi{constructor(t){var e,i,s;super(t,"https://api.cohere.ai/v1/generate","Once upon a time",null==(i=null==(e=t.directConnection)?void 0:e.cohere)?void 0:i.textGeneration,null==(s=t.directConnection)?void 0:s.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e[e.length-1].text;if(s)return{prompt:s,...i}}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Ie.request(this,i,t)}async extractResultData(t){var e;if(t.message)throw t.message;return{text:(null==(e=t.generations)?void 0:e[0].text)||""}}}class wi extends bi{constructor(t){var e,i,s;super(t,"https://api.cohere.ai/v1/summarize","Insert text to summarize",null==(i=null==(e=t.directConnection)?void 0:e.cohere)?void 0:i.summarization,null==(s=t.directConnection)?void 0:s.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e[e.length-1].text;if(s)return{text:s,...i}}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Ie.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.summary||""}}}class xi{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,s){const n=t;n.error?"invalid_api_key"===n.error.code?s(y.INVALID_KEY):s(y.CONNECTION_FAILED):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.openai.com/v1/models",method:"GET",handleVerificationResult:xi.handleVerificationResult}}static async directFetch(t,e,i,s=!0){t.connectSettings.method=i;const n=await xe.fetch(t,t.connectSettings.headers,s,e).then((t=>xe.processResponseByType(t)));if(n.error)throw n.error.message;return n}}const ki=class t extends Be{constructor(e){var i,s,n;const o=JSON.parse(JSON.stringify(e.directConnection)),r=null==o?void 0:o.openAI;super(e,xi.buildKeyVerificationDetails(),xi.buildHeaders,r),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/audio/speech",this.permittedErrorPrefixes=["Invalid"],this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI : Text To Speech</b></div>\n <p>Generate an audio file based on your text input.</p>\n <p>Click <a href="https://platform.openai.com/docs/guides/text-to-speech">here</a> for more information.</p>';const a=null==(i=null==o?void 0:o.openAI)?void 0:i.textToSpeech;"object"==typeof a&&Object.assign(this.rawBody,a),(s=this.rawBody).model??(s.model=t.DEFAULT_MODEL),(n=this.rawBody).voice??(n.voice=t.DEFAULT_VOIDE),this.textInputPlaceholderText="Insert text to generate audio",this.rawBody.response_format="mp3"}preprocessBody(t,e){var i,s;const n=JSON.parse(JSON.stringify(t)),o=null==(s=null==(i=e[e.length-1])?void 0:i.text)?void 0:s.trim();return o&&""!==o&&(n.input=o),n}async callServiceAPI(t,e){var i;if(null==(i=this.connectSettings)||!i.headers)throw new Error("Request settings have not been set up");this.url=this.connectSettings.url||this.url;const s=this.preprocessBody(this.rawBody,e);Ie.request(this,s,t)}async extractResultData(t){if(t instanceof Blob)return new Promise((e=>{const i=new FileReader;i.readAsDataURL(t),i.onload=t=>{e({files:[{src:t.target.result,type:"audio"}]})}}));if(t.error)throw t.error.message;return{error:"error"}}};ki.DEFAULT_MODEL="tts-1",ki.DEFAULT_VOIDE="alloy";let _i=ki;const Si=class t extends Be{constructor(e){var i,s;const n=JSON.parse(JSON.stringify(e.directConnection)),o=null==n?void 0:n.openAI;super(e,xi.buildKeyVerificationDetails(),xi.buildHeaders,o,{audio:{}}),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI : Speech To Text</b></div>\n <p><b>Upload an audio file</b> to transcribe it into text. You can optionally provide text to guide the audio\n processing.\n <p>Click <a href="https://platform.openai.com/docs/guides/speech-to-text">here</a> for more info.</p>',this.url="",this.permittedErrorPrefixes=["Invalid"],this.textInputPlaceholderText="Upload an audio file",this._service_url=t.AUDIO_TRANSCRIPTIONS_URL;const r=null==(i=null==n?void 0:n.openAI)?void 0:i.audio;"object"==typeof r&&(this.processConfig(r),t.cleanConfig(r),Object.assign(this.rawBody,r)),(s=this.rawBody).model??(s.model=t.DEFAULT_MODEL),this.rawBody.response_format="json",this.canSendMessage=t.canSendFileMessage}static canSendFileMessage(t,e){return!(null==e||!e[0])}processConfig(e){null!=e&&e.type&&"translation"===e.type&&(this._service_url=t.AUDIO_TRANSLATIONS_URL,delete e.language)}static cleanConfig(t){delete t.type}static createFormDataBody(t,e){const i=new FormData;return i.append("file",e),Object.keys(t).forEach((e=>{i.append(e,String(t[e]))})),i}preprocessBody(t,e){var i,s;const n=JSON.parse(JSON.stringify(t)),o=null==(s=null==(i=e[e.length-1])?void 0:i.text)?void 0:s.trim();return o&&""!==o&&(n.prompt=o),n}async callServiceAPI(e,i,s){var n;if(null==(n=this.connectSettings)||!n.headers)throw new Error("Request settings have not been set up");if(null==s||!s[0])throw new Error("No file was added");this.url=this.connectSettings.url||this._service_url;const o=this.preprocessBody(this.rawBody,i),r=t.createFormDataBody(o,s[0]);xe.tempRemoveContentHeader(this.connectSettings,Ie.request.bind(this,this,r,e),!1)}async extractResultData(t){if(t.error)throw t.error.message;return{text:t.text}}};Si.AUDIO_TRANSCRIPTIONS_URL="https://api.openai.com/v1/audio/transcriptions",Si.AUDIO_TRANSLATIONS_URL="https://api.openai.com/v1/audio/translations",Si.DEFAULT_MODEL="whisper-1";let Ti=Si;class Ai{static buildTextToSpeechHeaders(t,e){return{"Ocp-Apim-Subscription-Key":e,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":t}}static buildSpeechToTextHeaders(t){return{"Ocp-Apim-Subscription-Key":t,Accept:"application/json"}}static handleSpeechVerificationResult(t,e,i,s){t.error?s(y.INVALID_KEY):i(e)}static buildSpeechKeyVerificationDetails(t){return{url:`https://${t}.api.cognitive.microsoft.com/sts/v1.0/issuetoken`,method:"POST",createHeaders:t=>({"Ocp-Apim-Subscription-Key":`${t}`}),handleVerificationResult:Ai.handleSpeechVerificationResult}}static buildSummarizationHeader(t){return{"Ocp-Apim-Subscription-Key":t,"Content-Type":"application/json"}}static handleLanguageVerificationResult(t,e,i,s){var n;"401"===(null==(n=t.error)?void 0:n.code)?s(y.INVALID_KEY):i(e)}static buildLanguageKeyVerificationDetails(t){return{url:`${t}/language/analyze-text/jobs?api-version=2022-10-01-preview`,method:"POST",createHeaders:t=>({"Ocp-Apim-Subscription-Key":`${t}`}),handleVerificationResult:Ai.handleLanguageVerificationResult}}static handleTranslationVerificationResult(t,e,i,s){t.json().then((t=>{Array.isArray(t)||401e3!==t.error.code?i(e):s(y.INVALID_KEY)}))}static buildTranslationKeyVerificationDetails(t){return{url:"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es",method:"POST",createHeaders:e=>Ai.buildTranslationHeaders(t,e),handleVerificationResult:Ai.handleTranslationVerificationResult}}static buildTranslationHeaders(t,e){const i={"Ocp-Apim-Subscription-Key":e,"Content-Type":"application/json"};return t&&(i["Ocp-Apim-Subscription-Region"]=t),i}}class ji extends Be{constructor(t,e,i,s,n){super(t,Ai.buildLanguageKeyVerificationDetails(i),e,s,n),this.insertKeyPlaceholderText="Azure Language Subscription Key",this.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",this.permittedErrorPrefixes=["Access"]}}class Mi extends ji{constructor(t){var e,i,s,n;const o=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.summarization,r=null==(s=t.directConnection)?void 0:s.azure;super(t,Ai.buildSummarizationHeader,o.endpoint,r),this.url="",this.textInputPlaceholderText="Insert text to summarize",(n=this.rawBody).language??(n.language="en"),Object.assign(this.rawBody,o),this.url=`${o.endpoint}/language/analyze-text/jobs?api-version=2022-10-01-preview`}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return{analysisInput:{documents:[{id:"1",language:t.language,text:i}]},tasks:[{kind:"ExtractiveSummarization"}]}}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Ie.request(this,i,t),this.messages=t}async extractResultData(t){var e;if(t.error)throw t.error.message;if(this.messages&&this.completionsHandlers){const i=t.headers.get("operation-location"),s={method:"GET",headers:null==(e=this.connectSettings)?void 0:e.headers};Ie.executePollRequest(this,i,s,this.messages)}return{makingAnotherRequest:!0}}async extractPollResultData(t){if(t.error)throw t.error;if("running"===t.status)return{timeoutMS:2e3};if(t.errors.length>0)throw t.errors[0];if(t.tasks.items[0].results.errors.length>0)throw t.tasks.items[0].results.errors[0];let e="";for(const i of t.tasks.items[0].results.documents[0].sentences)e+=i.text;return{text:e||""}}}class Ci{static async poll(t,e){const i={authorization:t,"content-type":"application/json"},s=`https://api.assemblyai.com/v2/transcript/${(await(await fetch("https://api.assemblyai.com/v2/transcript",{method:"POST",body:JSON.stringify({audio_url:e}),headers:i})).json()).id}`;let n;for(;!n;){const t=await(await fetch(s,{headers:i})).json();if("completed"===t.status)n=t;else{if("error"===t.status)throw new Error(`Transcription failed: ${t.error}`);await new Promise((t=>setTimeout(t,3e3)))}}return n}static buildHeaders(t){return{Authorization:t,"Content-Type":"application/octet-stream"}}static handleVerificationResult(t,e,i,s){const n=t;n.error?"invalid_api_key"===n.error.code?s(y.INVALID_KEY):s(y.CONNECTION_FAILED):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.assemblyai.com/v2/upload",method:"POST",handleVerificationResult:Ci.handleVerificationResult}}}class Oi extends Be{constructor(t){var e;const i=null==(e=t.directConnection)?void 0:e.assemblyAI;super(t,Ci.buildKeyVerificationDetails(),Ci.buildHeaders,i,{audio:{}}),this.insertKeyPlaceholderText="AssemblyAI API Key",this.keyHelpUrl="https://www.assemblyai.com/app/account",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>AssemblyAI Audio</b></div>\n <p><b>Upload an audio file</b> to transcribe it into text.\n <p>\n Click <a href="https://www.assemblyai.com/docs/Guides/transcribing_an_audio_file#get-started">here</a> for more info.\n </p>',this.url="https://api.assemblyai.com/v2/upload",this.isTextInputDisabled=!0,this.textInputPlaceholderText="Upload an audio file",this.permittedErrorPrefixes=["Authentication","Invalid"],this.canSendMessage=Oi.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])}async callServiceAPI(t,e,i){var s;if(null==(s=this.connectSettings)||!s.headers)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");Ie.request(this,i[0],t,!1)}async extractResultData(t){var e,i;if(t.error)throw t.error;const s=null==(i=null==(e=this.connectSettings)?void 0:e.headers)?void 0:i.Authorization;return{text:(await Ci.poll(s,t.upload_url)).text}}}class Ei extends Be{constructor(t,e,i,s,n){super(t,Ai.buildSpeechKeyVerificationDetails(i),e,s,n),this.insertKeyPlaceholderText="Azure Speech Subscription Key",this.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal"}}const Ii=class t extends Ei{constructor(e){var i,s,n,o,r,a;const l=null==(s=null==(i=e.directConnection)?void 0:i.azure)?void 0:s.textToSpeech,c=null==(n=e.directConnection)?void 0:n.azure;super(e,Ai.buildTextToSpeechHeaders.bind({},(null==l?void 0:l.outputFormat)||"audio-16khz-128kbitrate-mono-mp3"),l.region,c),this.introPanelMarkUp=`\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Azure Text To Speech</b></div>\n <p>Insert text to synthesize it to audio.\n <p>\n Click <a href="${t.HELP_LINK}">here</a> for more info.\n </p>`,this.url="",Object.assign(this.rawBody,l),(o=this.rawBody).lang??(o.lang="en-US"),(r=this.rawBody).name??(r.name="en-US-JennyNeural"),(a=this.rawBody).gender??(a.gender="Female"),this.url=`https://${l.region}.tts.speech.microsoft.com/cognitiveservices/v1`}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return`<speak version='1.0' xml:lang='${t.lang}'>\n <voice xml:lang='${t.lang}' xml:gender='${t.gender}' name='${t.name}'>\n ${i}\n </voice>\n </speak>`}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Ie.request(this,i,t,!1)}async extractResultData(t){return new Promise((e=>{const i=new FileReader;i.readAsDataURL(t),i.onload=t=>{e({files:[{src:t.target.result,type:"audio"}]})}}))}};Ii.HELP_LINK="https://learn.microsoft.com/en-GB/azure/cognitive-services/speech-service/get-started-text-to-speech?tabs=windows%2Cterminal&pivots=programming-language-rest";let Pi=Ii;const Ni=class t extends Ei{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;super(e,Ai.buildSpeechToTextHeaders,o.region,r,{audio:{files:{acceptedFormats:".wav,.ogg"}}}),this.introPanelMarkUp=`\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Azure Speech To Text</b></div>\n <p><b>Upload a .wav or .ogg audio file</b> to transcribe it into text.\n <p>\n Click <a href="${t.HELP_LINK}">here</a> for more info.\n </p>`,this.url="",this.isTextInputDisabled=!0,this.textInputPlaceholderText="Upload an audio file",this.canSendMessage=t.canFileSendMessage;const a=o.lang||"en-US";this.url=`https://${o.region}.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=${a}&format=detailed`,this.recordAudio=void 0}static canFileSendMessage(t,e){return!(null==e||!e[0])}async callServiceAPI(t,e,i){var s,n;if(null==(s=this.connectSettings)||!s.headers)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");null!=(n=this.connectSettings)&&n.headers&&(this.connectSettings.headers["Content-Type"]=i[0].name.toLocaleLowerCase().endsWith(".wav")?"audio/wav; codecs=audio/pcm; samplerate=16000":"audio/ogg; codecs=opus"),Ie.request(this,i[0],t,!1)}async extractResultData(t){if(t.error)throw t.error;return{text:t.DisplayText||""}}};Ni.HELP_LINK="https://learn.microsoft.com/en-GB/azure/cognitive-services/speech-service/get-started-text-to-speech?tabs=windows%2Cterminal&pivots=programming-language-rest";let qi=Ni;class Ri extends Be{constructor(t){var e,i,s;const n=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.translation,o=null==(s=t.directConnection)?void 0:s.azure;super(t,Ai.buildTranslationKeyVerificationDetails(n.region),Ai.buildTranslationHeaders.bind({},null==n?void 0:n.region),o),this.insertKeyPlaceholderText="Azure Translate Subscription Key",this.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",this.url="",this.url=`https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=${n.language||"es"}`}preprocessBody(t){const e=t[t.length-1].text;if(e)return[{Text:e}]}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(e);Ie.request(this,i,t)}async extractResultData(t){var e;if(Array.isArray(t))return{text:(null==(e=t[0].translations)?void 0:e[0].text)||""};throw t.error}}const Li=class t{static async storeFiles(t,e,i){const s=t.connectSettings.headers;if(!s)return;t.url="https://api.openai.com/v1/files";const n=s[xe.CONTENT_TYPE];delete s[xe.CONTENT_TYPE];const o=i.map((async e=>{const i=new FormData;return i.append("purpose","assistants"),i.append("file",e),new Promise((e=>{e(xi.directFetch(t,i,"POST",!1))}))}));try{const t=(await Promise.all(o)).map((t=>({id:t.id,name:t.filename})));return s[xe.CONTENT_TYPE]=n,t}catch(i){throw s[xe.CONTENT_TYPE]=n,xe.displayError(e,i),t.completionsHandlers.onFinish(),i}}static getType(t,e){const{path:i}=t[e];return!i||i.endsWith("png")?"image":"any"}static async getFiles(e,i){const s=i.map((({fileId:t})=>(e.url=`https://api.openai.com/v1/files/${t}/content`,new Promise((t=>{t(xi.directFetch(e,void 0,"GET",!1))}))))),n=(await Promise.all(s)).map(((e,s)=>new Promise((n=>{const o=new FileReader;o.readAsDataURL(e),o.onload=e=>{n({src:e.target.result,name:i[s].name,type:t.getType(i,s)})}}))));return await Promise.all(n)}static getFileName(t){const e=t.split("/");return e[e.length-1]}static async getFilesAndNewText(e,i,s,n){var o,r;let a;return i.length>0&&(a=await t.getFiles(e,i),null!=(o=null==n?void 0:n.text)&&o.value&&a.forEach(((t,e)=>{var s;if(!t.src)return;const o=i[e].path;null!=(s=null==n?void 0:n.text)&&s.value&&o&&(n.text.value=n.text.value.replace(o,t.src))}))),null!=(r=null==n?void 0:n.text)&&r.value?{text:n.text.value,role:s}:{files:a,role:s}}static getFileDetails(e,i){var s;const n=[];return null!=(s=null==i?void 0:i.text)&&s.value&&e.content.forEach((e=>{var i,s;null==(s=null==(i=e.text)?void 0:i.annotations)||s.forEach((e=>{var i;e.text&&e.text.startsWith("sandbox:")&&null!=(i=e.file_path)&&i.file_id&&n.push({path:e.text,fileId:e.file_path.file_id,name:t.getFileName(e.text)})}))})),null!=i&&i.image_file&&n.push({fileId:i.image_file.file_id}),n}static async getFilesAndText(e,i,s){const n=t.getFileDetails(i,s);return await t.getFilesAndNewText(e,n,i.role,s)}static parseResult(t,e){let i=[];if(e)i=t.data;else for(let e=0;e<t.data.length;e+=1){const s=t.data[e];if("assistant"!==s.role)break;i.push(s)}return i.reverse()}static parseMessages(e,i){const s=[];return i.forEach((async i=>{i.content.filter((t=>!!t.text||!!t.image_file)).sort((t=>t.text?-1:t.image_file?1:0)).forEach((async n=>{s.push(t.getFilesAndText(e,i,n))}))})),Promise.all(s)}static async processStreamMessages(e,i){return t.parseMessages(e,[{content:i,role:"assistant"}])}static async processAPIMessages(e,i,s){const n=t.parseResult(i,s);return t.parseMessages(e,n)}};Li.FILES_WITH_TEXT_ERROR="content with type `text` must have `text` values",Li.FUNCTION_TOOL_RESP_ERROR="Response must contain an array of strings for each individual function/tool_call, see https://deepchat.dev/docs/directConnection/OpenAI/#assistant-functions.";let Bi=Li;const Fi=class t extends Be{constructor(t){var e,i,s,n,o,r;const a=JSON.parse(JSON.stringify(t.directConnection)),l=a.openAI;super(t,xi.buildKeyVerificationDetails(),xi.buildHeaders,l),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.url="",this.permittedErrorPrefixes=["Incorrect","Please send text",Ne.FAILED_ERROR_MESSAGE],this.searchedForThreadId=!1,this.config={},this.newAssistantDetails={model:"gpt-4"},this.shouldFetchHistory=!1,this.waitingForStreamResponse=!1,this.isSSEStream=!1;const c=null==(e=a.openAI)?void 0:e.assistant;if("object"==typeof c){this.config=c;const{new_assistant:e,thread_id:n,load_thread_history:o}=this.config;Object.assign(this.newAssistantDetails,e),n&&(this.sessionId=n),o&&(this.shouldFetchHistory=!0);const{function_handler:r}=null==(s=null==(i=t.directConnection)?void 0:i.openAI)?void 0:s.assistant;r&&(this._functionHandler=r),this.filesToolType=c.files_tool_type}else null!=(n=a.openAI)&&n.assistant&&(a.openAI.assistant=c);(o=this.connectSettings).headers??(o.headers={}),(r=this.connectSettings.headers)["OpenAI-Beta"]??(r["OpenAI-Beta"]="assistants=v2"),this.maxMessages=1,this.isSSEStream=!(!this.stream||"object"==typeof this.stream&&this.stream.simulation),this.shouldFetchHistory&&this.sessionId&&(this.fetchHistory=this.fetchHistoryFunc.bind(this))}async fetchHistoryFunc(){setTimeout((()=>this.deepChat.disableSubmitButton()),2);try{const t=await this.getThreadMessages(this.sessionId,!0);return this.deepChat.disableSubmitButton(!1),t}catch{return[{error:"Failed to fetch history"}]}}static processImageMessage(t,e){const i=null==e?void 0:e.filter((t=>de.isImageFileExtension(t.name))).map((t=>({type:"image_file",image_file:{file_id:t.id}})));if(i&&i.length>0)return t.text&&t.text.length>0&&i.push({type:"text",text:t.text}),{content:i,role:"user"}}static processAttachmentsMessage(t,e,i){return{attachments:e.map((t=>({tools:[{type:i}],file_id:t.id}))),content:[{type:"text",text:t.text}],role:"user"}}processMessage(e,i){const s=this.totalMessagesMaxCharLength||-1,n=qe.getCharacterLimitMessages(e,s)[0];if(i&&i.length>0){let e=this.filesToolType;if("function"==typeof this.filesToolType){const t=this.filesToolType(i.map((({name:t})=>t)));"code_interpreter"===t||"file_search"===t||"images"===t?e=t:(console.error(`Tool type "${t}" is not valid`),console.error('Expected "code_interpreter" or "file_search" or "images". Going to default to "images"'))}if("file_search"===e)return t.processAttachmentsMessage(n,i,"file_search");if("code_interpreter"===e)return t.processAttachmentsMessage(n,i,"code_interpreter");if(i.find((({name:t})=>!de.isImageFileExtension(t))))console.error("The uploaded files contained a non-image file"),console.error('Make sure only images can be uploaded or define a "code_interpreter" or "file_search" value in the "files_tool_type" property'),console.warn('Make sure your existing assistant supports these "tools" or specify them in the "new_assistant" property');else{const e=t.processImageMessage(n,i);if(e)return e}}return{content:n.text||"",role:"user"}}createNewThreadMessages(t,e,i){const s=JSON.parse(JSON.stringify(t)),n=this.processMessage(e,i);return s.thread={messages:[n]},s}callService(e,i,s){if(this.messages=e,this.sessionId){this.url=`${t.THREAD_PREFIX}/${this.sessionId}/messages`;const n=this.processMessage(i,s);Ie.request(this,n,e)}else{this.url=`${t.THREAD_PREFIX}/runs`;const n=this.createNewThreadMessages(this.rawBody,i,s);this.isSSEStream?this.createStreamRun(n):Ie.request(this,n,e)}}async callServiceAPI(t,e,i){var s;if(this.waitingForStreamResponse=!1,!this.connectSettings)throw new Error("Request settings have not been set up");(s=this.rawBody).assistant_id??(s.assistant_id=this.config.assistant_id||await this.createNewAssistant()),this.searchedForThreadId||this.searchPreviousMessagesForThreadId(t.messages);const n=i?await Bi.storeFiles(this,t,i):void 0;this.connectSettings.method="POST",this.callService(t,e,n)}async createNewAssistant(){try{this.url=t.NEW_ASSISTANT_URL;const e=await xi.directFetch(this,JSON.parse(JSON.stringify(this.newAssistantDetails)),"POST");return this.config.assistant_id=e.id,this.config.assistant_id}catch(t){console.error(t),console.error("Failed to create a new assistant")}}searchPreviousMessagesForThreadId(t){const e=t.find((t=>t._sessionId));e&&(this.sessionId=e._sessionId),this.searchedForThreadId=!0}async extractResultData(e){var i;if(this.waitingForStreamResponse||this.isSSEStream&&this.sessionId)return await this.handleStream(e);if(e.error)throw e.error.message.startsWith(Bi.FILES_WITH_TEXT_ERROR)?Error("Please send text with your file(s)"):e.error.message;await this.assignThreadAndRun(e);const s=`${t.THREAD_PREFIX}/${this.sessionId}/runs/${this.run_id}`,n={method:"GET",headers:null==(i=this.connectSettings)?void 0:i.headers};return Ie.executePollRequest(this,s,n,this.messages),{makingAnotherRequest:!0}}async assignThreadAndRun(e){if(this.sessionId){this.url=`${t.THREAD_PREFIX}/${this.sessionId}/runs`;const e=await xi.directFetch(this,JSON.parse(JSON.stringify(this.rawBody)),"POST");this.run_id=e.id}else this.sessionId=e.thread_id,this.run_id=e.id,this.messages&&(this.messages.messages[this.messages.messages.length-1]._sessionId=this.sessionId)}async getThreadMessages(e,i=!1){var s,n;this.url=`${t.THREAD_PREFIX}/${e}/messages?order=desc`;let o=await xi.directFetch(this,{},"GET");return!i&&this.deepChat.responseInterceptor&&(o=await(null==(n=(s=this.deepChat).responseInterceptor)?void 0:n.call(s,o))),Bi.processAPIMessages(this,o,i)}async extractPollResultData(e){var i;const{status:s,required_action:n}=e;if("queued"===s||"in_progress"===s)return{timeoutMS:t.POLLING_TIMEOUT_MS};if("completed"===s&&this.messages){const t=await this.getThreadMessages(e.thread_id),{text:i,files:s}=t.shift();return setTimeout((()=>{t.forEach((t=>this.deepChat.addMessage(t)))})),{text:i,_sessionId:this.sessionId,files:s}}const o=null==(i=null==n?void 0:n.submit_tool_outputs)?void 0:i.tool_calls;if("requires_action"===s&&o)return await this.handleTools(o);throw Error(`Thread run status: ${s}`)}async handleTools(e){if(!this._functionHandler)throw Error("Please define the `function_handler` property inside the [openAI](https://deepchat.dev/docs/directConnection/openAI#Assistant) object.");const i=e.map((t=>({name:t.function.name,arguments:t.function.arguments}))),s=await this._functionHandler(i);if(!Array.isArray(s)||e.length!==s.length)throw Error(Bi.FUNCTION_TOOL_RESP_ERROR);const n=await Promise.all(s);if(n.find((t=>"string"!=typeof t)))throw Error(Bi.FUNCTION_TOOL_RESP_ERROR);const o=n.map(((t,i)=>({tool_call_id:e[i].id,output:t})));return this.url=`${t.THREAD_PREFIX}/${this.sessionId}/runs/${this.run_id}/submit_tool_outputs`,this.isSSEStream?await this.createStreamRun({tool_outputs:o}):await xi.directFetch(this,{tool_outputs:o},"POST"),{timeoutMS:t.POLLING_TIMEOUT_MS}}async handleStream(e){var i,s;const n=null==(s=null==(i=e.required_action)?void 0:i.submit_tool_outputs)?void 0:s.tool_calls;if("requires_action"===e.status&&n)return this.run_id=e.id,await this.handleTools(n);if(this.waitingForStreamResponse)return this.parseStreamResult(e);if(this.isSSEStream&&this.sessionId){this.url=`${t.THREAD_PREFIX}/${this.sessionId}/runs`;const e=JSON.parse(JSON.stringify(this.rawBody));this.createStreamRun(e)}return{makingAnotherRequest:!0}}async parseStreamResult(t){var e,i,s,n,o;if(t.content&&t.content.length>0&&this.messages){const s=t.content.find((t=>t.text));if(null!=(e=null==s?void 0:s.text)&&e.annotations&&s.text.annotations.length>0){const e=t.content.find((t=>!!t.text))||t.content[0],s=Bi.getFilesAndText.bind(this,this,{role:"assistant",content:t.content},e);return null==(i=this.messageStream)||i.endStreamAfterFileDownloaded(this.messages,s),{text:""}}}if(null!=(s=t.delta)&&s.content){if(t.delta.content.length>1){const e=t.delta.content.find((t=>t.text));if(null!=(n=null==e?void 0:e.text)&&n.annotations&&0===e.text.annotations.length){const e=await Bi.processStreamMessages(this,t.delta.content);return{text:e[0].text,files:e[1].files}}}return{text:null==(o=t.delta.content[0].text)?void 0:o.value}}return!this.sessionId&&t.thread_id&&(this.sessionId=t.thread_id),{makingAnotherRequest:!0}}async createStreamRun(t){t.stream=!0,this.waitingForStreamResponse=!0,this.messageStream=await je.request(this,t,this.messages,!0,!0)}};Fi.THREAD_PREFIX="https://api.openai.com/v1/threads",Fi.NEW_ASSISTANT_URL="https://api.openai.com/v1/assistants",Fi.POLLING_TIMEOUT_MS=800;let zi=Fi;const Di=class t extends Be{constructor(e){var i;const{directConnection:s}=e,n=null==s?void 0:s.openAI;super(e,xi.buildKeyVerificationDetails(),xi.buildHeaders,n,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI DALL·E</b></div>\n <p><b>Insert text</b> to generate an image.</p>\n <p><b>Upload 1</b> PNG image to generate its variation and optionally insert text to specify the change.</p>\n <p><b>Upload 2</b> PNG images where the second is a copy of the first with a transparent area where the edit should\n take place and text to specify the edit.</p>\n <p>Click <a href="https://platform.openai.com/docs/guides/images/introduction">here</a> for more info.</p>',this.url="",this.permittedErrorPrefixes=["Incorrect","Invalid input image"];const o=null==(i=null==s?void 0:s.openAI)?void 0:i.images;if(this.camera){const t="object"==typeof o&&o.size?Number.parseInt(o.size):1024;this.camera.files={dimensions:{width:t,height:t}}}"object"==typeof o&&Object.assign(this.rawBody,o),this.canSendMessage=t.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])||!(!t||""===t.trim())}static createFormDataBody(t,e,i){const s=new FormData;return s.append("image",e),i&&s.append("mask",i),Object.keys(t).forEach((e=>{s.append(e,String(t[e]))})),s}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t));return e&&""!==e&&(i.prompt=e),i}callApiWithImage(e,i,s){var n,o;let r;const a=null==(o=null==(n=i[i.length-1])?void 0:n.text)?void 0:o.trim();if(s[1]||a&&""!==a){this.url=t.IMAGE_EDIT_URL;const e=this.preprocessBody(this.rawBody,a);r=t.createFormDataBody(e,s[0],s[1])}else this.url=t.IMAGE_VARIATIONS_URL,r=t.createFormDataBody(this.rawBody,s[0]);xe.tempRemoveContentHeader(this.connectSettings,Ie.request.bind(this,this,r,e),!1)}async callServiceAPI(e,i,s){var n;if(null==(n=this.connectSettings)||!n.headers)throw new Error("Request settings have not been set up");if(null!=s&&s[0])this.callApiWithImage(e,i,s);else{if(!this.connectSettings)throw new Error("Request settings have not been set up");this.url=t.IMAGE_GENERATION_URL;const s=this.preprocessBody(this.rawBody,i[i.length-1].text);Ie.request(this,s,e)}}async extractResultData(t){if(t.error)throw t.error.message;return{files:t.data.map((t=>t.url?{src:t.url,type:"image"}:{src:`${si}${t.b64_json}`,type:"image"}))}}};Di.IMAGE_GENERATION_URL="https://api.openai.com/v1/images/generations",Di.IMAGE_VARIATIONS_URL="https://api.openai.com/v1/images/variations",Di.IMAGE_EDIT_URL="https://api.openai.com/v1/images/edits";let $i=Di;class Ji extends Be{constructor(t){var e,i,s,n;const o=JSON.parse(JSON.stringify(t.directConnection)),r=o.openAI;super(t,xi.buildKeyVerificationDetails(),xi.buildHeaders,r),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/chat/completions",this.permittedErrorPrefixes=["Incorrect"],this.asyncCallInProgress=!1,this._systemMessage=Ji.generateSystemMessage("You are a helpful assistant.");const a=null==(e=o.openAI)?void 0:e.chat;if("object"==typeof a){a.system_prompt&&(this._systemMessage=Ji.generateSystemMessage(a.system_prompt));const{function_handler:e}=null==(s=null==(i=t.directConnection)?void 0:i.openAI)?void 0:s.chat;e&&(this._functionHandler=e),this.cleanConfig(a),Object.assign(this.rawBody,a)}this.maxMessages??(this.maxMessages=-1),(n=this.rawBody).model??(n.model="gpt-4o")}static generateSystemMessage(t){return{role:"system",content:t}}cleanConfig(t){delete t.system_prompt,delete t.function_handler}static getContent(t){if(t.files&&t.files.length>0){const e=t.files.map((t=>({type:"image_url",image_url:{url:t.src}})));return t.text&&t.text.trim().length>0&&e.unshift({type:"text",text:t.text}),e}return t.text}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=qe.getCharacterLimitMessages(e,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.content.length:-1).map((t=>({content:Ji.getContent(t),role:t.role===I.USER_ROLE?"user":"assistant"})));return e.find((t=>t.files&&t.files.length>0))&&(i.max_tokens??(i.max_tokens=300)),i.messages=[this._systemMessage,...s],i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e),s=this.stream;s&&("object"!=typeof s||!s.simulation)||i.stream?(i.stream=!0,je.request(this,i,t)):Ie.request(this,i,t)}async extractResultData(t,e,i){var s,n,o,r;if(t.error)throw t.error.message;return null!=(n=null==(s=t.choices)?void 0:s[0])&&n.delta?this.extractStreamResult(t.choices[0],e,i):null!=(r=null==(o=t.choices)?void 0:o[0])&&r.message?t.choices[0].message.tool_calls?this.handleTools(t.choices[0].message,e,i):{text:t.choices[0].message.content}:{text:""}}async extractStreamResult(t,e,i){const{delta:s,finish_reason:n}=t;if("tool_calls"===n){this.asyncCallInProgress=!0;const t={tool_calls:this._streamToolCalls};return this._streamToolCalls=void 0,this.handleTools(t,e,i)}return null!=s&&s.tool_calls&&(this._streamToolCalls?s.tool_calls.forEach(((t,e)=>{this._streamToolCalls&&(this._streamToolCalls[e].function.arguments+=t.function.arguments)})):this._streamToolCalls=s.tool_calls),{text:(null==s?void 0:s.content)||""}}async handleTools(t,e,i){var s,n,o,r,a;if(!(t.tool_calls&&e&&i&&this._functionHandler))throw Error("Please define the `function_handler` property inside the [openAI](https://deepchat.dev/docs/directConnection/openAI#Chat) object.");const l=JSON.parse(JSON.stringify(i)),c=t.tool_calls.map((t=>({name:t.function.name,arguments:t.function.arguments}))),h=await(null==(s=this._functionHandler)?void 0:s.call(this,c));if(h.text){const t={text:h.text};return await(null==(o=(n=this.deepChat).responseInterceptor)?void 0:o.call(n,t))||t}if(l.messages.push({tool_calls:t.tool_calls,role:"assistant",content:null}),Array.isArray(h)&&!h.find((t=>"string"!=typeof t))||c.length===h.length){h.forEach(((e,i)=>{var s;const n=null==(s=t.tool_calls)?void 0:s[i];null==l||l.messages.push({role:"tool",tool_call_id:null==n?void 0:n.id,name:null==n?void 0:n.function.name,content:e.response})})),delete l.tools,delete l.tool_choice,delete l.stream;try{let t=await(null==e?void 0:e(l).then((t=>xe.processResponseByType(t))));if(t=await(null==(a=(r=this.deepChat).responseInterceptor)?void 0:a.call(r,t))||t,t.error)throw t.error.message;return{text:t.choices[0].message.content||""}}catch(t){throw this.asyncCallInProgress=!1,t}}throw Error("Response object must either be {response: string}[] for each individual function or {text: string} for a direct response, see https://deepchat.dev/docs/directConnection/OpenAI#FunctionHandler.")}}class Vi extends bi{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=null==(e=i.cohere)?void 0:e.chat;super(t,"https://api.cohere.ai/v1/chat","Ask me anything!",s,i.cohere),"object"==typeof s&&Object.assign(this.rawBody,s),this.maxMessages??(this.maxMessages=-1)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e.filter((t=>t.text));return i.query=s[s.length-1].text,i.chat_history=s.slice(0,s.length-1).map((t=>({text:t.text,user_name:"ai"===t.role?"CHATBOT":"USER"}))),i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Ie.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.text}}}class Ui{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json",accept:"application/json"}}static handleVerificationResult(t,e,i,s){var n;null!=(n=t.message)&&n.includes("invalid request: prompt must be at least 1 token long")?i(e):s(y.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api.mistral.ai/v1/models",method:"GET",handleVerificationResult:Ui.handleVerificationResult}}}class Hi extends Be{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)).mistral;super(t,Ui.buildKeyVerificationDetails(),Ui.buildHeaders,i),this.insertKeyPlaceholderText="Mistral API Key",this.keyHelpUrl="https://console.mistral.ai/api-keys/",this.url="https://api.mistral.ai/v1/chat/completions",this.permittedErrorPrefixes=["invalid"],i&&(this.cleanConfig(i),Object.assign(this.rawBody,i)),this.maxMessages??(this.maxMessages=-1),(e=this.rawBody).model??(e.model="open-mistral-7b")}cleanConfig(t){delete t.key}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e.filter((t=>t.text));return i.messages=s.slice(0,s.length-1).map((t=>({text:t.text,user_name:"ai"===t.role?"system":"user"}))),i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Ie.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.text}}}class Ki{static create(t){const{directConnection:e,connect:i,demo:s,webModel:n}=t;if(n)return new We(t);if(e){if(e.openAI)return e.openAI.images?new $i(t):e.openAI.speechToText?new Ti(t):e.openAI.textToSpeech?new _i(t):e.openAI.assistant?new zi(t):new Ji(t);if(e.assemblyAI)return new Oi(t);if(e.cohere)return e.cohere.textGeneration?new yi(t):e.cohere.summarization?new wi(t):new Vi(t);if(e.huggingFace)return e.huggingFace.textGeneration?new ci(t):e.huggingFace.summarization?new ui(t):e.huggingFace.translation?new mi(t):e.huggingFace.fillMask?new fi(t):e.huggingFace.questionAnswer?new hi(t):e.huggingFace.audioSpeechRecognition?new li(t):e.huggingFace.audioClassification?new ei(t):e.huggingFace.imageClassification?new ii(t):new di(t);if(e.azure){if(e.azure.speechToText)return new qi(t);if(e.azure.textToSpeech)return new Pi(t);if(e.azure.summarization)return new Mi(t);if(e.azure.translation)return new Ri(t)}if(e.stabilityAI)return e.stabilityAI.imageToImage?new pi(t):e.stabilityAI.imageToImageUpscale?new ri(t):e.stabilityAI.imageToImageMasking?new ai(t):new vi(t);if(e.mistral)return new Hi(t)}return!i||s&&i.stream?new Le(t,void 0,s||!0):new Le(t)}}const Gi=class{};Gi.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 Zi=Gi;function Wi(t){return function(e,i){Object.defineProperty(e,i,{});const s=e.constructor,n=i.toLocaleLowerCase();s._attributes_[n]=Zi.attibutes[t],s._attributeToProperty_[n]=i}}class Xi{constructor(t,e,i){this._isDisplayed=!1,t?(this._elementRef=this.createIntroPanelWithChild(t,i),this._isDisplayed=!0):e&&(this._elementRef=this.createInternalIntroPanel(e,i),this._isDisplayed=!0)}static createIntroPanel(t){const e=document.createElement("div");return e.classList.add("intro-panel"),Object.assign(e.style,t),e}createIntroPanelWithChild(t,e){const i=Xi.createIntroPanel(e);return"none"===t.style.display&&(t.style.display="block"),i.appendChild(t),i}createInternalIntroPanel(t,e){const i=Xi.createIntroPanel(e);return i.id="internal-intro-panel",i.innerHTML=t,i}hide(){this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="none",this._isDisplayed=!1)}display(){!this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="",this._isDisplayed=!0)}}class Qi{static getText(t,e){var i;if(!(t.directConnection||t.connect||t.webModel||t.demo))return"Connect to any API using the [connect](https://deepchat.dev/docs/connect#connect-1) property or a popular service via [directConnection](https://deepchat.dev/docs/directConnection/#directConnection).\n Host AI entirely on your browser via a [webModel](https://deepchat.dev/docs/webModel).\n To get started checkout the [Start](https://deepchat.dev/start) page and live code [examples](https://deepchat.dev/examples/frameworks).\n To remove this message set the [demo](https://deepchat.dev/docs/demo#demo) property to true.";if(t.directConnection){if(!e.isDirectConnection())return"Please define a valid service inside\n the [directConnection](https://deepchat.dev/docs/directConnection/#directConnection) object.";const s=null==(i=t.directConnection.openAI)?void 0:i.chat;if("object"==typeof s&&s.tools&&!s.function_handler)return"Please define the `function_handler` property inside the openAI [chat](https://deepchat.dev/docs/directConnection/openAI#Chat) object."}else if(t.connect&&!t.connect.url&&!t.connect.handler)return t.demo?t.connect.stream?null:"When [demo](https://deepchat.dev/docs/demo) mode is enabled - the [connect](https://deepchat.dev/docs/connect#connect-1) object can only accept the [stream](https://deepchat.dev/docs/connect#Stream) property.":"Please define a `url` or a `handler` property inside the [connect](https://deepchat.dev/docs/connect#connect-1) object.";return null}}class Yi{static createImage(t,e,i){const s=new Image;return s.src=t.src,i||de.scrollDownOnImageLoad(s.src,e),de.processContent("image",s,s.src,t.name)}static async addNewImageMessage(t,e,i,s){const n=Yi.createImage(e,t.elementRef,s),o=t.createNewMessageElement("",i);o.bubbleElement.appendChild(n),o.bubbleElement.classList.add("image-message"),de.addMessage(t,o,"image",i,s)}static createAudioElement(t,e){const i=document.createElement("audio");return i.src=t.src,i.classList.add("audio-player"),i.controls=!0,l.IS_SAFARI&&(i.classList.add("audio-player-safari"),i.classList.add(e===I.USER_ROLE?"audio-player-safari-right":"audio-player-safari-left")),i}static addNewAudioMessage(t,e,i,s){const n=Yi.createAudioElement(e,i),o=t.createMessageElementsOnOrientation("",i,s);o.bubbleElement.appendChild(n),o.bubbleElement.classList.add("audio-message"),de.addMessage(t,o,"audio",i,s)}static createAnyFile(t){const e=document.createElement("div");e.classList.add("any-file-message-contents");const i=document.createElement("div");i.classList.add("any-file-message-icon-container");const s=$e.createSVGElement('<?xml version="1.0" encoding="iso-8859-1"?>\n<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" \n\t viewBox="50 30 420 450" xml:space="preserve">\n<g filter="brightness(0) saturate(100%) invert(16%) sepia(0%) saturate(1942%) hue-rotate(215deg) brightness(99%) contrast(93%)">\n\t<g>\n\t\t<path d="M447.933,103.629c-0.034-3.076-1.224-6.09-3.485-8.352L352.683,3.511c-0.004-0.004-0.007-0.005-0.011-0.008\n\t\t\tC350.505,1.338,347.511,0,344.206,0H89.278C75.361,0,64.04,11.32,64.04,25.237v461.525c0,13.916,11.32,25.237,25.237,25.237\n\t\t\th333.444c13.916,0,25.237-11.32,25.237-25.237V103.753C447.96,103.709,447.937,103.672,447.933,103.629z M356.194,40.931\n\t\t\tl50.834,50.834h-49.572c-0.695,0-1.262-0.567-1.262-1.262V40.931z M423.983,486.763c0,0.695-0.566,1.261-1.261,1.261H89.278\n\t\t\tc-0.695,0-1.261-0.566-1.261-1.261V25.237c0-0.695,0.566-1.261,1.261-1.261h242.94v66.527c0,13.916,11.322,25.239,25.239,25.239\n\t\t\th66.527V486.763z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,164.014H149.912c-6.62,0-11.988,5.367-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,169.381,368.707,164.014,362.088,164.014z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,236.353H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,241.721,368.707,236.353,362.088,236.353z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,308.691H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C374.076,314.06,368.707,308.691,362.088,308.691z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M256,381.031H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988H256\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C267.988,386.398,262.62,381.031,256,381.031z"/>\n\t</g>\n</g>\n</svg>');s.classList.add("any-file-message-icon"),i.appendChild(s);const n=document.createElement("div");return n.classList.add("any-file-message-text"),n.textContent=t.name||de.DEFAULT_FILE_NAME,e.appendChild(i),e.appendChild(n),de.processContent("any",e,t.src,n.textContent)}static addNewAnyFileMessage(t,e,i,s){const n=t.createMessageElementsOnOrientation("",i,s),o=Yi.createAnyFile(e);n.bubbleElement.classList.add("any-file-message-bubble"),n.bubbleElement.appendChild(o),de.addMessage(t,n,"file",i,s)}static addMessages(t,e,i,s){e.forEach((e=>{e.ref&&(e=de.removeFileRef(e)),de.isAudioFile(e)?Yi.addNewAudioMessage(t,e,i,s):de.isImageFile(e)?Yi.addNewImageMessage(t,e,i,s):Yi.addNewAnyFileMessage(t,e,i,s)}))}}class ts extends ge{constructor(t,e,i){var s,n;super(t);const{permittedErrorPrefixes:o,introPanelMarkUp:r,demo:a}=e;this._errorMessageOverrides=null==(s=t.errorMessages)?void 0:s.overrides,this._onClearMessages=pe.onClearMessages.bind(this,t),this._onError=pe.onError.bind(this,t),this._displayLoadingMessage=ts.getDisplayLoadingMessage(t,e),this._permittedErrorPrefixes=o,this.addSetupMessageIfNeeded(t,e)||this.populateIntroPanel(i,r,t.introPanelStyle),this.addIntroductoryMessages(t,e),new Ne(t,this,e),this._displayServiceErrorMessages=null==(n=t.errorMessages)?void 0:n.displayServiceErrorMessages,t.getMessages=()=>JSON.parse(JSON.stringify(this.messages)),t.clearMessages=this.clearMessages.bind(this,e),t.refreshMessages=this.refreshTextMessages.bind(this),t.scrollToBottom=x.scrollToBottom.bind(this,this.elementRef),t.addMessage=(t,e)=>{this.addAnyMessage({...t,sendUpdate:!!e},!e)},e.isWebModel()&&e.setUpMessages(this),a&&this.prepareDemo(a),t.textToSpeech&&_.processConfig(t.textToSpeech,(t=>{this.textToSpeech=t}))}static getDisplayLoadingMessage(t,e){return!e.websocket&&(t.displayLoadingBubble??!0)}prepareDemo(t){"object"==typeof t&&(t.response&&(this.customDemoResponse=t.response),t.displayErrors&&(t.displayErrors.default&&this.addNewErrorMessage("",""),t.displayErrors.service&&this.addNewErrorMessage("service",""),t.displayErrors.speechToText&&this.addNewErrorMessage("speechToText","")),t.displayLoadingBubble&&this.addLoadingMessage())}addSetupMessageIfNeeded(t,e){const i=Qi.getText(t,e);if(i){const t=this.createAndAppendNewMessageElement(i,I.AI_ROLE);this.applyCustomStyles(t,I.AI_ROLE,!1)}return!!i}addIntroductoryMessages(t,e){null!=t&&t.shadowRoot&&(this._introMessage=t.introMessage);let i=this._introMessage;null!=e&&e.isWebModel()&&(i??(i=e.getIntroMessage(i))),i&&(Array.isArray(i)?i.forEach(((t,e)=>{0!==e&&I.hideRoleElements(this.messageElementRefs,!!this._avatars,!!this._names),this.addIntroductoryMessage(t)})):this.addIntroductoryMessage(i))}addIntroductoryMessage(t){var e;let i;null!=t&&t.text?i=this.createAndAppendNewMessageElement(t.text,I.AI_ROLE):null!=t&&t.html&&(i=B.add(this,t.html,I.AI_ROLE,this.messageElementRefs)),i&&(this.applyCustomStyles(i,I.AI_ROLE,!1,null==(e=this.messageStyles)?void 0:e.intro),i.outerContainer.classList.add("deep-chat-intro"))}removeIntroductoryMessage(){const t=this.messageElementRefs[0];t.outerContainer.classList.contains("deep-chat-intro")&&(t.outerContainer.remove(),this.messageElementRefs.shift())}addAnyMessage(t,e=!1,i=!1){return t.error?this.addNewErrorMessage("service",t.error):this.addNewMessage(t,e,i)}addNewMessage(t,e=!1,i=!1){const s=ts.createMessageContent(t),n={status:t.overwrite};if(!t.ignoreText&&void 0!==s.text&&null!==t.text&&(this.addNewTextMessage(s.text,s.role,n,i),!e&&this.textToSpeech&&s.role!==I.USER_ROLE&&_.speak(s.text,this.textToSpeech)),s.files&&Array.isArray(s.files)&&Yi.addMessages(this,s.files,s.role,i),void 0!==s.html&&null!==s.html){const t=B.add(this,s.html,s.role,this.messageElementRefs,n,i);R.isElementTemporary(t)&&delete s.html}return this.isValidMessageContent(s)&&!i&&this.updateStateOnMessage(s,t.overwrite,t.sendUpdate,e),s}isValidMessageContent(t){return t.text||t.html||t.files&&t.files.length>0}updateStateOnMessage(t,e,i=!0,s=!1){e||this.messages.push(t),i&&this.sendClientUpdate(t,s)}removeMessageOnError(){const t=this.messageElementRefs[this.messageElementRefs.length-1],e=null==t?void 0:t.bubbleElement;(null!=e&&e.classList.contains(ye.MESSAGE_CLASS)&&""===e.textContent||ts.isTemporaryElement(t))&&this.removeLastMessage()}addNewErrorMessage(t,e,i=!1){var s,n,o,r,a;this.removeMessageOnError();const l=this.getPermittedMessage(e)||(null==(s=this._errorMessageOverrides)?void 0:s[t])||(null==(n=this._errorMessageOverrides)?void 0:n.default)||"Error, please try again.",c=this.createMessageElementsOnOrientation(l,"",i);I.hideRoleElements(this.messageElementRefs,!!this._avatars,!!this._names);const{bubbleElement:h,outerContainer:u}=c;h.classList.add("error-message-text"),this.renderText(h,l);const d=fe.extractParticularSharedStyles(["fontSize","fontFamily"],null==(o=this.messageStyles)?void 0:o.default);fe.applyCustomStylesToElements(c,!1,d),fe.applyCustomStylesToElements(c,!1,null==(r=this.messageStyles)?void 0:r.error),i||this.elementRef.appendChild(u),this.textToSpeech&&_.speak(l,this.textToSpeech),null==(a=this._onError)||a.call(this,l)}static checkPermittedErrorPrefixes(t,e){for(let i=0;i<t.length;i+=1)if(e.startsWith(t[i]))return e}static extractErrorMessages(t){return Array.isArray(t)?t:t instanceof Error?[t.message]:"string"==typeof t?[t]:"object"==typeof t&&t.error?[t.error]:[]}getPermittedMessage(t){if(t){const e=ts.extractErrorMessages(t);for(let t=0;t<e.length;t+=1){const i=e[t];if("string"==typeof i){if(this._displayServiceErrorMessages)return i;if(this._permittedErrorPrefixes){const t=ts.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,i);if(t)return t}}}}}removeError(){this.isLastMessageError()&&I.getLastMessageElement(this.elementRef).remove()}addDefaultLoadingMessage(){const t=this.createMessageElements("",I.AI_ROLE),{bubbleElement:e}=t;t.bubbleElement.classList.add(A.DOTS_CONTAINER_CLASS);const i=document.createElement("div");return i.classList.add("loading-message-dots"),e.appendChild(i),A.setDots(e,this.messageStyles),t}addLoadingMessage(){var t,e,i,s,n,o;if(!this._displayLoadingMessage)return;const r=null==(i=null==(e=null==(t=this.messageStyles)?void 0:t.loading)?void 0:e.message)?void 0:i.html,a=r?B.createElements(this,r,I.AI_ROLE,!1):this.addDefaultLoadingMessage();this.elementRef.appendChild(a.outerContainer),a.bubbleElement.classList.add(A.BUBBLE_CLASS),this.applyCustomStyles(a,I.AI_ROLE,!1,null==(o=null==(n=null==(s=this.messageStyles)?void 0:s.loading)?void 0:n.message)?void 0:o.styles),x.scrollToBottom(this.elementRef)}populateIntroPanel(t,e,i){(t||e)&&(this._introPanel=new Xi(t,e,i),this._introPanel._elementRef&&(L.apply(this,this._introPanel._elementRef),this.elementRef.appendChild(this._introPanel._elementRef)))}async addMultipleFiles(t){return Promise.all((t||[]).map((t=>new Promise((e=>{if(t.type&&"any"!==t.type){const i=new FileReader;i.readAsDataURL(t.file),i.onload=()=>{e({src:i.result,type:t.type,ref:t.file})}}else{const i=t.file.name||de.DEFAULT_FILE_NAME;e({name:i,type:"any",ref:t.file})}})))))}static isActiveElement(t){return t.contains(A.BUBBLE_CLASS)||t.contains(ve.CLASS)||t.contains(ye.MESSAGE_CLASS)}clearMessages(t,e){var i,s;const n=[],o=[];this.messageElementRefs.forEach((t=>{const e=t.bubbleElement.classList;ts.isActiveElement(e)?n.push(t):t.outerContainer.remove()})),this.textElementsToText.forEach((t=>{const e=t[0].bubbleElement.classList;ts.isActiveElement(e)&&o.push(t)})),Array.from(this.elementRef.children).forEach((t=>{var e;const i=null==(e=t.children[0])?void 0:e.children[0];null!=i&&i.classList.contains("error-message-text")&&t.remove()})),this.messageElementRefs=n,this.messages.splice(0,this.messages.length),!1!==e&&(null!=(i=this._introPanel)&&i._elementRef&&this._introPanel.display(),this.addIntroductoryMessages()),this.textElementsToText=o,null==(s=this._onClearMessages)||s.call(this),delete t.sessionId}}const es=class t{static adjustInputPadding(t,e){e["inside-left"].length>0&&t.classList.add("text-input-inner-left-adjustment"),e["inside-right"].length>0&&t.classList.add("text-input-inner-right-adjustment")}static adjustForOutsideButton(e,i,s){0===s["outside-right"].length&&s["outside-left"].length>0?(e[0].classList.add(t.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS)):0===s["outside-left"].length&&s["outside-right"].length>0&&(e[3].classList.add(t.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS))}static adjustOutsideSubmit(e,i,s){if(!(s["inside-left"].length>0||s["inside-right"].length>0)){if(0===s["outside-right"].length&&s["outside-left"].length>0)return e[0].classList.add(t.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),s["outside-left"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")));if(0===s["outside-left"].length&&s["outside-right"].length>0)return e[3].classList.add(t.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),s["outside-right"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")))}}static set(e,i,s,n){!!t.adjustOutsideSubmit(i,s,n)||t.adjustForOutsideButton(i,s,n),t.adjustInputPadding(e,n)}};es.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS="text-input-container-left-adjustment",es.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS="text-input-container-right-adjustment",es.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS="text-input-container-left-small-adjustment",es.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS="text-input-container-right-small-adjustment";let is=es;class ss{static create(){return Array.from({length:4}).map(((t,e)=>{const i=document.createElement("div");return i.classList.add("input-button-container"),(0===e||3===e)&&i.classList.add("outer-button-container"),(1===e||2===e)&&i.classList.add("inner-button-container"),i}))}static add(t,e){t.insertBefore(e[1],t.firstChild),t.insertBefore(e[0],t.firstChild),t.appendChild(e[2]),t.appendChild(e[3])}static getContainerIndex(t){return"outside-left"===t?0:"inside-left"===t?1:"inside-right"===t?2:3}static addButton(t,e,i){e.classList.add(i);const s=ss.getContainerIndex(i);t[s].appendChild(e),3===s&&e.classList.add("outside-right")}}const ns=["camera","gifs","images","audio","mixedFiles","submit","microphone"];class os{static createTextElement(t){const e=document.createElement("div");return e.classList.add("text-button"),e.innerText=t,e}static createElement(t,e){return e?os.createTextElement(t):$e.createSVGElement(t)}static createCustomElement(t,e){var i,s,n,o;const r=null==e?void 0:e[t];return null!=(i=null==r?void 0:r.svg)&&i.content?os.createElement(null==(s=null==r?void 0:r.svg)?void 0:s.content,!1):null!=(n=null==r?void 0:r.text)&&n.content?os.createElement(null==(o=null==r?void 0:r.text)?void 0:o.content,!0):void 0}static processElement(t,e){null!=e&&e.classList.contains("text-button")||t.classList.add("input-button-svg")}static createSpecificStateElement(t,e,i){let s;return i&&(s=os.createCustomElement(e,i)),os.processElement(t,s),s}static createInnerElement(t,e,i,s,n=!1){var o,r;return(!n||null!=(r=null==(o=null==s?void 0:s[i])?void 0:o.svg)&&r.content)&&os.createSpecificStateElement(t,i,s)||e}}class rs{static unsetAllCSS(t,e){var s,n;e.container&&i.unsetAllCSSMouseStates(t,e.container),null!=(s=e.svg)&&s.styles&&i.unsetAllCSSMouseStates(t.children[0],e.svg.styles),null!=(n=e.text)&&n.styles&&i.unsetAllCSSMouseStates(t.children[0],e.text.styles)}static unsetActionCSS(t,e){var s,n;e.container&&i.unsetActivityCSSMouseStates(t,e.container),null!=(s=e.svg)&&s.styles&&i.unsetActivityCSSMouseStates(t.children[0],e.svg.styles),null!=(n=e.text)&&n.styles&&i.unsetActivityCSSMouseStates(t.children[0],e.text.styles)}static setElementsCSS(t,e,i){var s,n,o,r,a;Object.assign(t.style,null==(s=e.container)?void 0:s[i]),Object.assign(t.children[0].style,null==(o=null==(n=e.svg)?void 0:n.styles)?void 0:o[i]),Object.assign(t.children[0].style,null==(a=null==(r=e.text)?void 0:r.styles)?void 0:a[i])}static setElementCssUpToState(t,e,i){rs.setElementsCSS(t,e,"default"),"default"!==i&&(rs.setElementsCSS(t,e,"hover"),"hover"!==i&&rs.setElementsCSS(t,e,"click"))}}class as{constructor(t,e,i,s){this._mouseState={state:"default"},this.elementRef=t,this._customStyles=i,this.position=e,this.dropupText=s}buttonMouseLeave(t){this._mouseState.state="default",t&&(rs.unsetAllCSS(this.elementRef,t),rs.setElementsCSS(this.elementRef,t,"default"))}buttonMouseEnter(t){this._mouseState.state="hover",t&&rs.setElementsCSS(this.elementRef,t,"hover")}buttonMouseUp(t){t&&rs.unsetActionCSS(this.elementRef,t),this.buttonMouseEnter(t)}buttonMouseDown(t){this._mouseState.state="click",t&&rs.setElementsCSS(this.elementRef,t,"click")}setEvents(t){this.elementRef.onmousedown=this.buttonMouseDown.bind(this,t),this.elementRef.onmouseup=this.buttonMouseUp.bind(this,t),this.elementRef.onmouseenter=this.buttonMouseEnter.bind(this,t),this.elementRef.onmouseleave=this.buttonMouseLeave.bind(this,t)}unsetCustomStateStyles(t){if(this._customStyles)for(let e=0;e<t.length;e+=1){const i=t[e],s=i&&this._customStyles[i];s&&rs.unsetActionCSS(this.elementRef,s)}}reapplyStateStyle(t,e){if(!this._customStyles)return;e&&this.unsetCustomStateStyles(e);const i=this._customStyles[t];i&&rs.setElementCssUpToState(this.elementRef,i,this._mouseState.state),this.setEvents(i)}}class ls{static focusItemWhenOnEdge(t,e){const i=e?t.children[0]:t.children[t.children.length-1];ls.focusSiblingItem(i,t,e,!0)}static focusSiblingItem(t,e,i,s=!1){const n=s?t:t[i?"nextSibling":"previousSibling"];n?(t.dispatchEvent(new MouseEvent("mouseleave")),n.dispatchEvent(new MouseEvent("mouseenter"))):(t.dispatchEvent(new MouseEvent("mouseleave")),ls.focusItemWhenOnEdge(e,i))}}class cs{static addItemEvents(t,e,i,s){P.add(e,s),e.addEventListener("click",(()=>{i.click()})),e.addEventListener("mouseenter",(e=>{t.highlightedItem=e.target})),e.addEventListener("mouseleave",(()=>{t.highlightedItem=void 0}))}static createItemText(t,e){const i=document.createElement("div");return Object.assign(i.style,e),i.classList.add("dropup-menu-item-text"),i.textContent=t||"File",i}static createItemIcon(t,e){const i=document.createElement("div");return Object.assign(i.style,e),i.classList.add("dropup-menu-item-icon"),i.appendChild(t.children[0]),i}static populateItem(t,e,i,s){const n=t.children[0];n.classList.contains("text-button")?e.appendChild(cs.createItemText(n.textContent,null==s?void 0:s.text)):(e.appendChild(cs.createItemIcon(t,null==s?void 0:s.iconContainer)),e.appendChild(cs.createItemText(i,null==s?void 0:s.text)))}static createItem(t,e,s){var n;const{elementRef:o,dropupText:r}=e,a=document.createElement("div");Object.assign(a.style,null==(n=null==s?void 0:s.item)?void 0:n.default),cs.populateItem(o,a,r,s),a.classList.add("dropup-menu-item");const l=i.processStateful((null==s?void 0:s.item)||{},{backgroundColor:"#f3f3f3"},{backgroundColor:"#ebebeb"});return cs.addItemEvents(t,a,o,l),a}}class hs{constructor(t,e){var i;this._isOpen=!0,this._styles=e,this.elementRef=hs.createElement(null==(i=this._styles)?void 0:i.container),this.close(),setTimeout((()=>this.addWindowEvents(t)))}static createElement(t){const e=document.createElement("div");return e.id="dropup-menu",Object.assign(e.style,t),e}open(){this.elementRef.style.display="block",this._isOpen=!0}close(){this._isOpen&&(this.elementRef.style.display="none",this._isOpen=!1)}toggle(){this._isOpen?this.close():this.open()}addItem(t){const e=cs.createItem(this,t,this._styles);this.elementRef.appendChild(e)}addWindowEvents(t){this.clickEvent=this.windowClick.bind(this,t),window.addEventListener("click",this.clickEvent),this.keyDownEvent=this.windowKeyDown.bind(this,t),window.addEventListener("keydown",this.keyDownEvent)}windowClick(t,e){var i;!t.isConnected&&this.clickEvent?window.removeEventListener("click",this.clickEvent):t.parentElement!==(null==(i=e.target.shadowRoot)?void 0:i.children[0])&&this.close()}windowKeyDown(t,e){var i,s,n;!t.isConnected&&this.keyDownEvent?window.removeEventListener("keydown",this.keyDownEvent):this._isOpen&&(e.key===c.ESCAPE?(this.close(),null==(i=this.highlightedItem)||i.dispatchEvent(new MouseEvent("mouseleave"))):e.key===c.ENTER?(null==(s=this.highlightedItem)||s.click(),null==(n=this.highlightedItem)||n.dispatchEvent(new MouseEvent("mouseleave"))):e.key===c.ARROW_DOWN?ls.focusSiblingItem(this.highlightedItem||this.elementRef.children[this.elementRef.children.length-1],this.elementRef,!0):e.key===c.ARROW_UP&&ls.focusSiblingItem(this.highlightedItem||this.elementRef.children[0],this.elementRef,!1))}}class us extends as{constructor(t,e){var i;super(us.createButtonElement(),void 0,{styles:null==(i=null==e?void 0:e.button)?void 0:i.styles});const s=this.createInnerElements(this._customStyles);this._menu=new hs(t,null==e?void 0:e.menu),this.addClickEvent(),this.buttonContainer=us.createButtonContainer(),this.elementRef.appendChild(s.styles),this.buttonContainer.appendChild(this.elementRef),this.elementRef.classList.add("dropup-icon","upload-file-button"),this.elementRef.children[0].id="dropup-icon",this.buttonContainer.appendChild(this._menu.elementRef),this.reapplyStateStyle("styles"),this.addContainerEvents(t)}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}createInnerElements(t){return{styles:this.createInnerElement(us.createSVGIconElement(),"styles",t)}}createInnerElement(t,e,i){return os.createSpecificStateElement(this.elementRef,e,i)||t}static createSVGIconElement(){return $e.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <path d="M16 0c-8.836 0-16 7.163-16 16s7.163 16 16 16c8.837 0 16-7.163 16-16s-7.163-16-16-16zM16 30.032c-7.72 0-14-6.312-14-14.032s6.28-14 14-14 14 6.28 14 14-6.28 14.032-14 14.032zM23 15h-6v-6c0-0.552-0.448-1-1-1s-1 0.448-1 1v6h-6c-0.552 0-1 0.448-1 1s0.448 1 1 1h6v6c0 0.552 0.448 1 1 1s1-0.448 1-1v-6h6c0.552 0 1-0.448 1-1s-0.448-1-1-1z"></path>\n</svg>')}addClickEvent(){this.elementRef.onclick=this._menu.toggle.bind(this._menu)}static createButtonContainer(){const t=document.createElement("div");return t.id="dropup-container",t}addItem(t){this._menu.addItem(t)}addContainerEvents(t){t.addEventListener("click",(t=>{t.target.classList.contains("dropup-icon")||this._menu.close()}))}static getPosition(t,e){var i,s;return null!=(i=null==e?void 0:e.button)&&i.position?null==(s=null==e?void 0:e.button)?void 0:s.position:t["outside-left"].length>0&&0===t["outside-right"].length?"outside-right":"outside-left"}}class ds{static addToDropup(t,e,i,s){const n=new us(i,s);ns.forEach((t=>{const i=e["dropup-menu"].findIndex((e=>e.buttonType===t)),s=e["dropup-menu"][i];s&&(n.addItem(s.button),e["dropup-menu"].splice(i,1))}));const o=us.getPosition(e,s);ss.addButton(t,n.buttonContainer,o),e[o].push({})}static addToSideContainer(t,e){["inside-left","inside-right","outside-left","outside-right"].forEach((i=>{const s=i;e[s].forEach((e=>{ss.addButton(t,e.button.elementRef,s)}))}))}static setPosition(t,e,i){const s={...t[e],buttonType:e};i.push(s),delete t[e]}static createPositionsObj(){return{"dropup-menu":[],"outside-left":[],"inside-left":[],"inside-right":[],"outside-right":[]}}static generatePositions(t){const e=ds.createPositionsObj();Object.keys(t).forEach((i=>{var s;const n=null==(s=t[i])?void 0:s.button.position;n&&ds.setPosition(t,i,e[n])})),0===e["inside-right"].length&&t.submit&&ds.setPosition(t,"submit",e["inside-right"]),0===e["outside-right"].length&&(t.submit?ds.setPosition(t,"submit",e["outside-right"]):t.microphone?ds.setPosition(t,"microphone",e["outside-right"]):t.camera&&ds.setPosition(t,"camera",e["outside-right"])),t.submit&&ds.setPosition(t,"submit",0===e["outside-left"].length?e["outside-left"]:e["inside-right"]),t.microphone&&ds.setPosition(t,"microphone",0===e["outside-left"].length?e["outside-left"]:e["inside-right"]);const i=Object.keys(t);return i.length>1||e["dropup-menu"].length>0?ns.forEach((i=>{t[i]&&e["dropup-menu"].push({...t[i],buttonType:i})})):1===i.length&&ds.setPosition(t,i[0],0===e["outside-right"].length?e["outside-right"]:e["outside-left"]),e}static addButtons(t,e,i,s){const n=ds.generatePositions(e);return ds.addToSideContainer(t,n),n["dropup-menu"].length>0&&ds.addToDropup(t,n,i,s),n}}const ps={images:{id:"upload-images-icon",svgString:'<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">\n <path d="M20,15.2928932 L20,5.5 C20,4.67157288 19.3284271,4 18.5,4 L5.5,4 C4.67157288,4 4,4.67157288 4,5.5 L4,12.2928932 L7.14644661,9.14644661 C7.34170876,8.95118446 7.65829124,8.95118446 7.85355339,9.14644661 L13.5,14.7928932 L16.1464466,12.1464466 C16.3417088,11.9511845 16.6582912,11.9511845 16.8535534,12.1464466 L20,15.2928932 Z M20,16.7071068 L16.5,13.2071068 L13.8535534,15.8535534 C13.6582912,16.0488155 13.3417088,16.0488155 13.1464466,15.8535534 L7.5,10.2071068 L4,13.7071068 L4,18.5 C4,19.3284271 4.67157288,20 5.5,20 L18.5,20 C19.3284271,20 20,19.3284271 20,18.5 L20,16.7071068 Z M3,5.5 C3,4.11928813 4.11928813,3 5.5,3 L18.5,3 C19.8807119,3 21,4.11928813 21,5.5 L21,18.5 C21,19.8807119 19.8807119,21 18.5,21 L5.5,21 C4.11928813,21 3,19.8807119 3,18.5 L3,5.5 Z M15,6 L17,6 C17.5522847,6 18,6.44771525 18,7 L18,9 C18,9.55228475 17.5522847,10 17,10 L15,10 C14.4477153,10 14,9.55228475 14,9 L14,7 C14,6.44771525 14.4477153,6 15,6 Z M15,7 L15,9 L17,9 L17,7 L15,7 Z"/>\n</svg>\n',dropupText:"Image"},gifs:{id:"upload-gifs-icon",svgString:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 5.9266752 5.6408391" height="21.31971" width="22.4">\n <g>\n <path d="m 5.2564627,1.548212 c -3.1136005,-0.4796804 -1.5568006,-0.2398402 0,0 z M 2.0001198,2.0922063 c 0.1556781,0 0.2657489,0.020893 0.3917849,0.080366 0.081154,0.038347 0.1153492,0.134065 0.076377,0.2138602 -0.038973,0.07979 -0.1363527,0.1134129 -0.2175069,0.075091 -0.078199,-0.036919 -0.1407455,-0.048792 -0.250655,-0.048792 -0.2260486,0 -0.3921482,0.2042182 -0.3921482,0.4801409 0,0.2761822 0.1663188,0.4810688 0.3921482,0.4810688 0.1117901,0 0.2064255,-0.046133 0.255659,-0.1284198 l 0.00162,-0.00389 V 3.0534032 l -0.098011,1.75e-4 c -0.081844,0 -0.1495979,-0.059305 -0.1612403,-0.1365887 l -0.00175,-0.023683 c 0,-0.08047 0.060311,-0.1470874 0.1389194,-0.1585331 l 0.024085,-0.00195 h 0.2612303 c 0.081842,0 0.149598,0.059305 0.1612404,0.1365891 l 0.00175,0.023683 -3.398e-4,0.3968809 v 0 l -0.00168,0.014211 v 0 l -0.00553,0.023034 v 0 l -0.00532,0.014145 c -0.098178,0.22826 -0.3236506,0.3528713 -0.5706303,0.3528713 -0.4240855,0 -0.7181621,-0.3622714 -0.7181621,-0.8016063 0,-0.4391857 0.2940275,-0.8006848 0.7181621,-0.8006848 z m 1.2034759,0.031275 c 0.081843,0 0.1495977,0.059305 0.1612403,0.1365891 l 0.00175,0.023683 v 1.2211775 c 0,0.088516 -0.07298,0.1602721 -0.1630073,0.1602721 -0.081841,0 -0.1495972,-0.059305 -0.1612397,-0.1365892 L 3.040589,3.5049308 V 2.2837527 c 0,-0.088516 0.07298,-0.1602721 0.1630067,-0.1602714 z m 0.7813442,0 0.5209469,0.00195 c 0.090025,3.048e-4 0.1627543,0.072306 0.1624458,0.1608234 -2.809e-4,0.08047 -0.06083,0.1468798 -0.1394772,0.158066 l -0.024092,0.00195 -0.3575326,-0.0013 v 0.4497782 l 0.2928918,2.27e-4 c 0.081842,0 0.1495979,0.059305 0.1612403,0.136589 l 0.00175,0.023683 c 0,0.080469 -0.06031,0.1470871 -0.1389193,0.1585393 l -0.024092,0.00195 -0.2928919,-2.336e-4 1.563e-4,0.2860316 c 0,0.080471 -0.06031,0.1470873 -0.1389193,0.1585395 l -0.024085,0.00195 c -0.081843,0 -0.1495979,-0.059305 -0.1612403,-0.1365826 l -0.00175,-0.023691 V 2.2841354 c 2.798e-4,-0.08047 0.060829,-0.1468797 0.1394758,-0.1580594 z"/>\n <path d="m 5.0894191,1.0943261 c 0,-0.21918999 -0.177687,-0.39686999 -0.396876,-0.39686999 h -3.43959 c -0.2191879,0 -0.391262,0.1777519 -0.3968759,0.39686999 l -0.027082,3.4379266 c 0.040152,0.2939927 0.4235456,0.409415 0.4235456,0.409415 l 3.4785583,-0.00851 c 0,0 0.3008506,-0.1402998 0.3236271,-0.4201576 0.042911,-0.5272495 0.034693,-1.6106146 0.034693,-3.4186761 z m -4.49792494,0 c 0,-0.36530999 0.29614504,-0.66145999 0.66145894,-0.66145999 h 3.43959 c 0.365314,0 0.66146,0.29615 0.66146,0.66145999 v 3.43959 c 0,0.36532 -0.296146,0.66146 -0.66146,0.66146 h -3.43959 c -0.3653139,0 -0.66145894,-0.29614 -0.66145894,-0.66146 z"/>\n </g>\n</svg>\n',dropupText:"GIF"},audio:{id:"upload-audio-icon",svgString:'<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="-49.49 -49.49 593.87 593.87" stroke-width="3.95908" transform="rotate(0)">\n <g stroke-width="0"></g>\n <g stroke-linecap="round" stroke-linejoin="round" stroke-width="0.98977"></g>\n <g>\n <g>\n <g>\n <path d="M163.205,76.413v293.301c-3.434-3.058-7.241-5.867-11.486-8.339c-21.38-12.452-49.663-15.298-77.567-7.846 c-49.038,13.096-80.904,54.519-71.038,92.337c4.019,15.404,14.188,28.221,29.404,37.087c13.553,7.894,29.87,11.933,47.115,11.933 c9.962,0,20.231-1.356,30.447-4.087c42.74-11.406,72.411-44.344,72.807-77.654h0.011v-0.162c0.002-0.166,0-0.331,0-0.496V187.072 l290.971-67.3v178.082c-3.433-3.055-7.238-5.863-11.481-8.334c-21.385-12.452-49.654-15.308-77.567-7.846 c-49.038,13.087-80.904,54.519-71.038,92.356c4.019,15.385,14.183,28.212,29.404,37.067c13.548,7.894,29.875,11.933,47.115,11.933 c9.962,0,20.231-1.356,30.452-4.087c42.74-11.413,72.411-44.346,72.804-77.654h0.004v-0.065c0.003-0.236,0.001-0.469,0-0.704V0 L163.205,76.413z M104.999,471.779c-22.543,6.038-45.942,3.846-62.572-5.846c-10.587-6.163-17.591-14.817-20.255-25.038 c-7.144-27.375,18.452-58.029,57.062-68.346c8.409-2.25,16.938-3.346,25.188-3.346c13.87,0,26.962,3.115,37.389,9.192 c10.587,6.163,17.591,14.817,20.255,25.029c0.809,3.102,1.142,6.248,1.139,9.4v0.321h0.014 C162.99,437.714,139.082,462.678,104.999,471.779z M182.898,166.853V92.067l290.971-67.298v74.784L182.898,166.853z M415.677,399.923c-22.558,6.038-45.942,3.837-62.587-5.846c-10.587-6.163-17.587-14.817-20.25-25.019 c-7.144-27.385,18.452-58.058,57.058-68.365c8.414-2.25,16.942-3.346,25.192-3.346c13.875,0,26.962,3.115,37.385,9.192 c10.596,6.163,17.596,14.817,20.26,25.029v0.01c0.796,3.05,1.124,6.144,1.135,9.244v0.468h0.02 C473.668,365.851,449.763,390.814,415.677,399.923z">\n </path>\n </g>\n </g>\n </g>\n</svg>',dropupText:"Audio"},mixedFiles:{id:"upload-mixed-files-icon",svgString:'<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n<title>file</title>\n<path d="M20 10.9696L11.9628 18.5497C10.9782 19.4783 9.64274 20 8.25028 20C6.85782 20 5.52239 19.4783 4.53777 18.5497C3.55315 17.6211 3 16.3616 3 15.0483C3 13.7351 3.55315 12.4756 4.53777 11.547L12.575 3.96687C13.2314 3.34779 14.1217 3 15.05 3C15.9783 3 16.8686 3.34779 17.525 3.96687C18.1814 4.58595 18.5502 5.4256 18.5502 6.30111C18.5502 7.17662 18.1814 8.01628 17.525 8.63535L9.47904 16.2154C9.15083 16.525 8.70569 16.6989 8.24154 16.6989C7.77738 16.6989 7.33224 16.525 7.00403 16.2154C6.67583 15.9059 6.49144 15.4861 6.49144 15.0483C6.49144 14.6106 6.67583 14.1907 7.00403 13.8812L14.429 6.88674" stroke="#000000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>',dropupText:"File"}};class ms extends as{constructor(t){"dropup-menu"===(null==t?void 0:t.position)&&(t.position="outside-right"),super(ms.createMicrophoneElement(),null==t?void 0:t.position,t),this.isActive=!1,this._innerElements=this.createInnerElements(this._customStyles),this.changeToDefault()}createInnerElements(t){const e=ms.createSVGIconElement();return{default:this.createInnerElement(e,"default",t),active:this.createInnerElement(e,"active",t),unsupported:this.createInnerElement(e,"unsupported",t),commandMode:this.createInnerElement(e,"commandMode",t)}}createInnerElement(t,e,i){return os.createSpecificStateElement(this.elementRef,e,i)||t}static createMicrophoneElement(){const t=document.createElement("div");return t.id="microphone-button",t.classList.add("input-button"),t}static createSVGIconElement(){const t=$e.createSVGElement('<?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');return t.id="microphone-icon",t}changeToActive(){this.elementRef.replaceChildren(this._innerElements.active),this.toggleIconFilter("active"),this.reapplyStateStyle("active",["default","commandMode"]),this.isActive=!0}changeToDefault(){this.elementRef.replaceChildren(this._innerElements.default),this.toggleIconFilter("default"),this.reapplyStateStyle("default",["active","commandMode"]),this.isActive=!1}changeToCommandMode(){this.elementRef.replaceChildren(this._innerElements.unsupported),this.toggleIconFilter("command"),this.reapplyStateStyle("commandMode",["active"])}changeToUnsupported(){this.elementRef.replaceChildren(this._innerElements.unsupported),this.elementRef.classList.add("unsupported-microphone"),this.reapplyStateStyle("unsupported",["active"])}toggleIconFilter(t){const e=this.elementRef.children[0];if("svg"===e.tagName.toLocaleLowerCase())switch(t){case"default":e.classList.remove("active-microphone-icon","command-microphone-icon"),e.classList.add("default-microphone-icon");break;case"active":e.classList.remove("default-microphone-icon","command-microphone-icon"),e.classList.add("active-microphone-icon");break;case"command":e.classList.remove("active-microphone-icon","default-microphone-icon"),e.classList.add("command-microphone-icon")}}}var vs={},fs={},gs={},bs={},ys={};Object.defineProperty(ys,"h",{value:!0}),ys.Text=void 0;class ws{static capitalize(t){return t.replace(ws.FIRST_CHAR_REGEX,(t=>t.toUpperCase()))}static lineBreak(t){return t.replace(ws.DOUBLE_LINE,"<p></p>").replace(ws.ONE_LINE,"<br>")}static isCharDefined(t){return void 0!==t&&" "!==t&&" "!==t&&"\n"!==t&&""!==t}static breakupIntoWordsArr(t){return t.split(/(\W+)/)}}ys.Text=ws,ws.FIRST_CHAR_REGEX=/\S/,ws.DOUBLE_LINE=/\n\n/g,ws.ONE_LINE=/\n/g,Object.defineProperty(bs,"h",{value:!0}),bs.Translate=void 0;const xs=ys;bs.Translate=class{static translate(t,e){const i=xs.Text.breakupIntoWordsArr(t);for(let t=0;t<i.length;t+=1)e[i[t]]&&(i[t]=e[i[t]]);return i.join("")}},Object.defineProperty(gs,"h",{value:!0}),gs.WebSpeechTranscript=void 0;const ks=bs;gs.WebSpeechTranscript=class{static extract(t,e,i){let s="";for(let n=t.resultIndex;n<t.results.length;++n){let o=t.results[n][0].transcript;i&&(o=ks.Translate.translate(o,i)),t.results[n].isFinal?e+=o:s+=o}return{interimTranscript:s,finalTranscript:e,newText:s||e}}static extractSafari(t,e,i){let s="";for(let e=t.resultIndex;e<t.results.length;++e){let n=t.results[e][0].transcript;i&&(n=ks.Translate.translate(n,i)),s+=n}return{interimTranscript:"",finalTranscript:s,newText:s}}};var _s={};Object.defineProperty(_s,"h",{value:!0}),_s.Browser=void 0;class Ss{}_s.Browser=Ss,Ss.IS_SAFARI=()=>(void 0===Ss._IS_SAFARI&&(Ss._IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),Ss._IS_SAFARI);var Ts={},As={};Object.defineProperty(As,"h",{value:!0}),As.EventListeners=void 0;class js{static getElementIfFocusedOnAvailable(t,e){return Array.isArray(t)?t.find((t=>e===t)):e===t?t:void 0}static keyDownWindow(t){t.element&&js.getElementIfFocusedOnAvailable(t.element,document.activeElement)&&(null!==js.KEY_DOWN_TIMEOUT&&clearTimeout(js.KEY_DOWN_TIMEOUT),js.KEY_DOWN_TIMEOUT=setTimeout((()=>{js.KEY_DOWN_TIMEOUT=null,this.resetRecording(t)}),500))}static mouseDownWindow(t,e){this.mouseDownElement=js.getElementIfFocusedOnAvailable(t,e.target)}static mouseUpWindow(t){this.mouseDownElement&&this.resetRecording(t),this.mouseDownElement=void 0}static add(t,e){const i=void 0===(null==e?void 0:e.insertInCursorLocation)||(null==e?void 0:e.insertInCursorLocation);null!=e&&e.element&&i&&(t.mouseDownEvent=js.mouseDownWindow.bind(t,e.element),document.addEventListener("mousedown",t.mouseDownEvent),t.mouseUpEvent=js.mouseUpWindow.bind(t,e),document.addEventListener("mouseup",t.mouseUpEvent),t.keyDownEvent=js.keyDownWindow.bind(t,e),document.addEventListener("keydown",t.keyDownEvent))}static remove(t){document.removeEventListener("mousedown",t.mouseDownEvent),document.removeEventListener("mouseup",t.mouseUpEvent),document.removeEventListener("keydown",t.keyDownEvent)}}As.EventListeners=js,js.KEY_DOWN_TIMEOUT=null;var Ms={};Object.defineProperty(Ms,"h",{value:!0}),Ms.PreResultUtils=void 0;Ms.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)}};var Cs={},Os={};Object.defineProperty(Os,"h",{value:!0}),Os.AutoScroll=void 0;class Es{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(t,e){return t&&Es.isElementOverflown(e)}}Os.AutoScroll=Es;var Is={};Object.defineProperty(Is,"h",{value:!0}),Is.Elements=void 0;Is.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}};var Ps={};Object.defineProperty(Ps,"h",{value:!0}),Ps.Cursor=void 0;class Ns{static setOffsetForGeneric(t,e,i=0){let s=0;for(let n=0;n<t.childNodes.length;n+=1){const o=t.childNodes[n];if(o.childNodes.length>0){const t=Ns.setOffsetForGeneric(o,e,i);if(-1===t)return-1;i+=t}else if(null!==o.textContent){if(i+o.textContent.length>e){const s=document.createRange();s.setStart(o,e-i),s.collapse(!0);const n=window.getSelection();return null==n||n.removeAllRanges(),null==n||n.addRange(s),t.focus(),-1}i+=o.textContent.length,s+=o.textContent.length}}return s}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(t,e){const i=window.getSelection();if(i){const s=Ns.getGenericElementCursorOffset(t,i,!0);console.log(s),setTimeout((()=>{}),100),Ns.setOffsetForGeneric(t,s+e)}}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}}Ps.Cursor=Ns,Object.defineProperty(Cs,"h",{value:!0}),Cs.CommandUtils=void 0;const qs=Os,Rs=Is,Ls=_s,Bs=Ps,Fs=ys;class zs{static processCommand(t,e){return(!e||!e.caseSensitive)&&(t=t.toLowerCase()),!1===(null==e?void 0:e.substrings)?Fs.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?zs.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(t,e,i,s){zs.toggleCommandModeOff(t),Rs.Elements.isPrimitiveElement(s)?(s.value=i,t.isTargetInShadow||Bs.Cursor.setOffsetForPrimitive(s,i.length,!0),Ls.Browser.IS_SAFARI()&&t.autoScroll&&qs.AutoScroll.scrollSafariPrimitiveToEnd(s)):(s.textContent=i,t.isTargetInShadow||Bs.Cursor.focusEndOfGeneric(s),setTimeout((()=>qs.AutoScroll.scrollGeneric(t,s)))),t.resetRecording(e)}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,n){var o,r,a;const l=t.commands;if(!l||!s||!i)return;const c=!0===(null===(o=l.settings)||void 0===o?void 0:o.caseSensitive)?e:e.toLowerCase(),h=Fs.Text.breakupIntoWordsArr(c),u=!1===(null===(r=l.settings)||void 0===r?void 0:r.substrings)?zs.checkIfMatchesWord:zs.checkIfMatchesSubstring;if(l.commandMode&&u(l.commandMode,c,h))return t.setInterimColorToFinal(),setTimeout((()=>zs.toggleCommandModeOn(t))),{doNotProcessTranscription:!1};if(!l.commandMode||t.isWaitingForCommand){if(l.stop&&u(l.stop,c,h))return zs.toggleCommandModeOff(t),setTimeout((()=>t.stop())),{doNotProcessTranscription:!1};if(l.pause&&u(l.pause,c,h))return zs.toggleCommandModeOff(t),t.setInterimColorToFinal(),setTimeout((()=>{var e;t.isPaused=!0,null===(e=t.onPauseTrigger)||void 0===e||e.call(t,!0)})),{doNotProcessTranscription:!1};if(l.resume&&u(l.resume,c,h))return t.isPaused=!1,null===(a=t.onPauseTrigger)||void 0===a||a.call(t,!1),zs.toggleCommandModeOff(t),t.resetRecording(i),{doNotProcessTranscription:!0};if(l.reset&&u(l.reset,c,h))return void 0!==n&&zs.setText(t,i,n,s),{doNotProcessTranscription:!0};if(l.removeAllText&&u(l.removeAllText,c,h))return zs.setText(t,i,"",s),{doNotProcessTranscription:!0}}}}Cs.CommandUtils=zs;var Ds={};Object.defineProperty(Ds,"h",{value:!0}),Ds.Highlight=void 0;const $s=Is,Js=Ps;class Vs{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,e){const i=window.getSelection();if(null!=i&&i.focusNode){const s=Js.Cursor.getGenericElementCursorOffset(e,i,!0),n=Js.Cursor.getGenericElementCursorOffset(e,i,!1);t.isHighlighted=s!==n}}static setState(t,e){document.activeElement===e&&($s.Elements.isPrimitiveElement(e)?Vs.setStateForPrimitive(t,e):Vs.setStateForGeneric(t,e))}static removeForGeneric(t,e){const i=window.getSelection();if(i){const s=Js.Cursor.getGenericElementCursorOffset(e,i,!0);i.deleteFromDocument(),Js.Cursor.setOffsetForGeneric(e,s),t.isHighlighted=!1}}static removeForPrimitive(t,e){const i=e.selectionStart,s=e.selectionEnd,n=e.value;if(i&&s){const o=n.substring(0,i)+n.substring(s);e.value=o,Js.Cursor.setOffsetForPrimitive(e,i,t.autoScroll)}t.isHighlighted=!1}}Ds.Highlight=Vs;var Us={};Object.defineProperty(Us,"h",{value:!0}),Us.Padding=void 0;const Hs=Is,Ks=Ps,Gs=ys;class Zs{static setStateForPrimitiveElement(t,e){if(document.activeElement===e&&null!==e.selectionStart){const i=e.selectionStart,s=e.value[i-1],n=null===e.selectionEnd?i:e.selectionEnd,o=e.value[n];return Gs.Text.isCharDefined(s)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),Gs.Text.isCharDefined(o)&&(t.endPadding=" ",t.numberOfSpacesAfterNewText=1),void(t.isCursorAtEnd=e.value.length===n)}const i=e.value[e.value.length-1];Gs.Text.isCharDefined(i)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),t.isCursorAtEnd=!0}static setStateForGenericElement(t,e){var i,s,n;if(document.activeElement===e){const o=window.getSelection();if(null!=o&&o.focusNode){const r=Ks.Cursor.getGenericElementCursorOffset(e,o,!0),a=null===(i=e.textContent)||void 0===i?void 0:i[r-1],l=Ks.Cursor.getGenericElementCursorOffset(e,o,!1),c=null===(s=e.textContent)||void 0===s?void 0:s[l];return Gs.Text.isCharDefined(a)&&(t.startPadding=" "),Gs.Text.isCharDefined(c)&&(t.endPadding=" "),void(t.isCursorAtEnd=(null===(n=e.textContent)||void 0===n?void 0:n.length)===l)}}const o=e.innerText.charAt(e.innerText.length-1);Gs.Text.isCharDefined(o)&&(t.startPadding=" "),t.isCursorAtEnd=!0}static setState(t,e){Hs.Elements.isPrimitiveElement(e)?Zs.setStateForPrimitiveElement(t,e):Zs.setStateForGenericElement(t,e)}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)}}Us.Padding=Zs,Object.defineProperty(Ts,"h",{value:!0}),Ts.Speech=void 0;const Ws=As,Xs=Ms,Qs=Cs,Ys=Os,tn=Ds,en=Is,sn=Us,nn=_s,on=Ps,rn=ys;Ts.Speech=class{constructor(){this.finalTranscript="",this.interimSpan=en.Elements.createInterimSpan(),this.finalSpan=en.Elements.createGenericSpan(),this.scrollingSpan=en.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(t){var e,i;if(null!=t&&t.element)if(Ws.EventListeners.add(this,t),Array.isArray(t.element)){const e=t.element.find((t=>t===document.activeElement))||t.element[0];if(!e)return;this.prepare(e)}else this.prepare(t.element);void 0!==(null==t?void 0:t.displayInterimResults)&&(this._displayInterimResults=t.displayInterimResults),null!=t&&t.textColor&&(this._finalTextColor=null===(e=null==t?void 0:t.textColor)||void 0===e?void 0:e.final,en.Elements.applyCustomColors(this,t.textColor)),void 0!==(null==t?void 0:t.insertInCursorLocation)&&(this.insertInCursorLocation=t.insertInCursorLocation),void 0!==(null==t?void 0:t.autoScroll)&&(this.autoScroll=t.autoScroll),this._onResult=null==t?void 0:t.onResult,this._onPreResult=null==t?void 0:t.onPreResult,this._onStart=null==t?void 0:t.onStart,this._onStop=null==t?void 0:t.onStop,this._onError=null==t?void 0:t.onError,this.onCommandModeTrigger=null==t?void 0:t.onCommandModeTrigger,this.onPauseTrigger=null==t?void 0:t.onPauseTrigger,this._options=t,null!==(i=this._options)&&void 0!==i&&i.commands&&(this.commands=Qs.CommandUtils.process(this._options.commands))}prepare(t){sn.Padding.setState(this,t),tn.Highlight.setState(this,t),this.isTargetInShadow=en.Elements.isInsideShadowDOM(t),en.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,e,i){var s;const n=rn.Text.capitalize(e);if(this.finalTranscript===n&&""===t)return;Xs.PreResultUtils.process(this,i,""===t,this._onPreResult,this._options)&&(t="",i="");const o=this.commands&&Qs.CommandUtils.execCommand(this,i,this._options,this._primitiveElement||this._genericElement,this._originalText);if(o){if(o.doNotProcessTranscription)return;t="",i=""}if(this.isPaused||this.isWaitingForCommand)return;null===(s=this._onResult)||void 0===s||s.call(this,i,""===t),this.finalTranscript=n,this._displayInterimResults||(t="");const r=""===this.finalTranscript&&""===t;this._primitiveElement?this.updatePrimitiveElement(this._primitiveElement,t,r):this._genericElement&&this.updateGenericElement(this._genericElement,t,r)}updatePrimitiveElement(t,e,i){this.isHighlighted&&tn.Highlight.removeForPrimitive(this,t),this.primitiveTextRecorded||sn.Padding.adjustStateAfterRecodingPrimitiveElement(this,t),i&&sn.Padding.adjustSateForNoTextPrimitiveElement(this);const s=this.startPadding+this.finalTranscript+e;if(t.value=s+this.endPadding,!this.isTargetInShadow){const e=s.length+this.numberOfSpacesAfterNewText;on.Cursor.setOffsetForPrimitive(t,e,this.autoScroll)}this.autoScroll&&nn.Browser.IS_SAFARI()&&this.isCursorAtEnd&&Ys.AutoScroll.scrollSafariPrimitiveToEnd(t)}updateGenericElement(t,e,i){this.isHighlighted&&tn.Highlight.removeForGeneric(this,t),this.spansPopulated||en.Elements.appendSpans(this,t);const s=(i?"":this.startPadding)+rn.Text.lineBreak(this.finalTranscript);this.finalSpan.innerHTML=s;const n=Ys.AutoScroll.isRequired(this.autoScroll,t);Ys.AutoScroll.changeStateIfNeeded(this,n);const o=rn.Text.lineBreak(e)+(i?"":this.endPadding);this.interimSpan.innerHTML=o,nn.Browser.IS_SAFARI()&&this.insertInCursorLocation&&on.Cursor.setOffsetForSafariGeneric(t,s.length+o.length),n&&Ys.AutoScroll.scrollGeneric(this,t),i&&(this.scrollingSpan.innerHTML="")}finalise(t){this._genericElement&&(t?(this.finalSpan=en.Elements.createGenericSpan(),this.setInterimColorToFinal(),this.interimSpan=en.Elements.createInterimSpan(),this.scrollingSpan=en.Elements.createGenericSpan()):this._genericElement.textContent=this._genericElement.textContent,this.spansPopulated=!1),Ws.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}},Object.defineProperty(fs,"h",{value:!0}),fs.WebSpeech=void 0;const an=gs,ln=_s,cn=Ts;class hn extends cn.Speech{constructor(){super()}start(t){var e;void 0===this._extractText&&(this._extractText=ln.Browser.IS_SAFARI()?an.WebSpeechTranscript.extractSafari:an.WebSpeechTranscript.extract),this.validate()&&(this.prepareBeforeStart(t),this.instantiateService(t),null===(e=this._service)||void 0===e||e.start(),this._translations=null==t?void 0:t.translations)}validate(){return!!hn.getAPI()||(this.error("Speech Recognition is unsupported"),!1)}instantiateService(t){var e,i;const s=hn.getAPI();this._service=new s,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=>{ln.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()}}fs.WebSpeech=hn;var un={};Object.defineProperty(un,"h",{value:!0}),un.GlobalState=void 0;class dn{static doubleClickDetector(){return!!dn.doubleClickPending||(dn.doubleClickPending=!0,setTimeout((()=>{dn.doubleClickPending=!1}),300),!1)}}un.GlobalState=dn,dn.doubleClickPending=!1;var pn={},mn={};Object.defineProperty(mn,"h",{value:!0}),mn.PreventConnectionStop=void 0;mn.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}};var vn={},fn={};Object.defineProperty(fn,"h",{value:!0}),fn.README_URL=void 0,fn.README_URL="https://github.com/OvidijusParsiunas/speech-to-element",Object.defineProperty(vn,"h",{value:!0}),vn.AzureSpeechConfig=void 0;const gn=fn;class bn{static validateOptions(t,e){return e?e.subscriptionKey||e.token||e.retrieveToken?!!e.region||(t(`Please define a 'region' property - more info: ${gn.README_URL}`),!1):(t(`Please define a 'subscriptionKey', 'token' or 'retrieveToken' property - more info: ${gn.README_URL}`),!1):(t(`Please provide subscription details - more info: ${gn.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.language&&(t.speechRecognitionLanguage=e.language.trim())}static async get(t,e){const i=await bn.getNewSpeechConfig(t,e);return i&&bn.process(i,e),i}}vn.AzureSpeechConfig=bn;var yn={};Object.defineProperty(yn,"h",{value:!0}),yn.StopTimeout=void 0;class wn{static set(t){t.stopTimeout=setTimeout((()=>t.stop()),t.stopTimeoutMS)}static reset(t,e){t.stopTimeoutMS=e||wn.DEFAULT_MS,t.stopTimeout&&clearTimeout(t.stopTimeout),wn.set(t)}}yn.StopTimeout=wn,wn.DEFAULT_MS=2e4;var xn={};Object.defineProperty(xn,"h",{value:!0}),xn.AzureTranscript=void 0;const kn=bs;xn.AzureTranscript=class{static extract(t,e,i,s){return s&&(t=kn.Translate.translate(t,s)),i?{interimTranscript:"",finalTranscript:e+t,newText:t}:{interimTranscript:t,finalTranscript:e,newText:t}}},Object.defineProperty(pn,"h",{value:!0}),pn.Azure=void 0;const _n=mn,Sn=vn,Tn=yn,An=xn,jn=Ts;class Mn extends jn.Speech{constructor(){super(...arguments),this._newTextPadding=""}start(t,e){this._newTextPadding="",void 0===this.stopTimeout&&Tn.StopTimeout.reset(this,null==t?void 0:t.stopAfterSilenceMs),this.prepareBeforeStart(t),this.startAsync(t),e||_n.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 Mn.getAPI()?Sn.AzureSpeechConfig.validateOptions(this.error.bind(this),t):(this.moduleNotFound(),!1)}async instantiateService(t){const e=Mn.getAPI(),i=e.AudioConfig.fromDefaultMicrophoneInput(),s=await Sn.AzureSpeechConfig.get(e.SpeechConfig,t);if(s){const n=new e.SpeechRecognizer(s,i);this.setEvents(n),this._service=n,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:s,newText:n}=An.AzureTranscript.extract(this._newTextPadding+e.result.text,this.finalTranscript,!1,this._translations);Tn.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(i,s,n)}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:s}=An.AzureTranscript.extract(this._newTextPadding+i.text,this.finalTranscript,!0,this._translations);Tn.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(t,e,s),""!==e&&(this._newTextPadding=" ")}}}onCanceled(t,e){e.reason===window.SpeechSDK.CancellationReason.Error&&this.error(e.errorDetails)}onSessionStarted(){_n.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(),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()}}pn.Azure=Mn,Object.defineProperty(vs,"h",{value:!0});const Cn=fs,On=Cs,En=un,In=pn;class Pn{static toggle(t,e){var i,s;const n=t.toLocaleLowerCase().trim();null!==(i=En.GlobalState.service)&&void 0!==i&&i.recognizing?this.stop():"webspeech"===n?Pn.startWebSpeech(e):"azure"===n?Pn.startAzure(e):(console.error("service not found - must be either 'webspeech' or 'azure'"),null===(s=null==e?void 0:e.onError)||void 0===s||s.call(e,"service not found - must be either 'webspeech' or 'azure'"))}static startWebSpeech(t){Pn.stop()||(En.GlobalState.service=new Cn.WebSpeech,En.GlobalState.service.start(t))}static isWebSpeechSupported(){return!!Cn.WebSpeech.getAPI()}static startAzure(t){var e;Pn.stop()||null!==(e=En.GlobalState.service)&&void 0!==e&&e.cannotBeStopped||(En.GlobalState.service=new In.Azure,En.GlobalState.service.start(t))}static stop(){var t;return!!En.GlobalState.doubleClickDetector()||(!(null===(t=En.GlobalState.service)||void 0===t)&&t.recognizing&&En.GlobalState.service.stop(),!1)}static endCommandMode(){En.GlobalState.service&&On.CommandUtils.toggleCommandModeOff(En.GlobalState.service)}}var Nn=vs.default=Pn;class qn{constructor(t,e){this.silenceMS=2e3,this.stop=!0,"boolean"==typeof e&&!1===e&&(this.stop=!1),"number"==typeof t&&(this.silenceMS=t)}setSilenceTimeout(t,e){this._silenceTimeout=setTimeout((()=>{var i;null==(i=t.submit)||i.call(t),Nn.stop(),this.stop||setTimeout(e,Ln.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 Rn=class t extends ms{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||Nn.isWebSpeechSupported()){const i=!t.textInput||!t.textInput.disabled;this.elementRef.onclick=this.buttonClick.bind(this,e,i,n,o)}else this.changeToUnsupported();setTimeout((()=>{this._validationHandler=t._validationHandler}))}processConfiguration(e,i){var s;const n="object"==typeof i?i:{},o="object"==typeof n.webSpeech?n.webSpeech:{},r=n.azure||{},a={displayInterimResults:n.displayInterimResults??void 0,textColor:n.textColor??void 0,translations:n.translations??void 0,commands:n.commands??void 0,events:n.events??void 0,...o,...r},l=null==(s=n.commands)?void 0:s.submit;return l&&(a.onPreResult=t=>t.toLowerCase().includes(l)?(setTimeout((()=>{var t;return null==(t=e.submit)?void 0:t.call(e)})),Nn.endCommandMode(),{restart:!0,removeNewText:!0}):null),n.submitAfterSilence&&(this._silenceSubmit=new qn(n.submitAfterSilence,n.stopAfterSubmit)),{serviceName:t.getServiceName(n),processedConfig:a}}static getServiceName(t){return t.azure?"azure":"webspeech"}buttonClick(t,e,i,s){const n=null==s?void 0:s.events;t.removePlaceholderStyle(),Nn.toggle(i,{insertInCursorLocation:!1,element:e?t.inputElementRef:void 0,onError:()=>{var t;this.onError(),null==(t=this._silenceSubmit)||t.clearSilenceTimeout()},onStart:()=>{var t;this.changeToActive(),null==(t=null==n?void 0:n.onStart)||t.call(n)},onStop:()=>{var t,e,i;null==(t=this._validationHandler)||t.call(this),null==(e=this._silenceSubmit)||e.clearSilenceTimeout(),this.changeToDefault(),null==(i=null==n?void 0:n.onStop)||i.call(n)},onPauseTrigger:e=>{var i,s;null==(i=this._silenceSubmit)||i.onPause(e,t,this.elementRef.onclick),null==(s=null==n?void 0:n.onPauseTrigger)||s.call(n,e)},onPreResult:(t,e)=>{var i;null==(i=null==n?void 0:n.onPreResult)||i.call(n,t,e)},onResult:(e,i)=>{var s,o,r;i&&(null==(s=this._validationHandler)||s.call(this)),null==(o=this._silenceSubmit)||o.resetSilenceTimeout(t,this.elementRef.onclick),null==(r=null==n?void 0:n.onResult)||r.call(n,e,i)},onCommandModeTrigger:t=>{var e;this.onCommandModeTrigger(t),null==(e=null==n?void 0:n.onCommandModeTrigger)||e.call(n,t)},...s})}onCommandModeTrigger(t){t?this.changeToCommandMode():this.changeToActive()}onError(){this._addErrorMessage("speechToText","speech input error")}static toggleSpeechAfterSubmit(e,i=!0){e.click(),i||setTimeout((()=>e.click()),t.MICROPHONE_RESET_TIMEOUT_MS)}};Rn.MICROPHONE_RESET_TIMEOUT_MS=300;let Ln=Rn;class Bn{constructor(t,e,i,s){this._attachments=[],this._fileCountLimit=99,this._acceptedFormat="",e.maxNumberOfFiles&&(this._fileCountLimit=e.maxNumberOfFiles),this._toggleContainerDisplay=i,this._fileAttachmentsContainerRef=s,e.acceptedFormats&&(this._acceptedFormat=e.acceptedFormats),setTimeout((()=>{this._validationHandler=t._validationHandler}))}attemptAddFile(t,e){return!!Bn.isFileTypeValid(t,this._acceptedFormat)&&(this.addAttachmentBasedOnType(t,e,!0),!0)}static isFileTypeValid(t,e){if(""===e)return!0;const i=e.split(",");for(let e=0;e<i.length;e++){const s=i[e].trim();if(t.type===s)return!0;if(s.startsWith(".")){const e=s.slice(1);if(t.name.endsWith(e))return!0}else{if(t.name.endsWith(s))return!0;if(s.endsWith("/*")&&t.type.startsWith(s.slice(0,-2)))return!0}}return!1}static getTypeFromBlob(t){const{type:e}=t;return e.startsWith("image")?"image":e.startsWith("audio")?"audio":"any"}addAttachmentBasedOnType(t,e,i){const s=Bn.getTypeFromBlob(t);if("image"===s){const s=Bn.createImageAttachment(e);this.addFileAttachment(t,"image",s,i)}else if("audio"===s){const s=Dn.createAudioAttachment(e);this.addFileAttachment(t,"audio",s,i)}else{const e=Bn.createAnyFileAttachment(t.name);this.addFileAttachment(t,"any",e,i)}}static createImageAttachment(t){const e=new Image;return e.src=t,e.classList.add("image-attachment"),e}static createAnyFileAttachment(t){const e=document.createElement("div");e.classList.add("border-bound-attachment"),l.IS_SAFARI&&e.classList.add("border-bound-attachment-safari");const i=document.createElement("div");i.classList.add("any-file-attachment-text");const s=document.createElement("div");return s.classList.add("file-attachment-text-container"),s.appendChild(i),i.textContent=t,e.appendChild(s),e}addFileAttachment(t,e,i,s){var n;const o=Bn.createContainer(i);if(this._attachments.length>=this._fileCountLimit){const t=this._attachments[this._attachments.length-1].removeButton;null==t||t.click();const e=this._fileAttachmentsContainerRef.children;this._fileAttachmentsContainerRef.insertBefore(o,e[0])}else this._fileAttachmentsContainerRef.appendChild(o);const r={file:t,attachmentContainerElement:o,fileType:e};return s&&(r.removeButton=this.createRemoveAttachmentButton(r),o.appendChild(r.removeButton)),this._toggleContainerDisplay(!0),this._attachments.push(r),this._fileAttachmentsContainerRef.scrollTop=this._fileAttachmentsContainerRef.scrollHeight,null==(n=this._validationHandler)||n.call(this),r}static createContainer(t){const e=document.createElement("div");return e.classList.add("file-attachment"),e.appendChild(t),e}createRemoveAttachmentButton(t){const e=document.createElement("div");e.classList.add("remove-file-attachment-button"),e.onclick=this.removeAttachment.bind(this,t);const i=document.createElement("div");return i.classList.add("x-icon"),i.innerText="×",e.appendChild(i),e}removeAttachment(t){var e;const i=this._attachments.findIndex((e=>e===t)),s=this._attachments[i].attachmentContainerElement;this._attachments.splice(i,1),Dn.stopAttachmentPlayback(s),s.remove(),this._toggleContainerDisplay(!1),null==(e=this._validationHandler)||e.call(this)}getFiles(){return Array.from(this._attachments).map((t=>({file:t.file,type:t.fileType})))}removeAllAttachments(){this._attachments.forEach((t=>{setTimeout((()=>{var e;return null==(e=t.removeButton)?void 0:e.click()}))}))}}const Fn='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n<title>stop</title>\n<path d="M5.92 24.096q0 0.832 0.576 1.408t1.44 0.608h16.128q0.832 0 1.44-0.608t0.576-1.408v-16.16q0-0.832-0.576-1.44t-1.44-0.576h-16.128q-0.832 0-1.44 0.576t-0.576 1.44v16.16z"></path>\n</svg>',zn=class t extends Bn{constructor(t,e,i,s){super(t,e,i,s)}static createAudioContainer(){const t=document.createElement("div");return t.classList.add("border-bound-attachment","audio-attachment-icon-container"),l.IS_SAFARI&&t.classList.add("border-bound-attachment-safari"),t}static addAudioElements(t,e){const i=t.parentElement?x.cloneElement(t):t,s=document.createElement("audio");s.src=e;const n=$e.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <title>play</title>\n <path d="M5.92 24.096q0 1.088 0.928 1.728 0.512 0.288 1.088 0.288 0.448 0 0.896-0.224l16.16-8.064q0.48-0.256 0.8-0.736t0.288-1.088-0.288-1.056-0.8-0.736l-16.16-8.064q-0.448-0.224-0.896-0.224-0.544 0-1.088 0.288-0.928 0.608-0.928 1.728v16.16z"></path>\n</svg>');n.classList.add("attachment-icon","play-icon");const o=$e.createSVGElement(Fn);o.classList.add("attachment-icon","stop-icon"),i.replaceChildren(n),s.onplay=()=>{i.replaceChildren(o)},s.onpause=()=>{i.replaceChildren(n),s.currentTime=0},s.onended=()=>{i.replaceChildren(n)},i.onclick=()=>{s.paused?s.play():s.pause()}}static createAudioAttachment(e){const i=t.createAudioContainer();return t.addAudioElements(i,e),i}createTimer(e,i){let s=0;const n=void 0!==i&&i<t.TIMER_LIMIT_S?i:t.TIMER_LIMIT_S;return setInterval((()=>{var t;s+=1,s===n&&(null==(t=this.stopPlaceholderCallback)||t.call(this),this.clearTimer()),600===s&&e.classList.add("audio-placeholder-text-4-digits");const i=Math.floor(s/60),o=(s%60).toString().padStart(2,"0");e.textContent=`${i}:${o}`}),1e3)}createPlaceholderAudioAttachment(e){const i=t.createAudioContainer(),s=document.createElement("div");s.classList.add("audio-placeholder-text-3-digits");const n=document.createElement("div");n.classList.add("file-attachment-text-container","audio-placeholder-text-3-digits-container"),n.appendChild(s);const o=$e.createSVGElement(Fn);return o.classList.add("attachment-icon","stop-icon","not-removable-attachment-icon"),s.textContent="0:00",this._activePlaceholderTimer=this.createTimer(s,e),i.appendChild(n),this.addPlaceholderAudioAttachmentEvents(i,o,n),i}addPlaceholderAudioAttachmentEvents(t,e,i){t.addEventListener("mouseenter",(()=>t.replaceChildren(e)));t.addEventListener("mouseleave",(()=>t.replaceChildren(i)));t.addEventListener("click",(()=>{var t;return null==(t=this.stopPlaceholderCallback)?void 0:t.call(this)}))}addPlaceholderAttachment(t,e){const i=this.createPlaceholderAudioAttachment(e);this._activePlaceholderAttachment=this.addFileAttachment(new File([],""),"audio",i,!1),this.stopPlaceholderCallback=t}completePlaceholderAttachment(e,i){const s=this._activePlaceholderAttachment;s&&(s.file=e,t.addAudioElements(s.attachmentContainerElement.children[0],i),s.removeButton=this.createRemoveAttachmentButton(s),s.attachmentContainerElement.appendChild(s.removeButton),this._activePlaceholderAttachment=void 0,this.clearTimer())}removePlaceholderAttachment(){this._activePlaceholderAttachment&&(this.removeAttachment(this._activePlaceholderAttachment),this._activePlaceholderAttachment=void 0,this.clearTimer())}clearTimer(){void 0!==this._activePlaceholderTimer&&(clearInterval(this._activePlaceholderTimer),this._activePlaceholderTimer=void 0,this.stopPlaceholderCallback=void 0)}static stopAttachmentPlayback(t){var e,i,s;null!=(s=null==(i=null==(e=t.children[0])?void 0:e.children)?void 0:i[0])&&s.classList.contains("stop-icon")&&t.children[0].click()}};zn.TIMER_LIMIT_S=5999;let Dn=zn;class $n{static create(t,e,i,s,n){return"audio"===n?new Dn(t,e,i,s):new Bn(t,e,i,s)}}class Jn{constructor(t,e,i){this._fileAttachmentsTypes=[],this.elementRef=this.createAttachmentContainer();const s="object"==typeof i&&!!i.displayFileAttachmentContainer;this.toggleContainerDisplay(s),t.appendChild(this.elementRef),e&&Object.assign(this.elementRef.style,e)}addType(t,e,i){const s=$n.create(t,e,this.toggleContainerDisplay.bind(this),this.elementRef,i);return this._fileAttachmentsTypes.push(s),s}createAttachmentContainer(){const t=document.createElement("div");return t.id="file-attachment-container",t}toggleContainerDisplay(t){t?this.elementRef.style.display="block":0===this.elementRef.children.length&&(this.elementRef.style.display="none")}getAllFileData(){const t=this._fileAttachmentsTypes.map((t=>t.getFiles())).flat();return t.length>0?t:void 0}async completePlaceholders(){await Promise.all(this._fileAttachmentsTypes.map((async t=>{var e;return null==(e=t.stopPlaceholderCallback)?void 0:e.call(t)})))}static addFilesToType(t,e){t.forEach((t=>{const i=new FileReader;i.readAsDataURL(t),i.onload=i=>{for(let s=0;s<e.length&&!e[s].attemptAddFile(t,i.target.result);s+=1);}}))}addFilesToAnyType(t){Jn.addFilesToType(t,this._fileAttachmentsTypes)}removeAllFiles(){this._fileAttachmentsTypes.forEach((t=>t.removeAllAttachments())),this.elementRef.replaceChildren(),this.toggleContainerDisplay(!1)}getNumberOfTypes(){return this._fileAttachmentsTypes.length}}const Vn=class t{constructor(e,i,s){this._isOpen=!1,this._contentRef=t.createModalContent(i,null==s?void 0:s.backgroundColor),this._buttonPanel=t.createButtonPanel(null==s?void 0:s.backgroundColor),this._elementRef=t.createContainer(this._contentRef,s),this._elementRef.appendChild(this._buttonPanel),e.appendChild(this._elementRef),this._backgroundPanelRef=t.createDarkBackgroundPanel(),e.appendChild(this._backgroundPanelRef),this.addWindowEvents(e)}isOpen(){return this._isOpen}static createContainer(t,e){const i=document.createElement("div");return i.classList.add("modal"),i.appendChild(t),e&&delete e.backgroundColor,Object.assign(i.style,e),i}static createModalContent(t,e){const i=document.createElement("div");return i.classList.add(...t),e&&(i.style.backgroundColor=e),document.createElement("div").appendChild(i),i}static createButtonPanel(t){const e=document.createElement("div");return e.classList.add("modal-button-panel"),t&&(e.style.backgroundColor=t),e}static createDarkBackgroundPanel(){const t=document.createElement("div");return t.id="modal-background-panel",t}addButtons(...t){t.forEach((t=>this._buttonPanel.appendChild(t)))}static createTextButton(t){const e=document.createElement("div");return e.classList.add("modal-button"),e.textContent=t,e}static createSVGButton(t){const e=document.createElement("div");e.classList.add("modal-button","modal-svg-button");const i=$e.createSVGElement(t);return i.classList.add("modal-svg-button-icon"),e.appendChild(i),e}close(){this._elementRef.classList.remove("show-modal"),this._elementRef.classList.add("hide-modal"),this._backgroundPanelRef.classList.remove("show-modal-background"),this._backgroundPanelRef.classList.add("hide-modal-background"),this._isOpen=!1,setTimeout((()=>{this._elementRef.style.display="none",this._backgroundPanelRef.style.display="none"}),t.MODAL_CLOSE_TIMEOUT_MS)}displayModalElements(){this._elementRef.style.display="flex",this._elementRef.classList.remove("hide-modal"),this._elementRef.classList.add("show-modal"),this._backgroundPanelRef.style.display="block",this._backgroundPanelRef.classList.remove("hide-modal-background"),this._backgroundPanelRef.classList.add("show-modal-background"),this._isOpen=!0}openTextModal(t){this._contentRef.innerHTML=t,this.displayModalElements()}addCloseButton(e,i,s){const n=i?t.createSVGButton(e):t.createTextButton(e);return this.addButtons(n),n.onclick=()=>{this.close(),setTimeout((()=>{null==s||s()}),140)},n}static createTextModalFunc(e,i,s){var n;if("object"==typeof i&&null!=(n=i.files)&&n.infoModal){const n=new t(e,["modal-content"],i.files.infoModal.containerStyle);return n.addCloseButton("OK",!1,s),n.openTextModal.bind(n,i.infoModalTextMarkUp||"")}}addWindowEvents(t){this.keyDownEvent=this.windowKeyDown.bind(this,t),window.addEventListener("keydown",this.keyDownEvent)}windowKeyDown(t,e){var i,s;!t.isConnected&&this.keyDownEvent?window.removeEventListener("keydown",this.keyDownEvent):this._isOpen&&(e.key===c.ESCAPE?(this.close(),null==(i=this.extensionCloseCallback)||i.call(this)):e.key===c.ENTER&&(this.close(),null==(s=this.extensionCloseCallback)||s.call(this)))}};Vn.MODAL_CLOSE_TIMEOUT_MS=190;let Un=Vn;class Hn extends as{constructor(t,e,i,s,n,o){var r,a,l,c,h,u,d,p,m;const v=null==(r=null==i?void 0:i.button)?void 0:r.position,f=(null==(c=null==(l=null==(a=null==i?void 0:i.button)?void 0:a.styles)?void 0:l.text)?void 0:c.content)||o;super(Hn.createButtonElement(),v,i.button,f);const g="dropup-menu"===v,b=this.createInnerElements(s,n,this._customStyles,g);this._inputElement=Hn.createInputElement(null==(h=null==i?void 0:i.files)?void 0:h.acceptedFormats),this.addClickEvent(t,i),this.elementRef.replaceChildren(b.styles),this.reapplyStateStyle("styles"),this._fileAttachmentsType=e,this._openModalOnce=!1===(null==(d=null==(u=i.files)?void 0:u.infoModal)?void 0:d.openModalOnce)||null==(m=null==(p=i.files)?void 0:p.infoModal)?void 0:m.openModalOnce}createInnerElements(t,e,i,s=!1){const n=Hn.createSVGIconElement(t,e);return{styles:os.createInnerElement(this.elementRef,n,"styles",i,s)}}triggerImportPrompt(t){t.onchange=this.import.bind(this,t),t.click()}import(t){Jn.addFilesToType(Array.from(t.files||[]),[this._fileAttachmentsType]),t.value=""}static createInputElement(t){const e=document.createElement("input");return e.type="file",e.accept=t||"",e.hidden=!0,e.multiple=!0,e}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button","upload-file-button"),t}static createSVGIconElement(t,e){const i=$e.createSVGElement(e);return i.id=t,i}addClickEvent(t,e){const i=this.triggerImportPrompt.bind(this,this._inputElement),s=Un.createTextModalFunc(t,e,i);this.elementRef.onclick=this.click.bind(this,s)}click(t){!t||void 0!==this._openModalOnce&&!0!==this._openModalOnce?this.triggerImportPrompt(this._inputElement):(t(),!0===this._openModalOnce&&(this._openModalOnce=!1))}}class Kn{static create(t,e,i){const s=Kn.createElement(i);Kn.addEvents(s,t,e),t.appendChild(s)}static createElement(t){const e=document.createElement("div");return e.id="drag-and-drop","object"==typeof t&&Object.assign(e.style,t),e}static addEvents(t,e,i){e.ondragenter=e=>{e.preventDefault(),Kn.display(t)},t.ondragleave=e=>{e.preventDefault(),Kn.hide(t)},t.ondragover=t=>{t.preventDefault()},t.ondrop=e=>{e.preventDefault(),Kn.uploadFile(i,e),Kn.hide(t)}}static uploadFile(t,e){var i;const s=null==(i=e.dataTransfer)?void 0:i.files;s&&t.addFilesToAnyType(Array.from(s))}static display(t){t.style.display="block"}static hide(t){t.style.display="none"}static isEnabled(t,e){return(void 0===e||!1!==e)&&(!!e||t.getNumberOfTypes()>0)}}class Gn{static validate(t,e,i,s,n){const o=t(i,s,n);return o?e.changeToSubmitIcon():e.changeToDisabledIcon(),o}static async useValidationFunc(t,e,i,s){const n=e.isTextInputEmpty()?"":e.inputElementRef.textContent;await i.completePlaceholders();const o=i.getAllFileData(),r=null==o?void 0:o.map((t=>t.file));return Gn.validate(t,s,n,r)}static async useValidationFuncProgrammatic(t,e,i){var s;const n=null==(s=e.files)?void 0:s.map((t=>t.file));return Gn.validate(t,i,e.text,n,!0)}static validateWebsocket(t,e){return!(t.websocket&&!Oe.canSendMessage(t.websocket))||(e.changeToDisabledIcon(),!1)}static attach(t,e,i,s,n){const o=t.validateInput||S.processValidateInput(t);t._validationHandler=async t=>{if(n.status.loadingActive||n.status.requestInProgress||!0===e.isSubmitProgrammaticallyDisabled||!Gn.validateWebsocket(e,n))return!1;const r=o||e.canSendMessage;return r?t?Gn.useValidationFuncProgrammatic(r,t,n):Gn.useValidationFunc(r,i,s,n):null}}}class Zn{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 Wn extends ms{constructor(t,e){var i,s;super(e.button),this._waitingForBrowserApproval=!1,this._audioType=t,this._extension=(null==(i=e.files)?void 0:i.format)||"mp3",this._maxDurationSeconds=null==(s=e.files)?void 0:s.maxDurationSeconds,this.elementRef.onclick=this.buttonClick.bind(this)}buttonClick(){this._waitingForBrowserApproval||(this.isActive?this.stop():(this._waitingForBrowserApproval=!0,this.record()))}stop(){return new Promise((t=>{var e,i;this.changeToDefault(),null==(e=this._mediaRecorder)||e.stop(),null==(i=this._mediaStream)||i.getTracks().forEach((t=>t.stop())),setTimeout((()=>{t()}),10)}))}record(){navigator.mediaDevices.getUserMedia({audio:!0}).then((t=>{this.changeToActive(),this._mediaRecorder=new MediaRecorder(t),this._audioType.addPlaceholderAttachment(this.stop.bind(this),this._maxDurationSeconds),this._mediaStream=t,this._mediaRecorder.addEventListener("dataavailable",(t=>{this.createFile(t)})),this._mediaRecorder.start()})).catch((t=>{console.error(t),this.stop()})).finally((()=>{this._waitingForBrowserApproval=!1}))}createFile(t){const e=new Blob([t.data],{type:`audio/${this._extension}`}),i=Zn.getFileName(this._newFilePrefix||"audio",this._extension),s=new File([e],i,{type:e.type}),n=new FileReader;n.readAsDataURL(s),n.onload=t=>{this._audioType.completePlaceholderAttachment(s,t.target.result)}}}class Xn{static setPropertyValueIfDoesNotExist(t,e,i){const s=e[0];1===e.length?t[s]??(t[s]=i):(t[s]??(t[s]={}),e.shift(),Xn.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(),Xn.setPropertyValue(t[s],e,i))}static getObjectValue(t,e){const i=t[e[0]];return void 0===i||1===e.length?i:Xn.getObjectValue(i,e.slice(1))}static overwritePropertyObjectFromAnother(t,e,i){const s=Xn.getObjectValue(e,i);if(s){const e={...s,...Xn.getObjectValue(t,i)||{}};Xn.setPropertyValue(t,i,e)}}}class Qn{static resetSubmit(t,e){e?t.unsetCustomStateStyles(["loading","submit"]):t.unsetCustomStateStyles(["stop","loading","submit"]),t.reapplyStateStyle("submit")}static overwriteDefaultStyleWithSubmit(t,e){if(!t.submit)return;const i=JSON.parse(JSON.stringify(t[e]||{}));Xn.overwritePropertyObjectFromAnother(i,t.submit,["container","default"]),Xn.overwritePropertyObjectFromAnother(i,t.submit,["text","styles","default"]),Xn.overwritePropertyObjectFromAnother(i,t.submit,["svg","styles","default"]),t[e]=i}static setUpDisabledButton(t){Xn.setPropertyValueIfDoesNotExist(t,["submit","container","default","backgroundColor"],""),Xn.setPropertyValueIfDoesNotExist(t,["disabled","container","default","backgroundColor"],"unset"),Xn.setPropertyValueIfDoesNotExist(t.submit,["svg","styles","default","filter"],""),Xn.setPropertyValueIfDoesNotExist(t.disabled,["svg","styles","default","filter"],"brightness(0) saturate(100%) invert(70%) sepia(0%) saturate(5564%) hue-rotate(207deg) brightness(100%) contrast(97%)"),Qn.overwriteDefaultStyleWithSubmit(t,"disabled")}static process(t){const e=JSON.parse(JSON.stringify(t||{}));return Qn.overwriteDefaultStyleWithSubmit(e,"loading"),Qn.overwriteDefaultStyleWithSubmit(e,"stop"),null!=t&&t.alwaysEnabled||Qn.setUpDisabledButton(e),e}}const Yn=class t extends as{constructor(e,i,s,n,o,r){const a=Qn.process(e.submitButtonStyles);super(t.createButtonContainerElement(),null==a?void 0:a.position,a),this._isSVGLoadingIconOverriden=!1,this.status={requestInProgress:!1,loadingActive:!1},this._messages=s,this._textInput=i,this._fileAttachments=o,this._innerElements=this.createInnerElements(),this._abortStream=new AbortController,this._stopClicked={listener:()=>{}},this._serviceIO=n,this._alwaysEnabled=!(null==a||!a.alwaysEnabled),e.disableSubmitButton=this.disableSubmitButton.bind(this,n),this.attemptOverwriteLoadingStyle(e),r.microphone&&this.setUpSpeechToText(r.microphone.button,e.speechToText),setTimeout((()=>{var t;this._validationHandler=e._validationHandler,this.assignHandlers(this._validationHandler),null==(t=this._validationHandler)||t.call(this)}))}createInnerElements(){const{submit:e,loading:i,stop:s}=this.createCustomElements(),n=e||t.createSubmitIconElement();return{submit:n,loading:i||t.createLoadingIconElement(),stop:s||t.createStopIconElement(),disabled:this.createDisabledIconElement(n)}}createCustomElements(){const t=os.createSpecificStateElement(this.elementRef,"submit",this._customStyles),e={loading:void 0,stop:void 0};return Object.keys(e).forEach((t=>{const i=t,s=os.createCustomElement(i,this._customStyles);s&&(e[i]=s)})),e.submit=t,e}static createButtonContainerElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSubmitIconElement(){const t=$e.createSVGElement('<?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');return t.id="submit-icon",t}static createLoadingIconElement(){const t=document.createElement("div");return t.classList.add("loading-submit-button"),t}static createStopIconElement(){const t=document.createElement("div");return t.id="stop-icon",t}createDisabledIconElement(t){return os.createCustomElement("disabled",this._customStyles)||t.cloneNode(!0)}attemptOverwriteLoadingStyle(t){var e,i,s,n,o,r,a,l,c;if(!(null!=(i=null==(e=this._customStyles)?void 0:e.submit)&&i.svg||null!=(o=null==(n=null==(s=this._customStyles)?void 0:s.loading)?void 0:n.svg)&&o.content||null!=(l=null==(a=null==(r=this._customStyles)?void 0:r.loading)?void 0:a.text)&&l.content||void 0!==t.displayLoadingBubble&&!0!==t.displayLoadingBubble)){const e=document.createElement("style");e.textContent="\n .loading-button > * {\n filter: brightness(0) saturate(100%) invert(72%) sepia(0%) saturate(3044%) hue-rotate(322deg) brightness(100%)\n contrast(96%) !important;\n }",null==(c=t.shadowRoot)||c.appendChild(e),this._isSVGLoadingIconOverriden=!0}}assignHandlers(t){this._serviceIO.completionsHandlers={onFinish:this.resetSubmit.bind(this,t)},this._serviceIO.streamHandlers={onOpen:this.changeToStopIcon.bind(this),onClose:this.resetSubmit.bind(this,t),abortStream:this._abortStream,stopClicked:this._stopClicked};const{stream:e}=this._serviceIO;"object"==typeof e&&"number"==typeof e.simulation&&(this._serviceIO.streamHandlers.simulationInterim=e.simulation)}setUpSpeechToText(t,e){this._microphoneButton=t,this._stopSTTAfterSubmit="object"==typeof e&&e.stopAfterSubmit}resetSubmit(t){this.status.requestInProgress=!1,this.status.loadingActive=!1,t()}async submitFromInput(){await this._fileAttachments.completePlaceholders();const t=this._fileAttachments.getAllFileData();if(this._textInput.isTextInputEmpty())this.attemptSubmit({text:"",files:t});else{const e=this._textInput.inputElementRef.innerText.trim();this.attemptSubmit({text:e,files:t})}}async programmaticSubmit(t){"string"==typeof t&&(t=S.processSubmitUserMessage(t));const e={text:t.text};t.files&&(e.files=Array.from(t.files).map((t=>({file:t,type:Bn.getTypeFromBlob(t)})))),setTimeout((()=>this.attemptSubmit(e,!0)))}async attemptSubmit(t,e=!1){var i,s,n;if(!1===await(null==(i=this._validationHandler)?void 0:i.call(this,e?t:void 0)))return;this.changeToLoadingIcon(),await this.addNewMessage(t),this._serviceIO.isWebModel()||this._messages.addLoadingMessage(),this._textInput.clear();const o=null==(s=t.files)?void 0:s.map((t=>t.file)),r={text:""===t.text?void 0:t.text,files:o};await this._serviceIO.callAPI(r,this._messages),null==(n=this._fileAttachments)||n.removeAllFiles()}async addNewMessage({text:t,files:e}){const i={role:I.USER_ROLE};t&&(i.text=t),e&&(i.files=await this._messages.addMultipleFiles(e)),this._serviceIO.sessionId&&(i._sessionId=this._serviceIO.sessionId),Object.keys(i).length>0&&this._messages.addNewMessage(i)}stopStream(){var t;this._abortStream.abort(),null==(t=this._stopClicked)||t.listener(),this._validationHandler&&this.resetSubmit(this._validationHandler)}changeToStopIcon(){this._serviceIO.websocket||(this.elementRef.classList.remove(t.LOADING_CLASS,t.DISABLED_CLASS,t.SUBMIT_CLASS),this.elementRef.replaceChildren(this._innerElements.stop),this.reapplyStateStyle("stop",["loading","submit"]),this.elementRef.onclick=this.stopStream.bind(this),this.status.loadingActive=!1)}changeToLoadingIcon(){this._serviceIO.websocket||(this._isSVGLoadingIconOverriden||this.elementRef.replaceChildren(this._innerElements.loading),this.elementRef.classList.remove(t.SUBMIT_CLASS,t.DISABLED_CLASS),this.elementRef.classList.add(t.LOADING_CLASS),this.reapplyStateStyle("loading",["submit"]),this.elementRef.onclick=()=>{},this.status.requestInProgress=!0,this.status.loadingActive=!0)}changeToSubmitIcon(){this.elementRef.classList.contains(t.SUBMIT_CLASS)||(this.elementRef.classList.remove(t.LOADING_CLASS,t.DISABLED_CLASS),this.elementRef.classList.add(t.SUBMIT_CLASS),this.elementRef.replaceChildren(this._innerElements.submit),Qn.resetSubmit(this,this.status.loadingActive),this.elementRef.onclick=()=>{var t;this.submitFromInput(),null!=(t=this._microphoneButton)&&t.isActive&&Ln.toggleSpeechAfterSubmit(this._microphoneButton.elementRef,!!this._stopSTTAfterSubmit)})}changeToDisabledIcon(e=!1){this._alwaysEnabled&&!e?this.changeToSubmitIcon():this.elementRef.classList.contains(t.DISABLED_CLASS)||(this.elementRef.classList.remove(t.LOADING_CLASS,t.SUBMIT_CLASS),this.elementRef.classList.add(t.DISABLED_CLASS),this.elementRef.replaceChildren(this._innerElements.disabled),this.reapplyStateStyle("disabled",["submit"]),this.elementRef.onclick=()=>{})}disableSubmitButton(t,e){var i;t.isSubmitProgrammaticallyDisabled=!1!==e,!this.status.requestInProgress&&!this.status.loadingActive&&(!1===e?null==(i=this._validationHandler)||i.call(this):this.changeToDisabledIcon(!0))}};Yn.SUBMIT_CLASS="submit-button",Yn.LOADING_CLASS="loading-button",Yn.DISABLED_CLASS="disabled-button";let to=Yn;class eo extends Un{constructor(t,e,i,s){super(t,["modal-content","modal-camera-content"],i),this._stopped=!1,this._format="image/png",this._canvas=document.createElement("canvas"),this._canvas.classList.add("camera-modal-canvas");const{captureButton:n,submitButton:o}=this.addButtonsAndTheirEvents(e);this._captureButton=n,this._submitButton=o,this._captureIcon=this._captureButton.children[0],this._refreshIcon=$e.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">\n <path d="M27.1 14.313V5.396L24.158 8.34c-2.33-2.325-5.033-3.503-8.11-3.503C9.902 4.837 4.901 9.847 4.899 16c.001 6.152 5.003 11.158 11.15 11.16 4.276 0 9.369-2.227 10.836-8.478l.028-.122h-3.23l-.022.068c-1.078 3.242-4.138 5.421-7.613 5.421a8 8 0 0 1-5.691-2.359A7.993 7.993 0 0 1 8 16.001c0-4.438 3.611-8.049 8.05-8.049 2.069 0 3.638.58 5.924 2.573l-3.792 3.789H27.1z"/>\n</svg>\n'),this._refreshIcon.classList.add("modal-svg-button-icon","modal-svg-refresh-icon"),"jpeg"===(null==s?void 0:s.format)&&(this._format="image/jpeg"),null!=s&&s.dimensions&&(this._dimensions=s.dimensions),this._contentRef.appendChild(this._canvas),this.extensionCloseCallback=this.stop}addButtonsAndTheirEvents(t){const e=Un.createSVGButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <title>capture</title>\n <path d="M0 16q0 3.264 1.28 6.208t3.392 5.12 5.12 3.424 6.208 1.248 6.208-1.248 5.12-3.424 3.392-5.12 1.28-6.208-1.28-6.208-3.392-5.12-5.088-3.392-6.24-1.28q-3.264 0-6.208 1.28t-5.12 3.392-3.392 5.12-1.28 6.208zM4 16q0-3.264 1.6-6.016t4.384-4.352 6.016-1.632 6.016 1.632 4.384 4.352 1.6 6.016-1.6 6.048-4.384 4.352-6.016 1.6-6.016-1.6-4.384-4.352-1.6-6.048z"></path>\n</svg>\n');e.classList.add("modal-svg-camera-button"),e.children[0].classList.add("modal-svg-camera-icon");const i=this.addCloseButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="M195.2 195.2a64 64 0 0 1 90.496 0L512 421.504 738.304 195.2a64 64 0 0 1 90.496 90.496L602.496 512 828.8 738.304a64 64 0 0 1-90.496 90.496L512 602.496 285.696 828.8a64 64 0 0 1-90.496-90.496L421.504 512 195.2 285.696a64 64 0 0 1 0-90.496z"/>\n</svg>',!0);i.classList.add("modal-svg-close-button"),i.children[0].classList.add("modal-svg-close-icon");const s=Un.createSVGButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M4.89163 13.2687L9.16582 17.5427L18.7085 8" stroke="#000000" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>');return s.classList.add("modal-svg-submit-button"),this.addButtons(e,s),this.addButtonEvents(e,i,s,t),{captureButton:e,submitButton:s}}addButtonEvents(t,e,i,s){t.onclick=()=>{this.capture()},e.addEventListener("click",this.stop.bind(this)),i.onclick=()=>{const t=this.getFile();t&&Jn.addFilesToType([t],[s]),this.stop(),this.close()}}stop(){this._mediaStream&&this._mediaStream.getTracks().forEach((t=>t.stop())),this._stopped=!0,setTimeout((()=>{this._captureButton.replaceChildren(this._captureIcon),this._captureButton.classList.replace("modal-svg-refresh-button","modal-svg-camera-button");const t=this._canvas.getContext("2d");null==t||t.clearRect(0,0,this._canvas.width,this._canvas.height)}),Un.MODAL_CLOSE_TIMEOUT_MS)}start(){this._dataURL=void 0,this._submitButton.classList.add("modal-svg-submit-disabled"),this._stopped=!1,navigator.mediaDevices.getUserMedia({video:this._dimensions||!0}).then((t=>{if(this._mediaStream=t,!this.isOpen())return this.stop();const e=document.createElement("video");e.srcObject=t,e.play(),requestAnimationFrame(this.updateCanvas.bind(this,e,this._canvas))})).catch((t=>{console.error(t),this.stop(),this.close()}))}capture(){this._dataURL?(this._captureButton.replaceChildren(this._captureIcon),this._captureButton.classList.replace("modal-svg-refresh-button","modal-svg-camera-button"),this._submitButton.classList.add("modal-svg-submit-disabled"),this._dataURL=void 0):(this._captureButton.replaceChildren(this._refreshIcon),this._captureButton.classList.replace("modal-svg-camera-button","modal-svg-refresh-button"),this._submitButton.classList.remove("modal-svg-submit-disabled"),this._dataURL=this._canvas.toDataURL())}getFile(){if(this._dataURL){const t=atob(this._dataURL.split(",")[1]),e=new Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);const i=new Uint8Array(e),s=new Blob([i],{type:this._format}),n="image/jpeg"===this._format?"jpeg":"png",o=Zn.getFileName(this._newFilePrefix||"photo",n);return new File([s],o,{type:s.type})}}updateCanvas(t,e){if(!this._stopped){if(!this._dataURL){e.width=t.videoWidth,e.height=t.videoHeight;const i=e.getContext("2d");null==i||i.drawImage(t,0,0,e.width,e.height)}requestAnimationFrame(this.updateCanvas.bind(this,t,e))}}openCameraModal(t){this.displayModalElements(),t.start()}static createCameraModalFunc(t,e,i,s){const n=new eo(t,e,i,s);return n.openCameraModal.bind(n,n)}}class io extends as{constructor(t,e,i){var s,n,o,r;const a=null==(s=null==i?void 0:i.button)?void 0:s.position,l=(null==(r=null==(o=null==(n=null==i?void 0:i.button)?void 0:n.styles)?void 0:o.text)?void 0:r.content)||"Photo";super(io.createButtonElement(),a,(null==i?void 0:i.button)||{},l);const c=this.createInnerElements(this._customStyles,"dropup-menu"===a);i&&this.addClickEvent(t,e,i.modalContainerStyle,i.files),this.elementRef.classList.add("upload-file-button"),this.elementRef.appendChild(c.styles),this.reapplyStateStyle("styles")}createInnerElements(t,e=!1){return{styles:os.createInnerElement(this.elementRef,io.createSVGIconElement(),"styles",t,e)}}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSVGIconElement(){const t=$e.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <path d="M29 7h-4.599l-2.401-4h-12l-2.4 4h-4.6c-1 0-3 1-3 2.969v16.031c0 1.657 1.5 3 2.792 3h26.271c1.313 0 2.938-1.406 2.938-2.968v-16.032c0-1-1-3-3-3zM30 26.032c0 0.395-0.639 0.947-0.937 0.969h-26.265c-0.232-0.019-0.797-0.47-0.797-1v-16.031c0-0.634 0.851-0.953 1-0.969h5.732l2.4-4h9.802l1.785 3.030 0.55 0.97h5.731c0.705 0 0.99 0.921 1 1v16.032zM16 10c-3.866 0-7 3.134-7 7s3.134 7 7 7 7-3.134 7-7-3.134-7-7-7zM16 22c-2.757 0-5-2.243-5-5s2.243-5 5-5 5 2.243 5 5-2.243 5-5 5z"></path>\n</svg>');return t.id="camera-icon",t}addClickEvent(t,e,i,s){const n=eo.createCameraModalFunc(t,e,i,s);this.elementRef.onclick=n}}class so{constructor(t,e,i,s){this.elementRef=so.createPanelElement(t.inputAreaStyle);const n={},o=this.createFileUploadComponents(t,i,s,n),r=new m(t,i,o);t.speechToText&&!n.microphone&&(n.microphone={button:new Ln(t,r,e.addNewErrorMessage.bind(e))});const a=new to(t,r,e,i,o,n);r.submit=a.submitFromInput.bind(a),Gn.attach(t,i,r,o,a),t.submitUserMessage=a.programmaticSubmit.bind(a),n.submit={button:a},so.addElements(this.elementRef,r,n,s,o,t.dropupStyles)}static createPanelElement(t){const e=document.createElement("div");return e.id="input",Object.assign(e.style,t),e}createFileUploadComponents(t,e,i,s){var n,o,r,a;const l=new Jn(this.elementRef,t.attachmentContainerStyle,e.demo);if(so.createUploadButtons(t,e.fileTypes||{},l,i,s),null!=(n=e.camera)&&n.files){const n=(null==(o=s.images)?void 0:o.fileType)||l.addType(t,e.camera.files,"images");s.camera={button:new io(i,n,e.camera)}}if(null!=(r=e.recordAudio)&&r.files){const i=(null==(a=s.audio)?void 0:a.fileType)||l.addType(t,e.recordAudio.files,"audio");s.microphone={button:new Wn(i,e.recordAudio)}}return Kn.isEnabled(l,t.dragAndDrop)&&Kn.create(i,l,t.dragAndDrop),l}static createUploadButtons(t,e,i,s,n){Object.keys(e).forEach((o=>{const r=o,a=e[r];if(a.files){const e=i.addType(t,a.files,r),{id:o,svgString:l,dropupText:c}=ps[r],h=new Hn(s,e,a,o,l,c);n[r]={button:h,fileType:e}}}))}static addElements(t,e,i,s,n,o){x.addElements(t,e.elementRef);const r=ss.create(),a=ds.addButtons(r,i,s,o);is.set(e.inputElementRef,r,n.elementRef,a),ss.add(t,r)}}class no{static createElements(t,e,i){const s=document.createElement("div");s.id="chat-view";const n=new ts(t,e,i);e.websocket&&Oe.createConnection(e,n);const o=new so(t,n,e,s);return x.addElements(s,n.elementRef,o.elementRef),s}static render(t,e,i,s){const n=no.createElements(t,i,s);e.replaceChildren(n)}}var oo=Object.defineProperty,ro=(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&&oo(e,i,o),o};class ao extends De{constructor(){super(),this.getMessages=()=>[],this.submitUserMessage=()=>console.warn("submitUserMessage failed - please wait for chat view to render before calling this property."),this.addMessage=()=>console.warn("addMessage failed - please wait for chat view to render before calling this property."),this.focusInput=()=>v.focusFromParentElement(this._elementRef),this.refreshMessages=()=>{},this.clearMessages=()=>{},this.scrollToBottom=()=>{},this.disableSubmitButton=()=>{},this.setPlaceholderText=()=>{},this._hasBeenRendered=!1,this._auxiliaryStyleApplied=!1,this._elementRef=document.createElement("div"),this._elementRef.id="container",this.attachShadow({mode:"open"}).appendChild(this._elementRef),r.apply('#validate-property-key-view{height:100%;position:relative;display:flex;justify-content:center;align-items:center;padding:8px}#loading-validate-key-property{display:inline-block;width:50px;height:50px}#loading-validate-key-property:after{content:" ";display:block;width:38px;height:38px;margin:1px;border-radius:50%;border:5px solid #5fb2ff;border-color:#5fb2ff transparent #5fb2ff transparent;animation:loading-spinner 1.4s linear infinite}#insert-key-view{height:100%;position:relative}#insert-key-contents{text-align:center;position:absolute;top:44%;left:50%;transform:translate(-50%,-50%);width:82%;display:flex;max-width:700px}#insert-key-title{margin-bottom:15px}#insert-key-input-container{margin-right:2.7em;width:calc(100% - 80px)}#insert-key-input{padding:.3em 1.7em .3em .3em;border-width:1px;border-style:solid;border-radius:3px;width:100%;font-size:inherit}.insert-key-input-valid{border-color:gray}.insert-key-input-invalid{border-color:red}#visibility-icon-container{position:relative;float:right;cursor:pointer;-webkit-user-select:none;user-select:none}.visibility-icon{filter:brightness(0) saturate(100%) invert(63%) sepia(1%) saturate(9%) hue-rotate(43deg) brightness(98%) contrast(92%);position:absolute;right:-1.7em;top:-1.43em}#visible-icon{top:-1.4em}.visibility-icon:hover{filter:unset}.visibility-icon>*{pointer-events:none}#start-button{border:1px solid grey;color:#454545;border-radius:4px;width:3em;display:flex;justify-content:center;align-items:center;cursor:pointer;padding:.28em .3em;-webkit-user-select:none;user-select:none;background-color:#fff}#start-button:hover{background-color:#f2f2f2}#start-button:active{background-color:#d2d2d2}#insert-key-help-text-container{width:100%;position:absolute;margin-top:32px;margin-bottom:20px}#insert-key-help-text-contents{width:100%;position:absolute}#insert-key-input-invalid-text{display:block;margin-top:1em;margin-bottom:.5em;color:red}.insert-key-input-help-text{display:block;margin-top:16px}#loading-key{display:inline-block;width:16px;height:16px}#loading-key:after{content:" ";display:block;width:11px;height:11px;margin:1px;border-radius:50%;border:2px solid #0084ff;border-color:#0084ff transparent #0084ff transparent;animation:loading-spinner 1.2s linear infinite}#error-view{color:red;font-size:1.2em;line-height:1.3em;margin-top:-5px;text-align:center;height:100%;display:flex;justify-content:center;align-items:center;padding-left:8px;padding-right:8px}@keyframes loading-spinner{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.intro-panel{position:absolute;display:flex;justify-content:center;right:0;bottom:0;left:0;margin:auto;height:fit-content;top:-2.5em}#internal-intro-panel{width:250px;height:min-content;display:block;border-radius:5px;overflow:auto;border:1px solid rgb(203,203,203);padding:10px;max-height:calc(100% - 6.8em)}#internal-intro-panel>p{margin-block-start:.8em;margin-block-end:.8em}pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}/*!\n Theme: a11y-dark\n Author: @ericwbailey\n Maintainer: @ericwbailey\n\n Based on the Tomorrow Night Eighties theme: https://github.com/isagalaev/highlight.js/blob/master/src/styles/tomorrow-night-eighties.css\n*/.hljs{background:#2b2b2b;color:#f8f8f2}.hljs-comment,.hljs-quote{color:#d4d0ab}.hljs-deletion,.hljs-name,.hljs-regexp,.hljs-selector-class,.hljs-selector-id,.hljs-tag,.hljs-template-variable,.hljs-variable{color:#ffa07a}.hljs-built_in,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-type{color:#f5ab35}.hljs-attribute{color:gold}.hljs-addition,.hljs-bullet,.hljs-string,.hljs-symbol{color:#abe338}.hljs-section,.hljs-title{color:#00e0e0}.hljs-keyword,.hljs-selector-tag{color:#dcc6e0}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}@media screen and (-ms-high-contrast: active){.hljs-addition,.hljs-attribute,.hljs-built_in,.hljs-bullet,.hljs-comment,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-quote,.hljs-string,.hljs-symbol,.hljs-type{color:highlight}.hljs-keyword,.hljs-selector-tag{font-weight:700}}#messages{overflow:auto}.outer-message-container:last-child{margin-bottom:5px}.inner-message-container{display:flex;margin-left:auto;margin-right:auto;width:calc(97.5% - 24px);max-width:100%}.message-bubble{margin-top:10px;word-wrap:break-word;width:fit-content;max-width:60%;border-radius:10px;padding:.42em .55em;height:fit-content;line-height:1.26em}.user-message-text{color:#fff;background-color:#0084ff;margin-right:0;margin-left:auto}.ai-message-text{color:#000;background-color:#e4e6eb;margin-left:0;margin-right:auto}.loading-history-message-full-view{position:absolute;height:70%;width:100%;display:flex;align-items:center}.loading-history-message-small{height:20px;margin-bottom:30px}.loading-history-message-small>div>div{scale:.6}.loading-history-message{margin-top:0;width:100%;max-width:100%;display:flex;justify-content:center;background-color:unset}.loading-history{width:70px}.loading-history div{position:absolute;width:var(--loading-history-width);height:var(--loading-history-height);margin:var(--loading-history-margin);border:var(--loading-history-border) solid;border-radius:50%;animation:loading-spinner 1.2s cubic-bezier(.5,0,.5,1) infinite;border-color:var(--loading-history-color) transparent transparent transparent}.loading-history div:nth-child(1){animation-delay:-.45s}.loading-history div:nth-child(2){animation-delay:-.3s}.loading-history div:nth-child(3){animation-delay:-.15s}.html-message{max-width:unset}.error-message-text{margin:14px auto 10px;background-color:#f4c0c0;color:#474747;text-align:center;max-width:95%}.deep-chat-loading-message-dots-container{width:1em;padding:.6em .75em .6em 1.3em}.loading-message-dots{position:relative;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite linear alternate;animation-delay:.5s}.loading-message-dots:before,.loading-message-dots:after{content:"";display:inline-block;position:absolute;top:0}.loading-message-dots:before{left:-.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite alternate;animation-delay:0s}.loading-message-dots:after{left:.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite alternate;animation-delay:1s}@keyframes loading-message-dots{0%{background-color:var(--loading-message-color)}50%,to{background-color:var(--loading-message-color-fade)}}.message-bubble>p:first-child{margin-top:0}.message-bubble>p:last-child{margin-bottom:0}pre{overflow:auto;display:block;word-break:break-all;word-wrap:break-word;border-radius:7px;background:#2b2b2b;color:#f8f8f2;margin-top:.8em;margin-bottom:.8em;padding:.6em;font-size:.9em;line-height:1.5em}.image-message{padding:0;display:flex;background-color:#ddd}.image-message>*,.image-message>*>*{width:100%;border-radius:8px;display:flex}.audio-message{width:60%;max-width:300px;height:2.2em;max-height:54px;padding:0;background-color:unset}.audio-player{width:100%;height:100%}.audio-player-safari{height:fit-content;width:40px}.audio-player-safari-left{float:left}.audio-player-safari-right{float:right}.any-file-message-bubble{padding:1px}.any-file-message-contents{display:flex}.any-file-message-icon-container{width:1.3em;min-width:1.3em;position:relative;border-radius:4px;margin-left:6px;margin-right:2px}.any-file-message-icon{background-color:#fff;border-radius:4px;position:absolute;width:1em;height:1.25em;padding:1px;margin-top:auto;margin-bottom:auto;top:0;bottom:0}.any-file-message-text{padding-top:5px;overflow-wrap:anywhere;padding-bottom:5px;padding-right:7px}.message-bubble>a{color:inherit}.left-item-position{margin-right:10px}.right-item-position{margin-left:10px}.avatar{padding-top:5px;width:1.5em;height:1.5em;border-radius:1px}.avatar-container{margin-top:9px}.name{margin-top:16px;font-size:15px}#drag-and-drop{position:absolute;display:none;z-index:10;height:calc(100% - 10px);width:calc(100% - 10px);background-color:#70c6ff4d;border:5px dashed #6dafff}#file-attachment-container{position:absolute;height:3.6em;width:calc(80% - 4px);top:-2.5em;border-radius:5px;overflow:auto;text-align:left;background-color:#d7d7d73b;padding-left:4px}.file-attachment{width:2.85em;height:2.85em;display:inline-flex;margin-right:.6em;margin-bottom:.44em;margin-top:4px;position:relative;background-color:#fff;border-radius:5px}.image-attachment{width:100%;height:100%;object-fit:cover;border-radius:5px}.border-bound-attachment{width:calc(100% - 2px);height:calc(100% - 2px);border:1px solid #c3c3c3;border-radius:5px;overflow:hidden}.border-bound-attachment-safari{width:calc(100% - 1px);height:calc(100% - 1px)}.audio-attachment-icon-container{cursor:pointer}.audio-attachment-icon-container:hover{background-color:#f8f8f8}.attachment-icon{left:0;right:0;bottom:0;top:2px;margin:auto;position:absolute;width:25px;-webkit-user-select:none;user-select:none}.not-removable-attachment-icon{top:0;right:0;bottom:0;left:0}.play-icon{filter:brightness(0) saturate(100%) invert(17%) sepia(0%) saturate(1392%) hue-rotate(67deg) brightness(98%) contrast(97%)}.stop-icon{filter:brightness(0) saturate(100%) invert(29%) sepia(90%) saturate(1228%) hue-rotate(198deg) brightness(93%) contrast(98%)}.audio-placeholder-text-3-digits{padding-left:.26rem}.audio-placeholder-text-4-digits{padding-left:.1rem}.any-file-attachment{padding:2px 0}.file-attachment-text-container{position:absolute;width:inherit;display:flex;align-items:center;height:100%;top:-1px}.audio-placeholder-text-3-digits-container{padding-top:1px;cursor:default}.any-file-attachment-text{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;padding-left:.13em;margin-left:auto;margin-right:auto}.remove-file-attachment-button{height:1.25em;width:1.25em;border:1px solid #cfcfcf;border-radius:25px;background-color:#fff;top:-4px;right:-5px;position:absolute;display:flex;justify-content:center;cursor:pointer;-webkit-user-select:none;user-select:none}.remove-file-attachment-button:hover{background-color:#e4e4e4}.remove-file-attachment-button:active{background-color:#d7d7d7}.x-icon{color:#4e4e4e;top:-.075em;position:relative;font-size:1.05em}.modal{display:none;flex-direction:column;align-items:center;justify-content:center;position:absolute;width:80%;max-width:420px;max-height:80%;margin:auto;top:0;right:0;bottom:0;left:0;z-index:2}.modal-content{border-top:1px solid rgb(217,217,217);border-left:1px solid rgb(217,217,217);border-right:1px solid rgb(217,217,217);border-top-left-radius:inherit;border-top-right-radius:inherit;background-color:#fff;overflow-y:auto;height:fit-content;max-height:calc(100% - 3.3em);width:100%}.modal-content>p{margin-left:1em;margin-right:1em}.modal-content>ul{margin-right:1em}.modal-button-panel{height:3.3em;border:1px solid;border-color:rgb(223,223,223) rgb(217,217,217) rgb(217,217,217);border-bottom-left-radius:inherit;border-bottom-right-radius:inherit;background-color:#fff;text-align:center;justify-content:center;display:flex;width:100%}.modal-button{min-width:2.5em;text-align:center;color:#fff;border-radius:5px;padding:.4em .4em .3em;height:1.25em;background-color:#3279b2;top:0;bottom:0;cursor:pointer;-webkit-user-select:none;user-select:none;margin:auto .31em}.modal-button:hover{background-color:#276da7}.modal-button:active{background-color:#1b5687}.modal-svg-button{padding:0 0 2px;width:2em;height:1.8em}.modal-svg-button-icon{width:100%;height:100%;filter:brightness(0) saturate(100%) invert(100%) sepia(15%) saturate(4%) hue-rotate(346deg) brightness(101%) contrast(102%)}#modal-background-panel{position:absolute;width:100%;height:100%;background-color:#00000042;z-index:1;display:none}.show-modal-background{animation:fadeInBackground .3s ease-in-out}@keyframes fadeInBackground{0%{opacity:0}to{opacity:1}}.show-modal{animation:fadeInModal .3s ease-in-out}@keyframes fadeInModal{0%{opacity:0;scale:.95}to{opacity:1;scale:1}}.hide-modal-background{animation:fadeOutBackground .2s ease-in-out}@keyframes fadeOutBackground{0%{opacity:1}to{opacity:0}}.hide-modal{animation:fadeOutModal .2s ease-in-out}@keyframes fadeOutModal{0%{opacity:1;scale:1}to{opacity:0;scale:.95}}.modal-camera-content{overflow:hidden;text-align:center;border:unset;height:100%;background-color:#2a2a2a;display:flex;justify-content:center}.camera-modal-canvas{max-width:100%;max-height:100%;margin-top:auto;margin-bottom:auto}.modal-svg-submit-button{background-color:green}.modal-svg-submit-button:hover{background-color:#007500}.modal-svg-submit-button:active{background-color:#006500}.modal-svg-submit-disabled{pointer-events:none;background-color:#747474}.modal-svg-close-button{height:1.56em;padding-top:.37em;padding-bottom:0;background-color:#c13e3e}.modal-svg-close-button:hover{background-color:#b43434}.modal-svg-close-button:active{background-color:#972929}.modal-svg-close-icon{width:80%;height:80%}.modal-svg-camera-button{height:1.6em;padding-top:.38em;padding-bottom:0}.modal-svg-camera-icon{height:76%}.modal-svg-refresh-icon{height:105%}.modal-svg-refresh-button{height:1.66em;padding-top:.11em;padding-bottom:.21em}.input-button-container{position:relative;z-index:1}.inside-right{position:absolute;right:calc(10% + .35em);bottom:.85em}.inside-left{position:absolute;left:calc(10% + .35em);bottom:.85em}.outside-left{position:absolute;right:calc(11px - .55em);bottom:.88em}.outside-right{position:absolute;left:calc(11px - .55em);bottom:.88em}#upload-images-icon{position:absolute;pointer-events:none;width:1.45em;height:1.45em;left:.11em;bottom:.08em;filter:brightness(0) saturate(100%) invert(43%) sepia(0%) saturate(740%) hue-rotate(77deg) brightness(99%) contrast(92%)}#upload-gifs-icon{position:absolute;pointer-events:none;width:1.5em;height:1.48em;left:.07em;bottom:.08em;filter:brightness(0) saturate(100%) invert(49%) sepia(0%) saturate(2586%) hue-rotate(12deg) brightness(93%) contrast(90%)}#upload-audio-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.17em;bottom:.2em;filter:brightness(0) saturate(100%) invert(15%) sepia(0%) saturate(337%) hue-rotate(125deg) brightness(91%) contrast(94%);transform:scaleX(.95)}#camera-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.23em;bottom:.2em;filter:brightness(0) saturate(100%) invert(52%) sepia(0%) saturate(161%) hue-rotate(164deg) brightness(91%) contrast(92%);transform:scaleX(.95)}#upload-mixed-files-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.2em;filter:brightness(0) saturate(100%) invert(53%) sepia(0%) saturate(36%) hue-rotate(74deg) brightness(98%) contrast(93%);transform:scaleX(.95)}#interim-text{color:gray}#microphone-button{padding-top:.5px}.outer-button-container>#microphone-button{padding-bottom:1px}#microphone-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.25em}.default-microphone-icon{filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%)}.active-microphone-icon{filter:brightness(0) saturate(100%) invert(10%) sepia(97%) saturate(7495%) hue-rotate(0deg) brightness(101%) contrast(107%);border-radius:10px}.command-microphone-icon{filter:brightness(0) saturate(100%) invert(42%) sepia(96%) saturate(1067%) hue-rotate(77deg) brightness(99%) contrast(102%)}.unsupported-microphone{display:none}#submit-icon{height:100%;filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%);width:1.21em}#stop-icon{background-color:#acacac;position:absolute;width:.95em;height:.95em;left:.35em;bottom:.35em;border-radius:2px}.submit-button-enlarged{scale:1.1;margin-right:.3em;margin-left:.3em}.loading-submit-button{position:relative;left:calc(-9990px + .275em);width:.22em;height:.22em;border-radius:5px;background-color:#848484;color:#848484;box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484;animation:loading-submit-button 1.5s infinite linear;bottom:-.75em}@keyframes loading-submit-button{0%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}16.667%{box-shadow:9990px -6px #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}33.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}50%{box-shadow:9990px 0 #848484,calc(9990px + .44em) -6px 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}66.667%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}83.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) -6px 0 0 #848484}to{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}}.input-button{border-radius:4px;cursor:pointer;margin-bottom:.2em;-webkit-user-select:none;user-select:none}.input-button-svg{width:1.65em;height:1.65em}.input-button:hover{background-color:#9c9c9c2e}.input-button:active{background-color:#9c9c9c5e}.loading-button{cursor:auto}.loading-button:hover{background-color:unset}.text-button{filter:unset!important;display:flex;justify-content:center;align-items:center;margin-left:4px;margin-right:4px;height:1.6em}#text-input-container{background-color:#fff;width:80%;display:flex;border:1px solid #0000001a;border-radius:5px;margin-top:.8em;margin-bottom:.8em;box-shadow:#959da533 0 1px 12px;overflow-y:auto;max-height:200px;position:relative}.text-input-container-left-adjustment{margin-left:1.5em}.text-input-container-right-adjustment{margin-right:1.5em}.text-input-container-left-small-adjustment{margin-left:1.1em}.text-input-container-left-small-adjustment>.outside-left{right:calc(14px - .55em)}.text-input-container-right-small-adjustment{margin-right:1.1em}.text-input-container-right-small-adjustment>.outside-right{left:calc(14px - .55em)}#text-input{text-align:left;outline:none;word-wrap:break-word;line-break:auto}.text-input-styling{padding:.4em .5em;overflow:overlay;width:100%}.text-input-inner-left-adjustment{padding-left:2.2em}.text-input-inner-right-adjustment{padding-right:2em}.text-input-disabled{pointer-events:none;-webkit-user-select:none;user-select:none}[contenteditable]:empty:before{content:attr(deep-chat-placeholder-text);pointer-events:none}[contenteditable][textcolor]:empty:before{color:gray}.outside-right>#dropup-menu,.inside-right>#dropup-menu{right:0}#dropup-icon{position:absolute;pointer-events:none;width:1.16em;height:1.2em;left:.265em;bottom:.43em;filter:brightness(0) saturate(100%) invert(54%) sepia(0%) saturate(724%) hue-rotate(6deg) brightness(92%) contrast(90%)}#dropup-menu{background-color:#fff;position:absolute;transform:translateY(-100%);border-radius:5px;z-index:1;top:-.49em;box-shadow:#0003 -1px 2px 10px,#0000001a 0 2px 4px;cursor:pointer;-webkit-user-select:none;user-select:none}.dropup-menu-item{height:1.4em;padding:.28em .84em .28em .35em;display:flex;position:relative}.dropup-menu-item:first-child{padding-top:.49em;border-top-left-radius:inherit;border-top-right-radius:inherit}.dropup-menu-item:last-child{padding-bottom:.45em;border-bottom-left-radius:inherit;border-bottom-right-radius:inherit}.dropup-menu-item-icon{width:1.39em;position:relative;margin-right:.56em}.dropup-menu-item-icon>svg{bottom:0!important;top:0!important;margin-bottom:auto;margin-top:auto}.dropup-menu-item-text{margin-top:.08em;width:max-content}#input{width:100%;display:inline-flex;text-align:center;margin-left:auto;margin-right:auto;margin-top:auto;position:relative;justify-content:center}#chat-view{height:100%;display:grid;grid-template-columns:100%}::-webkit-scrollbar{width:9px;height:9px}::-webkit-scrollbar-thumb{background-color:#d0d0d0;border-radius:5px}::-webkit-scrollbar-track{background-color:#f2f2f2}.deep-chat-web-model-button{margin-top:10px;margin-bottom:5px;margin-left:1px}:host{all:initial;display:table-cell}#container{height:inherit;width:inherit;overflow:hidden}',this.shadowRoot),setTimeout((()=>{this._hasBeenRendered||this.onRender()}),20)}changeToChatView(){this._activeService&&(this._activeService.validateKeyProperty=!1),this.onRender()}onRender(){n.attemptAppendStyleSheetToHead(this.style),S.processConnect(this),(!this._activeService||this._activeService.demo)&&(this._activeService=Ki.create(this)),this.auxiliaryStyle&&!this._auxiliaryStyleApplied&&(r.apply(this.auxiliaryStyle,this.shadowRoot),this._auxiliaryStyleApplied=!0),r.applyDefaultStyleToComponent(this.style,this.chatStyle),S.checkForContainerStyles(this,this._elementRef),this._activeService.key&&this._activeService.validateKeyProperty?e.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):this._activeService instanceof Be&&!this._activeService.key?this._activeService instanceof Be&&Ue.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):(this._childElement??(this._childElement=this.children[0]),no.render(this,this._elementRef,this._activeService,this._childElement)),this._hasBeenRendered=!0,pe.onRender(this)}disconnectedCallback(){We.chat=void 0}}ro([Wi("object")],ao.prototype,"connect"),ro([Wi("object")],ao.prototype,"directConnection"),ro([Wi("object")],ao.prototype,"webModel"),ro([Wi("object")],ao.prototype,"requestBodyLimits"),ro([Wi("function")],ao.prototype,"requestInterceptor"),ro([Wi("function")],ao.prototype,"responseInterceptor"),ro([Wi("function")],ao.prototype,"validateInput"),ro([Wi("function")],ao.prototype,"loadHistory"),ro([Wi("object")],ao.prototype,"chatStyle"),ro([Wi("object")],ao.prototype,"attachmentContainerStyle"),ro([Wi("object")],ao.prototype,"dropupStyles"),ro([Wi("object")],ao.prototype,"inputAreaStyle"),ro([Wi("object")],ao.prototype,"textInput"),ro([Wi("object")],ao.prototype,"submitButtonStyles"),ro([Wi("string")],ao.prototype,"auxiliaryStyle"),ro([Wi("array")],ao.prototype,"history"),ro([Wi("object")],ao.prototype,"introMessage"),ro([Wi("object")],ao.prototype,"avatars"),ro([Wi("object")],ao.prototype,"names"),ro([Wi("boolean")],ao.prototype,"displayLoadingBubble"),ro([Wi("object")],ao.prototype,"errorMessages"),ro([Wi("object")],ao.prototype,"messageStyles"),ro([Wi("object")],ao.prototype,"textToSpeech"),ro([Wi("object")],ao.prototype,"speechToText"),ro([Wi("object")],ao.prototype,"images"),ro([Wi("object")],ao.prototype,"gifs"),ro([Wi("object")],ao.prototype,"camera"),ro([Wi("object")],ao.prototype,"audio"),ro([Wi("object")],ao.prototype,"microphone"),ro([Wi("object")],ao.prototype,"mixedFiles"),ro([Wi("object")],ao.prototype,"dragAndDrop"),ro([Wi("object")],ao.prototype,"introPanelStyle"),ro([Wi("object")],ao.prototype,"htmlClassUtilities"),ro([Wi("function")],ao.prototype,"onMessage"),ro([Wi("function")],ao.prototype,"onClearMessages"),ro([Wi("function")],ao.prototype,"onComponentRender"),ro([Wi("function")],ao.prototype,"onError"),ro([Wi("object")],ao.prototype,"demo"),ro([Wi("object")],ao.prototype,"_insertKeyViewStyles"),customElements.define("deep-chat",ao);export{ao as DeepChat};
1
+ class t{static render(t,e){const i=document.createElement("div");i.id="error-view",i.innerText=e,t.replaceChildren(i)}}class e{static onLoad(t){t.innerHTML='<div id="loading-validate-key-property"></div>'}static createElements(){const t=document.createElement("div");return t.id="validate-property-key-view",t}static render(i,s,n){const o=e.createElements(),r={onSuccess:s,onFail:t.render.bind(this,i,"Your 'key' has failed authentication"),onLoad:e.onLoad.bind(this,o)};n.key&&n.verifyKey(n.key,r),i.replaceChildren(o)}}class i{static unsetStyle(t,e){const i=Object.keys(e).reduce(((t,e)=>(t[e]="",t)),{});Object.assign(t.style,i)}static unsetActivityCSSMouseStates(t,e){e.click&&i.unsetStyle(t,e.click),e.hover&&i.unsetStyle(t,e.hover)}static unsetAllCSSMouseStates(t,e){i.unsetActivityCSSMouseStates(t,e),e.default&&i.unsetStyle(t,e.default)}static processStateful(t,e,i){const s=t.default||{},n=Object.assign(JSON.parse(JSON.stringify({...s,...e})),null==t?void 0:t.hover);return{default:s,hover:n,click:Object.assign(JSON.parse(JSON.stringify({...n,...i})),null==t?void 0:t.click)}}static mergeStatefulStyles(t){const e={default:{},hover:{},click:{}};return t.forEach((t=>{e.default=Object.assign(e.default,t.default),e.hover=Object.assign(e.hover,t.hover),e.click=Object.assign(e.click,t.click)})),e}static overwriteDefaultWithAlreadyApplied(t,e){Object.keys(t.default||[]).forEach((i=>{var s;const n=i;e.style[n]&&null!=(s=t.default)&&s[n]&&(t.default[i]=e.style[n])}))}static applyToStyleIfNotDefined(t,e){for(const i in e){const s=e[i];""===t[i]&&s&&(t[i]=s)}}}const s=class t{static attemptAppendStyleSheetToHead(e){if(e.fontFamily&&e.fontFamily!==t.DEFAULT_FONT_FAMILY)return;const i=document.getElementsByTagName("head")[0];if(!Array.from(i.getElementsByTagName("link")).some((e=>e.getAttribute("href")===t.FONT_URL))){const e=document.createElement("link");e.rel="stylesheet",e.href=t.FONT_URL,i.appendChild(e)}}};s.FONT_URL="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap",s.DEFAULT_FONT_FAMILY="'Inter', sans-serif, Avenir, Helvetica, Arial";let n=s;const o=class t{static apply(e,i){if(i)try{t.applyStyleSheet(e,i)}catch{t.addStyleElement(e,i)}}static applyStyleSheet(t,e){const i=new CSSStyleSheet;i.replaceSync(t),e.adoptedStyleSheets.push(i)}static addStyleElement(t,e){const i=document.createElement("style");i.innerHTML=t,e.appendChild(i)}static applyDefaultStyleToComponent(e,s){s&&i.applyToStyleIfNotDefined(e,s),i.applyToStyleIfNotDefined(e,t.DEFAULT_COMPONENT_STYLE)}};o.DEFAULT_COMPONENT_STYLE={height:"350px",width:"320px",border:"1px solid #cacaca",fontFamily:n.DEFAULT_FONT_FAMILY,fontSize:"0.9rem",backgroundColor:"white",position:"relative",overflow:"hidden"};let r=o;var a;let l=((a=class{}).IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),a.IS_CHROMIUM=window.chrome,a);var c=(t=>(t.ESCAPE="Escape",t.ENTER="Enter",t.TAB="Tab",t.ARROW_UP="ArrowUp",t.ARROW_DOWN="ArrowDown",t.ARROW_RIGHT="ArrowRight",t.ARROW_LEFT="ArrowLeft",t.BACKSPACE="Backspace",t.DELETE="Delete",t.META="Meta",t.CONTROL="Control",t))(c||{});const h=class t{static add(e,i,s,n){void 0!==s&&e.addEventListener("keydown",t.onKeyDown.bind(this,s)),e.oninput=t.onInput.bind(this,s,n),e.addEventListener("paste",(t=>{var e;t.preventDefault(),null!=(e=t.clipboardData)&&e.files.length&&i.addFilesToAnyType(Array.from(t.clipboardData.files))}))}static onKeyDown(e,i){const s=i.target.textContent;s&&s.length>=e&&!t.PERMITTED_KEYS.has(i.key)&&!t.isKeyCombinationPermitted(i)&&i.preventDefault()}static isKeyCombinationPermitted(t){return"a"===t.key&&(t.ctrlKey||t.metaKey)}static onInput(t,e,i){const s=i.target,n=s.textContent||"";void 0!==t&&n.length>t&&(s.textContent=n.substring(0,t),v.focusEndOfInput(s)),null==e||e()}};h.PERMITTED_KEYS=new Set([c.BACKSPACE,c.DELETE,c.ARROW_RIGHT,c.ARROW_LEFT,c.ARROW_DOWN,c.ARROW_UP,c.META,c.CONTROL,c.ENTER]);let u=h;class d{static sanitizePastedTextContent(t){var e,i;t.preventDefault();const s=null==(e=t.clipboardData)?void 0:e.getData("text/plain");s&&(null==(i=document.execCommand)||i.call(document,"insertText",!1,s))}}const p=class t{constructor(e,i,s){var n,o;const r=t.processConfig(i,e.textInput);this.elementRef=t.createContainerElement(null==(n=null==r?void 0:r.styles)?void 0:n.container),this._config=r,this.inputElementRef=this.createInputElement(),this.elementRef.appendChild(this.inputElementRef),e.setPlaceholderText=this.setPlaceholderText.bind(this),e.setPlaceholderText((null==(o=this._config.placeholder)?void 0:o.text)||"Ask me anything!"),setTimeout((()=>{u.add(this.inputElementRef,s,this._config.characterLimit,e._validationHandler)}))}static processConfig(t,e){var i;return e??(e={}),e.disabled??(e.disabled=t.isTextInputDisabled),e.placeholder??(e.placeholder={}),(i=e.placeholder).text??(i.text=t.textInputPlaceholderText),e}static createContainerElement(t){const e=document.createElement("div");return e.id="text-input-container",Object.assign(e.style,t),e}static preventAutomaticScrollUpOnNewLine(t){let e;t.addEventListener("keydown",(()=>{e=window.scrollY})),t.addEventListener("input",(()=>{e!==window.scrollY&&window.scrollTo({top:e})}))}clear(){var t;const e=window.scrollY;this.inputElementRef.classList.contains("text-input-disabled")||(Object.assign(this.inputElementRef.style,null==(t=this._config.placeholder)?void 0:t.style),this.inputElementRef.textContent="",v.focusEndOfInput(this.inputElementRef)),l.IS_CHROMIUM&&window.scrollTo({top:e})}createInputElement(){var e,i,s,n;const o=document.createElement("div");return o.id=t.TEXT_INPUT_ID,o.classList.add("text-input-styling"),l.IS_CHROMIUM&&t.preventAutomaticScrollUpOnNewLine(o),"boolean"==typeof this._config.disabled&&!0===this._config.disabled?(o.contentEditable="false",o.classList.add("text-input-disabled")):(o.contentEditable="true",this.addEventListeners(o)),Object.assign(o.style,null==(e=this._config.styles)?void 0:e.text),Object.assign(o.style,null==(i=this._config.placeholder)?void 0:i.style),null!=(n=null==(s=this._config.placeholder)?void 0:s.style)&&n.color||o.setAttribute("textcolor",""),o}removePlaceholderStyle(){var t,e,s,n;!this.inputElementRef.classList.contains("text-input-disabled")&&null!=(t=this._config.placeholder)&&t.style&&(i.unsetStyle(this.inputElementRef,null==(e=this._config.placeholder)?void 0:e.style),Object.assign(this.inputElementRef.style,null==(n=null==(s=this._config)?void 0:s.styles)?void 0:n.text))}addEventListeners(t){var e,i;null!=(e=this._config.styles)&&e.focus&&(t.onfocus=()=>{var t;return Object.assign(this.elementRef.style,null==(t=this._config.styles)?void 0:t.focus)},t.onblur=this.onBlur.bind(this,this._config.styles.focus,null==(i=this._config.styles)?void 0:i.container)),t.addEventListener("keydown",this.onKeydown.bind(this)),t.addEventListener("input",this.onInput.bind(this)),t.addEventListener("paste",d.sanitizePastedTextContent)}onBlur(t,e){i.unsetStyle(this.elementRef,t),e&&Object.assign(this.elementRef.style,e)}onKeydown(t){var e;t.key===c.ENTER&&!t.ctrlKey&&!t.shiftKey&&(t.preventDefault(),null==(e=this.submit)||e.call(this))}onInput(){var t;this.isTextInputEmpty()?Object.assign(this.inputElementRef.style,null==(t=this._config.placeholder)?void 0:t.style):this.removePlaceholderStyle()}setPlaceholderText(t){this.inputElementRef.setAttribute("deep-chat-placeholder-text",t)}isTextInputEmpty(){return""===this.inputElementRef.textContent}};p.TEXT_INPUT_ID="text-input";let m=p;class v{static focusEndOfInput(t){const e=document.createRange();e.selectNodeContents(t),e.collapse(!1);const i=window.getSelection();null==i||i.removeAllRanges(),null==i||i.addRange(e)}static focusFromParentElement(t){const e=t.querySelector(`#${m.TEXT_INPUT_ID}`);e&&(l.IS_SAFARI&&e.focus(),v.focusEndOfInput(e))}}function f(t){return t.charAt(0).toUpperCase()+t.slice(1)}function g(t,e,i,s){const n=`\n${f(e)} message: ${JSON.stringify(t)} \n`,o=i?`${f(e)} message after interceptor: ${function(t){return t&&JSON.stringify(t)}(s)} \n`:"";return n+o}const b="Make sure the events are using {text: string} or {html: string} format.\nYou can also augment them using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor",y={INVALID_KEY:"Invalid API Key",CONNECTION_FAILED:"Failed to connect",INVALID_RESPONSE:function(t,e,i,s){return`${g(t,e,i,s)}Make sure the ${e} message is using the Response format: https://deepchat.dev/docs/connect/#Response \nYou can also augment it using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor`},INVALID_MODEL_REQUEST:function(t,e){const i="request";return`${g(t,i,e)}Make sure the ${i} message is using the {body: {text: string}} format, e.g: {body: {text: "Model Response"}}`},INVALID_MODEL_RESPONSE:function(t,e,i){const s="response";return`${g(t,s,e,i)}Make sure the ${s} message is using the {text: string} format, e.g: {text: "Model Response"}`},INVALID_STREAM_EVENT:b,INVALID_STREAM_EVENT_MIX:"Cannot mix {text: string} and {html: string} responses.",NO_VALID_STREAM_EVENTS_SENT:`No valid stream events were sent.\n${b}`},w=class t{static addElements(t,...e){e.forEach((e=>t.appendChild(e)))}static isScrollbarAtBottomOfElement(e){const i=e.scrollHeight,s=e.clientHeight;return e.scrollTop>=i-s-t.CODE_SNIPPET_GENERATION_JUMP}static cloneElement(t){const e=t.cloneNode(!0);return t.parentNode.replaceChild(e,t),e}static scrollToBottom(t){t.scrollTop=t.scrollHeight}static scrollToTop(t){t.scrollTop=0}};w.CODE_SNIPPET_GENERATION_JUMP=.5;let x=w;const k=class t{static speak(t,e){if(window.SpeechSynthesisUtterance){const i=new SpeechSynthesisUtterance(t);Object.assign(i,e),speechSynthesis.speak(i)}}static processConfig(e,i){const s={};setTimeout((()=>{if("object"==typeof e&&(e.lang&&(s.lang=e.lang),e.pitch&&(s.pitch=e.pitch),e.rate&&(s.rate=e.rate),e.volume&&(s.volume=e.volume),e.voiceName)){const t=window.speechSynthesis.getVoices().find((t=>{var i;return t.name.toLocaleLowerCase()===(null==(i=e.voiceName)?void 0:i.toLocaleLowerCase())}));t&&(s.voice=t)}i(s)}),t.LOAD_VOICES_MS)}};k.LOAD_VOICES_MS=200;let _=k;class S{static checkForContainerStyles(t,e){const i=t.containerStyle;i&&(Object.assign(e.style,i),console.error("The containerStyle property is deprecated since version 1.3.14."),console.error("Please change to using the style property instead: https://deepchat.dev/docs/styles#style"))}static handleResponseProperty(t){return console.error("The {result: ....} response object type is deprecated since version 1.3.0."),console.error("Please change to using the new response object: https://deepchat.dev/docs/connect#Response"),t.result}static processHistory(t){const e=t.initialMessages;if(e)return console.error("The initialMessages property is deprecated since version 2.0.0."),console.error("Please change to using the history property instead: https://deepchat.dev/docs/messages/#history"),e}static processHistoryFile(t){const e=t.file;e&&(console.error("The file property in MessageContent is deprecated since version 1.3.17."),console.error("Please change to using the files array property: https://deepchat.dev/docs/messages/#MessageContent"),t.files=[e])}static processValidateInput(t){const e=t.validateMessageBeforeSending;if(e)return console.error("The validateMessageBeforeSending property is deprecated since version 1.3.24."),console.error("Please change to using validateInput: https://deepchat.dev/docs/interceptors#validateInput"),e}static processSubmitUserMessage(t){return console.error("The submitUserMessage(text: string) argument string type is deprecated since version 1.4.4."),console.error("Please change to using the new argument type: https://deepchat.dev/docs/methods#submitUserMessage"),{text:t}}static flagHTMLUpdateClass(t){var e;null!=(e=t.children[0])&&e.classList.contains("deep-chat-update-message")&&(console.error('The "deep-chat-update-message" html class is deprecated since version 1.4.4.'),console.error("Please change to using {..., overwrite: true} object: https://deepchat.dev/docs/connect#Response"))}static processConnect(t){const e=t;e.request&&(e.connect?Object.assign(e.connect,e.request):e.connect=e.request,console.error("The request property is deprecated since version 2.0.0."),console.error("Please see the connect object: https://deepchat.dev/docs/connect#connect-1"))}static checkForStream(t){const e=t.stream;if(e)return console.error("The stream property has been moved to the connect object in version 2.0.0."),console.error("Please see the connect object: https://deepchat.dev/docs/connect#connect-1"),e}static fireOnNewMessage(t,e){var i;const s=t;s.onNewMessage&&(console.error("The onNewMessage event has been deprecated since version 2.0.0."),console.error("Please see the onMessage event: https://deepchat.dev/docs/events#onMessage"),null==(i=s.onNewMessage)||i.call(s,e)),t.dispatchEvent(new CustomEvent("new-message",{detail:e}))}static processFileConfigConnect(t){const e=t;e.request&&(console.error("The request property in file configuration is deprecated since version 2.0.0."),console.error("Please use the connect property instead: https://deepchat.dev/docs/files"),e.connect||(e.connect=e.request))}}const T=class t{static colorToHex(t){const e=document.createElement("div");return e.style.color=t,document.body.appendChild(e),`#${window.getComputedStyle(e).color.match(/\d+/g).map((t=>parseInt(t).toString(16).padStart(2,"0"))).join("")}`}static setDots(e,i){var s,n,o,r;if(null!=(r=null==(o=null==(n=null==(s=null==i?void 0:i.loading)?void 0:s.message)?void 0:n.styles)?void 0:o.bubble)&&r.color){const s=t.colorToHex(i.loading.message.styles.bubble.color);e.style.setProperty("--loading-message-color",s),e.style.setProperty("--loading-message-color-fade",`${s}33`)}else e.style.setProperty("--loading-message-color","#848484"),e.style.setProperty("--loading-message-color-fade","#55555533")}static setRing(e,i){const{color:s,width:n,height:o,margin:r,border:a}=i||{};if(s){const i=t.colorToHex(s);e.style.setProperty("--loading-history-color",i)}else e.style.setProperty("--loading-history-color","#dbdbdb");e.style.setProperty("--loading-history-height",o||"57px"),e.style.setProperty("--loading-history-width",n||"57px"),e.style.setProperty("--loading-history-margin",r||"7px"),e.style.setProperty("--loading-history-border",a||"6px")}};T.BUBBLE_CLASS="deep-chat-loading-message-bubble",T.DOTS_CONTAINER_CLASS="deep-chat-loading-message-dots-container";let A=T;const M=class t{static hide(e){var i;(i=e.getElementsByClassName(t.CONTAINER_CLASS)[0].style).visibility||(i.visibility="hidden")}static reveal(e){e.getElementsByClassName(t.CONTAINER_CLASS)[0].style.visibility=""}static applyCustomStylesToElements(t,e,i){Object.assign(t.style,i.container),Object.assign(e.style,i.avatar)}static applyCustomStyles(e,i,s,n){var o,r,a,l;if(null!=(o=s.default)&&o.styles&&t.applyCustomStylesToElements(e,i,s.default.styles),n===I.USER_ROLE)null!=(r=s.user)&&r.styles&&t.applyCustomStylesToElements(e,i,s.user.styles);else{null!=(a=s.ai)&&a.styles&&t.applyCustomStylesToElements(e,i,s.ai.styles);const o=null==(l=s[n])?void 0:l.styles;o&&t.applyCustomStylesToElements(e,i,o)}}static createAvatar(e,i){var s,n,o,r,a;const l=document.createElement("img");e===I.USER_ROLE?l.src=(null==(s=null==i?void 0:i.user)?void 0:s.src)||(null==(n=null==i?void 0:i.default)?void 0:n.src)||"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==":l.src=(null==(o=null==i?void 0:i[e])?void 0:o.src)||(null==(r=null==i?void 0:i.ai)?void 0:r.src)||(null==(a=null==i?void 0:i.default)?void 0:a.src)||"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",l.classList.add("avatar");const c=document.createElement("div");return c.classList.add(t.CONTAINER_CLASS),c.appendChild(l),i&&t.applyCustomStyles(c,l,i,e),c}static getPosition(t,e){var i,s,n,o,r,a;let l=null==(s=null==(i=null==e?void 0:e[t])?void 0:i.styles)?void 0:s.position;return t!==I.USER_ROLE&&(l??(l=null==(o=null==(n=null==e?void 0:e.ai)?void 0:n.styles)?void 0:o.position)),l??(l=null==(a=null==(r=null==e?void 0:e.default)?void 0:r.styles)?void 0:a.position),l??(l=t===I.USER_ROLE?"right":"left"),l}static add(e,i,s){const n="boolean"==typeof s?void 0:s,o=t.createAvatar(i,n),r=t.getPosition(i,n);o.classList.add("left"===r?"left-item-position":"right-item-position"),e.insertAdjacentElement("left"===r?"beforebegin":"afterend",o)}};M.CONTAINER_CLASS="avatar-container";let O=M;const j=class t{static hide(e){var i;(i=e.getElementsByClassName(t.NAME_CLASS)[0].style).visibility||(i.visibility="hidden")}static reveal(e){e.getElementsByClassName(t.NAME_CLASS)[0].style.visibility=""}static getPosition(t,e){var i,s,n;let o=null==(i=null==e?void 0:e[t])?void 0:i.position;return t!==I.USER_ROLE&&(o??(o=null==(s=null==e?void 0:e.ai)?void 0:s.position)),o??(o=null==(n=null==e?void 0:e.default)?void 0:n.position),o??(o=t===I.USER_ROLE?"right":"left"),o}static applyStyle(t,e,i){var s,n,o,r;Object.assign(t.style,null==(s=i.default)?void 0:s.style),e===I.USER_ROLE?Object.assign(t.style,null==(n=i.user)?void 0:n.style):(Object.assign(t.style,null==(o=i.ai)?void 0:o.style),Object.assign(t.style,null==(r=i[e])?void 0:r.style))}static getNameText(t,e){var i,s,n,o,r,a;return t===I.USER_ROLE?(null==(i=e.user)?void 0:i.text)||(null==(s=e.default)?void 0:s.text)||"User":t===I.AI_ROLE?(null==(n=e.ai)?void 0:n.text)||(null==(o=e.default)?void 0:o.text)||"AI":(null==(r=e[t])?void 0:r.text)||(null==(a=e.default)?void 0:a.text)||t}static createName(e,i){const s=document.createElement("div");return s.classList.add(t.NAME_CLASS),s.textContent=t.getNameText(e,i),t.applyStyle(s,e,i),s}static add(e,i,s){const n="boolean"==typeof s?{}:s,o=t.createName(i,n),r=t.getPosition(i,n);o.classList.add("left"===r?"left-item-position":"right-item-position"),e.insertAdjacentElement("left"===r?"beforebegin":"afterend",o)}};j.NAME_CLASS="name";let C=j;const E=class t{static getLastElementsByClass(t,e,i){for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n.bubbleElement.classList.contains(e[0])&&!e.slice(1).find((t=>!n.bubbleElement.classList.contains(t)))){if(!i)return n;if(!i.find((t=>n.bubbleElement.classList.contains(t))))return n}}}static getLastMessage(t,e,i){for(let s=t.length-1;s>=0;s-=1)if(t[s].role===e){if(!i)return t[s];if(t[s][i])return t[s]}}static getLastTextToElement(t,e){for(let i=t.length-1;i>=0;i-=1)if(t[i][0]===e)return t[i]}static overwriteMessage(e,i,s,n,o,r){const a=t.getLastElementsByClass(i,[t.getRoleClass(n),r],[A.BUBBLE_CLASS]),l=t.getLastMessage(e,n,o);return l&&(l[o]=s),a}static getRoleClass(t){return`${t}-message`}static fillEmptyMessageElement(e,i){0===i.trim().length&&(e.classList.add(t.EMPTY_MESSAGE_CLASS),e.innerHTML='<div style="color:#00000000">.</div>')}static unfillEmptyMessageElement(e,i){e.classList.contains(t.EMPTY_MESSAGE_CLASS)&&i.trim().length>0&&e.replaceChildren()}static getLastMessageBubbleElement(e){var i,s,n;return Array.from((null==(n=null==(s=null==(i=t.getLastMessageElement(e))?void 0:i.children)?void 0:s[0])?void 0:n.children)||[]).find((t=>t.classList.contains("message-bubble")))}static getLastMessageElement(t){return t.children[t.children.length-1]}static addRoleElements(t,e,i,s){i&&O.add(t,e,i),s&&C.add(t,e,s)}static hideRoleElements(t,e,i){const s=t[t.length-1].innerContainer;e&&O.hide(s),i&&C.hide(s)}static revealRoleElements(t,e,i){e&&O.reveal(t),i&&C.reveal(t)}static updateRefArr(t,e,i){i?t.unshift(e):t.push(e)}};E.AI_ROLE="ai",E.USER_ROLE="user",E.EMPTY_MESSAGE_CLASS="empty-message";let I=E;class P{static mouseUp(t,e){i.unsetAllCSSMouseStates(t,e),Object.assign(t.style,e.default),Object.assign(t.style,e.hover)}static mouseDown(t,e){Object.assign(t.style,e.click)}static mouseLeave(t,e){i.unsetAllCSSMouseStates(t,e),Object.assign(t.style,e.default)}static mouseEnter(t,e){Object.assign(t.style,e.hover)}static add(t,e){t.addEventListener("mouseenter",P.mouseEnter.bind(this,t,e)),t.addEventListener("mouseleave",P.mouseLeave.bind(this,t,e)),t.addEventListener("mousedown",P.mouseDown.bind(this,t,e)),t.addEventListener("mouseup",P.mouseUp.bind(this,t,e))}}const N={"deep-chat-button":{styles:{default:{backgroundColor:"white",padding:"5px",paddingLeft:"7px",paddingRight:"7px",border:"1px solid #c2c2c2",borderRadius:"6px",cursor:"pointer"},hover:{backgroundColor:"#fafafa"},click:{backgroundColor:"#f1f1f1"}}}},q=Object.keys(N);class R{static applySuggestionEvent(t,e){setTimeout((()=>{e.addEventListener("click",(()=>{var i,s;null==(s=t.submitUserMessage)||s.call(t,{text:(null==(i=e.textContent)?void 0:i.trim())||""})}))}))}static isElementTemporary(t){var e;return!!t&&(null==(e=t.bubbleElement.children[0])?void 0:e.classList.contains("deep-chat-temporary-message"))}static doesElementContainDeepChatClass(t){return q.find((e=>t.classList.contains(e)))}static applyEvents(t,e){const i=N[e].events;Object.keys(i||[]).forEach((e=>{t.addEventListener(e,null==i?void 0:i[e])}))}static getProcessedStyles(t,e,s){const n=Array.from(e.classList).reduce(((e,i)=>{var s;const n=null==(s=t[i])?void 0:s.styles;return n&&t[i].styles&&e.push(n),e}),[]),o=N[s].styles;if(o){const t=JSON.parse(JSON.stringify(o));t.default&&i.overwriteDefaultWithAlreadyApplied(t,e),n.unshift(t)}const r=i.mergeStatefulStyles(n);return i.processStateful(r,{},{})}static applyDeepChatUtilities(t,e,i){q.forEach((t=>{const s=i.getElementsByClassName(t);Array.from(s||[]).forEach((i=>{const s=R.getProcessedStyles(e,i,t);L.applyStylesToElement(i,s),R.applyEvents(i,t)}))}));const s=i.getElementsByClassName("deep-chat-suggestion-button");Array.from(s).forEach((e=>R.applySuggestionEvent(t,e)))}}class L{static applyStylesToElement(t,e){const s=i.processStateful(e,{},{});P.add(t,s),Object.assign(t.style,s.default)}static applyEventsToElement(t,e){Object.keys(e).forEach((i=>{const s=e[i];s&&t.addEventListener(i,s)}))}static applyClassUtilitiesToElement(t,e){const{events:i,styles:s}=e;i&&L.applyEventsToElement(t,i),s&&!R.doesElementContainDeepChatClass(t)&&L.applyStylesToElement(t,s)}static applyCustomClassUtilities(t,e){Object.keys(t).forEach((i=>{const s=e.getElementsByClassName(i);Array.from(s).forEach((e=>{t[i]&&L.applyClassUtilitiesToElement(e,t[i])}))}))}static apply(t,e){R.applyDeepChatUtilities(t,t.htmlClassUtilities,e),L.applyCustomClassUtilities(t.htmlClassUtilities,e)}static traverseNodes(t,e){t.nodeType===Node.ELEMENT_NODE&&e.push(t.outerHTML),t.childNodes.forEach((t=>{L.traverseNodes(t,e)}))}static splitHTML(t){const e=(new DOMParser).parseFromString(t,"text/html"),i=[];return e.body.childNodes.forEach((t=>{L.traverseNodes(t,i)})),i}}class B{static addElement(t,e){t.elementRef.appendChild(e),t.elementRef.scrollTop=t.elementRef.scrollHeight}static createElements(t,e,i,s){const n=t.createMessageElementsOnOrientation("",i,s);return n.bubbleElement.classList.add("html-message"),n.bubbleElement.innerHTML=e,n}static overwrite(t,e,i,s){const{messages:n}=t,o=I.overwriteMessage(n,s,e,i,"html","html-message");return o&&(o.bubbleElement.innerHTML=e,L.apply(t,o.outerContainer),S.flagHTMLUpdateClass(o.bubbleElement)),o}static add(t,e,i,s,n,o=!1){var r;if(null!=n&&n.status){const o=this.overwrite(t,e,i,s);if(o)return o;n.status=!1}const a=B.createElements(t,e,i,o);return I.fillEmptyMessageElement(a.bubbleElement,e),L.apply(t,a.outerContainer),S.flagHTMLUpdateClass(a.bubbleElement),t.applyCustomStyles(a,i,!1,null==(r=t.messageStyles)?void 0:r.html),o||B.addElement(t,a.outerContainer),a}}var F;function z(t){return(F=F||document.createElement("textarea")).innerHTML="&"+t+";",F.value}var D=Object.prototype.hasOwnProperty;function $(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 J=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function U(t){return t.indexOf("\\")<0?t:t.replace(J,"$1")}function V(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 H(t){if(t>65535){var e=55296+((t-=65536)>>10),i=56320+(1023&t);return String.fromCharCode(e,i)}return String.fromCharCode(t)}var K=/&([a-z#][a-z0-9]{1,31});/gi,G=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;function Z(t,e){var i=0,s=z(e);return e!==s?s:35===e.charCodeAt(0)&&G.test(e)&&V(i="x"===e[1].toLowerCase()?parseInt(e.slice(2),16):parseInt(e.slice(1),10))?H(i):t}function W(t){return t.indexOf("&")<0?t:t.replace(K,Z)}var X=/[&<>"]/,Q=/[&<>"]/g,Y={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function tt(t){return Y[t]}function et(t){return X.test(t)?t.replace(Q,tt):t}var it={};function st(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?st(t,e+2):e}it.blockquote_open=function(){return"<blockquote>\n"},it.blockquote_close=function(t,e){return"</blockquote>"+nt(t,e)},it.code=function(t,e){return t[e].block?"<pre><code>"+et(t[e].content)+"</code></pre>"+nt(t,e):"<code>"+et(t[e].content)+"</code>"},it.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&&D.call(t,e)}(n.rules.fence_custom,o[0]))return n.rules.fence_custom[o[0]](t,e,i,s,n);l=' class="'+c+et(W(U(r)))+'"'}return"<pre><code"+l+">"+(i.highlight&&i.highlight.apply(i.highlight,[a.content].concat(o))||et(a.content))+"</code></pre>"+nt(t,e)},it.fence_custom={},it.heading_open=function(t,e){return"<h"+t[e].hLevel+">"},it.heading_close=function(t,e){return"</h"+t[e].hLevel+">\n"},it.hr=function(t,e,i){return(i.xhtmlOut?"<hr />":"<hr>")+nt(t,e)},it.bullet_list_open=function(){return"<ul>\n"},it.bullet_list_close=function(t,e){return"</ul>"+nt(t,e)},it.list_item_open=function(){return"<li>"},it.list_item_close=function(){return"</li>\n"},it.ordered_list_open=function(t,e){var i=t[e];return"<ol"+(i.order>1?' start="'+i.order+'"':"")+">\n"},it.ordered_list_close=function(t,e){return"</ol>"+nt(t,e)},it.paragraph_open=function(t,e){return t[e].tight?"":"<p>"},it.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?nt(t,e):"")},it.link_open=function(t,e,i){var s=t[e].title?' title="'+et(W(t[e].title))+'"':"",n=i.linkTarget?' target="'+i.linkTarget+'"':"";return'<a href="'+et(t[e].href)+'"'+s+n+">"},it.link_close=function(){return"</a>"},it.image=function(t,e,i){var s=' src="'+et(t[e].src)+'"',n=t[e].title?' title="'+et(W(t[e].title))+'"':"";return"<img"+s+(' alt="'+(t[e].alt?et(W(U(t[e].alt))):"")+'"')+n+(i.xhtmlOut?" /":"")+">"},it.table_open=function(){return"<table>\n"},it.table_close=function(){return"</table>\n"},it.thead_open=function(){return"<thead>\n"},it.thead_close=function(){return"</thead>\n"},it.tbody_open=function(){return"<tbody>\n"},it.tbody_close=function(){return"</tbody>\n"},it.tr_open=function(){return"<tr>"},it.tr_close=function(){return"</tr>\n"},it.th_open=function(t,e){var i=t[e];return"<th"+(i.align?' style="text-align:'+i.align+'"':"")+">"},it.th_close=function(){return"</th>"},it.td_open=function(t,e){var i=t[e];return"<td"+(i.align?' style="text-align:'+i.align+'"':"")+">"},it.td_close=function(){return"</td>"},it.strong_open=function(){return"<strong>"},it.strong_close=function(){return"</strong>"},it.em_open=function(){return"<em>"},it.em_close=function(){return"</em>"},it.del_open=function(){return"<del>"},it.del_close=function(){return"</del>"},it.ins_open=function(){return"<ins>"},it.ins_close=function(){return"</ins>"},it.mark_open=function(){return"<mark>"},it.mark_close=function(){return"</mark>"},it.sub=function(t,e){return"<sub>"+et(t[e].content)+"</sub>"},it.sup=function(t,e){return"<sup>"+et(t[e].content)+"</sup>"},it.hardbreak=function(t,e,i){return i.xhtmlOut?"<br />\n":"<br>\n"},it.softbreak=function(t,e,i){return i.breaks?i.xhtmlOut?"<br />\n":"<br>\n":"\n"},it.text=function(t,e){return et(t[e].content)},it.htmlblock=function(t,e){return t[e].content},it.htmltag=function(t,e){return t[e].content},it.abbr_open=function(t,e){return'<abbr title="'+et(W(t[e].title))+'">'},it.abbr_close=function(){return"</abbr>"},it.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>"},it.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'},it.footnote_block_close=function(){return"</ol>\n</section>\n"},it.footnote_open=function(t,e){return'<li id="fn'+Number(t[e].id+1).toString()+'" class="footnote-item">'},it.footnote_close=function(){return"</li>\n"},it.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>'},it.dl_open=function(){return"<dl>\n"},it.dt_open=function(){return"<dt>"},it.dd_open=function(){return"<dd>"},it.dl_close=function(){return"</dl>\n"},it.dt_close=function(){return"</dt>\n"},it.dd_close=function(){return"</dd>\n"};var nt=it.getBreak=function(t,e){return(e=st(t,e))<t.length&&"list_item_close"===t[e].type?"":"\n"};function ot(){this.rules=$({},it),this.getBreak=it.getBreak}function rt(){this.t=[],this.i=null}function at(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 lt(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 ct(t,e,i,s){var n,o,r,a,l,c;if(42!==t.charCodeAt(0)||91!==t.charCodeAt(1)||-1===t.indexOf("]:")||((o=lt(n=new at(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 ht(t){var e=W(t);try{e=decodeURI(e)}catch{}return encodeURI(e)}function ut(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=ht(U(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=U(t.src.slice(o,e)),!t.parser.validateLink(n)))&&(t.linkContent=n,t.pos=e,!0)}function dt(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=U(t.src.slice(s+1,e)),!0;92===i&&e+1<n?e+=2:e++}return!1}function pt(t){return t.trim().replace(/\s+/g," ").toUpperCase()}function mt(t,e,i,s){var n,o,r,a,l,c,h,u,d;if(91!==t.charCodeAt(0)||-1===t.indexOf("]:")||((o=lt(n=new at(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(!ut(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&&dt(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=pt(t.slice(1,o)),typeof s.references[d]>"u"&&(s.references[d]={title:u,href:h}),r)}ot.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},ot.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},rt.prototype.o=function(t){for(var e=this.t.length,i=-1;e--;)if(this.t[++i].name===t)return i;return-1},rt.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))}))}))},rt.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},rt.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},rt.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},rt.prototype.push=function(t,e,i){var s=i||{};this.t.push({name:t,enabled:!0,fn:e,alt:s.alt||[]}),this.i=null},rt.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},rt.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},rt.prototype.getRules=function(t){return null===this.i&&this.l(),this.i[t]||[]},at.prototype.pushPending=function(){this.tokens.push({type:"text",content:this.pending,level:this.pendingLevel}),this.pending=""},at.prototype.push=function(t){this.pending&&this.pushPending(),this.tokens.push(t),this.pendingLevel=this.level},at.prototype.cacheSet=function(t,e){for(var i=this.cache.length;i<=t;i++)this.cache.push(0);this.cache[t]=e},at.prototype.cacheGet=function(t){return t<this.cache.length?this.cache[t]:0};var vt=" \n()[]'\".,!?-";function ft(t){return t.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1")}var gt=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,bt=/\((c|tm|r|p)\)/gi,yt={c:"©",r:"®",p:"§",tm:"™"};function wt(t){return t.indexOf("(")<0?t:t.replace(bt,(function(t,e){return yt[e.toLowerCase()]}))}var xt=/['"]/,kt=/['"]/g,_t=/[-\s()\[\]]/;function St(t,e){return!(e<0||e>=t.length)&&!_t.test(t[e])}function Tt(t,e,i){return t.substr(0,e)+i+t.substr(e+1)}var At=[["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=ct(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=mt(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="(^|["+vt.split("").map(ft).join("")+"])("+Object.keys(t.env.abbreviations).map((function(t){return t.substr(1)})).sort((function(t,e){return e.length-t.length})).map(ft).join("|")+")($|["+vt.split("").map(ft).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=wt(s=i.content),gt.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&&!xt.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&&(kt.lastIndex=o,n=kt.exec(s),n);)if(l=!St(s,n.index-1),o=n.index+1,m="'"===n[0],(c=!St(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=Tt(f[h.token].content,h.pos,t.options.quotes[2]),i.content=Tt(i.content,n.index,t.options.quotes[3])):(f[h.token].content=Tt(f[h.token].content,h.pos,t.options.quotes[0]),i.content=Tt(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=Tt(i.content,n.index,"’"))}else m&&(i.content=Tt(i.content,n.index,"’"))}}]];function Mt(){this.options={},this.ruler=new rt;for(var t=0;t<At.length;t++)this.ruler.push(At[t][0],At[t][1])}function Ot(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 jt(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 Ct(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}Mt.prototype.process=function(t){var e,i,s;for(e=0,i=(s=this.ruler.getRules("")).length;e<i;e++)s[e](t)},Ot.prototype.isEmpty=function(t){return this.bMarks[t]+this.tShift[t]>=this.eMarks[t]},Ot.prototype.skipEmptyLines=function(t){for(var e=this.lineMax;t<e&&!(this.bMarks[t]+this.tShift[t]<this.eMarks[t]);t++);return t},Ot.prototype.skipSpaces=function(t){for(var e=this.src.length;t<e&&32===this.src.charCodeAt(t);t++);return t},Ot.prototype.skipChars=function(t,e){for(var i=this.src.length;t<i&&this.src.charCodeAt(t)===e;t++);return t},Ot.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},Ot.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 Et={};["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){Et[t]=!0}));var It=/^<([a-zA-Z]{1,15})[\s\/>]/,Pt=/^<\/([a-zA-Z]{1,15})[\s>]/;function Nt(t,e){var i=t.bMarks[e]+t.blkIndent,s=t.eMarks[e];return t.src.substr(i,s-i)}function qt(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 Rt=[["code",function(t,e,i){var s,n;if(t.tShift[e]-t.blkIndent<4)return!1;for(n=s=e+1;s<i;)if(t.isEmpty(s))s++;else{if(!(t.tShift[s]-t.blkIndent>=4))break;n=++s}return t.line=s,t.tokens.push({type:"code",content:t.getLines(e,n,4+t.blkIndent,!0),block:!0,lines:[e,t.line],level:t.level}),!0}],["fences",function(t,e,i,s){var n,o,r,a,l,c=!1,h=t.bMarks[e]+t.tShift[e],u=t.eMarks[e];if(h+3>u||126!==(n=t.src.charCodeAt(h))&&96!==n||(l=h,(o=(h=t.skipChars(h,n))-l)<3)||(r=t.src.slice(h,u).trim()).indexOf("`")>=0)return!1;if(s)return!0;for(a=e;!(++a>=i||(h=l=t.bMarks[a]+t.tShift[a],u=t.eMarks[a],h<u&&t.tShift[a]<t.blkIndent));)if(!(t.src.charCodeAt(h)!==n||t.tShift[a]-t.blkIndent>=4||(h=t.skipChars(h,n),h-l<o||(h=t.skipSpaces(h),h<u)))){c=!0;break}return o=t.tShift[e],t.line=a+(c?1:0),t.tokens.push({type:"fence",params:r,content:t.getLines(e+1,a,o,!0),lines:[e,t.line],level:t.level}),!0},["paragraph","blockquote","list"]],["blockquote",function(t,e,i,s){var n,o,r,a,l,c,h,u,d,p,m,v=t.bMarks[e]+t.tShift[e],f=t.eMarks[e];if(v>f||62!==t.src.charCodeAt(v++)||t.level>=t.options.maxNesting)return!1;if(s)return!0;for(32===t.src.charCodeAt(v)&&v++,l=t.blkIndent,t.blkIndent=0,a=[t.bMarks[e]],t.bMarks[e]=v,o=(v=v<f?t.skipSpaces(v):v)>=f,r=[t.tShift[e]],t.tShift[e]=v-t.bMarks[e],u=t.parser.ruler.getRules("blockquote"),n=e+1;n<i&&!((v=t.bMarks[n]+t.tShift[n])>=(f=t.eMarks[n]));n++)if(62!==t.src.charCodeAt(v++)){if(o)break;for(m=!1,d=0,p=u.length;d<p;d++)if(u[d](t,n,i,!0)){m=!0;break}if(m)break;a.push(t.bMarks[n]),r.push(t.tShift[n]),t.tShift[n]=-1337}else 32===t.src.charCodeAt(v)&&v++,a.push(t.bMarks[n]),t.bMarks[n]=v,o=(v=v<f?t.skipSpaces(v):v)>=f,r.push(t.tShift[n]),t.tShift[n]=v-t.bMarks[n];for(c=t.parentType,t.parentType="blockquote",t.tokens.push({type:"blockquote_open",lines:h=[e,0],level:t.level++}),t.parser.tokenize(t,e,n),t.tokens.push({type:"blockquote_close",level:--t.level}),t.parentType=c,h[1]=t.line,d=0;d<r.length;d++)t.bMarks[d+e]=a[d],t.tShift[d+e]=r[d];return t.blkIndent=l,!0},["paragraph","blockquote","list"]],["hr",function(t,e,i,s){var n,o,r,a=t.bMarks[e],l=t.eMarks[e];if((a+=t.tShift[e])>l||42!==(n=t.src.charCodeAt(a++))&&45!==n&&95!==n)return!1;for(o=1;a<l;){if((r=t.src.charCodeAt(a++))!==n&&32!==r)return!1;r===n&&o++}return!(o<3)&&(s||(t.line=e+1,t.tokens.push({type:"hr",lines:[e,t.line],level:t.level})),!0)},["paragraph","blockquote","list"]],["list",function(t,e,i,s){var n,o,r,a,l,c,h,u,d,p,m,v,f,g,b,y,w,x,k,_,S,T=!0;if((u=Ct(t,e))>=0)v=!0;else{if(!((u=jt(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)&&(T=!1),b=t.line-e>1&&t.isEmpty(t.line-1),t.blkIndent=a,t.tShift[e]=r,t.tight=l,t.parentType=c,t.tokens.push({type:"list_item_close",level:--t.level}),n=e=t.line,w[1]=n,f=t.bMarks[e],!(n>=i||t.isEmpty(n)||t.tShift[n]<t.blkIndent));){for(S=!1,k=0,_=x.length;k<_;k++)if(x[k](t,n,i,!0)){S=!0;break}if(S)break;if(v){if((u=Ct(t,n))<0)break}else if((u=jt(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,T&&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(Pt)))return!1}else if(!(o=t.src.slice(a,l).match(It)))return!1;if(!0!==Et[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=Nt(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=Nt(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=Nt(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)&&qt(t,e)>=0;if(h=e+1,t.isEmpty(h)&&++h>i||t.tShift[h]<t.blkIndent||(n=qt(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=qt(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=qt(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 Lt(){this.ruler=new rt;for(var t=0;t<Rt.length;t++)this.ruler.push(Rt[t][0],Rt[t][1],{alt:(Rt[t][2]||[]).slice()})}Lt.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 Bt=/[\n\t]/g,Ft=/\r[\n\u0085]|[\u2424\u2028\u0085]/g,zt=/\u00a0/g;function Dt(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}}Lt.prototype.parse=function(t,e,i,s){var n,o=0,r=0;if(!t)return[];(t=(t=t.replace(zt," ")).replace(Ft,"\n")).indexOf("\t")>=0&&(t=t.replace(Bt,(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 Ot(t,this,e,i,s),this.tokenize(n,n.line,n.lineMax)};for(var $t=[],Jt=0;Jt<256;Jt++)$t.push(0);function Ut(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}function Vt(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&&(Ut(i)&&(r=!1),Ut(s)&&(a=!1))),{can_open:r,can_close:a,delims:n}}"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach((function(t){$t[t.charCodeAt(0)]=1}));var Ht=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Kt=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Gt=["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"],Zt=/^<([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])?)*)>/,Wt=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;function Xt(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 Qt=Xt(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",/[^"'=<>`\x00-\x20]+/)("single_quoted",/'[^']*'/)("double_quoted",/"[^"]*"/)(),Yt=Xt(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",/[a-zA-Z_:][a-zA-Z0-9:._-]*/)("attr_value",Qt)(),te=Xt(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",Yt)(),ee=Xt(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",te)("close_tag",/<\/[A-Za-z][A-Za-z0-9]*\s*>/)("comment",/<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->/)("processing",/<[?].*?[?]>/)("declaration",/<![A-Z]+\s+[^>]*>/)("cdata",/<!\[CDATA\[[\s\S]*?\]\]>/)();var ie=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,se=/^&([a-z][a-z0-9]{1,31});/i;var ne=[["text",function(t,e){for(var i=t.pos;i<t.posMax&&!Dt(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!==$t[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=Vt(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=Vt(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(Ht,"$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(Kt,"$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=lt(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,ut(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&&dt(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=lt(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[pt(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=lt(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(Wt))?!(Gt.indexOf(s[1].toLowerCase())<0||(o=s[0].slice(1,-1),r=ht(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(Zt))&&(r=ht("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(ee),!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(ie))return e||(i="x"===s[1][0].toLowerCase()?parseInt(s[1].slice(1),16):parseInt(s[1],10),t.pending+=V(i)?H(i):H(65533)),t.pos+=s[0].length,!0}else if(s=t.src.slice(n).match(se)){var r=z(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 oe(){this.ruler=new rt;for(var t=0;t<ne.length;t++)this.ruler.push(ne[t][0],ne[t][1]);this.validateLink=re}function re(t){var e=t.trim().toLowerCase();return!(-1!==(e=W(e)).indexOf(":")&&-1!==["vbscript","javascript","file","data"].indexOf(e.split(":")[0]))}oe.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)}},oe.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()},oe.prototype.parse=function(t,e,i,s){var n=new at(t,this,e,i,s);this.tokenize(n)};var ae={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 le(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 ce(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 oe,this.block=new Lt,this.core=new Mt,this.renderer=new ot,this.ruler=new rt,this.options={},this.configure(ae[t]),this.set(e||{})}ce.prototype.set=function(t){$(this.options,t)},ce.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)}))},ce.prototype.use=function(t,e){return t(this,e),this},ce.prototype.parse=function(t,e){var i=new le(this,t,e);return this.core.process(i),i.tokens},ce.prototype.render=function(t,e){return e=e||{},this.renderer.render(this.parse(t,e),this.options,e)},ce.prototype.parseInline=function(t,e){var i=new le(this,t,e);return i.inlineMode=!0,this.core.process(i),i.tokens},ce.prototype.renderInline=function(t,e){return e=e||{},this.renderer.render(this.parseInline(t,e),this.options,e)};class he{static instantiate(){const t=window.hljs;return new ce(t?{highlight:function(e,i){if(i&&t.getLanguage(i))try{return t.highlight(i,e).value}catch{console.error("failed to setup the highlight dependency")}try{return t.highlightAuto(e).value}catch{console.error("failed to automatically highlight messages")}return""},html:!1,xhtmlOut:!1,breaks:!0,langPrefix:"language-",linkTarget:"_blank",typographer:!0}:{breaks:!0,linkTarget:"_blank"})}static createNew(){const t=he.instantiate();return t.inline.validateLink=()=>!0,t}}const ue=class t{static addMessage(t,e,i,s,n){var o;"loading"!==i&&(t.applyCustomStyles(e,s,!0,null==(o=t.messageStyles)?void 0:o[i]),n||(t.elementRef.appendChild(e.outerContainer),t.elementRef.scrollTop=t.elementRef.scrollHeight))}static wrapInLink(e,i,s){const n=document.createElement("a");return n.href=i,n.download=s||t.DEFAULT_FILE_NAME,n.target="_blank",n.appendChild(e),n}static isNonLinkableDataUrl(t,e){return!(!e.startsWith("data")||"image"===t)&&("any"===t&&e.startsWith("data:text/javascript")||!e.startsWith("data:image")&&!e.startsWith("data:application"))}static processContent(e,i,s,n){return!s||t.isNonLinkableDataUrl(e,s)?i:t.wrapInLink(i,s,n)}static waitToLoadThenScroll(t){setTimeout((()=>{t.scrollTop=t.scrollHeight}),60)}static scrollDownOnImageLoad(e,i){if(e.startsWith("data"))t.waitToLoadThenScroll(i);else try{fetch(e,{mode:"no-cors"}).catch((()=>{})).finally((()=>{t.waitToLoadThenScroll(i)}))}catch{i.scrollTop=i.scrollHeight}}static reAddFileRefToObject(t,e){var i;null==(i=t.files)||i.forEach(((t,i)=>{var s;t.ref&&null!=(s=e.message.files)&&s[i]&&(e.message.files[i].ref=t.ref)}))}static removeFileRef(t){const e={...t};return delete e.ref,e}static isAudioFile(t){const{type:e,src:i}=t;return"audio"===e||(null==i?void 0:i.startsWith("data:audio"))||i&&/\.(mp3|ogg|wav|aac|webm|4a)$/i.test(i)}static isImageFile(e){const{type:i,src:s}=e;return"image"===i||(null==s?void 0:s.startsWith("data:image"))||s&&t.isImageFileExtension(s)}static isImageFileExtension(t){return/\.(jpg|jpeg|png|gif|bmp)$/i.test(t)}};ue.DEFAULT_FILE_NAME="file";let de=ue;class pe{static onMessage(t,e,i){var s;const n=JSON.parse(JSON.stringify({message:e,isHistory:i,isInitial:i}));de.reAddFileRefToObject(e,n),null==(s=t.onMessage)||s.call(t,n),t.dispatchEvent(new CustomEvent("message",{detail:n})),S.fireOnNewMessage(t,n)}static onClearMessages(t){var e;null==(e=t.onClearMessages)||e.call(t),t.dispatchEvent(new CustomEvent("clear-messages"))}static onRender(t){var e;null==(e=t.onComponentRender)||e.call(t,t),t.dispatchEvent(new CustomEvent("render",{detail:t}))}static onError(t,e){var i;null==(i=t.onError)||i.call(t,e),t.dispatchEvent(new CustomEvent("error",{detail:e}))}}const me=class t{static generateLoadingRingElement(){const t=document.createElement("div");return t.classList.add("loading-history"),t.appendChild(document.createElement("div")),t.appendChild(document.createElement("div")),t.appendChild(document.createElement("div")),t.appendChild(document.createElement("div")),t}static apply(t,e,i){A.setRing(e.bubbleElement,null==i?void 0:i.bubble),null!=i&&i.bubble&&delete(i=JSON.parse(JSON.stringify(i))).bubble,t.applyCustomStyles(e,"history",!1,i)}static addLoadHistoryMessage(e,i,s=!0){var n,o,r,a,l,c,h,u;e.bubbleElement.classList.add(t.CLASS);const d=s?t.FULL_VIEW_CLASS:t.SMALL_CLASS;e.outerContainer.classList.add(d);const p=s?null==(a=null==(r=null==(o=null==(n=i.messageStyles)?void 0:n.loading)?void 0:o.history)?void 0:r.full)?void 0:a.styles:null==(u=null==(h=null==(c=null==(l=i.messageStyles)?void 0:l.loading)?void 0:c.history)?void 0:h.small)?void 0:u.styles;t.apply(i,e,p),i.elementRef.prepend(e.outerContainer)}static createDefaultElements(e){const i=e.createMessageElements("",I.AI_ROLE),{bubbleElement:s}=i,n=t.generateLoadingRingElement();return s.appendChild(n),i}static addMessage(e,i=!0){var s,n,o,r;const a=null==(r=null==(o=null==(n=null==(s=e.messageStyles)?void 0:s.loading)?void 0:n.history)?void 0:o.full)?void 0:r.html,l=a?B.createElements(e,a,I.AI_ROLE,!0):t.createDefaultElements(e);return t.addLoadHistoryMessage(l,e,i),l}static changeFullViewToSmall(e,i){var s,n,o,r,a,l,c,h;if(null!=i&&i.outerContainer.classList.contains(t.FULL_VIEW_CLASS)){i.outerContainer.classList.replace(t.FULL_VIEW_CLASS,t.SMALL_CLASS);const u=null==(r=null==(o=null==(n=null==(s=e.messageStyles)?void 0:s.loading)?void 0:n.history)?void 0:o.small)?void 0:r.styles;u&&t.apply(e,i,u);const d=null==(h=null==(c=null==(l=null==(a=e.messageStyles)?void 0:a.loading)?void 0:l.history)?void 0:c.small)?void 0:h.html;d&&(i.bubbleElement.innerHTML=d)}}};me.CLASS="loading-history-message",me.FULL_VIEW_CLASS="loading-history-message-full-view",me.SMALL_CLASS="loading-history-message-small";let ve=me;class fe{static applyCustomStylesToElements(t,e,i){if(i&&(Object.assign(t.outerContainer.style,i.outerContainer),Object.assign(t.innerContainer.style,i.innerContainer),Object.assign(t.bubbleElement.style,i.bubble),e)){const e=t.bubbleElement.children[0],s="a"!==e.tagName.toLocaleLowerCase()?e:e.children[0];Object.assign(s.style,i.media)}}static applySideStyles(t,e,i,s){s&&(fe.applyCustomStylesToElements(t,i,s.shared),e===I.USER_ROLE?fe.applyCustomStylesToElements(t,i,s.user):(fe.applyCustomStylesToElements(t,i,s.ai),fe.applyCustomStylesToElements(t,i,s[e])))}static isElementsStyles(t){return!!(t.outerContainer||t.innerContainer||t.bubble||t.media)}static applyCustomStyles(t,e,i,s,n){var o;n&&t.default!==n?fe.isElementsStyles(n)?(fe.applyCustomStylesToElements(e,s,null==(o=t.default)?void 0:o.shared),fe.applyCustomStylesToElements(e,s,n)):(fe.applySideStyles(e,i,s,t.default),fe.applySideStyles(e,i,s,n)):fe.applySideStyles(e,i,s,t.default)}static extractParticularSharedStyles(t,e){if(null==e||!e.shared)return;const i=e.shared,s={outerContainer:{},innerContainer:{},bubble:{},media:{}};return t.forEach((t=>{var e,n,o,r;s.outerContainer[t]=(null==(e=i.outerContainer)?void 0:e[t])||"",s.innerContainer[t]=(null==(n=i.innerContainer)?void 0:n[t])||"",s.bubble[t]=(null==(o=i.bubble)?void 0:o[t])||"",s.media[t]=(null==(r=i.media)?void 0:r[t])||""})),s}}class ge{constructor(t){this.messageElementRefs=[],this.messages=[],this.htmlClassUtilities={},this.textElementsToText=[],this.elementRef=ge.createContainerElement(),this.messageStyles=t.messageStyles,this._remarkable=he.createNew(),this._avatars=t.avatars,this._names=t.names,this._onMessage=pe.onMessage.bind(this,t),t.htmlClassUtilities&&(this.htmlClassUtilities=t.htmlClassUtilities),setTimeout((()=>{this.submitUserMessage=t.submitUserMessage}))}static createContainerElement(){const t=document.createElement("div");return t.id="messages",t}addNewTextMessage(t,e,i,s=!1){if(null!=i&&i.status){const s=this.overwriteText(e,t,this.messageElementRefs);if(s)return s;i.status=!1}const n=s?this.createAndPrependNewMessageElement(t,e,s):this.createAndAppendNewMessageElement(t,e);n.bubbleElement.classList.add("text-message"),this.applyCustomStyles(n,e,!1),I.fillEmptyMessageElement(n.bubbleElement,t);const o=[n,t];return I.updateRefArr(this.textElementsToText,o,s),n}overwriteText(t,e,i){const s=I.overwriteMessage(this.messages,i,e,t,"text","text-message");if(s){this.renderText(s.bubbleElement,e);const t=I.getLastTextToElement(this.textElementsToText,s);t&&(t[1]=e)}return s}createAndAppendNewMessageElement(t,e){const i=this.createNewMessageElement(t,e);return this.elementRef.appendChild(i.outerContainer),setTimeout((()=>x.scrollToBottom(this.elementRef))),i}createAndPrependNewMessageElement(t,e,i){var s;const n=this.createNewMessageElement(t,e,i);if(i&&null!=(s=this.elementRef.firstChild)&&s.classList.contains("deep-chat-intro")){this.elementRef.firstChild.insertAdjacentElement("afterend",n.outerContainer);const t=this.messageElementRefs[0];this.messageElementRefs[0]=this.messageElementRefs[1],this.messageElementRefs[1]=t}else this.elementRef.insertBefore(n.outerContainer,this.elementRef.firstChild);return n}createMessageElementsOnOrientation(t,e,i){return i?this.createAndPrependNewMessageElement(t,e,!0):this.createNewMessageElement(t,e)}createNewMessageElement(t,e,i=!1){var s;null==(s=this._introPanel)||s.hide();const n=this.messageElementRefs[this.messageElementRefs.length-1];return ve.changeFullViewToSmall(this,n),ge.isTemporaryElement(n)&&(this.revealRoleElementsIfTempRemoved(n,e),n.outerContainer.remove(),this.messageElementRefs.pop()),this.createMessageElements(t,e,i)}revealRoleElementsIfTempRemoved(t,e){if((this._avatars||this._names)&&R.isElementTemporary(t)){const i=this.messageElementRefs[this.messageElementRefs.length-2];i&&this.messages[this.messages.length-1]&&!t.bubbleElement.classList.contains(I.getRoleClass(e))&&I.revealRoleElements(i.innerContainer,this._avatars,this._names)}}static isTemporaryElement(t){return ge.isLoadingMessage(t)||R.isElementTemporary(t)}createMessageElements(t,e,i=!1){const s=ge.createBaseElements(),{outerContainer:n,innerContainer:o,bubbleElement:r}=s;return n.appendChild(o),this.addInnerContainerElements(r,t,e),I.updateRefArr(this.messageElementRefs,s,i),s}static createBaseElements(){const t=document.createElement("div"),e=document.createElement("div");e.classList.add("inner-message-container"),t.appendChild(e),t.classList.add("outer-message-container");const i=document.createElement("div");return i.classList.add("message-bubble"),e.appendChild(i),{outerContainer:t,innerContainer:e,bubbleElement:i}}addInnerContainerElements(t,e,i){var s;return(null==(s=this.messages[this.messages.length-1])?void 0:s.role)===i&&!this.isLastMessageError()&&I.hideRoleElements(this.messageElementRefs,!!this._avatars,!!this._names),t.classList.add("message-bubble",I.getRoleClass(i),i===I.USER_ROLE?"user-message-text":"ai-message-text"),this.renderText(t,e),I.addRoleElements(t,i,this._avatars,this._names),{bubbleElement:t}}applyCustomStyles(t,e,i,s){t&&this.messageStyles&&fe.applyCustomStyles(this.messageStyles,t,e,i,s)}static createMessageContent(t){const{text:e,files:i,html:s,_sessionId:n,role:o}=t,r={role:o||I.AI_ROLE};return e&&(r.text=e),i&&(r.files=i),s&&(r.html=s),!e&&!i&&!s&&(r.text=""),n&&(r._sessionId=n),r}removeMessage(t){t.outerContainer.remove();const e=this.messageElementRefs.findIndex((e=>e===t));this.messageElementRefs.splice(e,1)}removeLastMessage(){this.messageElementRefs[this.messageElementRefs.length-1].outerContainer.remove(),this.messageElementRefs.pop()}isLastMessageError(){var t;return null==(t=I.getLastMessageBubbleElement(this.elementRef))?void 0:t.classList.contains("error-message-text")}static isLoadingMessage(t){return null==t?void 0:t.bubbleElement.classList.contains(A.BUBBLE_CLASS)}sendClientUpdate(t,e=!1){var i;null==(i=this._onMessage)||i.call(this,t,e)}renderText(t,e){t.innerHTML=this._remarkable.render(e),0===t.innerText.trim().length&&(t.innerText=e)}refreshTextMessages(){this._remarkable=he.createNew(),this.textElementsToText.forEach((t=>{this.renderText(t[0].bubbleElement,t[1])}))}}const be=class t{constructor(t){this._fileAdded=!1,this._streamedContent="",this._streamType="",this._hasStreamEnded=!1,this._messages=t}upsertStreamedMessage(t){var e;if(this._hasStreamEnded)return;if(void 0===(null==t?void 0:t.text)&&void 0===(null==t?void 0:t.html))return console.error(y.INVALID_STREAM_EVENT);const i=(null==t?void 0:t.text)||(null==t?void 0:t.html)||"",s=x.isScrollbarAtBottomOfElement(this._messages.elementRef),n=void 0!==(null==t?void 0:t.text)?"text":"html";if(this._elements||""!==this._streamedContent){if(this._streamType!==n)return console.error(y.INVALID_STREAM_EVENT_MIX);this.updateBasedOnType(i,n,null==(e=this._elements)?void 0:e.bubbleElement,null==t?void 0:t.overwrite)}else this.setInitialState(n,i,null==t?void 0:t.role);s&&x.scrollToBottom(this._messages.elementRef)}setInitialState(e,i,s){this._streamType=e,s??(s=I.AI_ROLE),this._elements="text"===e?this._messages.addNewTextMessage(i,s):B.add(this._messages,i,s,this._messages.messageElementRefs),this._elements.bubbleElement.classList.add(t.MESSAGE_CLASS),this._streamedContent=i,this._activeMessageRole=s,this._message={role:this._activeMessageRole,[e]:this._streamedContent},this._messages.messages.push(this._message)}updateBasedOnType(t,e,i,s=!1){I.unfillEmptyMessageElement(i,t),("text"===e?this.updateText:this.updateHTML).bind(this)(t,i,s)}updateText(t,e,i){this._streamedContent=i?t:this._streamedContent+t,this._messages.textElementsToText[this._messages.textElementsToText.length-1][1]=this._streamedContent,this._messages.renderText(e,this._streamedContent)}updateHTML(e,i,s){if(s)this._streamedContent=e,i.innerHTML=e;else{const s=document.createElement("span");s.innerHTML=e,i.appendChild(s),this._streamedContent=t.HTML_CONTENT_PLACEHOLDER}}finaliseStreamedMessage(){var e,i;const{textElementsToText:s}=this._messages;if(!this._endStreamAfterOperation&&(!this._fileAdded||this._elements)){if(!this._elements)throw Error(y.NO_VALID_STREAM_EVENTS_SENT);null!=(e=this._elements.bubbleElement)&&e.classList.contains(t.MESSAGE_CLASS)&&("text"===this._streamType?(s[s.length-1][1]=this._streamedContent,this._message&&(this._message.text=this._streamedContent),this._messages.textToSpeech&&_.speak(this._streamedContent,this._messages.textToSpeech)):"html"===this._streamType&&(this._streamedContent===t.HTML_CONTENT_PLACEHOLDER&&(this._streamedContent=(null==(i=this._elements.bubbleElement)?void 0:i.innerHTML)||""),this._elements&&L.apply(this._messages,this._elements.outerContainer),this._message&&(this._message.html=this._streamedContent)),this._elements.bubbleElement.classList.remove(t.MESSAGE_CLASS),this._message&&this._messages.sendClientUpdate(ge.createMessageContent(this._message),!1),this._hasStreamEnded=!0)}}markFileAdded(){this._fileAdded=!0}newMessage(){this.finaliseStreamedMessage(),this._elements=void 0,this._streamedContent="",this._fileAdded=!1,this._hasStreamEnded=!1,this._activeMessageRole=void 0}async endStreamAfterFileDownloaded(t,e){var i;this._endStreamAfterOperation=!0;const{text:s,files:n}=await e();s&&this.updateBasedOnType(s,"text",null==(i=this._elements)?void 0:i.bubbleElement,!0),this._endStreamAfterOperation=!1,this.finaliseStreamedMessage(),n&&t.addNewMessage({files:n})}};be.MESSAGE_CLASS="streamed-message",be.HTML_CONTENT_PLACEHOLDER="htmlplaceholder";let ye=be;const we=class t{static async tempRemoveContentHeader(e,i,s){if(null==e||!e.headers)throw new Error("Request settings have not been set up");const n=e.headers[t.CONTENT_TYPE];let o;delete e.headers[t.CONTENT_TYPE];try{o=await i(s)}catch(i){throw e.headers[t.CONTENT_TYPE]=n,i}return e.headers[t.CONTENT_TYPE]=n,o}static displayError(t,e,i="Service error, please try again."){if(console.error(e),"object"==typeof e)return e instanceof Error?t.addNewErrorMessage("service",e.message):Array.isArray(e)||"string"==typeof e.error?t.addNewErrorMessage("service",e):0===Object.keys(e).length?t.addNewErrorMessage("service",i):t.addNewErrorMessage("service",JSON.stringify(e));t.addNewErrorMessage("service",e)}static fetch(t,e,i,s){var n,o;const r={method:(null==(n=t.connectSettings)?void 0:n.method)||"POST",headers:e};return"GET"!==r.method&&(r.body=i?JSON.stringify(s):s),t.connectSettings.credentials&&(r.credentials=t.connectSettings.credentials),fetch((null==(o=t.connectSettings)?void 0:o.url)||t.url||"",r)}static processResponseByType(t){const e=t.headers.get("content-type");return null!=e&&e.includes("application/json")?t.json():null!=e&&e.includes("text/plain")||!e?t:t.blob()}static async processRequestInterceptor(t,e){var i;const s=await(null==(i=t.requestInterceptor)?void 0:i.call(t,e))||e,n=s,o=s;return{body:n.body,headers:n.headers,error:o.error}}static validateResponseFormat(t){return t&&"object"==typeof t&&("string"==typeof t.error||"string"==typeof t.text||"string"==typeof t.html||Array.isArray(t.files))}static onInterceptorError(t,e,i){t.addNewErrorMessage("service",e),null==i||i()}};we.CONTENT_TYPE="Content-Type";let xe=we;function ke(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 _e="text/event-stream",Se="last-event-id";function Te(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=_e),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??Ae;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,ke(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[Se]=t:delete d[Se]}),(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 Ae(t){const e=t.headers.get("content-type");if(null==e||!e.startsWith(_e))throw new Error(`Expected content-type to be ${_e}, Actual: ${e}`)}class Me{static async request(t,e,i,s=!0,n=!1){var o,r,a,l,c,h;const u={body:e,headers:null==(o=t.connectSettings)?void 0:o.headers},{body:d,headers:p,error:m}=await xe.processRequestInterceptor(t.deepChat,u),{onOpen:v,onClose:f,abortStream:g}=t.streamHandlers;if(m)return xe.onInterceptorError(i,m,f);if(null!=(r=t.connectSettings)&&r.handler)return Ee.stream(t,d,i);if((null==(a=t.connectSettings)?void 0:a.url)===je.URL)return je.requestStream(i,t.streamHandlers);const b=new ye(i),y=xe.fetch.bind(this,t,p,s);return Te((null==(l=t.connectSettings)?void 0:l.url)||t.url||"",{method:(null==(c=t.connectSettings)?void 0:c.method)||"POST",headers:p,credentials:null==(h=t.connectSettings)?void 0:h.credentials,body:s?JSON.stringify(d):d,openWhenHidden:!0,async onopen(t){if(t.ok)return v();throw await xe.processResponseByType(t)},async onmessage(e){var s,n,o;if(JSON.stringify(e.data)!==JSON.stringify("[DONE]")){let r;try{r=JSON.parse(e.data)}catch{r={}}const a=await(null==(n=(s=t.deepChat).responseInterceptor)?void 0:n.call(s,r))||r;null==(o=t.extractResultData)||o.call(t,a,y,d).then((e=>{t.asyncCallInProgress&&e&&""!==e.text?(Me.simulate(i,t.streamHandlers,e),f(),t.asyncCallInProgress=!1):Me.upsertWFiles(i,b.upsertStreamedMessage.bind(b),b,e)})).catch((t=>xe.displayError(i,t)))}},onerror(t){throw f(),t},onclose(){if(!t.asyncCallInProgress)try{b.finaliseStreamedMessage(),f()}catch(t){if(!n)throw t}},signal:g.signal}).catch((e=>{var s;i.isLastMessageError()||null==(s=t.extractResultData)||s.call(t,e).then((()=>{xe.displayError(i,e)})).catch((t=>{xe.displayError(i,t)}))})),b}static simulate(t,e,i){const s=e;if(i.files&&t.addNewMessage({sendUpdate:!1,ignoreText:!0,...i},!1),i.text){e.onOpen();const n=i.text.split("");Me.populateMessages(n,new ye(t),s,"text")}if(i.html){e.onOpen();const n=L.splitHTML(i.html);Me.populateMessages(n,new ye(t),s,"html")}}static populateMessages(t,e,i,s,n=0){const o=t[n];if(o){e.upsertStreamedMessage({[s]:o});const r=setTimeout((()=>{Me.populateMessages(t,e,i,s,n+1)}),i.simulationInterim||6);i.abortStream.abort=()=>{Me.abort(r,e,i.onClose)}}else e.finaliseStreamedMessage(),i.onClose()}static isSimulation(t){return"object"==typeof t&&!!t.simulation}static isSimulatable(t,e){return Me.isSimulation(t)&&e&&(e.text||e.html)}static abort(t,e,i){clearTimeout(t),e.finaliseStreamedMessage(),i()}static upsertWFiles(t,e,i,s){if(null!=s&&s.text||null!=s&&s.html){const t=e(s);i??(i=t||void 0)}null!=s&&s.files&&(t.addNewMessage({files:s.files}),null==i||i.markFileAdded())}}const Oe=class t{static generateResponse(t){const e=t.messages[t.messages.length-1];if(e.files&&e.files.length>0){if(e.files.length>1)return"These are interesting files!";const t=e.files[0];return t.src&&t.src.startsWith("data:image/gif")?"That is a nice gif!":"image"===t.type?"That is a nice image!":"audio"===t.type?"I like the sound of that!":"That is an interesting file!"}if(e.text){if("?"===e.text.charAt(e.text.length-1))return"I'm sorry but I can't answer that question...";if(e.text.includes("updog"))return"What's updog?"}return"Hi there! This is a demo response!"}static getCustomResponse(t,e){return"function"==typeof t?t(e):t}static getResponse(e){return e.customDemoResponse?t.getCustomResponse(e.customDemoResponse,e.messages[e.messages.length-1]):{text:t.generateResponse(e)}}static request(e,i){const s=t.getResponse(i);setTimeout((async()=>{var t,n;const o=await(null==(n=(t=e.deepChat).responseInterceptor)?void 0:n.call(t,s))||s;o.error?(i.addNewErrorMessage("service",o.error),e.completionsHandlers.onFinish()):Me.isSimulatable(e.stream,o)?Me.simulate(i,e.streamHandlers,o):(i.addNewMessage(o),e.completionsHandlers.onFinish())}),400)}static requestStream(e,i){setTimeout((()=>{const s=t.getResponse(e);Me.simulate(e,i,s)}),400)}};Oe.URL="deep-chat-demo";let je=Oe;class Ce{static setup(t){t.connectSettings.url!==je.URL&&(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(!Ce.isElementPresentInDOM(t.deepChat))return;const i=t.connectSettings.websocket;if(i){if(t.connectSettings.handler)return Ee.websocket(t,e);try{const s="boolean"!=typeof i?i:void 0,n=new WebSocket(t.connectSettings.url||"",s);t.websocket=n,t.websocket.onopen=()=>{var i,s;e.removeError(),t.websocket&&"object"==typeof t.websocket&&Ce.assignListeners(t,n,e),null==(s=(i=t.deepChat)._validationHandler)||s.call(i)},t.websocket.onerror=i=>{console.error(i),Ce.retryConnection(t,e)}}catch(i){console.error(i),Ce.retryConnection(t,e)}}}static retryConnection(t,e){var i,s;null==(s=(i=t.deepChat)._validationHandler)||s.call(i),Ce.isElementPresentInDOM(t.deepChat)&&(t.websocket="pending",e.isLastMessageError()||e.addNewErrorMessage("service","Connection error"),setTimeout((()=>{Ce.createConnection(t,e)}),5e3))}static assignListeners(t,e,i){const s={};e.onmessage=async e=>{var n,o;if(t.extractResultData)try{const r=JSON.parse(e.data),a=await(null==(o=(n=t.deepChat).responseInterceptor)?void 0:o.call(n,r))||r,l=await t.extractResultData(a);if(!l||"object"!=typeof l)throw Error(y.INVALID_RESPONSE(r,"server",!!t.deepChat.responseInterceptor,a));if(Me.isSimulation(t.stream)){const e=Ce.stream.bind(this,t,i,s),n=s[r.role||I.AI_ROLE];Me.upsertWFiles(i,e,n,l)}else i.addNewMessage(l)}catch(t){xe.displayError(i,t,"Error in server message")}},e.onclose=()=>{console.error("Connection closed"),i.isLastMessageError()||i.addNewErrorMessage("service","Connection error"),t.stream&&t.streamHandlers.abortStream.abort(),Ce.createConnection(t,i)}}static async sendWebsocket(t,e,i,s=!0){var n,o;const r=t.websocket;if(!r||"pending"===r)return;const a={body:e,headers:null==(n=t.connectSettings)?void 0:n.headers},{body:l,error:c}=await xe.processRequestInterceptor(t.deepChat,a);if(c)return i.addNewErrorMessage("service",c);if(!Ce.isWebSocket(r))return r.newUserMessage.listener(l);const h=s?JSON.stringify(l):l;if((null==(o=t.connectSettings)?void 0:o.url)===je.URL)return je.request(t,i);void 0===r.readyState||r.readyState!==r.OPEN?(console.error("Connection is not open"),i.isLastMessageError()||i.addNewErrorMessage("service","Connection error")):(r.send(JSON.stringify(h)),t.completionsHandlers.onFinish())}static canSendMessage(t){return!t||"pending"!==t&&(Ce.isWebSocket(t)?void 0!==t.readyState&&t.readyState===t.OPEN:t.isOpen)}static isWebSocket(t){return void 0!==t.send}static stream(t,e,i,s){if(!s)return;const n=t.stream.simulation;if("string"==typeof n){const t=s.role||I.AI_ROLE,o=i[t];s.text===n||s.html===n?(null==o||o.finaliseStreamedMessage(),delete i[t]):(i[t]??(i[t]=new ye(e)),i[t].upsertStreamedMessage(s))}else Me.simulate(e,t.streamHandlers,s)}}class Ee{static async request(t,e,i){var s,n;let o=!0;const r=Ee.generateOptionalSignals();null==(n=(s=t.connectSettings).handler)||n.call(s,e,{...r,onResponse:async e=>{var s,n;if(!o)return;o=!1;const r=await(null==(n=(s=t.deepChat).responseInterceptor)?void 0:n.call(s,e))||e;xe.validateResponseFormat(r)?"string"==typeof r.error?(console.error(r.error),i.addNewErrorMessage("service",r.error),t.completionsHandlers.onFinish()):Me.isSimulatable(t.stream,r)?Me.simulate(i,t.streamHandlers,r):(i.addNewMessage(r),t.completionsHandlers.onFinish()):(console.error(y.INVALID_RESPONSE(e,"server",!!t.deepChat.responseInterceptor,r)),i.addNewErrorMessage("service","Error in server message"),t.completionsHandlers.onFinish())}})}static attemptToFinaliseStream(t,e){try{const i=e.messageElementRefs[e.messageElementRefs.length-1];ge.isLoadingMessage(i)?e.removeLastMessage():t.finaliseStreamedMessage()}catch(t){console.error(t),e.addNewErrorMessage("service",t)}}static stream(t,e,i){var s,n;let o=!0,r=!1;const a=new ye(i);t.streamHandlers.abortStream.abort=()=>{Ee.attemptToFinaliseStream(a,i),t.streamHandlers.onClose(),o=!1};const l=Ee.generateOptionalSignals();null==(n=(s=t.connectSettings).handler)||n.call(s,e,{...l,onOpen:()=>{r||!o||(t.streamHandlers.onOpen(),r=!0)},onResponse:async e=>{var s,n;if(!o)return;const r=await(null==(n=(s=t.deepChat).responseInterceptor)?void 0:n.call(s,e))||e;xe.validateResponseFormat(r)?r.error?(console.error(r.error),a.finaliseStreamedMessage(),i.addNewErrorMessage("service",r.error),t.streamHandlers.onClose(),o=!1):Me.upsertWFiles(i,a.upsertStreamedMessage.bind(a),a,r):console.error(y.INVALID_RESPONSE(e,"server",!!t.deepChat.responseInterceptor,r))},onClose:()=>{o&&(Ee.attemptToFinaliseStream(a,i),t.streamHandlers.onClose(),o=!1)},stopClicked:t.streamHandlers.stopClicked})}static websocket(t,e){var i,s;const n={isOpen:!1,newUserMessage:{listener:()=>{}},roleToStream:{}};t.websocket=n;const o=Ee.generateOptionalSignals();null==(s=(i=t.connectSettings).handler)||s.call(i,void 0,{...o,onOpen:()=>{e.removeError(),n.isOpen=!0},onResponse:async i=>{var s,o;if(!n.isOpen)return;const r=await(null==(o=(s=t.deepChat).responseInterceptor)?void 0:o.call(s,i))||i;if(xe.validateResponseFormat(r))if("string"==typeof r.error)console.error(r.error),e.isLastMessageError()||e.addNewErrorMessage("service",r.error);else if(Me.isSimulation(t.stream)){const s=Ce.stream.bind(this,t,e,n.roleToStream),o=n.roleToStream[i.role||I.AI_ROLE];Me.upsertWFiles(e,s,o,i)}else e.addNewMessage(r);else console.error(y.INVALID_RESPONSE(i,"server",!!t.deepChat.responseInterceptor,r)),e.addNewErrorMessage("service","Error in server message")},onClose:()=>{n.isOpen=!1},newUserMessage:n.newUserMessage})}static generateOptionalSignals(){return{onClose:()=>{},onOpen:()=>{},stopClicked:{listener:()=>{}},newUserMessage:{listener:()=>{}}}}}class Ie{static async request(t,e,i,s=!0){var n,o,r;const a={body:e,headers:null==(n=t.connectSettings)?void 0:n.headers},{body:l,headers:c,error:h}=await xe.processRequestInterceptor(t.deepChat,a),{onFinish:u}=t.completionsHandlers;if(h)return xe.onInterceptorError(i,h,u);if(null!=(o=t.connectSettings)&&o.handler)return Ee.request(t,l,i);if((null==(r=t.connectSettings)?void 0:r.url)===je.URL)return je.request(t,i);let d=!0;const p=xe.fetch.bind(this,t,c,s);p(l).then((t=>(d=!!t.ok,t))).then((t=>xe.processResponseByType(t))).then((async e=>{var s,n;if(!t.extractResultData)return;const o=await(null==(n=(s=t.deepChat).responseInterceptor)?void 0:n.call(s,e))||e,r=await t.extractResultData(o,p,l);if(!d)throw e;if(!r||"object"!=typeof r)throw Error(y.INVALID_RESPONSE(e,"response",!!t.deepChat.responseInterceptor,o));r.makingAnotherRequest||(Me.isSimulatable(t.stream,r)?Me.simulate(i,t.streamHandlers,r):(i.addNewMessage(r),u()))})).catch((t=>{xe.displayError(i,t),u()}))}static executePollRequest(t,e,i,s){const{onFinish:n}=t.completionsHandlers;fetch(e,i).then((t=>t.json())).then((async o=>{var r,a;if(!t.extractPollResultData)return;const l=await t.extractPollResultData(await(null==(a=(r=t.deepChat).responseInterceptor)?void 0:a.call(r,o))||o);l.timeoutMS?setTimeout((()=>{Ie.executePollRequest(t,e,i,s)}),l.timeoutMS):Me.isSimulatable(t.stream,l)?Me.simulate(s,t.streamHandlers,l):(s.addNewMessage(l),n())})).catch((t=>{xe.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 xe.processRequestInterceptor(t.deepChat,a);if(h)return xe.onInterceptorError(i,h);const u=(null==(o=t.connectSettings)?void 0:o.url)||t.url||"",d={method:(null==(r=t.connectSettings)?void 0:r.method)||"POST",body:s?JSON.stringify(l):l,headers:c};t.connectSettings.credentials&&(d.credentials=t.connectSettings.credentials),Ie.executePollRequest(t,u,d,i)}static verifyKey(t,e,i,s,n,o,r,a,l){if(""===t)return o(y.INVALID_KEY);r(),fetch(e,{method:s,headers:i,body:l||null}).then((t=>xe.processResponseByType(t))).then((e=>{a(e,t,n,o)})).catch((t=>{o(y.CONNECTION_FAILED),console.error(t)}))}}const Pe=class t{constructor(t,e,i){this._isLoading=!1,this._isPaginationComplete=!1,this._index=0,this._messages=e,i.fetchHistory&&this.fetchHistory(i.fetchHistory),t.loadHistory&&this.setupLoadHistoryOnScroll(t.loadHistory),this.setupInitialHistory(t)}async fetchHistory(t){const e=ve.addMessage(this._messages),i=await t();this._messages.removeMessage(e),i.forEach((t=>this._messages.addAnyMessage(t,!0))),setTimeout((()=>x.scrollToBottom(this._messages.elementRef)),0)}processLoadedHistory(t){var e;const i=null==(e=this._messages.messageElementRefs[0])?void 0:e.outerContainer,s=this._messages.elementRef.scrollTop;null==t||t.reverse().map((t=>{if(t){const e=this._messages.addAnyMessage({...t,sendUpdate:!0},!0,!0);return e&&this._messages.messages.unshift(e),e}this._isPaginationComplete=!0})).filter((t=>!!t)).reverse().forEach((t=>this._messages.sendClientUpdate(t,!0))),i&&(this._messages.elementRef.scrollTop=s+i.offsetTop)}async setupLoadHistoryOnScroll(e){this._messages.elementRef.onscroll=async()=>{if(!this._isLoading&&!this._isPaginationComplete&&0===this._messages.elementRef.scrollTop){this._isLoading=!0;const i=ve.addMessage(this._messages,!1);try{const t=await e(this._index++);this._messages.removeMessage(i),this.processLoadedHistory(t),this._isLoading=!1}catch(e){this._messages.removeMessage(i),this._isPaginationComplete=!0,this._messages.addNewErrorMessage("service",t.FAILED_ERROR_MESSAGE,!0),console.error(e)}}}}populateInitialHistory(t){t.forEach((t=>{S.processHistoryFile(t),this._messages.addNewMessage(t,!0)}))}async loadInitialHistory(e){this._isLoading=!0;const i=ve.addMessage(this._messages);try{const t=await e(this._index++),s=this._messages.elementRef.scrollTop;this._messages.removeMessage(i),this._isPaginationComplete=!!t.find((t=>!t));const n=t.filter((t=>!!t));this.processLoadedHistory(n),0===s&&setTimeout((()=>x.scrollToBottom(this._messages.elementRef)),0)}catch(e){this._messages.removeMessage(i),this._isPaginationComplete=!0,this._messages.addNewErrorMessage("service",t.FAILED_ERROR_MESSAGE,!0),console.error(e)}this._isLoading=!1}async setupInitialHistory(t){t.loadHistory&&this.loadInitialHistory(t.loadHistory);const e=t.history||S.processHistory(t);e&&(this.populateInitialHistory(e),this._index+=1)}static addErrorPrefix(e){e.permittedErrorPrefixes??(e.permittedErrorPrefixes=[]),e.permittedErrorPrefixes.push(t.FAILED_ERROR_MESSAGE)}};Pe.FAILED_ERROR_MESSAGE="Failed to load history";let Ne=Pe;class qe{static getCharacterLimitMessages(t,e){var i;if(-1===e)return t;let s=0,n=t.length-1;for(;n>=0;n-=1){const o=null==(i=t[n])?void 0:i.text;if(void 0!==o&&(s+=o.length,s>e)){t[n].text=o.substring(0,o.length-(s-e));break}}return t.slice(Math.max(n,0))}static getMaxMessages(t,e){return t.slice(Math.max(t.length-e,0))}static processMessages(t,e,i){return void 0!==e?e>0&&(t=qe.getMaxMessages(t,e)):t=[t[t.length-1]],t=JSON.parse(JSON.stringify(t)),void 0===i?t:qe.getCharacterLimitMessages(t,i)}}class Re{static parseConfig(t,e,i,s){var n;const o={files:e};if("object"==typeof s){S.processFileConfigConnect(s);const{files:e,connect:r,button:a}=s;e&&(e.infoModal&&(o.files.infoModal=e.infoModal,null!=(n=e.infoModal)&&n.textMarkDown&&(o.infoModalTextMarkUp=i.render(e.infoModal.textMarkDown))),e.acceptedFormats&&(o.files.acceptedFormats=e.acceptedFormats),e.maxNumberOfFiles&&(o.files.maxNumberOfFiles=e.maxNumberOfFiles)),o.button=a,r&&(r.headers||r.method||r.url||r.credentials||t.headers||t.method||t.url||t.credentials)&&(o.connect={url:(null==r?void 0:r.url)||t.url,method:(null==r?void 0:r.method)||t.method,headers:(null==r?void 0:r.headers)||t.headers,credentials:(null==r?void 0:r.credentials)||t.credentials})}return o}static processMixedFiles(t,e,i){if(i){const s={acceptedFormats:""};t.fileTypes.mixedFiles=Re.parseConfig(t.connectSettings,s,e,i)}}static processMicrophone(t,e,i,s){var n,o,r,a,l,c;const h={acceptedFormats:"audio/*",...(null==(n=t.fileTypes.audio)?void 0:n.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.recordAudio=Re.parseConfig(t.connectSettings,h,e,i),"object"==typeof i&&i.files&&((o=t.recordAudio).files??(o.files={}),t.recordAudio.files.format=null==(r=i.files)?void 0:r.format,t.recordAudio.files.maxDurationSeconds=null==(a=i.files)?void 0:a.maxDurationSeconds,null!=(l=t.fileTypes.audio)&&l.files&&((c=t.fileTypes.audio.files).maxNumberOfFiles??(c.maxNumberOfFiles=i.files.maxNumberOfFiles)))):s||(t.fileTypes.audio=Re.parseConfig(t.connectSettings,h,e,i)))}static processAudioConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"audio/*",...(null==s?void 0:s.files)||{}};t.fileTypes.audio=Re.parseConfig(t.connectSettings,n,e,i)}static processGifConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"image/gif",...(null==s?void 0:s.files)||{}};t.fileTypes.gifs=Re.parseConfig(t.connectSettings,n,e,i)}static processCamera(t,e,i,s){var n,o,r,a;const l={acceptedFormats:"image/*",...(null==(n=t.fileTypes.images)?void 0:n.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.camera=Re.parseConfig(t.connectSettings,l,e,i),"object"==typeof i&&(t.camera.modalContainerStyle=i.modalContainerStyle,i.files&&((o=t.camera).files??(o.files={}),t.camera.files.format=null==(r=i.files)?void 0:r.format,t.camera.files.dimensions=null==(a=i.files)?void 0:a.dimensions))):s||(t.fileTypes.images=Re.parseConfig(t.connectSettings,l,e,i)))}static processImagesConfig(t,e,i,s){if(!i&&!s)return;const n={acceptedFormats:"image/*",...(null==s?void 0:s.files)||{}};t.fileTypes.images=Re.parseConfig(t.connectSettings,n,e,i)}static populateDefaultFileIO(t,e){var i,s;t&&(t.files??(t.files={}),(i=t.files).acceptedFormats??(i.acceptedFormats=e),(s=t.files).maxNumberOfFiles??(s.maxNumberOfFiles=1))}static set(t,e,i){Re.populateDefaultFileIO(null==i?void 0:i.audio,".4a,.mp3,.webm,.mp4,.mpga,.wav,.mpeg,.m4a"),Re.populateDefaultFileIO(null==i?void 0:i.images,".png,.jpg");const s=he.createNew();Re.processImagesConfig(e,s,t.images,null==i?void 0:i.images),Re.processCamera(e,s,t.camera,t.images),Re.processGifConfig(e,s,t.gifs,null==i?void 0:i.gifs),Re.processAudioConfig(e,s,t.audio,null==i?void 0:i.audio),Re.processMicrophone(e,s,t.microphone,t.audio),Re.processMixedFiles(e,s,t.mixedFiles)}}class Le{constructor(t,e,i){var s,n,o,r,a;this.rawBody={},this.validateKeyProperty=!1,this.canSendMessage=Le.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,Re.set(t,this,e),t.connect&&(this.connectSettings=t.connect),this.demo&&((r=this.connectSettings).url??(r.url=je.URL)),this.connectSettings.websocket&&Ce.setup(this),this.stream=(null==(a=this.deepChat.connect)?void 0:a.stream)||S.checkForStream(this.deepChat),t.loadHistory&&Ne.addErrorPrefix(this)}static canSendMessage(t,e,i){return!!i||(!(!t||""===t.trim())||!!(e&&e.length>0))}verifyKey(t,e){}static createCustomFormDataBody(t,e,i){const s=new FormData;i.forEach((t=>s.append("files",t))),Object.keys(t).forEach((e=>s.append(e,String(t[e]))));let n=0;e.slice(0,e.length-1).forEach((t=>{s.append(`message${n+=1}`,JSON.stringify(t))}));const o=e[e.length-1];return o.text&&(delete o.files,s.append(`message${n+=1}`,JSON.stringify(o))),s}getServiceIOByType(t){if(t.type.startsWith("audio")&&this.fileTypes.audio)return this.fileTypes.audio;if(t.type.startsWith("image")){if(this.fileTypes.gifs&&t.type.endsWith("/gif"))return this.fileTypes.gifs;if(this.fileTypes.images)return this.fileTypes.images;if(this.camera)return this.camera}return this.fileTypes.mixedFiles}async request(t,e,i=!0){return this.stream&&!Me.isSimulation(this.stream)?Me.request(this,t,e,i):Ie.request(this,t,e,i)}async callAPIWithText(t,e){var i,s,n,o;const r={messages:e,...this.rawBody};let a=!1;null!=(i=this.connectSettings.headers)&&i["Content-Type"]||((s=this.connectSettings).headers??(s.headers={}),(n=this.connectSettings.headers)["Content-Type"]??(n["Content-Type"]="application/json"),a=!0),await this.request(r,t),a&&(null==(o=this.connectSettings.headers)||delete o["Content-Type"])}async callApiWithFiles(t,e,i){const s=Le.createCustomFormDataBody(this.rawBody,e,i),n=this.connectSettings,o=this.getServiceIOByType(i[0]);this.connectSettings=(null==o?void 0:o.connect)||this.connectSettings,await this.request(s,t,!1),this.connectSettings=n}async callServiceAPI(t,e,i){i?this.callApiWithFiles(t,e,i):this.callAPIWithText(t,e)}async callAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=qe.processMessages(e.messages,this.maxMessages,this.totalMessagesMaxCharLength);if(this.connectSettings.websocket){const t={messages:i,...this.rawBody};Ce.sendWebsocket(this,t,e,!1)}else this.callServiceAPI(e,i,t.files)}async extractResultData(t){if(t.error)throw t.error;return t.result?S.handleResponseProperty(t):xe.validateResponseFormat(t)?t:void 0}isDirectConnection(){return!1}isWebModel(){return!1}}class Be extends Le{constructor(t,e,i,s,n){var o;super(t,n),this.insertKeyPlaceholderText="API Key",this.keyHelpUrl="",Object.assign(this.rawBody,null==(o=t.connect)?void 0:o.additionalBodyProps),this.keyVerificationDetails=e,this.buildHeadersFunc=i,s&&this.setApiKeyProperties(s),this.connectSettings=this.buildConnectSettings(this.key||"",t.connect)}setApiKeyProperties(t){this.key=t.key,t.validateKeyProperty&&(this.validateKeyProperty=t.validateKeyProperty)}buildConnectSettings(t,e){const i=e??{};return i.headers??(i.headers={}),Object.assign(i.headers,this.buildHeadersFunc(t)),i}keyAuthenticated(t,e){this.connectSettings=this.buildConnectSettings(e,this.connectSettings),this.key=e,t()}verifyKey(t,e){const{url:i,method:s,handleVerificationResult:n,createHeaders:o,body:r}=this.keyVerificationDetails,a=(null==o?void 0:o(t))||this.buildHeadersFunc(t);Ie.verifyKey(t,i,a,s,this.keyAuthenticated.bind(this,e.onSuccess),e.onFail,e.onLoad,n,r)}isDirectConnection(){return!0}}class Fe{static waitForPropertiesToBeUpdatedBeforeRender(t){t._propUpdated_=!1,setTimeout((()=>{t._propUpdated_?Fe.waitForPropertiesToBeUpdatedBeforeRender(t):(t._waitingToRender_=!1,t.onRender())}))}static attemptRender(t){t._propUpdated_=!0,t._waitingToRender_||(t._waitingToRender_=!0,Fe.waitForPropertiesToBeUpdatedBeforeRender(t))}}const ze=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:Fe.attemptRender(this)}})}attributeChangedCallback(e,i,s){if(i===s)return;const n=t._attributes_[e](s);this[t._attributeToProperty_[e]]=n}onRender(){}};ze._attributes_={},ze._attributeToProperty_={};let De=ze;class $e{static createSVGElement(t){return(new DOMParser).parseFromString(t,"image/svg+xml").documentElement}}const Je=class t{static changeVisibility(e,i,s,n){n.target.id===t.VISIBLE_ICON_ID?(i.style.display="none",s.style.display="block",e.type="password"):(i.style.display="block",s.style.display="none",e.type="text")}static createIconElement(t,e){const i=$e.createSVGElement(t);return i.id=e,i.classList.add("visibility-icon"),i}static create(e){const i=document.createElement("div");i.id="visibility-icon-container";const s=t.createIconElement('<?xml version="1.0" standalone="no"?>\n<svg version="1.1"\n\txmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n\txmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0.9em" height="0.9em"\n\tviewBox="0 0 1200 1200" enable-background="new 0 0 1200 1200">\n\t\t<path id="path6686" inkscape:connector-curvature="0" d="M779.843,599.925c0,95.331-80.664,172.612-180.169,172.612\n\t\t\tc-99.504,0-180.168-77.281-180.168-172.612c0-95.332,80.664-172.612,180.168-172.612\n\t\t\tC699.179,427.312,779.843,504.594,779.843,599.925z M600,240.521c-103.025,0.457-209.814,25.538-310.904,73.557\n\t\t\tc-75.058,37.122-148.206,89.496-211.702,154.141C46.208,501.218,6.431,549,0,599.981c0.76,44.161,48.13,98.669,77.394,131.763\n\t\t\tc59.543,62.106,130.786,113.018,211.702,154.179c94.271,45.751,198.616,72.092,310.904,73.557\n\t\t\tc103.123-0.464,209.888-25.834,310.866-73.557c75.058-37.122,148.243-89.534,211.74-154.179\n\t\t\tc31.185-32.999,70.962-80.782,77.394-131.763c-0.76-44.161-48.13-98.671-77.394-131.764\n\t\t\tc-59.543-62.106-130.824-112.979-211.74-154.141C816.644,268.36,712.042,242.2,600,240.521z M599.924,329.769\n\t\t\tc156.119,0,282.675,120.994,282.675,270.251c0,149.256-126.556,270.25-282.675,270.25S317.249,749.275,317.249,600.02\n\t\t\tC317.249,450.763,443.805,329.769,599.924,329.769L599.924,329.769z"/>\n</svg>\n',t.VISIBLE_ICON_ID);s.style.display="none",i.appendChild(s);const n=t.createIconElement('<?xml version="1.0" standalone="no"?>\n<svg version="1.1"\n\txmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"\n\txmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0.9em" height="0.9em"\n\tviewBox="0 0 1200 1200" enable-background="new 0 0 1200 1200">\n\t\t<path d="\n\t\t\tM669.727,273.516c-22.891-2.476-46.15-3.895-69.727-4.248c-103.025,0.457-209.823,25.517-310.913,73.536\n\t\t\tc-75.058,37.122-148.173,89.529-211.67,154.174C46.232,529.978,6.431,577.76,0,628.74c0.76,44.162,48.153,98.67,77.417,131.764\n\t\t\tc59.543,62.106,130.754,113.013,211.67,154.174c2.75,1.335,5.51,2.654,8.276,3.955l-75.072,131.102l102.005,60.286l551.416-960.033\n\t\t\tl-98.186-60.008L669.727,273.516z M902.563,338.995l-74.927,129.857c34.47,44.782,54.932,100.006,54.932,159.888\n\t\t\tc0,149.257-126.522,270.264-282.642,270.264c-6.749,0-13.29-0.728-19.922-1.172l-49.585,85.84c22.868,2.449,45.99,4.233,69.58,4.541\n\t\t\tc103.123-0.463,209.861-25.812,310.84-73.535c75.058-37.122,148.246-89.529,211.743-154.174\n\t\t\tc31.186-32.999,70.985-80.782,77.417-131.764c-0.76-44.161-48.153-98.669-77.417-131.763\n\t\t\tc-59.543-62.106-130.827-113.013-211.743-154.175C908.108,341.478,905.312,340.287,902.563,338.995L902.563,338.995z\n\t\t\tM599.927,358.478c6.846,0,13.638,0.274,20.361,0.732l-58.081,100.561c-81.514,16.526-142.676,85.88-142.676,168.897\n\t\t\tc0,20.854,3.841,40.819,10.913,59.325c0.008,0.021-0.008,0.053,0,0.074l-58.228,100.854\n\t\t\tc-34.551-44.823-54.932-100.229-54.932-160.182C317.285,479.484,443.808,358.477,599.927,358.478L599.927,358.478z M768.896,570.513\n\t\t\tL638.013,797.271c81.076-16.837,141.797-85.875,141.797-168.603C779.81,608.194,775.724,588.729,768.896,570.513L768.896,570.513z"\n\t\t\t/>\n</svg>\n',"not-visible-icon");return i.appendChild(n),i.onclick=t.changeVisibility.bind(this,e,s,n),i}};Je.VISIBLE_ICON_ID="visible-icon";let Ue=Je;class Ve{static createCautionText(){const t=document.createElement("a");return t.classList.add("insert-key-input-help-text"),t.innerText="Please exercise CAUTION when inserting your API key outside of deepchat.dev or localhost!!",t}static createHelpLink(t){const e=document.createElement("a");return e.classList.add("insert-key-input-help-text"),e.href=t,e.innerText="Find more info here",e.target="_blank",e}static createFailText(){const t=document.createElement("div");return t.id="insert-key-input-invalid-text",t.style.display="none",t}static createHelpTextContainer(t,e=!0){const i=document.createElement("div");i.id="insert-key-help-text-container";const s=document.createElement("div");s.id="insert-key-help-text-contents";const n=Ve.createFailText();if(s.appendChild(n),t){const e=Ve.createHelpLink(t);s.appendChild(e)}if(!0===e){const t=Ve.createCautionText();s.appendChild(t)}return i.appendChild(s),{helpTextContainerElement:i,failTextElement:n}}static onFail(t,e,i,s){t.classList.replace("insert-key-input-valid","insert-key-input-invalid"),i.innerText=s,i.style.display="block",e.innerText="Start",t.classList.remove("loading")}static onLoad(t,e){t.classList.add("loading"),e.innerHTML='<div id="loading-key"></div>'}static verifyKey(t,e,i){const s=t.value.trim();i.verifyKey(s,e)}static addVerificationEvents(t,e,i,s,n){const o={onSuccess:s,onFail:Ve.onFail.bind(this,t,e,i),onLoad:Ve.onLoad.bind(this,t,e)},r=Ve.verifyKey.bind(this,t,o,n);e.onclick=r,t.onkeydown=e=>{!t.classList.contains("loading")&&e.key===c.ENTER&&r()}}static createStartButton(){const t=document.createElement("div");return t.id="start-button",t.innerText="Start",t}static onInputFocus(t){t.target.classList.replace("insert-key-input-invalid","insert-key-input-valid")}static createInput(t){const e=document.createElement("div");e.id="insert-key-input-container";const i=document.createElement("input");return i.id="insert-key-input",i.placeholder=t||"API Key",i.type="password",i.classList.add("insert-key-input-valid"),i.onfocus=Ve.onInputFocus,e.appendChild(i),e}static createContents(t,e){var i;const s=document.createElement("div");s.id="insert-key-contents";const n=Ve.createInput(e.insertKeyPlaceholderText),o=n.children[0],r=Ue.create(o);n.appendChild(r),s.appendChild(n);const a=Ve.createStartButton(),{helpTextContainerElement:l,failTextElement:c}=Ve.createHelpTextContainer(e.keyHelpUrl,null==(i=e.deepChat._insertKeyViewStyles)?void 0:i.displayCautionText);return s.appendChild(a),s.appendChild(l),Ve.addVerificationEvents(o,a,c,t,e),s}static createElements(t,e){const i=document.createElement("div");i.id="insert-key-view";const s=Ve.createContents(t,e);return i.appendChild(s),i}static render(t,e,i){const s=Ve.createElements(e,i);t.replaceChildren(s)}}const He=class t{static enableButtons(e,i,s=0){window.webLLM?(e&&(e.disabled=!1),i&&(i.disabled=!1)):s<4*We.MODULE_SEARCH_LIMIT_S&&setTimeout((()=>t.enableButtons(e,i,s+1)),250)}static setUpInitial(e,i,s,n){const o=(null==i?void 0:i.downloadClass)||t.DOWNLOAD_BUTTON_CLASS,r=(null==i?void 0:i.uploadClass)||t.UPLOAD_BUTTON_CLASS,a=(null==i?void 0:i.fileInputClass)||t.FILE_INPUT_CLASS;return setTimeout((()=>{const i=null==s?void 0:s.getElementsByClassName(o)[0],n=null==s?void 0:s.getElementsByClassName(a)[0],l=null==s?void 0:s.getElementsByClassName(r)[0];i&&(i.onclick=()=>e()),n&&(n.onchange=()=>{n.files&&n.files.length>0&&e(n.files)}),l&&(l.onclick=()=>n.click()),(i||l)&&t.enableButtons(i,l)})),(null==i?void 0:i.initialHtml)||`<div>\n Download or upload a web model that will run entirely on your browser: <br/> \n <button disabled class="${o} deep-chat-button deep-chat-web-model-button">Download</button>\n ${n?"":`<input type="file" class="${a}" hidden multiple />\n <button disabled class="${r} deep-chat-button deep-chat-web-model-button">Upload</button>`}\n </div>`}static exportFile(t){const e=document.createElement("a");for(let i=0;i<t.length/4;i+=1)setTimeout((()=>{const s=4*i;for(let i=s;i<Math.min(s+4,t.length);i+=1){const s=URL.createObjectURL(t[i]);e.href=s,e.download=t[i].name,document.body.appendChild(e),e.click(),URL.revokeObjectURL(s)}}),500*i)}static setUpAfterLoad(e,i,s,n){const o=(null==i?void 0:i.exportFilesClass)||t.EXPORT_BUTTON_CLASS;return setTimeout((()=>{const i=null==s?void 0:s.getElementsByClassName(o)[0];i&&(i.onclick=()=>t.exportFile(e))})),(null==i?void 0:i.afterLoadHtml)||`<div>\n Model loaded successfully and has been cached for future requests.\n ${n?"":`<br/> <button style="margin-top: 5px" class="${o} deep-chat-button">Export</button>`}\n </div>`}};He.DOWNLOAD_BUTTON_CLASS="deep-chat-download-button",He.UPLOAD_BUTTON_CLASS="deep-chat-upload-button",He.FILE_INPUT_CLASS="deep-chat-file-input",He.EXPORT_BUTTON_CLASS="deep-chat-export-button";let Ke=He;const Ge={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},Ze=class t extends Le{constructor(e){var i,s;super(e),this._isModelLoaded=!1,this._isModelLoading=!1,this._loadOnFirstMessage=!1,this._webModel={},this.permittedErrorPrefixes=[t.MULTIPLE_MODELS_ERROR,t.WEB_LLM_NOT_FOUND_ERROR,t.GENERIC_ERROR],this._conversationHistory=[],"object"==typeof e.webModel&&(this._webModel=e.webModel),null!=(i=this._webModel.load)&&i.clearCache&&t.clearAllCache(),this.findModelInWindow(e),this.canSendMessage=this.canSubmit.bind(this),this._chatEl=null==(s=e.shadowRoot)?void 0:s.children[0],e.history&&t.setUpHistory(this._conversationHistory,e.history)}setUpMessages(t){this._messages=t,this._removeIntro=()=>{t.removeIntroductoryMessage(),this._removeIntro=void 0}}static setUpHistory(t,e){e.forEach(((i,s)=>{if(i.role===I.USER_ROLE&&i.text){const n=e[s+1];null!=n&&n.text&&n.role!==I.USER_ROLE&&t.push([i.text,n.text])}}))}findModelInWindow(e,i=0){var s;window.webLLM?this.configureInit(this.shouldAddIntroMessage(e.introMessage)):i>t.MODULE_SEARCH_LIMIT_S?(null==(s=this._messages)||s.addNewErrorMessage("service",t.WEB_LLM_NOT_FOUND_ERROR),console.error("The deep-chat-web-llm module has not been attached to the window object. Please see the following guide:"),console.error("https://deepchat.dev/examples/externalModules")):setTimeout((()=>this.findModelInWindow(e,i+1)),1e3)}shouldAddIntroMessage(t){var e;return!t&&this._webModel&&!1!==(null==(e=this._webModel.introMessage)?void 0:e.displayed)}scrollToTop(t){var e;!1!==(null==(e=this._webModel.introMessage)?void 0:e.autoScroll)&&setTimeout((()=>{var t,e;null!=(t=this._messages)&&t.elementRef&&x.scrollToTop(null==(e=this._messages)?void 0:e.elementRef)}),t)}getIntroMessage(t){if(!this.shouldAddIntroMessage(t)||!this._chatEl)return;const e=Ke.setUpInitial(this.init.bind(this),this._webModel.introMessage,this._chatEl,!!this._webModel.worker);return this.scrollToTop(1),{role:I.AI_ROLE,html:e,sendUpdate:!1}}async configureInit(t){const{load:e}=this._webModel;if(e){if(e.onInit)return void this.init();if(e.onMessage)return void(this._loadOnFirstMessage=!0)}t||this.init()}async init(t){var e;null==(e=this._messages)||e.removeError();const i=this.attemptToCreateChat();i&&await this.loadModel(i,t)}attemptToCreateChat(){var e;if(t.chat)return null==(e=this._messages)||e.addNewErrorMessage("service",t.MULTIPLE_MODELS_ERROR),void console.error(t.MULTIPLE_MODELS_ERROR);if(this._isModelLoaded||this._isModelLoading)return;const{worker:i}=this._webModel;return Ge.use_web_worker&&i?new window.webLLM.ChatWorkerClient(i):new window.webLLM.ChatModule}getConfig(){var e;let i=t.DEFAULT_MODEL;this._webModel.model&&(i=this._webModel.model);const s=JSON.parse(JSON.stringify(Ge));if(this._webModel.urls){const t=s.model_list.find((t=>t.local_id=i));t&&(this._webModel.urls.model&&(t.model_url=this._webModel.urls.model),this._webModel.urls.wasm&&(t.model_lib_url=this._webModel.urls.wasm))}return null!=(e=this._webModel.load)&&e.skipCache&&(s.use_cache=!1),{model:i,appConfig:s}}async loadModel(e,i){var s,n,o,r,a,l,c;this.scrollToTop(),t.chat=e,this._isModelLoading=!0;let h=!1===(null==(s=this._webModel.introMessage)?void 0:s.displayed);let u;t.chat.setInitProgressCallback((t=>{var e;null==(e=this._messages)||e.addNewMessage({html:`<div>${t.text}</div>`,overwrite:!0,sendUpdate:!1}),h&&(setTimeout((()=>{var t;return x.scrollToBottom(null==(t=this._messages)?void 0:t.elementRef)})),h=!1)}));try{const{model:e,appConfig:s}=this.getConfig(),n={};this._webModel.instruction&&(n.conv_config={system:this._webModel.instruction}),this._conversationHistory.length>0&&(n.conversation_history=this._conversationHistory),u=await t.chat.reload(e,n,s,i)}catch(t){return this.unloadChat(t)}if(null==(o=(n=this.deepChat)._validationHandler)||o.call(n),null!=(r=this._webModel.introMessage)&&r.removeAfterLoad)!1===this._webModel.introMessage.displayed?null==(l=this._messages)||l.removeLastMessage():null==(c=this._removeIntro)||c.call(this);else{const t=Ke.setUpAfterLoad(u,this._webModel.introMessage,this._chatEl,!!this._webModel.worker);null==(a=this._messages)||a.addNewMessage({html:t,overwrite:!0,sendUpdate:!1})}this._isModelLoaded=!0,this._isModelLoading=!1}async unloadChat(e){var i;null==(i=this._messages)||i.addNewErrorMessage("service",t.GENERIC_ERROR),console.error(e),this._isModelLoaded=!1,this._isModelLoading=!1,t.chat&&(await t.chat.unload(),t.chat=void 0)}async immediateResp(e,i,s){const n={text:await s.generate(i,void 0,0)},o=await t.processResponse(this.deepChat,e,n);o&&e.addNewMessage(o),this.completionsHandlers.onFinish()}async streamResp(e,i,s){this.streamHandlers.abortStream.abort=()=>{s.interruptGenerate()},this.streamHandlers.onOpen();const n=new ye(e);await s.generate(i,(async(i,s)=>{const o=await t.processResponse(this.deepChat,e,{text:s});o&&n.upsertStreamedMessage({text:o.text,overwrite:!0})})),n.finaliseStreamedMessage(),this.streamHandlers.onClose()}async generateRespByType(t,e,i,s){var n;try{i?await this.streamResp(t,e,s):await this.immediateResp(t,e,s)}catch(t){null==(n=this._messages)||n.addNewErrorMessage("service"),console.log(t)}}async generateResp(t,e,i){const s=e[e.length-1].text,{body:n,error:o}=await xe.processRequestInterceptor(this.deepChat,{body:{text:s}}),r=!!this.stream;try{if(o)xe.displayError(t,new Error(o)),(r?this.streamHandlers.onClose:this.completionsHandlers.onFinish)();else if(n&&n.text)this.generateRespByType(t,n.text,!!this.stream,i);else{const e=y.INVALID_MODEL_REQUEST({body:n},!1);console.error(e);const i=r?this.streamHandlers.onClose:this.completionsHandlers.onFinish;xe.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;const n=await(null==(s=t.responseInterceptor)?void 0:s.call(t,i))||i;if(n.error)xe.displayError(e,new Error(n.error));else{if(n&&n.text)return n;{const s=y.INVALID_MODEL_RESPONSE(i,!!t.responseInterceptor,n);xe.displayError(e,new Error(s))}}}isWebModel(){return!0}static clearAllCache(){t.clearCache("webllm/model"),t.clearCache("webllm/wasm")}static clearCache(t){caches.open(t).then((t=>{t.keys().then((e=>{e.forEach((e=>{t.delete(e)}))}))}))}};Ze.GENERIC_ERROR="Error, please check the [troubleshooting](https://deepchat.dev/docs/webModel#troubleshooting) section of documentation for help.",Ze.MULTIPLE_MODELS_ERROR="Cannot run multiple web models",Ze.WEB_LLM_NOT_FOUND_ERROR="WebLLM module not found",Ze.DEFAULT_MODEL="Llama-2-7b-chat-hf-q4f32_1",Ze.MODULE_SEARCH_LIMIT_S=5;let We=Ze;class Xe{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,s){const n=t;Array.isArray(n.error)&&"Error in `parameters`: field required"===n.error[0]?i(e):s(y.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api-inference.huggingface.co/models/gpt2",method:"POST",handleVerificationResult:Xe.handleVerificationResult}}}const Qe=class t extends Be{constructor(e,i,s,n,o,r){super(e,Xe.buildKeyVerificationDetails(),Xe.buildHeaders,o,r),this.insertKeyPlaceholderText="Hugging Face Token",this.keyHelpUrl="https://huggingface.co/settings/tokens",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Hugging Face</b></div>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>',this.permittedErrorPrefixes=["Authorization header"],this.url=`${t.URL_PREFIX}${s}`,this.textInputPlaceholderText=i,"object"==typeof n&&(n.model&&(this.url=`${t.URL_PREFIX}${n.model}`),n.options&&(this.rawBody.options=n.options),n.parameters&&(this.rawBody.parameters=n.parameters))}preprocessBody(t,e,i){const s=JSON.parse(JSON.stringify(t)),n=e[e.length-1].text;if(n)return s.options??(s.options={}),s.options.wait_for_model=!0,{inputs:n,...s}}async callServiceAPI(t,e,i){if(!this.connectSettings)throw new Error("Request settings have not been set up");const s=this.preprocessBody(this.rawBody,e,i);Ie.request(this,s,t)}};Qe.URL_PREFIX="https://api-inference.huggingface.co/models/";let Ye=Qe;class ti extends Ye{constructor(t,e,i,s,n,o){super(t,e,i,s,n,o),this.isTextInputDisabled=!0,this.canSendMessage=ti.canSendFile}static canSendFile(t,e){return!(null==e||!e[0])}preprocessBody(t,e,i){return i[0]}async callServiceAPI(t,e,i){if(!this.connectSettings)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");Ie.poll(this,i[0],t,!1)}}class ei extends ti{constructor(t){var e,i,s;super(t,"Attach an audio file","ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.audioClassification,null==(s=t.directConnection)?void 0:s.huggingFace,{audio:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.label)||""}}}class ii extends ti{constructor(t){var e,i,s;super(t,"Attach an image file","google/vit-base-patch16-224",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.imageClassification,null==(s=t.directConnection)?void 0:s.huggingFace,{images:{}})}async extractPollResultData(t){var e;if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.label)||""}}}const si="data:image/png;base64,";class ni{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,s){t.message?s(y.INVALID_KEY):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.stability.ai/v1/engines/list",method:"GET",handleVerificationResult:ni.handleVerificationResult}}}class oi extends Be{constructor(t,e,i,s,n){super(t,e,i,s,n),this.insertKeyPlaceholderText="Stability AI API Key",this.keyHelpUrl="https://platform.stability.ai/docs/getting-started/authentication",this.permittedErrorPrefixes=["Incorrect","invalid_"]}}class ri extends oi{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=null==i?void 0:i.stabilityAI;super(t,ni.buildKeyVerificationDetails(),ni.buildHeaders,s,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}),this.url="https://api.stability.ai/v1/generation/esrgan-v1-x2plus/image-to-image/upscale",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI</b></div>\n <div style="width: 100%; text-align: center; margin-left: -10px; margin-top: 5px"><b>Image to Image Upscale</b></div>\n <p>Upload an image to generate a new one with higher resolution.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageUpscale;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/image-to-image/upscale`),ri.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=ri.canSendFileMessage}static cleanConfig(t){delete t.engine_id}static canSendFileMessage(t,e){return!(null==e||!e[0])}createFormDataBody(t,e){const i=new FormData;return i.append("image",e),Object.keys(t).forEach((e=>{i.append(e,String(t[e]))})),i}async callServiceAPI(t,e,i){if(!this.connectSettings)throw new Error("Request settings have not been set up");if(!i)throw new Error("Image was not found");const s=this.createFormDataBody(this.rawBody,i[0]);xe.tempRemoveContentHeader(this.connectSettings,Ie.request.bind(this,this,s,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${si}${t.base64}`,type:"image"})))}}}class ai extends oi{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=null==i?void 0:i.stabilityAI;super(t,ni.buildKeyVerificationDetails(),ni.buildHeaders,s,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.url="https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/image-to-image/masking",this._maskSource="MASK_IMAGE_WHITE",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI</b></div>\n <div style="width: 100%; text-align: center; margin-left: -10px; margin-top: 5px"><b>Image to Image Masking</b></div>\n <p>Upload an image, its mask image to create a new one based on the changes you have described for the mask area.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageMasking;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/image-to-image/masking`),void 0!==n.weight&&null!==n.weight&&(this._imageWeight=n.weight),void 0!==n.mask_source&&null!==n.mask_source&&(this._maskSource=n.mask_source),ai.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=ai.canSendFileTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendFileTextMessage(t,e){return!(null==e||!e[0]||!t||""===t.trim())}createFormDataBody(t,e,i,s){const n=new FormData;return n.append("init_image",e),n.append("mask_source",String(this._maskSource)),n.append("mask_image",i),s&&""!==s&&n.append("text_prompts[0][text]",s),void 0!==this._imageWeight&&null!==this._imageWeight&&n.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach((e=>{n.append(e,String(t[e]))})),void 0===n.get("weight")&&n.append("weight",String(1)),n}async callServiceAPI(t,e,i){var s,n;if(!this.connectSettings)throw new Error("Request settings have not been set up");if(!i||!i[0]||!i[1])throw new Error("Image was not found");const o=null==(n=null==(s=e[e.length-1])?void 0:s.text)?void 0:n.trim(),r=this.createFormDataBody(this.rawBody,i[0],i[1],o);xe.tempRemoveContentHeader(this.connectSettings,Ie.request.bind(this,this,r,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${si}${t.base64}`,type:"image"})))}}}class li extends ti{constructor(t){var e,i,s;super(t,"Attach an audio file","facebook/wav2vec2-large-960h-lv60-self",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.audioSpeechRecognition,null==(s=t.directConnection)?void 0:s.huggingFace,{audio:{}})}async extractPollResultData(t){if(t.estimated_time)return{timeoutMS:1e3*(t.estimated_time+1)};if(t.error)throw t.error;return{text:t.text||""}}}class ci extends Ye{constructor(t){var e,i,s;super(t,"Once upon a time","gpt2",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.textGeneration,null==(s=t.directConnection)?void 0:s.huggingFace)}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.generated_text)||""}}}class hi extends Ye{constructor(t){var e,i,s;const n=null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.questionAnswer;super(t,"Ask a question","bert-large-uncased-whole-word-masking-finetuned-squad",n,null==(s=t.directConnection)?void 0:s.huggingFace),this.permittedErrorPrefixes=["Authorization header","Error in"],this.context=n.context}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return{inputs:{question:i,context:this.context,options:{wait_for_model:!0}}}}async extractResultData(t){if(t.error)throw t.error;return{text:t.answer||""}}}class ui extends Ye{constructor(t){var e,i,s;super(t,"Insert text to summarize","facebook/bart-large-cnn",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.summarization,null==(s=t.directConnection)?void 0:s.huggingFace)}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.summary_text)||""}}}class di extends Ye{constructor(t){var e,i,s;super(t,"Ask me anything!","facebook/blenderbot-400M-distill",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.conversation,null==(s=t.directConnection)?void 0:s.huggingFace),this.maxMessages??(this.maxMessages=-1)}processMessages(t){const e=t.filter((t=>t.text)),i=e[e.length-1].text,s=e.slice(0,e.length-1);if(!i)return;return{past_user_inputs:s.filter((t=>"user"===t.role)).map((t=>t.text)),generated_responses:s.filter((t=>"ai"===t.role)).map((t=>t.text)),mostRecentMessageText:i}}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=this.processMessages(e);if(s)return i.options??(i.options={}),i.options.wait_for_model=!0,{inputs:{past_user_inputs:s.past_user_inputs,generated_responses:s.generated_responses,text:s.mostRecentMessageText},...i}}async extractResultData(t){if(t.error)throw t.error;return{text:t.generated_text||""}}}class pi extends oi{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=i.stabilityAI;super(t,ni.buildKeyVerificationDetails(),ni.buildHeaders,s,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/image-to-image",this.textInputPlaceholderText="Describe image changes",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI: Image to Image</b></div>\n <p>Upload an image to create a new one with the changes you have described.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=i.stabilityAI)?void 0:e.imageToImage;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/text-to-image`),void 0!==n.weight&&null!==n.weight&&(this._imageWeight=n.weight),pi.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=pi.canSendFileTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendFileTextMessage(t,e){return!(null==e||!e[0]||!t||""===t.trim())}createFormDataBody(t,e,i){const s=new FormData;return s.append("init_image",e),i&&""!==i&&s.append("text_prompts[0][text]",i),void 0!==this._imageWeight&&null!==this._imageWeight&&s.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach((e=>{s.append(e,String(t[e]))})),void 0===s.get("weight")&&s.append("weight",String(1)),s}async callServiceAPI(t,e,i){var s,n;if(!this.connectSettings)throw new Error("Request settings have not been set up");if(!i)throw new Error("Image was not found");const o=null==(n=null==(s=e[e.length-1])?void 0:s.text)?void 0:n.trim(),r=this.createFormDataBody(this.rawBody,i[0],o);xe.tempRemoveContentHeader(this.connectSettings,Ie.request.bind(this,this,r,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${si}${t.base64}`,type:"image"})))}}}class mi extends Ye{constructor(t){var e,i,s;super(t,"Insert text to translate","Helsinki-NLP/opus-tatoeba-en-ja",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.translation,null==(s=t.directConnection)?void 0:s.huggingFace)}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.translation_text)||""}}}class vi extends oi{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=i.stabilityAI;super(t,ni.buildKeyVerificationDetails(),ni.buildHeaders,s),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-6/text-to-image",this.textInputPlaceholderText="Describe an image",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Stability AI: Text to Image</b></div>\n <p>Insert text to generate an image.</p>\n <p>Click <a href="https://platform.stability.ai/">here</a> for more info.</p>';const n=null==(e=i.stabilityAI)?void 0:e.textToImage;"object"==typeof n&&(n.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${n.engine_id}/text-to-image`),void 0!==n.weight&&null!==n.weight&&(this._imageWeight=n.weight),vi.cleanConfig(n),Object.assign(this.rawBody,n)),this.canSendMessage=vi.canSendTextMessage}static cleanConfig(t){delete t.engine_id,delete t.weight}static canSendTextMessage(t){return!(!t||""===t.trim())}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s={text:e};return this._imageWeight&&(s.weight=this._imageWeight),i.text_prompts=[s],i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e[e.length-1].text);Ie.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${si}${t.base64}`,type:"image"})))}}}class fi extends Ye{constructor(t){var e,i,s;super(t,"The goal of life is [MASK].","bert-base-uncased",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.fillMask,null==(s=t.directConnection)?void 0:s.huggingFace),this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Hugging Face</b></div>\n <p>Insert a sentence with the word [MASK] and the model will try to fill it for you. E.g. I want [MASK].</p>\n <p>First message may take an extented amount of time to complete as the model needs to be initialized.</p>',this.permittedErrorPrefixes=["Authorization header","No mask_token"]}async extractResultData(t){var e;if(t.error)throw t.error;return{text:(null==(e=t[0])?void 0:e.sequence)||""}}}class gi{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,s){const n=t;n.error?"invalid_api_key"===n.error.code?s(y.INVALID_KEY):s(y.CONNECTION_FAILED):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.openai.com/v1/models",method:"GET",handleVerificationResult:gi.handleVerificationResult}}static async directFetch(t,e,i,s=!0){t.connectSettings.method=i;const n=await xe.fetch(t,t.connectSettings.headers,s,e).then((t=>xe.processResponseByType(t)));if(n.error)throw n.error.message;return n}}const bi=class t{static async storeFiles(t,e,i,s){const n=t.connectSettings.headers;if(!n)return;t.url=s;const o=n[xe.CONTENT_TYPE];delete n[xe.CONTENT_TYPE];const r=i.map((async e=>{const i=new FormData;return i.append("purpose","assistants"),i.append("file",e),new Promise((e=>{e(gi.directFetch(t,i,"POST",!1))}))}));try{const t=(await Promise.all(r)).map((t=>({id:t.id,name:t.filename})));return n[xe.CONTENT_TYPE]=o,t}catch(i){throw n[xe.CONTENT_TYPE]=o,xe.displayError(e,i),t.completionsHandlers.onFinish(),i}}static getType(t,e){const{path:i}=t[e];return!i||i.endsWith("png")?"image":"any"}static async getFiles(e,i,s,n){const o=i.map((({fileId:t})=>(e.url=`${s}${t}${n}`,new Promise((t=>{t(gi.directFetch(e,void 0,"GET",!1))}))))),r=(await Promise.all(o)).map(((e,s)=>new Promise((n=>{const o=new FileReader;o.readAsDataURL(e),o.onload=e=>{n({src:e.target.result,name:i[s].name,type:t.getType(i,s)})}}))));return await Promise.all(r)}static getFileName(t){const e=t.split("/");return e[e.length-1]}static async getFilesAndNewText(e,i,s,n,o){var r,a;let l;const{getFilesPrefix:c,getFilesPostfix:h}=s;return i.length>0&&(l=await t.getFiles(e,i,c,h),null!=(r=null==o?void 0:o.text)&&r.value&&l.forEach(((t,e)=>{var s;if(!t.src)return;const n=i[e].path;null!=(s=null==o?void 0:o.text)&&s.value&&n&&(o.text.value=o.text.value.replace(n,t.src))}))),null!=(a=null==o?void 0:o.text)&&a.value?{text:o.text.value,role:n}:{files:l,role:n}}static getFileDetails(e,i){var s;const n=[];return null!=(s=null==i?void 0:i.text)&&s.value&&e.content.forEach((e=>{var i,s;null==(s=null==(i=e.text)?void 0:i.annotations)||s.forEach((e=>{var i;e.text&&e.text.startsWith("sandbox:")&&null!=(i=e.file_path)&&i.file_id&&n.push({path:e.text,fileId:e.file_path.file_id,name:t.getFileName(e.text)})}))})),null!=i&&i.image_file&&n.push({fileId:i.image_file.file_id}),n}static async getFilesAndText(e,i,s,n){const o=t.getFileDetails(i,n);return await t.getFilesAndNewText(e,o,s,i.role,n)}static parseResult(t,e){let i=[];if(e)i=t.data;else for(let e=0;e<t.data.length;e+=1){const s=t.data[e];if("assistant"!==s.role)break;i.push(s)}return i.reverse()}static parseMessages(e,i,s){const n=[];return i.forEach((async i=>{i.content.filter((t=>!!t.text||!!t.image_file)).sort((t=>t.text?-1:t.image_file?1:0)).forEach((async o=>{n.push(t.getFilesAndText(e,i,s,o))}))})),Promise.all(n)}static async processStreamMessages(e,i,s){return t.parseMessages(e,[{content:i,role:"assistant"}],s)}static async processAPIMessages(e,i,s,n){const o=t.parseResult(i,s);return t.parseMessages(e,o,n)}};bi.FILES_WITH_TEXT_ERROR="content with type `text` must have `text` values",bi.FUNCTION_TOOL_RESP_ERROR="Response must contain an array of strings for each individual function/tool_call, see https://deepchat.dev/docs/directConnection/OpenAI/#assistant-functions.";let yi=bi;const wi=class t extends Be{constructor(t,e,i,s){if(super(t,gi.buildKeyVerificationDetails(),gi.buildHeaders,s),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.url="",this.permittedErrorPrefixes=["Incorrect","Please send text",Ne.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);const{function_handler:n}=e;n&&(this._functionHandler=n),this.filesToolType=e.files_tool_type}this.maxMessages=1,this.isSSEStream=!(!this.stream||"object"==typeof this.stream&&this.stream.simulation)}async fetchHistoryFunc(){setTimeout((()=>this.deepChat.disableSubmitButton()),2);try{const t=await this.getThreadMessages(this.sessionId,!0);return this.deepChat.disableSubmitButton(!1),t}catch{return[{error:"Failed to fetch history"}]}}static processImageMessage(t,e){const i=null==e?void 0:e.filter((t=>de.isImageFileExtension(t.name))).map((t=>({type:"image_file",image_file:{file_id:t.id}})));if(i&&i.length>0)return t.text&&t.text.length>0&&i.push({type:"text",text:t.text}),{content:i,role:"user"}}static processAttachmentsMessage(t,e,i){return{attachments:e.map((t=>({tools:[{type:i}],file_id:t.id}))),content:[{type:"text",text:t.text}],role:"user"}}processMessage(e,i){const s=this.totalMessagesMaxCharLength||-1,n=qe.getCharacterLimitMessages(e,s)[0];if(i&&i.length>0){let e=this.filesToolType;if("function"==typeof this.filesToolType){const t=this.filesToolType(i.map((({name:t})=>t)));"code_interpreter"===t||"file_search"===t||"images"===t?e=t:(console.error(`Tool type "${t}" is not valid`),console.error('Expected "code_interpreter" or "file_search" or "images". Going to default to "images"'))}if("file_search"===e)return t.processAttachmentsMessage(n,i,"file_search");if("code_interpreter"===e)return t.processAttachmentsMessage(n,i,"code_interpreter");if(i.find((({name:t})=>!de.isImageFileExtension(t))))console.error("The uploaded files contained a non-image file"),console.error('Make sure only images can be uploaded or define a "code_interpreter" or "file_search" value in the "files_tool_type" property'),console.warn('Make sure your existing assistant supports these "tools" or specify them in the "new_assistant" property');else{const e=t.processImageMessage(n,i);if(e)return e}}return{content:n.text||"",role:"user"}}createNewThreadMessages(t,e,i){const s=JSON.parse(JSON.stringify(t)),n=this.processMessage(e,i);return s.thread={messages:[n]},s}callService(t,e,i){if(this.messages=t,this.sessionId){this.url=`${this.urlSegments.threadsPrefix}/${this.sessionId}/messages${this.urlSegments.createMessagePostfix}`;const s=this.processMessage(e,i);Ie.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):Ie.request(this,s,t)}}async callServiceAPI(t,e,i){var s;if(this.waitingForStreamResponse=!1,!this.connectSettings)throw new Error("Request settings have not been set up");(s=this.rawBody).assistant_id??(s.assistant_id=this.config.assistant_id||await this.createNewAssistant()),this.searchedForThreadId||this.searchPreviousMessagesForThreadId(t.messages);const n=i?await yi.storeFiles(this,t,i,this.urlSegments.storeFiles):void 0;this.connectSettings.method="POST",this.callService(t,e,n)}async createNewAssistant(){try{this.url=this.urlSegments.newAssistantUrl;const t=await gi.directFetch(this,JSON.parse(JSON.stringify(this.newAssistantDetails)),"POST");return this.config.assistant_id=t.id,this.config.assistant_id}catch(t){console.error(t),console.error("Failed to create a new assistant")}}searchPreviousMessagesForThreadId(t){const e=t.find((t=>t._sessionId));e&&(this.sessionId=e._sessionId),this.searchedForThreadId=!0}async extractResultData(t){var e;if(this.waitingForStreamResponse||this.isSSEStream&&this.sessionId)return await this.handleStream(t);if(t.error)throw t.error.message.startsWith(yi.FILES_WITH_TEXT_ERROR)?Error("Please send text with your file(s)"):t.error.message;await this.assignThreadAndRun(t);const i=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs/${this.run_id}${this.urlSegments.threadsPosfix}`,s={method:"GET",headers:null==(e=this.connectSettings)?void 0:e.headers};return Ie.executePollRequest(this,i,s,this.messages),{makingAnotherRequest:!0}}async assignThreadAndRun(t){if(this.sessionId){this.url=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs${this.urlSegments.threadsPosfix}`;const t=await gi.directFetch(this,JSON.parse(JSON.stringify(this.rawBody)),"POST");this.run_id=t.id}else this.sessionId=t.thread_id,this.run_id=t.id,this.messages&&this.messages.messages.length>0&&(this.messages.messages[this.messages.messages.length-1]._sessionId=this.sessionId)}async getThreadMessages(t,e=!1){var i,s;this.url=`${this.urlSegments.threadsPrefix}/${t}/messages?${this.urlSegments.listMessagesPostfix}`;let n=await gi.directFetch(this,{},"GET");return!e&&this.deepChat.responseInterceptor&&(n=await(null==(s=(i=this.deepChat).responseInterceptor)?void 0:s.call(i,n))),yi.processAPIMessages(this,n,e,this.urlSegments)}async extractPollResultData(e){var i;const{status:s,required_action:n}=e;if("queued"===s||"in_progress"===s)return{timeoutMS:t.POLLING_TIMEOUT_MS};if("completed"===s&&this.messages){const t=await this.getThreadMessages(e.thread_id),{text:i,files:s}=t.shift();return setTimeout((()=>{t.forEach((t=>this.deepChat.addMessage(t)))})),{text:i,_sessionId:this.sessionId,files:s}}const o=null==(i=null==n?void 0:n.submit_tool_outputs)?void 0:i.tool_calls;if("requires_action"===s&&o)return await this.handleTools(o);throw Error(`Thread run status: ${s}`)}async handleTools(e){if(!this._functionHandler)throw Error("Please define the `function_handler` property inside the [openAI](https://deepchat.dev/docs/directConnection/openAI#Assistant) object.");const i=e.map((t=>({name:t.function.name,arguments:t.function.arguments}))),s=await this._functionHandler(i);if(!Array.isArray(s)||e.length!==s.length)throw Error(yi.FUNCTION_TOOL_RESP_ERROR);const n=await Promise.all(s);if(n.find((t=>"string"!=typeof t)))throw Error(yi.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 gi.directFetch(this,{tool_outputs:o},"POST"),{timeoutMS:t.POLLING_TIMEOUT_MS}}async handleStream(t){var e,i;const s=null==(i=null==(e=t.required_action)?void 0:e.submit_tool_outputs)?void 0:i.tool_calls;if("requires_action"===t.status&&s)return this.run_id=t.id,await this.handleTools(s);if(this.waitingForStreamResponse)return this.parseStreamResult(t);if(this.isSSEStream&&this.sessionId){this.url=`${this.urlSegments.threadsPrefix}/${this.sessionId}/runs${this.urlSegments.threadsPosfix}`;const t=JSON.parse(JSON.stringify(this.rawBody));this.createStreamRun(t)}return{makingAnotherRequest:!0}}async parseStreamResult(t){var e,i,s,n,o;if(t.content&&t.content.length>0&&this.messages){const s=t.content.find((t=>t.text));if(null!=(e=null==s?void 0:s.text)&&e.annotations&&s.text.annotations.length>0){const e=t.content.find((t=>!!t.text))||t.content[0],s=yi.getFilesAndText.bind(this,this,{role:"assistant",content:t.content},this.urlSegments,e);return null==(i=this.messageStream)||i.endStreamAfterFileDownloaded(this.messages,s),{text:""}}}if(null!=(s=t.delta)&&s.content){if(t.delta.content.length>1){const e=t.delta.content.find((t=>t.text));if(null!=(n=null==e?void 0:e.text)&&n.annotations&&0===e.text.annotations.length){const e=await yi.processStreamMessages(this,t.delta.content,this.urlSegments);return{text:e[0].text,files:e[1].files}}}return{text:null==(o=t.delta.content[0].text)?void 0:o.value}}return!this.sessionId&&t.thread_id&&(this.sessionId=t.thread_id),{makingAnotherRequest:!0}}async createStreamRun(t){t.stream=!0,this.waitingForStreamResponse=!0,this.messageStream=await Me.request(this,t,this.messages,!0,!0)}};wi.POLLING_TIMEOUT_MS=800;let xi=wi;const ki=class t extends xi{constructor(e){var i,s,n;const o=JSON.parse(JSON.stringify(e.directConnection)),r=o.openAI;super(e,null==(i=o.openAI)?void 0:i.assistant,t.URL_SEGMENTS,r),(s=this.connectSettings).headers??(s.headers={}),(n=this.connectSettings.headers)["OpenAI-Beta"]??(n["OpenAI-Beta"]="assistants=v2"),this.shouldFetchHistory&&this.sessionId&&(this.fetchHistory=this.fetchHistoryFunc.bind(this))}};ki.URL_SEGMENTS={threadsPrefix:"https://api.openai.com/v1/threads",threadsPosfix:"",newAssistantUrl:"https://api.openai.com/v1/assistants",createMessagePostfix:"",listMessagesPostfix:"order=desc",storeFiles:"https://api.openai.com/v1/files",getFilesPrefix:"https://api.openai.com/v1/files/",getFilesPostfix:"/content"};let _i=ki;class Si{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json",accept:"application/json"}}static handleVerificationResult(t,e,i,s){var n;null!=(n=t.message)&&n.includes("invalid request: prompt must be at least 1 token long")?i(e):s(y.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api.cohere.ai/v1/generate",method:"POST",handleVerificationResult:Si.handleVerificationResult,body:JSON.stringify({prompt:""})}}}class Ti extends Be{constructor(t,e,i,s,n){super(t,Si.buildKeyVerificationDetails(),Si.buildHeaders,n),this.insertKeyPlaceholderText="Cohere API Key",this.keyHelpUrl="https://dashboard.cohere.ai/api-keys",this.permittedErrorPrefixes=["invalid"],this.url=e,this.textInputPlaceholderText=i,s&&"object"==typeof s&&Object.assign(this.rawBody,s)}}class Ai extends Ti{constructor(t){var e,i,s;super(t,"https://api.cohere.ai/v1/generate","Once upon a time",null==(i=null==(e=t.directConnection)?void 0:e.cohere)?void 0:i.textGeneration,null==(s=t.directConnection)?void 0:s.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e[e.length-1].text;if(s)return{prompt:s,...i}}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Ie.request(this,i,t)}async extractResultData(t){var e;if(t.message)throw t.message;return{text:(null==(e=t.generations)?void 0:e[0].text)||""}}}const Mi=class{static buildHeaders(t){return{"api-key":t,"Content-Type":"application/json"}}static buildKeyVerificationDetails(t){return{url:`${t.endpoint}/openai/models?api-version=${t.version}`,method:"GET",handleVerificationResult:gi.handleVerificationResult}}static validateURLDetails(t){const{endpoint:e,version:i,deploymentId:s}=t;return e&&i&&s}};Mi.URL_DETAILS_ERROR_MESSAGE="Please define the Azure URL Details. [More Information](https://deepchat.dev/docs/directConnection/Azure)";let Oi=Mi;const ji=class t extends xi{constructor(e){var i,s,n,o,r;const a=JSON.parse(JSON.stringify(e.directConnection)),l=a.azure,c=null==(i=a.azure)?void 0:i.openAI,h=(null==c?void 0:c.urlDetails)||{},u=`${null==(s=null==c?void 0:c.urlDetails)?void 0:s.endpoint}/openai/`,d=`?api-version=${null==(n=null==c?void 0:c.urlDetails)?void 0:n.version}`,p={threadsPrefix:`${u}${t.THREAD_RESOURCE}`,threadsPosfix:d,newAssistantUrl:`${u}${t.NEW_ASSISTANT_RESOURCE}${d}`,createMessagePostfix:`?order=desc&api-version=${null==(o=null==c?void 0:c.urlDetails)?void 0:o.version}`,listMessagesPostfix:d,storeFiles:`${u}files${d}`,getFilesPrefix:`${u}files/`,getFilesPostfix:`/content${d}`};super(e,null==c?void 0:c.assistant,p,l),this.permittedErrorPrefixes=[Oi.URL_DETAILS_ERROR_MESSAGE],this.isTextInputDisabled=!1,Oi.validateURLDetails(h)?(r=this.connectSettings).headers??(r.headers={}):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout((()=>{e.addMessage({error:Oi.URL_DETAILS_ERROR_MESSAGE})})))}};ji.THREAD_RESOURCE="threads",ji.NEW_ASSISTANT_RESOURCE="assistants";let Ci=ji;class Ei extends Ti{constructor(t){var e,i,s;super(t,"https://api.cohere.ai/v1/summarize","Insert text to summarize",null==(i=null==(e=t.directConnection)?void 0:e.cohere)?void 0:i.summarization,null==(s=t.directConnection)?void 0:s.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e[e.length-1].text;if(s)return{text:s,...i}}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Ie.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.summary||""}}}const Ii=class t extends Be{constructor(e){var i,s,n;const o=JSON.parse(JSON.stringify(e.directConnection)),r=null==o?void 0:o.openAI;super(e,gi.buildKeyVerificationDetails(),gi.buildHeaders,r),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/audio/speech",this.permittedErrorPrefixes=["Invalid"],this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI : Text To Speech</b></div>\n <p>Generate an audio file based on your text input.</p>\n <p>Click <a href="https://platform.openai.com/docs/guides/text-to-speech">here</a> for more information.</p>';const a=null==(i=null==o?void 0:o.openAI)?void 0:i.textToSpeech;"object"==typeof a&&Object.assign(this.rawBody,a),(s=this.rawBody).model??(s.model=t.DEFAULT_MODEL),(n=this.rawBody).voice??(n.voice=t.DEFAULT_VOIDE),this.textInputPlaceholderText="Insert text to generate audio",this.rawBody.response_format="mp3"}preprocessBody(t,e){var i,s;const n=JSON.parse(JSON.stringify(t)),o=null==(s=null==(i=e[e.length-1])?void 0:i.text)?void 0:s.trim();return o&&""!==o&&(n.input=o),n}async callServiceAPI(t,e){var i;if(null==(i=this.connectSettings)||!i.headers)throw new Error("Request settings have not been set up");this.url=this.connectSettings.url||this.url;const s=this.preprocessBody(this.rawBody,e);Ie.request(this,s,t)}async extractResultData(t){if(t instanceof Blob)return new Promise((e=>{const i=new FileReader;i.readAsDataURL(t),i.onload=t=>{e({files:[{src:t.target.result,type:"audio"}]})}}));if(t.error)throw t.error.message;return{error:"error"}}};Ii.DEFAULT_MODEL="tts-1",Ii.DEFAULT_VOIDE="alloy";let Pi=Ii;const Ni=class t extends Be{constructor(e){var i,s;const n=JSON.parse(JSON.stringify(e.directConnection)),o=null==n?void 0:n.openAI;super(e,gi.buildKeyVerificationDetails(),gi.buildHeaders,o,{audio:{}}),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI : Speech To Text</b></div>\n <p><b>Upload an audio file</b> to transcribe it into text. You can optionally provide text to guide the audio\n processing.\n <p>Click <a href="https://platform.openai.com/docs/guides/speech-to-text">here</a> for more info.</p>',this.url="",this.permittedErrorPrefixes=["Invalid"],this.textInputPlaceholderText="Upload an audio file",this._service_url=t.AUDIO_TRANSCRIPTIONS_URL;const r=null==(i=null==n?void 0:n.openAI)?void 0:i.audio;"object"==typeof r&&(this.processConfig(r),t.cleanConfig(r),Object.assign(this.rawBody,r)),(s=this.rawBody).model??(s.model=t.DEFAULT_MODEL),this.rawBody.response_format="json",this.canSendMessage=t.canSendFileMessage}static canSendFileMessage(t,e){return!(null==e||!e[0])}processConfig(e){null!=e&&e.type&&"translation"===e.type&&(this._service_url=t.AUDIO_TRANSLATIONS_URL,delete e.language)}static cleanConfig(t){delete t.type}static createFormDataBody(t,e){const i=new FormData;return i.append("file",e),Object.keys(t).forEach((e=>{i.append(e,String(t[e]))})),i}preprocessBody(t,e){var i,s;const n=JSON.parse(JSON.stringify(t)),o=null==(s=null==(i=e[e.length-1])?void 0:i.text)?void 0:s.trim();return o&&""!==o&&(n.prompt=o),n}async callServiceAPI(e,i,s){var n;if(null==(n=this.connectSettings)||!n.headers)throw new Error("Request settings have not been set up");if(null==s||!s[0])throw new Error("No file was added");this.url=this.connectSettings.url||this._service_url;const o=this.preprocessBody(this.rawBody,i),r=t.createFormDataBody(o,s[0]);xe.tempRemoveContentHeader(this.connectSettings,Ie.request.bind(this,this,r,e),!1)}async extractResultData(t){if(t.error)throw t.error.message;return{text:t.text}}};Ni.AUDIO_TRANSCRIPTIONS_URL="https://api.openai.com/v1/audio/transcriptions",Ni.AUDIO_TRANSLATIONS_URL="https://api.openai.com/v1/audio/translations",Ni.DEFAULT_MODEL="whisper-1";let qi=Ni;class Ri{static buildTextToSpeechHeaders(t,e){return{"Ocp-Apim-Subscription-Key":e,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":t}}static buildSpeechToTextHeaders(t){return{"Ocp-Apim-Subscription-Key":t,Accept:"application/json"}}static handleSpeechVerificationResult(t,e,i,s){t.error?s(y.INVALID_KEY):i(e)}static buildSpeechKeyVerificationDetails(t){return{url:`https://${t}.api.cognitive.microsoft.com/sts/v1.0/issuetoken`,method:"POST",createHeaders:t=>({"Ocp-Apim-Subscription-Key":`${t}`}),handleVerificationResult:Ri.handleSpeechVerificationResult}}static buildSummarizationHeader(t){return{"Ocp-Apim-Subscription-Key":t,"Content-Type":"application/json"}}static handleLanguageVerificationResult(t,e,i,s){var n;"401"===(null==(n=t.error)?void 0:n.code)?s(y.INVALID_KEY):i(e)}static buildLanguageKeyVerificationDetails(t){return{url:`${t}/language/analyze-text/jobs?api-version=2022-10-01-preview`,method:"POST",createHeaders:t=>({"Ocp-Apim-Subscription-Key":`${t}`}),handleVerificationResult:Ri.handleLanguageVerificationResult}}static handleTranslationVerificationResult(t,e,i,s){t.json().then((t=>{Array.isArray(t)||401e3!==t.error.code?i(e):s(y.INVALID_KEY)}))}static buildTranslationKeyVerificationDetails(t){return{url:"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es",method:"POST",createHeaders:e=>Ri.buildTranslationHeaders(t,e),handleVerificationResult:Ri.handleTranslationVerificationResult}}static buildTranslationHeaders(t,e){const i={"Ocp-Apim-Subscription-Key":e,"Content-Type":"application/json"};return t&&(i["Ocp-Apim-Subscription-Region"]=t),i}}class Li extends Be{constructor(t,e,i,s,n){super(t,Ri.buildLanguageKeyVerificationDetails(i),e,s,n),this.insertKeyPlaceholderText="Azure Language Subscription Key",this.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",this.permittedErrorPrefixes=["Access"]}}class Bi extends Li{constructor(t){var e,i,s,n;const o=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.summarization,r=null==(s=t.directConnection)?void 0:s.azure;super(t,Ri.buildSummarizationHeader,o.endpoint,r),this.url="",this.textInputPlaceholderText="Insert text to summarize",(n=this.rawBody).language??(n.language="en"),Object.assign(this.rawBody,o),this.url=`${o.endpoint}/language/analyze-text/jobs?api-version=2022-10-01-preview`}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return{analysisInput:{documents:[{id:"1",language:t.language,text:i}]},tasks:[{kind:"ExtractiveSummarization"}]}}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Ie.request(this,i,t),this.messages=t}async extractResultData(t){var e;if(t.error)throw t.error.message;if(this.messages&&this.completionsHandlers){const i=t.headers.get("operation-location"),s={method:"GET",headers:null==(e=this.connectSettings)?void 0:e.headers};Ie.executePollRequest(this,i,s,this.messages)}return{makingAnotherRequest:!0}}async extractPollResultData(t){if(t.error)throw t.error;if("running"===t.status)return{timeoutMS:2e3};if(t.errors.length>0)throw t.errors[0];if(t.tasks.items[0].results.errors.length>0)throw t.tasks.items[0].results.errors[0];let e="";for(const i of t.tasks.items[0].results.documents[0].sentences)e+=i.text;return{text:e||""}}}class Fi{static async poll(t,e){const i={authorization:t,"content-type":"application/json"},s=`https://api.assemblyai.com/v2/transcript/${(await(await fetch("https://api.assemblyai.com/v2/transcript",{method:"POST",body:JSON.stringify({audio_url:e}),headers:i})).json()).id}`;let n;for(;!n;){const t=await(await fetch(s,{headers:i})).json();if("completed"===t.status)n=t;else{if("error"===t.status)throw new Error(`Transcription failed: ${t.error}`);await new Promise((t=>setTimeout(t,3e3)))}}return n}static buildHeaders(t){return{Authorization:t,"Content-Type":"application/octet-stream"}}static handleVerificationResult(t,e,i,s){const n=t;n.error?"invalid_api_key"===n.error.code?s(y.INVALID_KEY):s(y.CONNECTION_FAILED):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.assemblyai.com/v2/upload",method:"POST",handleVerificationResult:Fi.handleVerificationResult}}}class zi extends Be{constructor(t){var e;const i=null==(e=t.directConnection)?void 0:e.assemblyAI;super(t,Fi.buildKeyVerificationDetails(),Fi.buildHeaders,i,{audio:{}}),this.insertKeyPlaceholderText="AssemblyAI API Key",this.keyHelpUrl="https://www.assemblyai.com/app/account",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>AssemblyAI Audio</b></div>\n <p><b>Upload an audio file</b> to transcribe it into text.\n <p>\n Click <a href="https://www.assemblyai.com/docs/Guides/transcribing_an_audio_file#get-started">here</a> for more info.\n </p>',this.url="https://api.assemblyai.com/v2/upload",this.isTextInputDisabled=!0,this.textInputPlaceholderText="Upload an audio file",this.permittedErrorPrefixes=["Authentication","Invalid"],this.canSendMessage=zi.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])}async callServiceAPI(t,e,i){var s;if(null==(s=this.connectSettings)||!s.headers)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");Ie.request(this,i[0],t,!1)}async extractResultData(t){var e,i;if(t.error)throw t.error;const s=null==(i=null==(e=this.connectSettings)?void 0:e.headers)?void 0:i.Authorization;return{text:(await Fi.poll(s,t.upload_url)).text}}}class Di extends Be{constructor(t,e,i,s,n){super(t,Ri.buildSpeechKeyVerificationDetails(i),e,s,n),this.insertKeyPlaceholderText="Azure Speech Subscription Key",this.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal"}}const $i=class t extends Di{constructor(e){var i,s,n,o,r,a;const l=null==(s=null==(i=e.directConnection)?void 0:i.azure)?void 0:s.textToSpeech,c=null==(n=e.directConnection)?void 0:n.azure;super(e,Ri.buildTextToSpeechHeaders.bind({},(null==l?void 0:l.outputFormat)||"audio-16khz-128kbitrate-mono-mp3"),l.region,c),this.introPanelMarkUp=`\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Azure Text To Speech</b></div>\n <p>Insert text to synthesize it to audio.\n <p>\n Click <a href="${t.HELP_LINK}">here</a> for more info.\n </p>`,this.url="",Object.assign(this.rawBody,l),(o=this.rawBody).lang??(o.lang="en-US"),(r=this.rawBody).name??(r.name="en-US-JennyNeural"),(a=this.rawBody).gender??(a.gender="Female"),this.url=`https://${l.region}.tts.speech.microsoft.com/cognitiveservices/v1`}preprocessBody(t,e){const i=e[e.length-1].text;if(i)return`<speak version='1.0' xml:lang='${t.lang}'>\n <voice xml:lang='${t.lang}' xml:gender='${t.gender}' name='${t.name}'>\n ${i}\n </voice>\n </speak>`}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Ie.request(this,i,t,!1)}async extractResultData(t){return new Promise((e=>{const i=new FileReader;i.readAsDataURL(t),i.onload=t=>{e({files:[{src:t.target.result,type:"audio"}]})}}))}};$i.HELP_LINK="https://learn.microsoft.com/en-GB/azure/cognitive-services/speech-service/get-started-text-to-speech?tabs=windows%2Cterminal&pivots=programming-language-rest";let Ji=$i;const Ui=class t extends Di{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;super(e,Ri.buildSpeechToTextHeaders,o.region,r,{audio:{files:{acceptedFormats:".wav,.ogg"}}}),this.introPanelMarkUp=`\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>Azure Speech To Text</b></div>\n <p><b>Upload a .wav or .ogg audio file</b> to transcribe it into text.\n <p>\n Click <a href="${t.HELP_LINK}">here</a> for more info.\n </p>`,this.url="",this.isTextInputDisabled=!0,this.textInputPlaceholderText="Upload an audio file",this.canSendMessage=t.canFileSendMessage;const a=o.lang||"en-US";this.url=`https://${o.region}.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=${a}&format=detailed`,this.recordAudio=void 0}static canFileSendMessage(t,e){return!(null==e||!e[0])}async callServiceAPI(t,e,i){var s,n;if(null==(s=this.connectSettings)||!s.headers)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");null!=(n=this.connectSettings)&&n.headers&&(this.connectSettings.headers["Content-Type"]=i[0].name.toLocaleLowerCase().endsWith(".wav")?"audio/wav; codecs=audio/pcm; samplerate=16000":"audio/ogg; codecs=opus"),Ie.request(this,i[0],t,!1)}async extractResultData(t){if(t.error)throw t.error;return{text:t.DisplayText||""}}};Ui.HELP_LINK="https://learn.microsoft.com/en-GB/azure/cognitive-services/speech-service/get-started-text-to-speech?tabs=windows%2Cterminal&pivots=programming-language-rest";let Vi=Ui;class Hi extends Be{constructor(t){var e,i,s;const n=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.translation,o=null==(s=t.directConnection)?void 0:s.azure;super(t,Ri.buildTranslationKeyVerificationDetails(n.region),Ri.buildTranslationHeaders.bind({},null==n?void 0:n.region),o),this.insertKeyPlaceholderText="Azure Translate Subscription Key",this.keyHelpUrl="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",this.url="",this.url=`https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=${n.language||"es"}`}preprocessBody(t){const e=t[t.length-1].text;if(e)return[{Text:e}]}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(e);Ie.request(this,i,t)}async extractResultData(t){var e;if(Array.isArray(t))return{text:(null==(e=t[0].translations)?void 0:e[0].text)||""};throw t.error}}class Ki extends Be{constructor(t,e,i,s,n){var o,r,a,l;const c=JSON.parse(JSON.stringify(t.directConnection));super(t,e||gi.buildKeyVerificationDetails(),i||gi.buildHeaders,s||c.openAI),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/chat/completions",this.permittedErrorPrefixes=["Incorrect"],this.asyncCallInProgress=!1,this._systemMessage=Ki.generateSystemMessage("You are a helpful assistant.");const h=n||(null==(o=c.openAI)?void 0:o.chat);if("object"==typeof h){h.system_prompt&&(this._systemMessage=Ki.generateSystemMessage(h.system_prompt));const{function_handler:e}=null==(a=null==(r=t.directConnection)?void 0:r.openAI)?void 0:a.chat;e&&(this._functionHandler=e),this.cleanConfig(h),Object.assign(this.rawBody,h)}this.maxMessages??(this.maxMessages=-1),(l=this.rawBody).model??(l.model="gpt-4o")}static generateSystemMessage(t){return{role:"system",content:t}}cleanConfig(t){delete t.system_prompt,delete t.function_handler}static getContent(t){if(t.files&&t.files.length>0){const e=t.files.map((t=>({type:"image_url",image_url:{url:t.src}})));return t.text&&t.text.trim().length>0&&e.unshift({type:"text",text:t.text}),e}return t.text}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=qe.getCharacterLimitMessages(e,this.totalMessagesMaxCharLength?this.totalMessagesMaxCharLength-this._systemMessage.content.length:-1).map((t=>({content:Ki.getContent(t),role:t.role===I.USER_ROLE?"user":"assistant"})));return e.find((t=>t.files&&t.files.length>0))&&(i.max_tokens??(i.max_tokens=300)),i.messages=[this._systemMessage,...s],i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e),s=this.stream;s&&("object"!=typeof s||!s.simulation)||i.stream?(i.stream=!0,Me.request(this,i,t)):Ie.request(this,i,t)}async extractResultData(t,e,i){var s,n,o,r;if(t.error)throw t.error.message;return null!=(n=null==(s=t.choices)?void 0:s[0])&&n.delta?this.extractStreamResult(t.choices[0],e,i):null!=(r=null==(o=t.choices)?void 0:o[0])&&r.message?t.choices[0].message.tool_calls?this.handleTools(t.choices[0].message,e,i):{text:t.choices[0].message.content}:{text:""}}async extractStreamResult(t,e,i){const{delta:s,finish_reason:n}=t;if("tool_calls"===n){this.asyncCallInProgress=!0;const t={tool_calls:this._streamToolCalls};return this._streamToolCalls=void 0,this.handleTools(t,e,i)}return null!=s&&s.tool_calls&&(this._streamToolCalls?s.tool_calls.forEach(((t,e)=>{this._streamToolCalls&&(this._streamToolCalls[e].function.arguments+=t.function.arguments)})):this._streamToolCalls=s.tool_calls),{text:(null==s?void 0:s.content)||""}}async handleTools(t,e,i){var s,n,o,r,a;if(!(t.tool_calls&&e&&i&&this._functionHandler))throw Error("Please define the `function_handler` property inside the [openAI](https://deepchat.dev/docs/directConnection/openAI#Chat) object.");const l=JSON.parse(JSON.stringify(i)),c=t.tool_calls.map((t=>({name:t.function.name,arguments:t.function.arguments}))),h=await(null==(s=this._functionHandler)?void 0:s.call(this,c));if(h.text){const t={text:h.text};return await(null==(o=(n=this.deepChat).responseInterceptor)?void 0:o.call(n,t))||t}if(l.messages.push({tool_calls:t.tool_calls,role:"assistant",content:null}),Array.isArray(h)&&!h.find((t=>"string"!=typeof t))||c.length===h.length){h.forEach(((e,i)=>{var s;const n=null==(s=t.tool_calls)?void 0:s[i];null==l||l.messages.push({role:"tool",tool_call_id:null==n?void 0:n.id,name:null==n?void 0:n.function.name,content:e.response})})),delete l.tools,delete l.tool_choice,delete l.stream;try{let t=await(null==e?void 0:e(l).then((t=>xe.processResponseByType(t))));if(t=await(null==(a=(r=this.deepChat).responseInterceptor)?void 0:a.call(r,t))||t,t.error)throw t.error.message;return{text:t.choices[0].message.content||""}}catch(t){throw this.asyncCallInProgress=!1,t}}throw Error("Response object must either be {response: string}[] for each individual function or {text: string} for a direct response, see https://deepchat.dev/docs/directConnection/OpenAI#FunctionHandler.")}}class Gi extends Ki{constructor(t){var e,i,s,n;const o=JSON.parse(JSON.stringify(t.directConnection)),r=o.azure,a=(null==(i=null==(e=o.azure)?void 0:e.openAI)?void 0:i.urlDetails)||{},l=null==(n=null==(s=o.azure)?void 0:s.openAI)?void 0:n.chat;super(t,Oi.buildKeyVerificationDetails(a),Oi.buildHeaders,r,l),this.permittedErrorPrefixes=[Oi.URL_DETAILS_ERROR_MESSAGE],this.isTextInputDisabled=!1,Oi.validateURLDetails(a)?this.url=Gi.buildURL(a):(this.isTextInputDisabled=!0,this.canSendMessage=()=>!1,setTimeout((()=>{t.addMessage({error:Oi.URL_DETAILS_ERROR_MESSAGE})})))}static buildURL(t){const{endpoint:e,deploymentId:i,version:s}=t;return`${e}/openai/deployments/${i}/completions?api-version=${s}`}}const Zi=class t extends Be{constructor(e){var i;const{directConnection:s}=e,n=null==s?void 0:s.openAI;super(e,gi.buildKeyVerificationDetails(),gi.buildHeaders,n,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.insertKeyPlaceholderText="OpenAI API Key",this.keyHelpUrl="https://platform.openai.com/account/api-keys",this.introPanelMarkUp='\n <div style="width: 100%; text-align: center; margin-left: -10px"><b>OpenAI DALL·E</b></div>\n <p><b>Insert text</b> to generate an image.</p>\n <p><b>Upload 1</b> PNG image to generate its variation and optionally insert text to specify the change.</p>\n <p><b>Upload 2</b> PNG images where the second is a copy of the first with a transparent area where the edit should\n take place and text to specify the edit.</p>\n <p>Click <a href="https://platform.openai.com/docs/guides/images/introduction">here</a> for more info.</p>',this.url="",this.permittedErrorPrefixes=["Incorrect","Invalid input image"];const o=null==(i=null==s?void 0:s.openAI)?void 0:i.images;if(this.camera){const t="object"==typeof o&&o.size?Number.parseInt(o.size):1024;this.camera.files={dimensions:{width:t,height:t}}}"object"==typeof o&&Object.assign(this.rawBody,o),this.canSendMessage=t.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])||!(!t||""===t.trim())}static createFormDataBody(t,e,i){const s=new FormData;return s.append("image",e),i&&s.append("mask",i),Object.keys(t).forEach((e=>{s.append(e,String(t[e]))})),s}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t));return e&&""!==e&&(i.prompt=e),i}callApiWithImage(e,i,s){var n,o;let r;const a=null==(o=null==(n=i[i.length-1])?void 0:n.text)?void 0:o.trim();if(s[1]||a&&""!==a){this.url=t.IMAGE_EDIT_URL;const e=this.preprocessBody(this.rawBody,a);r=t.createFormDataBody(e,s[0],s[1])}else this.url=t.IMAGE_VARIATIONS_URL,r=t.createFormDataBody(this.rawBody,s[0]);xe.tempRemoveContentHeader(this.connectSettings,Ie.request.bind(this,this,r,e),!1)}async callServiceAPI(e,i,s){var n;if(null==(n=this.connectSettings)||!n.headers)throw new Error("Request settings have not been set up");if(null!=s&&s[0])this.callApiWithImage(e,i,s);else{if(!this.connectSettings)throw new Error("Request settings have not been set up");this.url=t.IMAGE_GENERATION_URL;const s=this.preprocessBody(this.rawBody,i[i.length-1].text);Ie.request(this,s,e)}}async extractResultData(t){if(t.error)throw t.error.message;return{files:t.data.map((t=>t.url?{src:t.url,type:"image"}:{src:`${si}${t.b64_json}`,type:"image"}))}}};Zi.IMAGE_GENERATION_URL="https://api.openai.com/v1/images/generations",Zi.IMAGE_VARIATIONS_URL="https://api.openai.com/v1/images/variations",Zi.IMAGE_EDIT_URL="https://api.openai.com/v1/images/edits";let Wi=Zi;class Xi extends Ti{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),s=null==(e=i.cohere)?void 0:e.chat;super(t,"https://api.cohere.ai/v1/chat","Ask me anything!",s,i.cohere),"object"==typeof s&&Object.assign(this.rawBody,s),this.maxMessages??(this.maxMessages=-1)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e.filter((t=>t.text));return i.query=s[s.length-1].text,i.chat_history=s.slice(0,s.length-1).map((t=>({text:t.text,user_name:"ai"===t.role?"CHATBOT":"USER"}))),i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Ie.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.text}}}class Qi{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json",accept:"application/json"}}static handleVerificationResult(t,e,i,s){var n;null!=(n=t.message)&&n.includes("invalid request: prompt must be at least 1 token long")?i(e):s(y.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api.mistral.ai/v1/models",method:"GET",handleVerificationResult:Qi.handleVerificationResult}}}class Yi extends Be{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)).mistral;super(t,Qi.buildKeyVerificationDetails(),Qi.buildHeaders,i),this.insertKeyPlaceholderText="Mistral API Key",this.keyHelpUrl="https://console.mistral.ai/api-keys/",this.url="https://api.mistral.ai/v1/chat/completions",this.permittedErrorPrefixes=["invalid"],i&&(this.cleanConfig(i),Object.assign(this.rawBody,i)),this.maxMessages??(this.maxMessages=-1),(e=this.rawBody).model??(e.model="open-mistral-7b")}cleanConfig(t){delete t.key}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),s=e.filter((t=>t.text));return i.messages=s.slice(0,s.length-1).map((t=>({text:t.text,user_name:"ai"===t.role?"system":"user"}))),i}async callServiceAPI(t,e){if(!this.connectSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);Ie.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.text}}}class ts{static create(t){const{directConnection:e,connect:i,demo:s,webModel:n}=t;if(n)return new We(t);if(e){if(e.openAI)return e.openAI.images?new Wi(t):e.openAI.speechToText?new qi(t):e.openAI.textToSpeech?new Pi(t):e.openAI.assistant?new _i(t):new Ki(t);if(e.assemblyAI)return new zi(t);if(e.cohere)return e.cohere.textGeneration?new Ai(t):e.cohere.summarization?new Ei(t):new Xi(t);if(e.huggingFace)return e.huggingFace.textGeneration?new ci(t):e.huggingFace.summarization?new ui(t):e.huggingFace.translation?new mi(t):e.huggingFace.fillMask?new fi(t):e.huggingFace.questionAnswer?new hi(t):e.huggingFace.audioSpeechRecognition?new li(t):e.huggingFace.audioClassification?new ei(t):e.huggingFace.imageClassification?new ii(t):new di(t);if(e.azure){if(e.azure.openAI){if(e.azure.openAI.chat)return new Gi(t);if(e.azure.openAI.assistant)return new Ci(t)}if(e.azure.speechToText)return new Vi(t);if(e.azure.textToSpeech)return new Ji(t);if(e.azure.summarization)return new Bi(t);if(e.azure.translation)return new Hi(t)}if(e.stabilityAI)return e.stabilityAI.imageToImage?new pi(t):e.stabilityAI.imageToImageUpscale?new ri(t):e.stabilityAI.imageToImageMasking?new ai(t):new vi(t);if(e.mistral)return new Yi(t)}return!i||s&&i.stream?new Le(t,void 0,s||!0):new Le(t)}}const es=class{};es.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 is=es;function ss(t){return function(e,i){Object.defineProperty(e,i,{});const s=e.constructor,n=i.toLocaleLowerCase();s._attributes_[n]=is.attibutes[t],s._attributeToProperty_[n]=i}}class ns{constructor(t,e,i){this._isDisplayed=!1,t?(this._elementRef=this.createIntroPanelWithChild(t,i),this._isDisplayed=!0):e&&(this._elementRef=this.createInternalIntroPanel(e,i),this._isDisplayed=!0)}static createIntroPanel(t){const e=document.createElement("div");return e.classList.add("intro-panel"),Object.assign(e.style,t),e}createIntroPanelWithChild(t,e){const i=ns.createIntroPanel(e);return"none"===t.style.display&&(t.style.display="block"),i.appendChild(t),i}createInternalIntroPanel(t,e){const i=ns.createIntroPanel(e);return i.id="internal-intro-panel",i.innerHTML=t,i}hide(){this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="none",this._isDisplayed=!1)}display(){!this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="",this._isDisplayed=!0)}}class os{static getText(t,e){var i;if(!(t.directConnection||t.connect||t.webModel||t.demo))return"Connect to any API using the [connect](https://deepchat.dev/docs/connect#connect-1) property or a popular service via [directConnection](https://deepchat.dev/docs/directConnection/#directConnection).\n Host AI entirely on your browser via a [webModel](https://deepchat.dev/docs/webModel).\n To get started checkout the [Start](https://deepchat.dev/start) page and live code [examples](https://deepchat.dev/examples/frameworks).\n To remove this message set the [demo](https://deepchat.dev/docs/demo#demo) property to true.";if(t.directConnection){if(!e.isDirectConnection())return"Please define a valid service inside\n the [directConnection](https://deepchat.dev/docs/directConnection/#directConnection) object.";const s=null==(i=t.directConnection.openAI)?void 0:i.chat;if("object"==typeof s&&s.tools&&!s.function_handler)return"Please define the `function_handler` property inside the openAI [chat](https://deepchat.dev/docs/directConnection/openAI#Chat) object."}else if(t.connect&&!t.connect.url&&!t.connect.handler)return t.demo?t.connect.stream?null:"When [demo](https://deepchat.dev/docs/demo) mode is enabled - the [connect](https://deepchat.dev/docs/connect#connect-1) object can only accept the [stream](https://deepchat.dev/docs/connect#Stream) property.":"Please define a `url` or a `handler` property inside the [connect](https://deepchat.dev/docs/connect#connect-1) object.";return null}}class rs{static createImage(t,e,i){const s=new Image;return s.src=t.src,i||de.scrollDownOnImageLoad(s.src,e),de.processContent("image",s,s.src,t.name)}static async addNewImageMessage(t,e,i,s){const n=rs.createImage(e,t.elementRef,s),o=t.createNewMessageElement("",i);o.bubbleElement.appendChild(n),o.bubbleElement.classList.add("image-message"),de.addMessage(t,o,"image",i,s)}static createAudioElement(t,e){const i=document.createElement("audio");return i.src=t.src,i.classList.add("audio-player"),i.controls=!0,l.IS_SAFARI&&(i.classList.add("audio-player-safari"),i.classList.add(e===I.USER_ROLE?"audio-player-safari-right":"audio-player-safari-left")),i}static addNewAudioMessage(t,e,i,s){const n=rs.createAudioElement(e,i),o=t.createMessageElementsOnOrientation("",i,s);o.bubbleElement.appendChild(n),o.bubbleElement.classList.add("audio-message"),de.addMessage(t,o,"audio",i,s)}static createAnyFile(t){const e=document.createElement("div");e.classList.add("any-file-message-contents");const i=document.createElement("div");i.classList.add("any-file-message-icon-container");const s=$e.createSVGElement('<?xml version="1.0" encoding="iso-8859-1"?>\n<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" \n\t viewBox="50 30 420 450" xml:space="preserve">\n<g filter="brightness(0) saturate(100%) invert(16%) sepia(0%) saturate(1942%) hue-rotate(215deg) brightness(99%) contrast(93%)">\n\t<g>\n\t\t<path d="M447.933,103.629c-0.034-3.076-1.224-6.09-3.485-8.352L352.683,3.511c-0.004-0.004-0.007-0.005-0.011-0.008\n\t\t\tC350.505,1.338,347.511,0,344.206,0H89.278C75.361,0,64.04,11.32,64.04,25.237v461.525c0,13.916,11.32,25.237,25.237,25.237\n\t\t\th333.444c13.916,0,25.237-11.32,25.237-25.237V103.753C447.96,103.709,447.937,103.672,447.933,103.629z M356.194,40.931\n\t\t\tl50.834,50.834h-49.572c-0.695,0-1.262-0.567-1.262-1.262V40.931z M423.983,486.763c0,0.695-0.566,1.261-1.261,1.261H89.278\n\t\t\tc-0.695,0-1.261-0.566-1.261-1.261V25.237c0-0.695,0.566-1.261,1.261-1.261h242.94v66.527c0,13.916,11.322,25.239,25.239,25.239\n\t\t\th66.527V486.763z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,164.014H149.912c-6.62,0-11.988,5.367-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,169.381,368.707,164.014,362.088,164.014z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,236.353H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.62,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.368,11.988-11.988C374.076,241.721,368.707,236.353,362.088,236.353z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M362.088,308.691H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988h212.175\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C374.076,314.06,368.707,308.691,362.088,308.691z"/>\n\t</g>\n</g>\n<g>\n\t<g>\n\t\t<path d="M256,381.031H149.912c-6.62,0-11.988,5.368-11.988,11.988c0,6.621,5.368,11.988,11.988,11.988H256\n\t\t\tc6.62,0,11.988-5.367,11.988-11.988C267.988,386.398,262.62,381.031,256,381.031z"/>\n\t</g>\n</g>\n</svg>');s.classList.add("any-file-message-icon"),i.appendChild(s);const n=document.createElement("div");return n.classList.add("any-file-message-text"),n.textContent=t.name||de.DEFAULT_FILE_NAME,e.appendChild(i),e.appendChild(n),de.processContent("any",e,t.src,n.textContent)}static addNewAnyFileMessage(t,e,i,s){const n=t.createMessageElementsOnOrientation("",i,s),o=rs.createAnyFile(e);n.bubbleElement.classList.add("any-file-message-bubble"),n.bubbleElement.appendChild(o),de.addMessage(t,n,"file",i,s)}static addMessages(t,e,i,s){e.forEach((e=>{e.ref&&(e=de.removeFileRef(e)),de.isAudioFile(e)?rs.addNewAudioMessage(t,e,i,s):de.isImageFile(e)?rs.addNewImageMessage(t,e,i,s):rs.addNewAnyFileMessage(t,e,i,s)}))}}class as extends ge{constructor(t,e,i){var s,n;super(t);const{permittedErrorPrefixes:o,introPanelMarkUp:r,demo:a}=e;this._errorMessageOverrides=null==(s=t.errorMessages)?void 0:s.overrides,this._onClearMessages=pe.onClearMessages.bind(this,t),this._onError=pe.onError.bind(this,t),this._displayLoadingMessage=as.getDisplayLoadingMessage(t,e),this._permittedErrorPrefixes=o,this.addSetupMessageIfNeeded(t,e)||this.populateIntroPanel(i,r,t.introPanelStyle),this.addIntroductoryMessages(t,e),new Ne(t,this,e),this._displayServiceErrorMessages=null==(n=t.errorMessages)?void 0:n.displayServiceErrorMessages,t.getMessages=()=>JSON.parse(JSON.stringify(this.messages)),t.clearMessages=this.clearMessages.bind(this,e),t.refreshMessages=this.refreshTextMessages.bind(this),t.scrollToBottom=x.scrollToBottom.bind(this,this.elementRef),t.addMessage=(t,e)=>{this.addAnyMessage({...t,sendUpdate:!!e},!e)},e.isWebModel()&&e.setUpMessages(this),a&&this.prepareDemo(a),t.textToSpeech&&_.processConfig(t.textToSpeech,(t=>{this.textToSpeech=t}))}static getDisplayLoadingMessage(t,e){return!e.websocket&&(t.displayLoadingBubble??!0)}prepareDemo(t){"object"==typeof t&&(t.response&&(this.customDemoResponse=t.response),t.displayErrors&&(t.displayErrors.default&&this.addNewErrorMessage("",""),t.displayErrors.service&&this.addNewErrorMessage("service",""),t.displayErrors.speechToText&&this.addNewErrorMessage("speechToText","")),t.displayLoadingBubble&&this.addLoadingMessage())}addSetupMessageIfNeeded(t,e){const i=os.getText(t,e);if(i){const t=this.createAndAppendNewMessageElement(i,I.AI_ROLE);this.applyCustomStyles(t,I.AI_ROLE,!1)}return!!i}addIntroductoryMessages(t,e){null!=t&&t.shadowRoot&&(this._introMessage=t.introMessage);let i=this._introMessage;null!=e&&e.isWebModel()&&(i??(i=e.getIntroMessage(i))),i&&(Array.isArray(i)?i.forEach(((t,e)=>{0!==e&&I.hideRoleElements(this.messageElementRefs,!!this._avatars,!!this._names),this.addIntroductoryMessage(t)})):this.addIntroductoryMessage(i))}addIntroductoryMessage(t){var e;let i;null!=t&&t.text?i=this.createAndAppendNewMessageElement(t.text,I.AI_ROLE):null!=t&&t.html&&(i=B.add(this,t.html,I.AI_ROLE,this.messageElementRefs)),i&&(this.applyCustomStyles(i,I.AI_ROLE,!1,null==(e=this.messageStyles)?void 0:e.intro),i.outerContainer.classList.add("deep-chat-intro"))}removeIntroductoryMessage(){const t=this.messageElementRefs[0];t.outerContainer.classList.contains("deep-chat-intro")&&(t.outerContainer.remove(),this.messageElementRefs.shift())}addAnyMessage(t,e=!1,i=!1){return t.error?this.addNewErrorMessage("service",t.error):this.addNewMessage(t,e,i)}addNewMessage(t,e=!1,i=!1){const s=as.createMessageContent(t),n={status:t.overwrite};if(!t.ignoreText&&void 0!==s.text&&null!==t.text&&(this.addNewTextMessage(s.text,s.role,n,i),!e&&this.textToSpeech&&s.role!==I.USER_ROLE&&_.speak(s.text,this.textToSpeech)),s.files&&Array.isArray(s.files)&&rs.addMessages(this,s.files,s.role,i),void 0!==s.html&&null!==s.html){const t=B.add(this,s.html,s.role,this.messageElementRefs,n,i);R.isElementTemporary(t)&&delete s.html}return this.isValidMessageContent(s)&&!i&&this.updateStateOnMessage(s,t.overwrite,t.sendUpdate,e),s}isValidMessageContent(t){return t.text||t.html||t.files&&t.files.length>0}updateStateOnMessage(t,e,i=!0,s=!1){e||this.messages.push(t),i&&this.sendClientUpdate(t,s)}removeMessageOnError(){const t=this.messageElementRefs[this.messageElementRefs.length-1],e=null==t?void 0:t.bubbleElement;(null!=e&&e.classList.contains(ye.MESSAGE_CLASS)&&""===e.textContent||as.isTemporaryElement(t))&&this.removeLastMessage()}addNewErrorMessage(t,e,i=!1){var s,n,o,r,a;this.removeMessageOnError();const l=this.getPermittedMessage(e)||(null==(s=this._errorMessageOverrides)?void 0:s[t])||(null==(n=this._errorMessageOverrides)?void 0:n.default)||"Error, please try again.",c=this.createMessageElementsOnOrientation(l,"",i);I.hideRoleElements(this.messageElementRefs,!!this._avatars,!!this._names);const{bubbleElement:h,outerContainer:u}=c;h.classList.add("error-message-text"),this.renderText(h,l);const d=fe.extractParticularSharedStyles(["fontSize","fontFamily"],null==(o=this.messageStyles)?void 0:o.default);fe.applyCustomStylesToElements(c,!1,d),fe.applyCustomStylesToElements(c,!1,null==(r=this.messageStyles)?void 0:r.error),i||this.elementRef.appendChild(u),this.textToSpeech&&_.speak(l,this.textToSpeech),null==(a=this._onError)||a.call(this,l)}static checkPermittedErrorPrefixes(t,e){for(let i=0;i<t.length;i+=1)if(e.startsWith(t[i]))return e}static extractErrorMessages(t){return Array.isArray(t)?t:t instanceof Error?[t.message]:"string"==typeof t?[t]:"object"==typeof t&&t.error?[t.error]:[]}getPermittedMessage(t){if(t){const e=as.extractErrorMessages(t);for(let t=0;t<e.length;t+=1){const i=e[t];if("string"==typeof i){if(this._displayServiceErrorMessages)return i;if(this._permittedErrorPrefixes){const t=as.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,i);if(t)return t}}}}}removeError(){this.isLastMessageError()&&I.getLastMessageElement(this.elementRef).remove()}addDefaultLoadingMessage(){const t=this.createMessageElements("",I.AI_ROLE),{bubbleElement:e}=t;t.bubbleElement.classList.add(A.DOTS_CONTAINER_CLASS);const i=document.createElement("div");return i.classList.add("loading-message-dots"),e.appendChild(i),A.setDots(e,this.messageStyles),t}addLoadingMessage(){var t,e,i,s,n,o;if(!this._displayLoadingMessage)return;const r=null==(i=null==(e=null==(t=this.messageStyles)?void 0:t.loading)?void 0:e.message)?void 0:i.html,a=r?B.createElements(this,r,I.AI_ROLE,!1):this.addDefaultLoadingMessage();this.elementRef.appendChild(a.outerContainer),a.bubbleElement.classList.add(A.BUBBLE_CLASS),this.applyCustomStyles(a,I.AI_ROLE,!1,null==(o=null==(n=null==(s=this.messageStyles)?void 0:s.loading)?void 0:n.message)?void 0:o.styles),x.scrollToBottom(this.elementRef)}populateIntroPanel(t,e,i){(t||e)&&(this._introPanel=new ns(t,e,i),this._introPanel._elementRef&&(L.apply(this,this._introPanel._elementRef),this.elementRef.appendChild(this._introPanel._elementRef)))}async addMultipleFiles(t){return Promise.all((t||[]).map((t=>new Promise((e=>{if(t.type&&"any"!==t.type){const i=new FileReader;i.readAsDataURL(t.file),i.onload=()=>{e({src:i.result,type:t.type,ref:t.file})}}else{const i=t.file.name||de.DEFAULT_FILE_NAME;e({name:i,type:"any",ref:t.file})}})))))}static isActiveElement(t){return t.contains(A.BUBBLE_CLASS)||t.contains(ve.CLASS)||t.contains(ye.MESSAGE_CLASS)}clearMessages(t,e){var i,s;const n=[],o=[];this.messageElementRefs.forEach((t=>{const e=t.bubbleElement.classList;as.isActiveElement(e)?n.push(t):t.outerContainer.remove()})),this.textElementsToText.forEach((t=>{const e=t[0].bubbleElement.classList;as.isActiveElement(e)&&o.push(t)})),Array.from(this.elementRef.children).forEach((t=>{var e;const i=null==(e=t.children[0])?void 0:e.children[0];null!=i&&i.classList.contains("error-message-text")&&t.remove()})),this.messageElementRefs=n,this.messages.splice(0,this.messages.length),!1!==e&&(null!=(i=this._introPanel)&&i._elementRef&&this._introPanel.display(),this.addIntroductoryMessages()),this.textElementsToText=o,null==(s=this._onClearMessages)||s.call(this),delete t.sessionId}}const ls=class t{static adjustInputPadding(t,e){e["inside-left"].length>0&&t.classList.add("text-input-inner-left-adjustment"),e["inside-right"].length>0&&t.classList.add("text-input-inner-right-adjustment")}static adjustForOutsideButton(e,i,s){0===s["outside-right"].length&&s["outside-left"].length>0?(e[0].classList.add(t.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS)):0===s["outside-left"].length&&s["outside-right"].length>0&&(e[3].classList.add(t.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS))}static adjustOutsideSubmit(e,i,s){if(!(s["inside-left"].length>0||s["inside-right"].length>0)){if(0===s["outside-right"].length&&s["outside-left"].length>0)return e[0].classList.add(t.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),s["outside-left"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")));if(0===s["outside-left"].length&&s["outside-right"].length>0)return e[3].classList.add(t.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),s["outside-right"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")))}}static set(e,i,s,n){!!t.adjustOutsideSubmit(i,s,n)||t.adjustForOutsideButton(i,s,n),t.adjustInputPadding(e,n)}};ls.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS="text-input-container-left-adjustment",ls.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS="text-input-container-right-adjustment",ls.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS="text-input-container-left-small-adjustment",ls.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS="text-input-container-right-small-adjustment";let cs=ls;class hs{static create(){return Array.from({length:4}).map(((t,e)=>{const i=document.createElement("div");return i.classList.add("input-button-container"),(0===e||3===e)&&i.classList.add("outer-button-container"),(1===e||2===e)&&i.classList.add("inner-button-container"),i}))}static add(t,e){t.insertBefore(e[1],t.firstChild),t.insertBefore(e[0],t.firstChild),t.appendChild(e[2]),t.appendChild(e[3])}static getContainerIndex(t){return"outside-left"===t?0:"inside-left"===t?1:"inside-right"===t?2:3}static addButton(t,e,i){e.classList.add(i);const s=hs.getContainerIndex(i);t[s].appendChild(e),3===s&&e.classList.add("outside-right")}}const us=["camera","gifs","images","audio","mixedFiles","submit","microphone"];class ds{static createTextElement(t){const e=document.createElement("div");return e.classList.add("text-button"),e.innerText=t,e}static createElement(t,e){return e?ds.createTextElement(t):$e.createSVGElement(t)}static createCustomElement(t,e){var i,s,n,o;const r=null==e?void 0:e[t];return null!=(i=null==r?void 0:r.svg)&&i.content?ds.createElement(null==(s=null==r?void 0:r.svg)?void 0:s.content,!1):null!=(n=null==r?void 0:r.text)&&n.content?ds.createElement(null==(o=null==r?void 0:r.text)?void 0:o.content,!0):void 0}static processElement(t,e){null!=e&&e.classList.contains("text-button")||t.classList.add("input-button-svg")}static createSpecificStateElement(t,e,i){let s;return i&&(s=ds.createCustomElement(e,i)),ds.processElement(t,s),s}static createInnerElement(t,e,i,s,n=!1){var o,r;return(!n||null!=(r=null==(o=null==s?void 0:s[i])?void 0:o.svg)&&r.content)&&ds.createSpecificStateElement(t,i,s)||e}}class ps{static unsetAllCSS(t,e){var s,n;e.container&&i.unsetAllCSSMouseStates(t,e.container),null!=(s=e.svg)&&s.styles&&i.unsetAllCSSMouseStates(t.children[0],e.svg.styles),null!=(n=e.text)&&n.styles&&i.unsetAllCSSMouseStates(t.children[0],e.text.styles)}static unsetActionCSS(t,e){var s,n;e.container&&i.unsetActivityCSSMouseStates(t,e.container),null!=(s=e.svg)&&s.styles&&i.unsetActivityCSSMouseStates(t.children[0],e.svg.styles),null!=(n=e.text)&&n.styles&&i.unsetActivityCSSMouseStates(t.children[0],e.text.styles)}static setElementsCSS(t,e,i){var s,n,o,r,a;Object.assign(t.style,null==(s=e.container)?void 0:s[i]),Object.assign(t.children[0].style,null==(o=null==(n=e.svg)?void 0:n.styles)?void 0:o[i]),Object.assign(t.children[0].style,null==(a=null==(r=e.text)?void 0:r.styles)?void 0:a[i])}static setElementCssUpToState(t,e,i){ps.setElementsCSS(t,e,"default"),"default"!==i&&(ps.setElementsCSS(t,e,"hover"),"hover"!==i&&ps.setElementsCSS(t,e,"click"))}}class ms{constructor(t,e,i,s){this._mouseState={state:"default"},this.elementRef=t,this._customStyles=i,this.position=e,this.dropupText=s}buttonMouseLeave(t){this._mouseState.state="default",t&&(ps.unsetAllCSS(this.elementRef,t),ps.setElementsCSS(this.elementRef,t,"default"))}buttonMouseEnter(t){this._mouseState.state="hover",t&&ps.setElementsCSS(this.elementRef,t,"hover")}buttonMouseUp(t){t&&ps.unsetActionCSS(this.elementRef,t),this.buttonMouseEnter(t)}buttonMouseDown(t){this._mouseState.state="click",t&&ps.setElementsCSS(this.elementRef,t,"click")}setEvents(t){this.elementRef.onmousedown=this.buttonMouseDown.bind(this,t),this.elementRef.onmouseup=this.buttonMouseUp.bind(this,t),this.elementRef.onmouseenter=this.buttonMouseEnter.bind(this,t),this.elementRef.onmouseleave=this.buttonMouseLeave.bind(this,t)}unsetCustomStateStyles(t){if(this._customStyles)for(let e=0;e<t.length;e+=1){const i=t[e],s=i&&this._customStyles[i];s&&ps.unsetActionCSS(this.elementRef,s)}}reapplyStateStyle(t,e){if(!this._customStyles)return;e&&this.unsetCustomStateStyles(e);const i=this._customStyles[t];i&&ps.setElementCssUpToState(this.elementRef,i,this._mouseState.state),this.setEvents(i)}}class vs{static focusItemWhenOnEdge(t,e){const i=e?t.children[0]:t.children[t.children.length-1];vs.focusSiblingItem(i,t,e,!0)}static focusSiblingItem(t,e,i,s=!1){const n=s?t:t[i?"nextSibling":"previousSibling"];n?(t.dispatchEvent(new MouseEvent("mouseleave")),n.dispatchEvent(new MouseEvent("mouseenter"))):(t.dispatchEvent(new MouseEvent("mouseleave")),vs.focusItemWhenOnEdge(e,i))}}class fs{static addItemEvents(t,e,i,s){P.add(e,s),e.addEventListener("click",(()=>{i.click()})),e.addEventListener("mouseenter",(e=>{t.highlightedItem=e.target})),e.addEventListener("mouseleave",(()=>{t.highlightedItem=void 0}))}static createItemText(t,e){const i=document.createElement("div");return Object.assign(i.style,e),i.classList.add("dropup-menu-item-text"),i.textContent=t||"File",i}static createItemIcon(t,e){const i=document.createElement("div");return Object.assign(i.style,e),i.classList.add("dropup-menu-item-icon"),i.appendChild(t.children[0]),i}static populateItem(t,e,i,s){const n=t.children[0];n.classList.contains("text-button")?e.appendChild(fs.createItemText(n.textContent,null==s?void 0:s.text)):(e.appendChild(fs.createItemIcon(t,null==s?void 0:s.iconContainer)),e.appendChild(fs.createItemText(i,null==s?void 0:s.text)))}static createItem(t,e,s){var n;const{elementRef:o,dropupText:r}=e,a=document.createElement("div");Object.assign(a.style,null==(n=null==s?void 0:s.item)?void 0:n.default),fs.populateItem(o,a,r,s),a.classList.add("dropup-menu-item");const l=i.processStateful((null==s?void 0:s.item)||{},{backgroundColor:"#f3f3f3"},{backgroundColor:"#ebebeb"});return fs.addItemEvents(t,a,o,l),a}}class gs{constructor(t,e){var i;this._isOpen=!0,this._styles=e,this.elementRef=gs.createElement(null==(i=this._styles)?void 0:i.container),this.close(),setTimeout((()=>this.addWindowEvents(t)))}static createElement(t){const e=document.createElement("div");return e.id="dropup-menu",Object.assign(e.style,t),e}open(){this.elementRef.style.display="block",this._isOpen=!0}close(){this._isOpen&&(this.elementRef.style.display="none",this._isOpen=!1)}toggle(){this._isOpen?this.close():this.open()}addItem(t){const e=fs.createItem(this,t,this._styles);this.elementRef.appendChild(e)}addWindowEvents(t){this.clickEvent=this.windowClick.bind(this,t),window.addEventListener("click",this.clickEvent),this.keyDownEvent=this.windowKeyDown.bind(this,t),window.addEventListener("keydown",this.keyDownEvent)}windowClick(t,e){var i;!t.isConnected&&this.clickEvent?window.removeEventListener("click",this.clickEvent):t.parentElement!==(null==(i=e.target.shadowRoot)?void 0:i.children[0])&&this.close()}windowKeyDown(t,e){var i,s,n;!t.isConnected&&this.keyDownEvent?window.removeEventListener("keydown",this.keyDownEvent):this._isOpen&&(e.key===c.ESCAPE?(this.close(),null==(i=this.highlightedItem)||i.dispatchEvent(new MouseEvent("mouseleave"))):e.key===c.ENTER?(null==(s=this.highlightedItem)||s.click(),null==(n=this.highlightedItem)||n.dispatchEvent(new MouseEvent("mouseleave"))):e.key===c.ARROW_DOWN?vs.focusSiblingItem(this.highlightedItem||this.elementRef.children[this.elementRef.children.length-1],this.elementRef,!0):e.key===c.ARROW_UP&&vs.focusSiblingItem(this.highlightedItem||this.elementRef.children[0],this.elementRef,!1))}}class bs extends ms{constructor(t,e){var i;super(bs.createButtonElement(),void 0,{styles:null==(i=null==e?void 0:e.button)?void 0:i.styles});const s=this.createInnerElements(this._customStyles);this._menu=new gs(t,null==e?void 0:e.menu),this.addClickEvent(),this.buttonContainer=bs.createButtonContainer(),this.elementRef.appendChild(s.styles),this.buttonContainer.appendChild(this.elementRef),this.elementRef.classList.add("dropup-icon","upload-file-button"),this.elementRef.children[0].id="dropup-icon",this.buttonContainer.appendChild(this._menu.elementRef),this.reapplyStateStyle("styles"),this.addContainerEvents(t)}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}createInnerElements(t){return{styles:this.createInnerElement(bs.createSVGIconElement(),"styles",t)}}createInnerElement(t,e,i){return ds.createSpecificStateElement(this.elementRef,e,i)||t}static createSVGIconElement(){return $e.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <path d="M16 0c-8.836 0-16 7.163-16 16s7.163 16 16 16c8.837 0 16-7.163 16-16s-7.163-16-16-16zM16 30.032c-7.72 0-14-6.312-14-14.032s6.28-14 14-14 14 6.28 14 14-6.28 14.032-14 14.032zM23 15h-6v-6c0-0.552-0.448-1-1-1s-1 0.448-1 1v6h-6c-0.552 0-1 0.448-1 1s0.448 1 1 1h6v6c0 0.552 0.448 1 1 1s1-0.448 1-1v-6h6c0.552 0 1-0.448 1-1s-0.448-1-1-1z"></path>\n</svg>')}addClickEvent(){this.elementRef.onclick=this._menu.toggle.bind(this._menu)}static createButtonContainer(){const t=document.createElement("div");return t.id="dropup-container",t}addItem(t){this._menu.addItem(t)}addContainerEvents(t){t.addEventListener("click",(t=>{t.target.classList.contains("dropup-icon")||this._menu.close()}))}static getPosition(t,e){var i,s;return null!=(i=null==e?void 0:e.button)&&i.position?null==(s=null==e?void 0:e.button)?void 0:s.position:t["outside-left"].length>0&&0===t["outside-right"].length?"outside-right":"outside-left"}}class ys{static addToDropup(t,e,i,s){const n=new bs(i,s);us.forEach((t=>{const i=e["dropup-menu"].findIndex((e=>e.buttonType===t)),s=e["dropup-menu"][i];s&&(n.addItem(s.button),e["dropup-menu"].splice(i,1))}));const o=bs.getPosition(e,s);hs.addButton(t,n.buttonContainer,o),e[o].push({})}static addToSideContainer(t,e){["inside-left","inside-right","outside-left","outside-right"].forEach((i=>{const s=i;e[s].forEach((e=>{hs.addButton(t,e.button.elementRef,s)}))}))}static setPosition(t,e,i){const s={...t[e],buttonType:e};i.push(s),delete t[e]}static createPositionsObj(){return{"dropup-menu":[],"outside-left":[],"inside-left":[],"inside-right":[],"outside-right":[]}}static generatePositions(t){const e=ys.createPositionsObj();Object.keys(t).forEach((i=>{var s;const n=null==(s=t[i])?void 0:s.button.position;n&&ys.setPosition(t,i,e[n])})),0===e["inside-right"].length&&t.submit&&ys.setPosition(t,"submit",e["inside-right"]),0===e["outside-right"].length&&(t.submit?ys.setPosition(t,"submit",e["outside-right"]):t.microphone?ys.setPosition(t,"microphone",e["outside-right"]):t.camera&&ys.setPosition(t,"camera",e["outside-right"])),t.submit&&ys.setPosition(t,"submit",0===e["outside-left"].length?e["outside-left"]:e["inside-right"]),t.microphone&&ys.setPosition(t,"microphone",0===e["outside-left"].length?e["outside-left"]:e["inside-right"]);const i=Object.keys(t);return i.length>1||e["dropup-menu"].length>0?us.forEach((i=>{t[i]&&e["dropup-menu"].push({...t[i],buttonType:i})})):1===i.length&&ys.setPosition(t,i[0],0===e["outside-right"].length?e["outside-right"]:e["outside-left"]),e}static addButtons(t,e,i,s){const n=ys.generatePositions(e);return ys.addToSideContainer(t,n),n["dropup-menu"].length>0&&ys.addToDropup(t,n,i,s),n}}const ws={images:{id:"upload-images-icon",svgString:'<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">\n <path d="M20,15.2928932 L20,5.5 C20,4.67157288 19.3284271,4 18.5,4 L5.5,4 C4.67157288,4 4,4.67157288 4,5.5 L4,12.2928932 L7.14644661,9.14644661 C7.34170876,8.95118446 7.65829124,8.95118446 7.85355339,9.14644661 L13.5,14.7928932 L16.1464466,12.1464466 C16.3417088,11.9511845 16.6582912,11.9511845 16.8535534,12.1464466 L20,15.2928932 Z M20,16.7071068 L16.5,13.2071068 L13.8535534,15.8535534 C13.6582912,16.0488155 13.3417088,16.0488155 13.1464466,15.8535534 L7.5,10.2071068 L4,13.7071068 L4,18.5 C4,19.3284271 4.67157288,20 5.5,20 L18.5,20 C19.3284271,20 20,19.3284271 20,18.5 L20,16.7071068 Z M3,5.5 C3,4.11928813 4.11928813,3 5.5,3 L18.5,3 C19.8807119,3 21,4.11928813 21,5.5 L21,18.5 C21,19.8807119 19.8807119,21 18.5,21 L5.5,21 C4.11928813,21 3,19.8807119 3,18.5 L3,5.5 Z M15,6 L17,6 C17.5522847,6 18,6.44771525 18,7 L18,9 C18,9.55228475 17.5522847,10 17,10 L15,10 C14.4477153,10 14,9.55228475 14,9 L14,7 C14,6.44771525 14.4477153,6 15,6 Z M15,7 L15,9 L17,9 L17,7 L15,7 Z"/>\n</svg>\n',dropupText:"Image"},gifs:{id:"upload-gifs-icon",svgString:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 5.9266752 5.6408391" height="21.31971" width="22.4">\n <g>\n <path d="m 5.2564627,1.548212 c -3.1136005,-0.4796804 -1.5568006,-0.2398402 0,0 z M 2.0001198,2.0922063 c 0.1556781,0 0.2657489,0.020893 0.3917849,0.080366 0.081154,0.038347 0.1153492,0.134065 0.076377,0.2138602 -0.038973,0.07979 -0.1363527,0.1134129 -0.2175069,0.075091 -0.078199,-0.036919 -0.1407455,-0.048792 -0.250655,-0.048792 -0.2260486,0 -0.3921482,0.2042182 -0.3921482,0.4801409 0,0.2761822 0.1663188,0.4810688 0.3921482,0.4810688 0.1117901,0 0.2064255,-0.046133 0.255659,-0.1284198 l 0.00162,-0.00389 V 3.0534032 l -0.098011,1.75e-4 c -0.081844,0 -0.1495979,-0.059305 -0.1612403,-0.1365887 l -0.00175,-0.023683 c 0,-0.08047 0.060311,-0.1470874 0.1389194,-0.1585331 l 0.024085,-0.00195 h 0.2612303 c 0.081842,0 0.149598,0.059305 0.1612404,0.1365891 l 0.00175,0.023683 -3.398e-4,0.3968809 v 0 l -0.00168,0.014211 v 0 l -0.00553,0.023034 v 0 l -0.00532,0.014145 c -0.098178,0.22826 -0.3236506,0.3528713 -0.5706303,0.3528713 -0.4240855,0 -0.7181621,-0.3622714 -0.7181621,-0.8016063 0,-0.4391857 0.2940275,-0.8006848 0.7181621,-0.8006848 z m 1.2034759,0.031275 c 0.081843,0 0.1495977,0.059305 0.1612403,0.1365891 l 0.00175,0.023683 v 1.2211775 c 0,0.088516 -0.07298,0.1602721 -0.1630073,0.1602721 -0.081841,0 -0.1495972,-0.059305 -0.1612397,-0.1365892 L 3.040589,3.5049308 V 2.2837527 c 0,-0.088516 0.07298,-0.1602721 0.1630067,-0.1602714 z m 0.7813442,0 0.5209469,0.00195 c 0.090025,3.048e-4 0.1627543,0.072306 0.1624458,0.1608234 -2.809e-4,0.08047 -0.06083,0.1468798 -0.1394772,0.158066 l -0.024092,0.00195 -0.3575326,-0.0013 v 0.4497782 l 0.2928918,2.27e-4 c 0.081842,0 0.1495979,0.059305 0.1612403,0.136589 l 0.00175,0.023683 c 0,0.080469 -0.06031,0.1470871 -0.1389193,0.1585393 l -0.024092,0.00195 -0.2928919,-2.336e-4 1.563e-4,0.2860316 c 0,0.080471 -0.06031,0.1470873 -0.1389193,0.1585395 l -0.024085,0.00195 c -0.081843,0 -0.1495979,-0.059305 -0.1612403,-0.1365826 l -0.00175,-0.023691 V 2.2841354 c 2.798e-4,-0.08047 0.060829,-0.1468797 0.1394758,-0.1580594 z"/>\n <path d="m 5.0894191,1.0943261 c 0,-0.21918999 -0.177687,-0.39686999 -0.396876,-0.39686999 h -3.43959 c -0.2191879,0 -0.391262,0.1777519 -0.3968759,0.39686999 l -0.027082,3.4379266 c 0.040152,0.2939927 0.4235456,0.409415 0.4235456,0.409415 l 3.4785583,-0.00851 c 0,0 0.3008506,-0.1402998 0.3236271,-0.4201576 0.042911,-0.5272495 0.034693,-1.6106146 0.034693,-3.4186761 z m -4.49792494,0 c 0,-0.36530999 0.29614504,-0.66145999 0.66145894,-0.66145999 h 3.43959 c 0.365314,0 0.66146,0.29615 0.66146,0.66145999 v 3.43959 c 0,0.36532 -0.296146,0.66146 -0.66146,0.66146 h -3.43959 c -0.3653139,0 -0.66145894,-0.29614 -0.66145894,-0.66146 z"/>\n </g>\n</svg>\n',dropupText:"GIF"},audio:{id:"upload-audio-icon",svgString:'<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="-49.49 -49.49 593.87 593.87" stroke-width="3.95908" transform="rotate(0)">\n <g stroke-width="0"></g>\n <g stroke-linecap="round" stroke-linejoin="round" stroke-width="0.98977"></g>\n <g>\n <g>\n <g>\n <path d="M163.205,76.413v293.301c-3.434-3.058-7.241-5.867-11.486-8.339c-21.38-12.452-49.663-15.298-77.567-7.846 c-49.038,13.096-80.904,54.519-71.038,92.337c4.019,15.404,14.188,28.221,29.404,37.087c13.553,7.894,29.87,11.933,47.115,11.933 c9.962,0,20.231-1.356,30.447-4.087c42.74-11.406,72.411-44.344,72.807-77.654h0.011v-0.162c0.002-0.166,0-0.331,0-0.496V187.072 l290.971-67.3v178.082c-3.433-3.055-7.238-5.863-11.481-8.334c-21.385-12.452-49.654-15.308-77.567-7.846 c-49.038,13.087-80.904,54.519-71.038,92.356c4.019,15.385,14.183,28.212,29.404,37.067c13.548,7.894,29.875,11.933,47.115,11.933 c9.962,0,20.231-1.356,30.452-4.087c42.74-11.413,72.411-44.346,72.804-77.654h0.004v-0.065c0.003-0.236,0.001-0.469,0-0.704V0 L163.205,76.413z M104.999,471.779c-22.543,6.038-45.942,3.846-62.572-5.846c-10.587-6.163-17.591-14.817-20.255-25.038 c-7.144-27.375,18.452-58.029,57.062-68.346c8.409-2.25,16.938-3.346,25.188-3.346c13.87,0,26.962,3.115,37.389,9.192 c10.587,6.163,17.591,14.817,20.255,25.029c0.809,3.102,1.142,6.248,1.139,9.4v0.321h0.014 C162.99,437.714,139.082,462.678,104.999,471.779z M182.898,166.853V92.067l290.971-67.298v74.784L182.898,166.853z M415.677,399.923c-22.558,6.038-45.942,3.837-62.587-5.846c-10.587-6.163-17.587-14.817-20.25-25.019 c-7.144-27.385,18.452-58.058,57.058-68.365c8.414-2.25,16.942-3.346,25.192-3.346c13.875,0,26.962,3.115,37.385,9.192 c10.596,6.163,17.596,14.817,20.26,25.029v0.01c0.796,3.05,1.124,6.144,1.135,9.244v0.468h0.02 C473.668,365.851,449.763,390.814,415.677,399.923z">\n </path>\n </g>\n </g>\n </g>\n</svg>',dropupText:"Audio"},mixedFiles:{id:"upload-mixed-files-icon",svgString:'<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n<title>file</title>\n<path d="M20 10.9696L11.9628 18.5497C10.9782 19.4783 9.64274 20 8.25028 20C6.85782 20 5.52239 19.4783 4.53777 18.5497C3.55315 17.6211 3 16.3616 3 15.0483C3 13.7351 3.55315 12.4756 4.53777 11.547L12.575 3.96687C13.2314 3.34779 14.1217 3 15.05 3C15.9783 3 16.8686 3.34779 17.525 3.96687C18.1814 4.58595 18.5502 5.4256 18.5502 6.30111C18.5502 7.17662 18.1814 8.01628 17.525 8.63535L9.47904 16.2154C9.15083 16.525 8.70569 16.6989 8.24154 16.6989C7.77738 16.6989 7.33224 16.525 7.00403 16.2154C6.67583 15.9059 6.49144 15.4861 6.49144 15.0483C6.49144 14.6106 6.67583 14.1907 7.00403 13.8812L14.429 6.88674" stroke="#000000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>',dropupText:"File"}};class xs extends ms{constructor(t){"dropup-menu"===(null==t?void 0:t.position)&&(t.position="outside-right"),super(xs.createMicrophoneElement(),null==t?void 0:t.position,t),this.isActive=!1,this._innerElements=this.createInnerElements(this._customStyles),this.changeToDefault()}createInnerElements(t){const e=xs.createSVGIconElement();return{default:this.createInnerElement(e,"default",t),active:this.createInnerElement(e,"active",t),unsupported:this.createInnerElement(e,"unsupported",t),commandMode:this.createInnerElement(e,"commandMode",t)}}createInnerElement(t,e,i){return ds.createSpecificStateElement(this.elementRef,e,i)||t}static createMicrophoneElement(){const t=document.createElement("div");return t.id="microphone-button",t.classList.add("input-button"),t}static createSVGIconElement(){const t=$e.createSVGElement('<?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');return t.id="microphone-icon",t}changeToActive(){this.elementRef.replaceChildren(this._innerElements.active),this.toggleIconFilter("active"),this.reapplyStateStyle("active",["default","commandMode"]),this.isActive=!0}changeToDefault(){this.elementRef.replaceChildren(this._innerElements.default),this.toggleIconFilter("default"),this.reapplyStateStyle("default",["active","commandMode"]),this.isActive=!1}changeToCommandMode(){this.elementRef.replaceChildren(this._innerElements.unsupported),this.toggleIconFilter("command"),this.reapplyStateStyle("commandMode",["active"])}changeToUnsupported(){this.elementRef.replaceChildren(this._innerElements.unsupported),this.elementRef.classList.add("unsupported-microphone"),this.reapplyStateStyle("unsupported",["active"])}toggleIconFilter(t){const e=this.elementRef.children[0];if("svg"===e.tagName.toLocaleLowerCase())switch(t){case"default":e.classList.remove("active-microphone-icon","command-microphone-icon"),e.classList.add("default-microphone-icon");break;case"active":e.classList.remove("default-microphone-icon","command-microphone-icon"),e.classList.add("active-microphone-icon");break;case"command":e.classList.remove("active-microphone-icon","default-microphone-icon"),e.classList.add("command-microphone-icon")}}}var ks={},_s={},Ss={},Ts={},As={};Object.defineProperty(As,"h",{value:!0}),As.Text=void 0;class Ms{static capitalize(t){return t.replace(Ms.FIRST_CHAR_REGEX,(t=>t.toUpperCase()))}static lineBreak(t){return t.replace(Ms.DOUBLE_LINE,"<p></p>").replace(Ms.ONE_LINE,"<br>")}static isCharDefined(t){return void 0!==t&&" "!==t&&" "!==t&&"\n"!==t&&""!==t}static breakupIntoWordsArr(t){return t.split(/(\W+)/)}}As.Text=Ms,Ms.FIRST_CHAR_REGEX=/\S/,Ms.DOUBLE_LINE=/\n\n/g,Ms.ONE_LINE=/\n/g,Object.defineProperty(Ts,"h",{value:!0}),Ts.Translate=void 0;const Os=As;Ts.Translate=class{static translate(t,e){const i=Os.Text.breakupIntoWordsArr(t);for(let t=0;t<i.length;t+=1)e[i[t]]&&(i[t]=e[i[t]]);return i.join("")}},Object.defineProperty(Ss,"h",{value:!0}),Ss.WebSpeechTranscript=void 0;const js=Ts;Ss.WebSpeechTranscript=class{static extract(t,e,i){let s="";for(let n=t.resultIndex;n<t.results.length;++n){let o=t.results[n][0].transcript;i&&(o=js.Translate.translate(o,i)),t.results[n].isFinal?e+=o:s+=o}return{interimTranscript:s,finalTranscript:e,newText:s||e}}static extractSafari(t,e,i){let s="";for(let e=t.resultIndex;e<t.results.length;++e){let n=t.results[e][0].transcript;i&&(n=js.Translate.translate(n,i)),s+=n}return{interimTranscript:"",finalTranscript:s,newText:s}}};var Cs={};Object.defineProperty(Cs,"h",{value:!0}),Cs.Browser=void 0;class Es{}Cs.Browser=Es,Es.IS_SAFARI=()=>(void 0===Es._IS_SAFARI&&(Es._IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),Es._IS_SAFARI);var Is={},Ps={};Object.defineProperty(Ps,"h",{value:!0}),Ps.EventListeners=void 0;class Ns{static getElementIfFocusedOnAvailable(t,e){return Array.isArray(t)?t.find((t=>e===t)):e===t?t:void 0}static keyDownWindow(t){t.element&&Ns.getElementIfFocusedOnAvailable(t.element,document.activeElement)&&(null!==Ns.KEY_DOWN_TIMEOUT&&clearTimeout(Ns.KEY_DOWN_TIMEOUT),Ns.KEY_DOWN_TIMEOUT=setTimeout((()=>{Ns.KEY_DOWN_TIMEOUT=null,this.resetRecording(t)}),500))}static mouseDownWindow(t,e){this.mouseDownElement=Ns.getElementIfFocusedOnAvailable(t,e.target)}static mouseUpWindow(t){this.mouseDownElement&&this.resetRecording(t),this.mouseDownElement=void 0}static add(t,e){const i=void 0===(null==e?void 0:e.insertInCursorLocation)||(null==e?void 0:e.insertInCursorLocation);null!=e&&e.element&&i&&(t.mouseDownEvent=Ns.mouseDownWindow.bind(t,e.element),document.addEventListener("mousedown",t.mouseDownEvent),t.mouseUpEvent=Ns.mouseUpWindow.bind(t,e),document.addEventListener("mouseup",t.mouseUpEvent),t.keyDownEvent=Ns.keyDownWindow.bind(t,e),document.addEventListener("keydown",t.keyDownEvent))}static remove(t){document.removeEventListener("mousedown",t.mouseDownEvent),document.removeEventListener("mouseup",t.mouseUpEvent),document.removeEventListener("keydown",t.keyDownEvent)}}Ps.EventListeners=Ns,Ns.KEY_DOWN_TIMEOUT=null;var qs={};Object.defineProperty(qs,"h",{value:!0}),qs.PreResultUtils=void 0;qs.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)}};var Rs={},Ls={};Object.defineProperty(Ls,"h",{value:!0}),Ls.AutoScroll=void 0;class Bs{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(t,e){return t&&Bs.isElementOverflown(e)}}Ls.AutoScroll=Bs;var Fs={};Object.defineProperty(Fs,"h",{value:!0}),Fs.Elements=void 0;Fs.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}};var zs={};Object.defineProperty(zs,"h",{value:!0}),zs.Cursor=void 0;class Ds{static setOffsetForGeneric(t,e,i=0){let s=0;for(let n=0;n<t.childNodes.length;n+=1){const o=t.childNodes[n];if(o.childNodes.length>0){const t=Ds.setOffsetForGeneric(o,e,i);if(-1===t)return-1;i+=t}else if(null!==o.textContent){if(i+o.textContent.length>e){const s=document.createRange();s.setStart(o,e-i),s.collapse(!0);const n=window.getSelection();return null==n||n.removeAllRanges(),null==n||n.addRange(s),t.focus(),-1}i+=o.textContent.length,s+=o.textContent.length}}return s}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(t,e){const i=window.getSelection();if(i){const s=Ds.getGenericElementCursorOffset(t,i,!0);console.log(s),setTimeout((()=>{}),100),Ds.setOffsetForGeneric(t,s+e)}}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}}zs.Cursor=Ds,Object.defineProperty(Rs,"h",{value:!0}),Rs.CommandUtils=void 0;const $s=Ls,Js=Fs,Us=Cs,Vs=zs,Hs=As;class Ks{static processCommand(t,e){return(!e||!e.caseSensitive)&&(t=t.toLowerCase()),!1===(null==e?void 0:e.substrings)?Hs.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?Ks.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(t,e,i,s){Ks.toggleCommandModeOff(t),Js.Elements.isPrimitiveElement(s)?(s.value=i,t.isTargetInShadow||Vs.Cursor.setOffsetForPrimitive(s,i.length,!0),Us.Browser.IS_SAFARI()&&t.autoScroll&&$s.AutoScroll.scrollSafariPrimitiveToEnd(s)):(s.textContent=i,t.isTargetInShadow||Vs.Cursor.focusEndOfGeneric(s),setTimeout((()=>$s.AutoScroll.scrollGeneric(t,s)))),t.resetRecording(e)}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,n){var o,r,a;const l=t.commands;if(!l||!s||!i)return;const c=!0===(null===(o=l.settings)||void 0===o?void 0:o.caseSensitive)?e:e.toLowerCase(),h=Hs.Text.breakupIntoWordsArr(c),u=!1===(null===(r=l.settings)||void 0===r?void 0:r.substrings)?Ks.checkIfMatchesWord:Ks.checkIfMatchesSubstring;if(l.commandMode&&u(l.commandMode,c,h))return t.setInterimColorToFinal(),setTimeout((()=>Ks.toggleCommandModeOn(t))),{doNotProcessTranscription:!1};if(!l.commandMode||t.isWaitingForCommand){if(l.stop&&u(l.stop,c,h))return Ks.toggleCommandModeOff(t),setTimeout((()=>t.stop())),{doNotProcessTranscription:!1};if(l.pause&&u(l.pause,c,h))return Ks.toggleCommandModeOff(t),t.setInterimColorToFinal(),setTimeout((()=>{var e;t.isPaused=!0,null===(e=t.onPauseTrigger)||void 0===e||e.call(t,!0)})),{doNotProcessTranscription:!1};if(l.resume&&u(l.resume,c,h))return t.isPaused=!1,null===(a=t.onPauseTrigger)||void 0===a||a.call(t,!1),Ks.toggleCommandModeOff(t),t.resetRecording(i),{doNotProcessTranscription:!0};if(l.reset&&u(l.reset,c,h))return void 0!==n&&Ks.setText(t,i,n,s),{doNotProcessTranscription:!0};if(l.removeAllText&&u(l.removeAllText,c,h))return Ks.setText(t,i,"",s),{doNotProcessTranscription:!0}}}}Rs.CommandUtils=Ks;var Gs={};Object.defineProperty(Gs,"h",{value:!0}),Gs.Highlight=void 0;const Zs=Fs,Ws=zs;class Xs{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,e){const i=window.getSelection();if(null!=i&&i.focusNode){const s=Ws.Cursor.getGenericElementCursorOffset(e,i,!0),n=Ws.Cursor.getGenericElementCursorOffset(e,i,!1);t.isHighlighted=s!==n}}static setState(t,e){document.activeElement===e&&(Zs.Elements.isPrimitiveElement(e)?Xs.setStateForPrimitive(t,e):Xs.setStateForGeneric(t,e))}static removeForGeneric(t,e){const i=window.getSelection();if(i){const s=Ws.Cursor.getGenericElementCursorOffset(e,i,!0);i.deleteFromDocument(),Ws.Cursor.setOffsetForGeneric(e,s),t.isHighlighted=!1}}static removeForPrimitive(t,e){const i=e.selectionStart,s=e.selectionEnd,n=e.value;if(i&&s){const o=n.substring(0,i)+n.substring(s);e.value=o,Ws.Cursor.setOffsetForPrimitive(e,i,t.autoScroll)}t.isHighlighted=!1}}Gs.Highlight=Xs;var Qs={};Object.defineProperty(Qs,"h",{value:!0}),Qs.Padding=void 0;const Ys=Fs,tn=zs,en=As;class sn{static setStateForPrimitiveElement(t,e){if(document.activeElement===e&&null!==e.selectionStart){const i=e.selectionStart,s=e.value[i-1],n=null===e.selectionEnd?i:e.selectionEnd,o=e.value[n];return en.Text.isCharDefined(s)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),en.Text.isCharDefined(o)&&(t.endPadding=" ",t.numberOfSpacesAfterNewText=1),void(t.isCursorAtEnd=e.value.length===n)}const i=e.value[e.value.length-1];en.Text.isCharDefined(i)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),t.isCursorAtEnd=!0}static setStateForGenericElement(t,e){var i,s,n;if(document.activeElement===e){const o=window.getSelection();if(null!=o&&o.focusNode){const r=tn.Cursor.getGenericElementCursorOffset(e,o,!0),a=null===(i=e.textContent)||void 0===i?void 0:i[r-1],l=tn.Cursor.getGenericElementCursorOffset(e,o,!1),c=null===(s=e.textContent)||void 0===s?void 0:s[l];return en.Text.isCharDefined(a)&&(t.startPadding=" "),en.Text.isCharDefined(c)&&(t.endPadding=" "),void(t.isCursorAtEnd=(null===(n=e.textContent)||void 0===n?void 0:n.length)===l)}}const o=e.innerText.charAt(e.innerText.length-1);en.Text.isCharDefined(o)&&(t.startPadding=" "),t.isCursorAtEnd=!0}static setState(t,e){Ys.Elements.isPrimitiveElement(e)?sn.setStateForPrimitiveElement(t,e):sn.setStateForGenericElement(t,e)}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)}}Qs.Padding=sn,Object.defineProperty(Is,"h",{value:!0}),Is.Speech=void 0;const nn=Ps,on=qs,rn=Rs,an=Ls,ln=Gs,cn=Fs,hn=Qs,un=Cs,dn=zs,pn=As;Is.Speech=class{constructor(){this.finalTranscript="",this.interimSpan=cn.Elements.createInterimSpan(),this.finalSpan=cn.Elements.createGenericSpan(),this.scrollingSpan=cn.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(t){var e,i;if(null!=t&&t.element)if(nn.EventListeners.add(this,t),Array.isArray(t.element)){const e=t.element.find((t=>t===document.activeElement))||t.element[0];if(!e)return;this.prepare(e)}else this.prepare(t.element);void 0!==(null==t?void 0:t.displayInterimResults)&&(this._displayInterimResults=t.displayInterimResults),null!=t&&t.textColor&&(this._finalTextColor=null===(e=null==t?void 0:t.textColor)||void 0===e?void 0:e.final,cn.Elements.applyCustomColors(this,t.textColor)),void 0!==(null==t?void 0:t.insertInCursorLocation)&&(this.insertInCursorLocation=t.insertInCursorLocation),void 0!==(null==t?void 0:t.autoScroll)&&(this.autoScroll=t.autoScroll),this._onResult=null==t?void 0:t.onResult,this._onPreResult=null==t?void 0:t.onPreResult,this._onStart=null==t?void 0:t.onStart,this._onStop=null==t?void 0:t.onStop,this._onError=null==t?void 0:t.onError,this.onCommandModeTrigger=null==t?void 0:t.onCommandModeTrigger,this.onPauseTrigger=null==t?void 0:t.onPauseTrigger,this._options=t,null!==(i=this._options)&&void 0!==i&&i.commands&&(this.commands=rn.CommandUtils.process(this._options.commands))}prepare(t){hn.Padding.setState(this,t),ln.Highlight.setState(this,t),this.isTargetInShadow=cn.Elements.isInsideShadowDOM(t),cn.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,e,i){var s;const n=pn.Text.capitalize(e);if(this.finalTranscript===n&&""===t)return;on.PreResultUtils.process(this,i,""===t,this._onPreResult,this._options)&&(t="",i="");const o=this.commands&&rn.CommandUtils.execCommand(this,i,this._options,this._primitiveElement||this._genericElement,this._originalText);if(o){if(o.doNotProcessTranscription)return;t="",i=""}if(this.isPaused||this.isWaitingForCommand)return;null===(s=this._onResult)||void 0===s||s.call(this,i,""===t),this.finalTranscript=n,this._displayInterimResults||(t="");const r=""===this.finalTranscript&&""===t;this._primitiveElement?this.updatePrimitiveElement(this._primitiveElement,t,r):this._genericElement&&this.updateGenericElement(this._genericElement,t,r)}updatePrimitiveElement(t,e,i){this.isHighlighted&&ln.Highlight.removeForPrimitive(this,t),this.primitiveTextRecorded||hn.Padding.adjustStateAfterRecodingPrimitiveElement(this,t),i&&hn.Padding.adjustSateForNoTextPrimitiveElement(this);const s=this.startPadding+this.finalTranscript+e;if(t.value=s+this.endPadding,!this.isTargetInShadow){const e=s.length+this.numberOfSpacesAfterNewText;dn.Cursor.setOffsetForPrimitive(t,e,this.autoScroll)}this.autoScroll&&un.Browser.IS_SAFARI()&&this.isCursorAtEnd&&an.AutoScroll.scrollSafariPrimitiveToEnd(t)}updateGenericElement(t,e,i){this.isHighlighted&&ln.Highlight.removeForGeneric(this,t),this.spansPopulated||cn.Elements.appendSpans(this,t);const s=(i?"":this.startPadding)+pn.Text.lineBreak(this.finalTranscript);this.finalSpan.innerHTML=s;const n=an.AutoScroll.isRequired(this.autoScroll,t);an.AutoScroll.changeStateIfNeeded(this,n);const o=pn.Text.lineBreak(e)+(i?"":this.endPadding);this.interimSpan.innerHTML=o,un.Browser.IS_SAFARI()&&this.insertInCursorLocation&&dn.Cursor.setOffsetForSafariGeneric(t,s.length+o.length),n&&an.AutoScroll.scrollGeneric(this,t),i&&(this.scrollingSpan.innerHTML="")}finalise(t){this._genericElement&&(t?(this.finalSpan=cn.Elements.createGenericSpan(),this.setInterimColorToFinal(),this.interimSpan=cn.Elements.createInterimSpan(),this.scrollingSpan=cn.Elements.createGenericSpan()):this._genericElement.textContent=this._genericElement.textContent,this.spansPopulated=!1),nn.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}},Object.defineProperty(_s,"h",{value:!0}),_s.WebSpeech=void 0;const mn=Ss,vn=Cs,fn=Is;class gn extends fn.Speech{constructor(){super()}start(t){var e;void 0===this._extractText&&(this._extractText=vn.Browser.IS_SAFARI()?mn.WebSpeechTranscript.extractSafari:mn.WebSpeechTranscript.extract),this.validate()&&(this.prepareBeforeStart(t),this.instantiateService(t),null===(e=this._service)||void 0===e||e.start(),this._translations=null==t?void 0:t.translations)}validate(){return!!gn.getAPI()||(this.error("Speech Recognition is unsupported"),!1)}instantiateService(t){var e,i;const s=gn.getAPI();this._service=new s,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=>{vn.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()}}_s.WebSpeech=gn;var bn={};Object.defineProperty(bn,"h",{value:!0}),bn.GlobalState=void 0;class yn{static doubleClickDetector(){return!!yn.doubleClickPending||(yn.doubleClickPending=!0,setTimeout((()=>{yn.doubleClickPending=!1}),300),!1)}}bn.GlobalState=yn,yn.doubleClickPending=!1;var wn={},xn={};Object.defineProperty(xn,"h",{value:!0}),xn.PreventConnectionStop=void 0;xn.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}};var kn={},_n={};Object.defineProperty(_n,"h",{value:!0}),_n.README_URL=void 0,_n.README_URL="https://github.com/OvidijusParsiunas/speech-to-element",Object.defineProperty(kn,"h",{value:!0}),kn.AzureSpeechConfig=void 0;const Sn=_n;class Tn{static validateOptions(t,e){return e?e.subscriptionKey||e.token||e.retrieveToken?!!e.region||(t(`Please define a 'region' property - more info: ${Sn.README_URL}`),!1):(t(`Please define a 'subscriptionKey', 'token' or 'retrieveToken' property - more info: ${Sn.README_URL}`),!1):(t(`Please provide subscription details - more info: ${Sn.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.language&&(t.speechRecognitionLanguage=e.language.trim())}static async get(t,e){const i=await Tn.getNewSpeechConfig(t,e);return i&&Tn.process(i,e),i}}kn.AzureSpeechConfig=Tn;var An={};Object.defineProperty(An,"h",{value:!0}),An.StopTimeout=void 0;class Mn{static set(t){t.stopTimeout=setTimeout((()=>t.stop()),t.stopTimeoutMS)}static reset(t,e){t.stopTimeoutMS=e||Mn.DEFAULT_MS,t.stopTimeout&&clearTimeout(t.stopTimeout),Mn.set(t)}}An.StopTimeout=Mn,Mn.DEFAULT_MS=2e4;var On={};Object.defineProperty(On,"h",{value:!0}),On.AzureTranscript=void 0;const jn=Ts;On.AzureTranscript=class{static extract(t,e,i,s){return s&&(t=jn.Translate.translate(t,s)),i?{interimTranscript:"",finalTranscript:e+t,newText:t}:{interimTranscript:t,finalTranscript:e,newText:t}}},Object.defineProperty(wn,"h",{value:!0}),wn.Azure=void 0;const Cn=xn,En=kn,In=An,Pn=On,Nn=Is;class qn extends Nn.Speech{constructor(){super(...arguments),this._newTextPadding=""}start(t,e){this._newTextPadding="",void 0===this.stopTimeout&&In.StopTimeout.reset(this,null==t?void 0:t.stopAfterSilenceMs),this.prepareBeforeStart(t),this.startAsync(t),e||Cn.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 qn.getAPI()?En.AzureSpeechConfig.validateOptions(this.error.bind(this),t):(this.moduleNotFound(),!1)}async instantiateService(t){const e=qn.getAPI(),i=e.AudioConfig.fromDefaultMicrophoneInput(),s=await En.AzureSpeechConfig.get(e.SpeechConfig,t);if(s){const n=new e.SpeechRecognizer(s,i);this.setEvents(n),this._service=n,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:s,newText:n}=Pn.AzureTranscript.extract(this._newTextPadding+e.result.text,this.finalTranscript,!1,this._translations);In.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(i,s,n)}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:s}=Pn.AzureTranscript.extract(this._newTextPadding+i.text,this.finalTranscript,!0,this._translations);In.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(t,e,s),""!==e&&(this._newTextPadding=" ")}}}onCanceled(t,e){e.reason===window.SpeechSDK.CancellationReason.Error&&this.error(e.errorDetails)}onSessionStarted(){Cn.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(),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()}}wn.Azure=qn,Object.defineProperty(ks,"h",{value:!0});const Rn=_s,Ln=Rs,Bn=bn,Fn=wn;class zn{static toggle(t,e){var i,s;const n=t.toLocaleLowerCase().trim();null!==(i=Bn.GlobalState.service)&&void 0!==i&&i.recognizing?this.stop():"webspeech"===n?zn.startWebSpeech(e):"azure"===n?zn.startAzure(e):(console.error("service not found - must be either 'webspeech' or 'azure'"),null===(s=null==e?void 0:e.onError)||void 0===s||s.call(e,"service not found - must be either 'webspeech' or 'azure'"))}static startWebSpeech(t){zn.stop()||(Bn.GlobalState.service=new Rn.WebSpeech,Bn.GlobalState.service.start(t))}static isWebSpeechSupported(){return!!Rn.WebSpeech.getAPI()}static startAzure(t){var e;zn.stop()||null!==(e=Bn.GlobalState.service)&&void 0!==e&&e.cannotBeStopped||(Bn.GlobalState.service=new Fn.Azure,Bn.GlobalState.service.start(t))}static stop(){var t;return!!Bn.GlobalState.doubleClickDetector()||(!(null===(t=Bn.GlobalState.service)||void 0===t)&&t.recognizing&&Bn.GlobalState.service.stop(),!1)}static endCommandMode(){Bn.GlobalState.service&&Ln.CommandUtils.toggleCommandModeOff(Bn.GlobalState.service)}}var Dn=ks.default=zn;class $n{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),Dn.stop(),this.stop||setTimeout(e,Un.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 Jn=class t extends xs{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||Dn.isWebSpeechSupported()){const i=!t.textInput||!t.textInput.disabled;this.elementRef.onclick=this.buttonClick.bind(this,e,i,n,o)}else this.changeToUnsupported();setTimeout((()=>{this._validationHandler=t._validationHandler}))}processConfiguration(e,i){var s;const n="object"==typeof i?i:{},o="object"==typeof n.webSpeech?n.webSpeech:{},r=n.azure||{},a={displayInterimResults:n.displayInterimResults??void 0,textColor:n.textColor??void 0,translations:n.translations??void 0,commands:n.commands??void 0,events:n.events??void 0,...o,...r},l=null==(s=n.commands)?void 0:s.submit;return l&&(a.onPreResult=t=>t.toLowerCase().includes(l)?(setTimeout((()=>{var t;return null==(t=e.submit)?void 0:t.call(e)})),Dn.endCommandMode(),{restart:!0,removeNewText:!0}):null),n.submitAfterSilence&&(this._silenceSubmit=new $n(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(),Dn.toggle(i,{insertInCursorLocation:!1,element:e?t.inputElementRef:void 0,onError:()=>{var t;this.onError(),null==(t=this._silenceSubmit)||t.clearSilenceTimeout()},onStart:()=>{var t;this.changeToActive(),null==(t=null==n?void 0:n.onStart)||t.call(n)},onStop:()=>{var t,e,i;null==(t=this._validationHandler)||t.call(this),null==(e=this._silenceSubmit)||e.clearSilenceTimeout(),this.changeToDefault(),null==(i=null==n?void 0:n.onStop)||i.call(n)},onPauseTrigger:e=>{var i,s;null==(i=this._silenceSubmit)||i.onPause(e,t,this.elementRef.onclick),null==(s=null==n?void 0:n.onPauseTrigger)||s.call(n,e)},onPreResult:(t,e)=>{var i;null==(i=null==n?void 0:n.onPreResult)||i.call(n,t,e)},onResult:(e,i)=>{var s,o,r;i&&(null==(s=this._validationHandler)||s.call(this)),null==(o=this._silenceSubmit)||o.resetSilenceTimeout(t,this.elementRef.onclick),null==(r=null==n?void 0:n.onResult)||r.call(n,e,i)},onCommandModeTrigger:t=>{var e;this.onCommandModeTrigger(t),null==(e=null==n?void 0:n.onCommandModeTrigger)||e.call(n,t)},...s})}onCommandModeTrigger(t){t?this.changeToCommandMode():this.changeToActive()}onError(){this._addErrorMessage("speechToText","speech input error")}static toggleSpeechAfterSubmit(e,i=!0){e.click(),i||setTimeout((()=>e.click()),t.MICROPHONE_RESET_TIMEOUT_MS)}};Jn.MICROPHONE_RESET_TIMEOUT_MS=300;let Un=Jn;class Vn{constructor(t,e,i,s){this._attachments=[],this._fileCountLimit=99,this._acceptedFormat="",e.maxNumberOfFiles&&(this._fileCountLimit=e.maxNumberOfFiles),this._toggleContainerDisplay=i,this._fileAttachmentsContainerRef=s,e.acceptedFormats&&(this._acceptedFormat=e.acceptedFormats),setTimeout((()=>{this._validationHandler=t._validationHandler}))}attemptAddFile(t,e){return!!Vn.isFileTypeValid(t,this._acceptedFormat)&&(this.addAttachmentBasedOnType(t,e,!0),!0)}static isFileTypeValid(t,e){if(""===e)return!0;const i=e.split(",");for(let e=0;e<i.length;e++){const s=i[e].trim();if(t.type===s)return!0;if(s.startsWith(".")){const e=s.slice(1);if(t.name.endsWith(e))return!0}else{if(t.name.endsWith(s))return!0;if(s.endsWith("/*")&&t.type.startsWith(s.slice(0,-2)))return!0}}return!1}static getTypeFromBlob(t){const{type:e}=t;return e.startsWith("image")?"image":e.startsWith("audio")?"audio":"any"}addAttachmentBasedOnType(t,e,i){const s=Vn.getTypeFromBlob(t);if("image"===s){const s=Vn.createImageAttachment(e);this.addFileAttachment(t,"image",s,i)}else if("audio"===s){const s=Gn.createAudioAttachment(e);this.addFileAttachment(t,"audio",s,i)}else{const e=Vn.createAnyFileAttachment(t.name);this.addFileAttachment(t,"any",e,i)}}static createImageAttachment(t){const e=new Image;return e.src=t,e.classList.add("image-attachment"),e}static createAnyFileAttachment(t){const e=document.createElement("div");e.classList.add("border-bound-attachment"),l.IS_SAFARI&&e.classList.add("border-bound-attachment-safari");const i=document.createElement("div");i.classList.add("any-file-attachment-text");const s=document.createElement("div");return s.classList.add("file-attachment-text-container"),s.appendChild(i),i.textContent=t,e.appendChild(s),e}addFileAttachment(t,e,i,s){var n;const o=Vn.createContainer(i);if(this._attachments.length>=this._fileCountLimit){const t=this._attachments[this._attachments.length-1].removeButton;null==t||t.click();const e=this._fileAttachmentsContainerRef.children;this._fileAttachmentsContainerRef.insertBefore(o,e[0])}else this._fileAttachmentsContainerRef.appendChild(o);const r={file:t,attachmentContainerElement:o,fileType:e};return s&&(r.removeButton=this.createRemoveAttachmentButton(r),o.appendChild(r.removeButton)),this._toggleContainerDisplay(!0),this._attachments.push(r),this._fileAttachmentsContainerRef.scrollTop=this._fileAttachmentsContainerRef.scrollHeight,null==(n=this._validationHandler)||n.call(this),r}static createContainer(t){const e=document.createElement("div");return e.classList.add("file-attachment"),e.appendChild(t),e}createRemoveAttachmentButton(t){const e=document.createElement("div");e.classList.add("remove-file-attachment-button"),e.onclick=this.removeAttachment.bind(this,t);const i=document.createElement("div");return i.classList.add("x-icon"),i.innerText="×",e.appendChild(i),e}removeAttachment(t){var e;const i=this._attachments.findIndex((e=>e===t)),s=this._attachments[i].attachmentContainerElement;this._attachments.splice(i,1),Gn.stopAttachmentPlayback(s),s.remove(),this._toggleContainerDisplay(!1),null==(e=this._validationHandler)||e.call(this)}getFiles(){return Array.from(this._attachments).map((t=>({file:t.file,type:t.fileType})))}removeAllAttachments(){this._attachments.forEach((t=>{setTimeout((()=>{var e;return null==(e=t.removeButton)?void 0:e.click()}))}))}}const Hn='<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n<title>stop</title>\n<path d="M5.92 24.096q0 0.832 0.576 1.408t1.44 0.608h16.128q0.832 0 1.44-0.608t0.576-1.408v-16.16q0-0.832-0.576-1.44t-1.44-0.576h-16.128q-0.832 0-1.44 0.576t-0.576 1.44v16.16z"></path>\n</svg>',Kn=class t extends Vn{constructor(t,e,i,s){super(t,e,i,s)}static createAudioContainer(){const t=document.createElement("div");return t.classList.add("border-bound-attachment","audio-attachment-icon-container"),l.IS_SAFARI&&t.classList.add("border-bound-attachment-safari"),t}static addAudioElements(t,e){const i=t.parentElement?x.cloneElement(t):t,s=document.createElement("audio");s.src=e;const n=$e.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <title>play</title>\n <path d="M5.92 24.096q0 1.088 0.928 1.728 0.512 0.288 1.088 0.288 0.448 0 0.896-0.224l16.16-8.064q0.48-0.256 0.8-0.736t0.288-1.088-0.288-1.056-0.8-0.736l-16.16-8.064q-0.448-0.224-0.896-0.224-0.544 0-1.088 0.288-0.928 0.608-0.928 1.728v16.16z"></path>\n</svg>');n.classList.add("attachment-icon","play-icon");const o=$e.createSVGElement(Hn);o.classList.add("attachment-icon","stop-icon"),i.replaceChildren(n),s.onplay=()=>{i.replaceChildren(o)},s.onpause=()=>{i.replaceChildren(n),s.currentTime=0},s.onended=()=>{i.replaceChildren(n)},i.onclick=()=>{s.paused?s.play():s.pause()}}static createAudioAttachment(e){const i=t.createAudioContainer();return t.addAudioElements(i,e),i}createTimer(e,i){let s=0;const n=void 0!==i&&i<t.TIMER_LIMIT_S?i:t.TIMER_LIMIT_S;return setInterval((()=>{var t;s+=1,s===n&&(null==(t=this.stopPlaceholderCallback)||t.call(this),this.clearTimer()),600===s&&e.classList.add("audio-placeholder-text-4-digits");const i=Math.floor(s/60),o=(s%60).toString().padStart(2,"0");e.textContent=`${i}:${o}`}),1e3)}createPlaceholderAudioAttachment(e){const i=t.createAudioContainer(),s=document.createElement("div");s.classList.add("audio-placeholder-text-3-digits");const n=document.createElement("div");n.classList.add("file-attachment-text-container","audio-placeholder-text-3-digits-container"),n.appendChild(s);const o=$e.createSVGElement(Hn);return o.classList.add("attachment-icon","stop-icon","not-removable-attachment-icon"),s.textContent="0:00",this._activePlaceholderTimer=this.createTimer(s,e),i.appendChild(n),this.addPlaceholderAudioAttachmentEvents(i,o,n),i}addPlaceholderAudioAttachmentEvents(t,e,i){t.addEventListener("mouseenter",(()=>t.replaceChildren(e)));t.addEventListener("mouseleave",(()=>t.replaceChildren(i)));t.addEventListener("click",(()=>{var t;return null==(t=this.stopPlaceholderCallback)?void 0:t.call(this)}))}addPlaceholderAttachment(t,e){const i=this.createPlaceholderAudioAttachment(e);this._activePlaceholderAttachment=this.addFileAttachment(new File([],""),"audio",i,!1),this.stopPlaceholderCallback=t}completePlaceholderAttachment(e,i){const s=this._activePlaceholderAttachment;s&&(s.file=e,t.addAudioElements(s.attachmentContainerElement.children[0],i),s.removeButton=this.createRemoveAttachmentButton(s),s.attachmentContainerElement.appendChild(s.removeButton),this._activePlaceholderAttachment=void 0,this.clearTimer())}removePlaceholderAttachment(){this._activePlaceholderAttachment&&(this.removeAttachment(this._activePlaceholderAttachment),this._activePlaceholderAttachment=void 0,this.clearTimer())}clearTimer(){void 0!==this._activePlaceholderTimer&&(clearInterval(this._activePlaceholderTimer),this._activePlaceholderTimer=void 0,this.stopPlaceholderCallback=void 0)}static stopAttachmentPlayback(t){var e,i,s;null!=(s=null==(i=null==(e=t.children[0])?void 0:e.children)?void 0:i[0])&&s.classList.contains("stop-icon")&&t.children[0].click()}};Kn.TIMER_LIMIT_S=5999;let Gn=Kn;class Zn{static create(t,e,i,s,n){return"audio"===n?new Gn(t,e,i,s):new Vn(t,e,i,s)}}class Wn{constructor(t,e,i){this._fileAttachmentsTypes=[],this.elementRef=this.createAttachmentContainer();const s="object"==typeof i&&!!i.displayFileAttachmentContainer;this.toggleContainerDisplay(s),t.appendChild(this.elementRef),e&&Object.assign(this.elementRef.style,e)}addType(t,e,i){const s=Zn.create(t,e,this.toggleContainerDisplay.bind(this),this.elementRef,i);return this._fileAttachmentsTypes.push(s),s}createAttachmentContainer(){const t=document.createElement("div");return t.id="file-attachment-container",t}toggleContainerDisplay(t){t?this.elementRef.style.display="block":0===this.elementRef.children.length&&(this.elementRef.style.display="none")}getAllFileData(){const t=this._fileAttachmentsTypes.map((t=>t.getFiles())).flat();return t.length>0?t:void 0}async completePlaceholders(){await Promise.all(this._fileAttachmentsTypes.map((async t=>{var e;return null==(e=t.stopPlaceholderCallback)?void 0:e.call(t)})))}static addFilesToType(t,e){t.forEach((t=>{const i=new FileReader;i.readAsDataURL(t),i.onload=i=>{for(let s=0;s<e.length&&!e[s].attemptAddFile(t,i.target.result);s+=1);}}))}addFilesToAnyType(t){Wn.addFilesToType(t,this._fileAttachmentsTypes)}removeAllFiles(){this._fileAttachmentsTypes.forEach((t=>t.removeAllAttachments())),this.elementRef.replaceChildren(),this.toggleContainerDisplay(!1)}getNumberOfTypes(){return this._fileAttachmentsTypes.length}}const Xn=class t{constructor(e,i,s){this._isOpen=!1,this._contentRef=t.createModalContent(i,null==s?void 0:s.backgroundColor),this._buttonPanel=t.createButtonPanel(null==s?void 0:s.backgroundColor),this._elementRef=t.createContainer(this._contentRef,s),this._elementRef.appendChild(this._buttonPanel),e.appendChild(this._elementRef),this._backgroundPanelRef=t.createDarkBackgroundPanel(),e.appendChild(this._backgroundPanelRef),this.addWindowEvents(e)}isOpen(){return this._isOpen}static createContainer(t,e){const i=document.createElement("div");return i.classList.add("modal"),i.appendChild(t),e&&delete e.backgroundColor,Object.assign(i.style,e),i}static createModalContent(t,e){const i=document.createElement("div");return i.classList.add(...t),e&&(i.style.backgroundColor=e),document.createElement("div").appendChild(i),i}static createButtonPanel(t){const e=document.createElement("div");return e.classList.add("modal-button-panel"),t&&(e.style.backgroundColor=t),e}static createDarkBackgroundPanel(){const t=document.createElement("div");return t.id="modal-background-panel",t}addButtons(...t){t.forEach((t=>this._buttonPanel.appendChild(t)))}static createTextButton(t){const e=document.createElement("div");return e.classList.add("modal-button"),e.textContent=t,e}static createSVGButton(t){const e=document.createElement("div");e.classList.add("modal-button","modal-svg-button");const i=$e.createSVGElement(t);return i.classList.add("modal-svg-button-icon"),e.appendChild(i),e}close(){this._elementRef.classList.remove("show-modal"),this._elementRef.classList.add("hide-modal"),this._backgroundPanelRef.classList.remove("show-modal-background"),this._backgroundPanelRef.classList.add("hide-modal-background"),this._isOpen=!1,setTimeout((()=>{this._elementRef.style.display="none",this._backgroundPanelRef.style.display="none"}),t.MODAL_CLOSE_TIMEOUT_MS)}displayModalElements(){this._elementRef.style.display="flex",this._elementRef.classList.remove("hide-modal"),this._elementRef.classList.add("show-modal"),this._backgroundPanelRef.style.display="block",this._backgroundPanelRef.classList.remove("hide-modal-background"),this._backgroundPanelRef.classList.add("show-modal-background"),this._isOpen=!0}openTextModal(t){this._contentRef.innerHTML=t,this.displayModalElements()}addCloseButton(e,i,s){const n=i?t.createSVGButton(e):t.createTextButton(e);return this.addButtons(n),n.onclick=()=>{this.close(),setTimeout((()=>{null==s||s()}),140)},n}static createTextModalFunc(e,i,s){var n;if("object"==typeof i&&null!=(n=i.files)&&n.infoModal){const n=new t(e,["modal-content"],i.files.infoModal.containerStyle);return n.addCloseButton("OK",!1,s),n.openTextModal.bind(n,i.infoModalTextMarkUp||"")}}addWindowEvents(t){this.keyDownEvent=this.windowKeyDown.bind(this,t),window.addEventListener("keydown",this.keyDownEvent)}windowKeyDown(t,e){var i,s;!t.isConnected&&this.keyDownEvent?window.removeEventListener("keydown",this.keyDownEvent):this._isOpen&&(e.key===c.ESCAPE?(this.close(),null==(i=this.extensionCloseCallback)||i.call(this)):e.key===c.ENTER&&(this.close(),null==(s=this.extensionCloseCallback)||s.call(this)))}};Xn.MODAL_CLOSE_TIMEOUT_MS=190;let Qn=Xn;class Yn extends ms{constructor(t,e,i,s,n,o){var r,a,l,c,h,u,d,p,m;const v=null==(r=null==i?void 0:i.button)?void 0:r.position,f=(null==(c=null==(l=null==(a=null==i?void 0:i.button)?void 0:a.styles)?void 0:l.text)?void 0:c.content)||o;super(Yn.createButtonElement(),v,i.button,f);const g="dropup-menu"===v,b=this.createInnerElements(s,n,this._customStyles,g);this._inputElement=Yn.createInputElement(null==(h=null==i?void 0:i.files)?void 0:h.acceptedFormats),this.addClickEvent(t,i),this.elementRef.replaceChildren(b.styles),this.reapplyStateStyle("styles"),this._fileAttachmentsType=e,this._openModalOnce=!1===(null==(d=null==(u=i.files)?void 0:u.infoModal)?void 0:d.openModalOnce)||null==(m=null==(p=i.files)?void 0:p.infoModal)?void 0:m.openModalOnce}createInnerElements(t,e,i,s=!1){const n=Yn.createSVGIconElement(t,e);return{styles:ds.createInnerElement(this.elementRef,n,"styles",i,s)}}triggerImportPrompt(t){t.onchange=this.import.bind(this,t),t.click()}import(t){Wn.addFilesToType(Array.from(t.files||[]),[this._fileAttachmentsType]),t.value=""}static createInputElement(t){const e=document.createElement("input");return e.type="file",e.accept=t||"",e.hidden=!0,e.multiple=!0,e}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button","upload-file-button"),t}static createSVGIconElement(t,e){const i=$e.createSVGElement(e);return i.id=t,i}addClickEvent(t,e){const i=this.triggerImportPrompt.bind(this,this._inputElement),s=Qn.createTextModalFunc(t,e,i);this.elementRef.onclick=this.click.bind(this,s)}click(t){!t||void 0!==this._openModalOnce&&!0!==this._openModalOnce?this.triggerImportPrompt(this._inputElement):(t(),!0===this._openModalOnce&&(this._openModalOnce=!1))}}class to{static create(t,e,i){const s=to.createElement(i);to.addEvents(s,t,e),t.appendChild(s)}static createElement(t){const e=document.createElement("div");return e.id="drag-and-drop","object"==typeof t&&Object.assign(e.style,t),e}static addEvents(t,e,i){e.ondragenter=e=>{e.preventDefault(),to.display(t)},t.ondragleave=e=>{e.preventDefault(),to.hide(t)},t.ondragover=t=>{t.preventDefault()},t.ondrop=e=>{e.preventDefault(),to.uploadFile(i,e),to.hide(t)}}static uploadFile(t,e){var i;const s=null==(i=e.dataTransfer)?void 0:i.files;s&&t.addFilesToAnyType(Array.from(s))}static display(t){t.style.display="block"}static hide(t){t.style.display="none"}static isEnabled(t,e){return(void 0===e||!1!==e)&&(!!e||t.getNumberOfTypes()>0)}}class eo{static validate(t,e,i,s,n){const o=t(i,s,n);return o?e.changeToSubmitIcon():e.changeToDisabledIcon(),o}static async useValidationFunc(t,e,i,s){const n=e.isTextInputEmpty()?"":e.inputElementRef.textContent;await i.completePlaceholders();const o=i.getAllFileData(),r=null==o?void 0:o.map((t=>t.file));return eo.validate(t,s,n,r)}static async useValidationFuncProgrammatic(t,e,i){var s;const n=null==(s=e.files)?void 0:s.map((t=>t.file));return eo.validate(t,i,e.text,n,!0)}static validateWebsocket(t,e){return!(t.websocket&&!Ce.canSendMessage(t.websocket))||(e.changeToDisabledIcon(),!1)}static attach(t,e,i,s,n){const o=t.validateInput||S.processValidateInput(t);t._validationHandler=async t=>{if(n.status.loadingActive||n.status.requestInProgress||!0===e.isSubmitProgrammaticallyDisabled||!eo.validateWebsocket(e,n))return!1;const r=o||e.canSendMessage;return r?t?eo.useValidationFuncProgrammatic(r,t,n):eo.useValidationFunc(r,i,s,n):null}}}class io{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 so extends xs{constructor(t,e){var i,s;super(e.button),this._waitingForBrowserApproval=!1,this._audioType=t,this._extension=(null==(i=e.files)?void 0:i.format)||"mp3",this._maxDurationSeconds=null==(s=e.files)?void 0:s.maxDurationSeconds,this.elementRef.onclick=this.buttonClick.bind(this)}buttonClick(){this._waitingForBrowserApproval||(this.isActive?this.stop():(this._waitingForBrowserApproval=!0,this.record()))}stop(){return new Promise((t=>{var e,i;this.changeToDefault(),null==(e=this._mediaRecorder)||e.stop(),null==(i=this._mediaStream)||i.getTracks().forEach((t=>t.stop())),setTimeout((()=>{t()}),10)}))}record(){navigator.mediaDevices.getUserMedia({audio:!0}).then((t=>{this.changeToActive(),this._mediaRecorder=new MediaRecorder(t),this._audioType.addPlaceholderAttachment(this.stop.bind(this),this._maxDurationSeconds),this._mediaStream=t,this._mediaRecorder.addEventListener("dataavailable",(t=>{this.createFile(t)})),this._mediaRecorder.start()})).catch((t=>{console.error(t),this.stop()})).finally((()=>{this._waitingForBrowserApproval=!1}))}createFile(t){const e=new Blob([t.data],{type:`audio/${this._extension}`}),i=io.getFileName(this._newFilePrefix||"audio",this._extension),s=new File([e],i,{type:e.type}),n=new FileReader;n.readAsDataURL(s),n.onload=t=>{this._audioType.completePlaceholderAttachment(s,t.target.result)}}}class no{static setPropertyValueIfDoesNotExist(t,e,i){const s=e[0];1===e.length?t[s]??(t[s]=i):(t[s]??(t[s]={}),e.shift(),no.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(),no.setPropertyValue(t[s],e,i))}static getObjectValue(t,e){const i=t[e[0]];return void 0===i||1===e.length?i:no.getObjectValue(i,e.slice(1))}static overwritePropertyObjectFromAnother(t,e,i){const s=no.getObjectValue(e,i);if(s){const e={...s,...no.getObjectValue(t,i)||{}};no.setPropertyValue(t,i,e)}}}class oo{static resetSubmit(t,e){e?t.unsetCustomStateStyles(["loading","submit"]):t.unsetCustomStateStyles(["stop","loading","submit"]),t.reapplyStateStyle("submit")}static overwriteDefaultStyleWithSubmit(t,e){if(!t.submit)return;const i=JSON.parse(JSON.stringify(t[e]||{}));no.overwritePropertyObjectFromAnother(i,t.submit,["container","default"]),no.overwritePropertyObjectFromAnother(i,t.submit,["text","styles","default"]),no.overwritePropertyObjectFromAnother(i,t.submit,["svg","styles","default"]),t[e]=i}static setUpDisabledButton(t){no.setPropertyValueIfDoesNotExist(t,["submit","container","default","backgroundColor"],""),no.setPropertyValueIfDoesNotExist(t,["disabled","container","default","backgroundColor"],"unset"),no.setPropertyValueIfDoesNotExist(t.submit,["svg","styles","default","filter"],""),no.setPropertyValueIfDoesNotExist(t.disabled,["svg","styles","default","filter"],"brightness(0) saturate(100%) invert(70%) sepia(0%) saturate(5564%) hue-rotate(207deg) brightness(100%) contrast(97%)"),oo.overwriteDefaultStyleWithSubmit(t,"disabled")}static process(t){const e=JSON.parse(JSON.stringify(t||{}));return oo.overwriteDefaultStyleWithSubmit(e,"loading"),oo.overwriteDefaultStyleWithSubmit(e,"stop"),null!=t&&t.alwaysEnabled||oo.setUpDisabledButton(e),e}}const ro=class t extends ms{constructor(e,i,s,n,o,r){const a=oo.process(e.submitButtonStyles);super(t.createButtonContainerElement(),null==a?void 0:a.position,a),this._isSVGLoadingIconOverriden=!1,this.status={requestInProgress:!1,loadingActive:!1},this._messages=s,this._textInput=i,this._fileAttachments=o,this._innerElements=this.createInnerElements(),this._abortStream=new AbortController,this._stopClicked={listener:()=>{}},this._serviceIO=n,this._alwaysEnabled=!(null==a||!a.alwaysEnabled),e.disableSubmitButton=this.disableSubmitButton.bind(this,n),this.attemptOverwriteLoadingStyle(e),r.microphone&&this.setUpSpeechToText(r.microphone.button,e.speechToText),setTimeout((()=>{var t;this._validationHandler=e._validationHandler,this.assignHandlers(this._validationHandler),null==(t=this._validationHandler)||t.call(this)}))}createInnerElements(){const{submit:e,loading:i,stop:s}=this.createCustomElements(),n=e||t.createSubmitIconElement();return{submit:n,loading:i||t.createLoadingIconElement(),stop:s||t.createStopIconElement(),disabled:this.createDisabledIconElement(n)}}createCustomElements(){const t=ds.createSpecificStateElement(this.elementRef,"submit",this._customStyles),e={loading:void 0,stop:void 0};return Object.keys(e).forEach((t=>{const i=t,s=ds.createCustomElement(i,this._customStyles);s&&(e[i]=s)})),e.submit=t,e}static createButtonContainerElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSubmitIconElement(){const t=$e.createSVGElement('<?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');return t.id="submit-icon",t}static createLoadingIconElement(){const t=document.createElement("div");return t.classList.add("loading-submit-button"),t}static createStopIconElement(){const t=document.createElement("div");return t.id="stop-icon",t}createDisabledIconElement(t){return ds.createCustomElement("disabled",this._customStyles)||t.cloneNode(!0)}attemptOverwriteLoadingStyle(t){var e,i,s,n,o,r,a,l,c;if(!(null!=(i=null==(e=this._customStyles)?void 0:e.submit)&&i.svg||null!=(o=null==(n=null==(s=this._customStyles)?void 0:s.loading)?void 0:n.svg)&&o.content||null!=(l=null==(a=null==(r=this._customStyles)?void 0:r.loading)?void 0:a.text)&&l.content||void 0!==t.displayLoadingBubble&&!0!==t.displayLoadingBubble)){const e=document.createElement("style");e.textContent="\n .loading-button > * {\n filter: brightness(0) saturate(100%) invert(72%) sepia(0%) saturate(3044%) hue-rotate(322deg) brightness(100%)\n contrast(96%) !important;\n }",null==(c=t.shadowRoot)||c.appendChild(e),this._isSVGLoadingIconOverriden=!0}}assignHandlers(t){this._serviceIO.completionsHandlers={onFinish:this.resetSubmit.bind(this,t)},this._serviceIO.streamHandlers={onOpen:this.changeToStopIcon.bind(this),onClose:this.resetSubmit.bind(this,t),abortStream:this._abortStream,stopClicked:this._stopClicked};const{stream:e}=this._serviceIO;"object"==typeof e&&"number"==typeof e.simulation&&(this._serviceIO.streamHandlers.simulationInterim=e.simulation)}setUpSpeechToText(t,e){this._microphoneButton=t,this._stopSTTAfterSubmit="object"==typeof e&&e.stopAfterSubmit}resetSubmit(t){this.status.requestInProgress=!1,this.status.loadingActive=!1,t()}async submitFromInput(){await this._fileAttachments.completePlaceholders();const t=this._fileAttachments.getAllFileData();if(this._textInput.isTextInputEmpty())this.attemptSubmit({text:"",files:t});else{const e=this._textInput.inputElementRef.innerText.trim();this.attemptSubmit({text:e,files:t})}}async programmaticSubmit(t){"string"==typeof t&&(t=S.processSubmitUserMessage(t));const e={text:t.text};t.files&&(e.files=Array.from(t.files).map((t=>({file:t,type:Vn.getTypeFromBlob(t)})))),setTimeout((()=>this.attemptSubmit(e,!0)))}async attemptSubmit(t,e=!1){var i,s,n;if(!1===await(null==(i=this._validationHandler)?void 0:i.call(this,e?t:void 0)))return;this.changeToLoadingIcon(),await this.addNewMessage(t),this._serviceIO.isWebModel()||this._messages.addLoadingMessage(),this._textInput.clear();const o=null==(s=t.files)?void 0:s.map((t=>t.file)),r={text:""===t.text?void 0:t.text,files:o};await this._serviceIO.callAPI(r,this._messages),null==(n=this._fileAttachments)||n.removeAllFiles()}async addNewMessage({text:t,files:e}){const i={role:I.USER_ROLE};t&&(i.text=t),e&&(i.files=await this._messages.addMultipleFiles(e)),this._serviceIO.sessionId&&(i._sessionId=this._serviceIO.sessionId),Object.keys(i).length>0&&this._messages.addNewMessage(i)}stopStream(){var t;this._abortStream.abort(),null==(t=this._stopClicked)||t.listener(),this._validationHandler&&this.resetSubmit(this._validationHandler)}changeToStopIcon(){this._serviceIO.websocket||(this.elementRef.classList.remove(t.LOADING_CLASS,t.DISABLED_CLASS,t.SUBMIT_CLASS),this.elementRef.replaceChildren(this._innerElements.stop),this.reapplyStateStyle("stop",["loading","submit"]),this.elementRef.onclick=this.stopStream.bind(this),this.status.loadingActive=!1)}changeToLoadingIcon(){this._serviceIO.websocket||(this._isSVGLoadingIconOverriden||this.elementRef.replaceChildren(this._innerElements.loading),this.elementRef.classList.remove(t.SUBMIT_CLASS,t.DISABLED_CLASS),this.elementRef.classList.add(t.LOADING_CLASS),this.reapplyStateStyle("loading",["submit"]),this.elementRef.onclick=()=>{},this.status.requestInProgress=!0,this.status.loadingActive=!0)}changeToSubmitIcon(){this.elementRef.classList.contains(t.SUBMIT_CLASS)||(this.elementRef.classList.remove(t.LOADING_CLASS,t.DISABLED_CLASS),this.elementRef.classList.add(t.SUBMIT_CLASS),this.elementRef.replaceChildren(this._innerElements.submit),oo.resetSubmit(this,this.status.loadingActive),this.elementRef.onclick=()=>{var t;this.submitFromInput(),null!=(t=this._microphoneButton)&&t.isActive&&Un.toggleSpeechAfterSubmit(this._microphoneButton.elementRef,!!this._stopSTTAfterSubmit)})}changeToDisabledIcon(e=!1){this._alwaysEnabled&&!e?this.changeToSubmitIcon():this.elementRef.classList.contains(t.DISABLED_CLASS)||(this.elementRef.classList.remove(t.LOADING_CLASS,t.SUBMIT_CLASS),this.elementRef.classList.add(t.DISABLED_CLASS),this.elementRef.replaceChildren(this._innerElements.disabled),this.reapplyStateStyle("disabled",["submit"]),this.elementRef.onclick=()=>{})}disableSubmitButton(t,e){var i;t.isSubmitProgrammaticallyDisabled=!1!==e,!this.status.requestInProgress&&!this.status.loadingActive&&(!1===e?null==(i=this._validationHandler)||i.call(this):this.changeToDisabledIcon(!0))}};ro.SUBMIT_CLASS="submit-button",ro.LOADING_CLASS="loading-button",ro.DISABLED_CLASS="disabled-button";let ao=ro;class lo extends Qn{constructor(t,e,i,s){super(t,["modal-content","modal-camera-content"],i),this._stopped=!1,this._format="image/png",this._canvas=document.createElement("canvas"),this._canvas.classList.add("camera-modal-canvas");const{captureButton:n,submitButton:o}=this.addButtonsAndTheirEvents(e);this._captureButton=n,this._submitButton=o,this._captureIcon=this._captureButton.children[0],this._refreshIcon=$e.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">\n <path d="M27.1 14.313V5.396L24.158 8.34c-2.33-2.325-5.033-3.503-8.11-3.503C9.902 4.837 4.901 9.847 4.899 16c.001 6.152 5.003 11.158 11.15 11.16 4.276 0 9.369-2.227 10.836-8.478l.028-.122h-3.23l-.022.068c-1.078 3.242-4.138 5.421-7.613 5.421a8 8 0 0 1-5.691-2.359A7.993 7.993 0 0 1 8 16.001c0-4.438 3.611-8.049 8.05-8.049 2.069 0 3.638.58 5.924 2.573l-3.792 3.789H27.1z"/>\n</svg>\n'),this._refreshIcon.classList.add("modal-svg-button-icon","modal-svg-refresh-icon"),"jpeg"===(null==s?void 0:s.format)&&(this._format="image/jpeg"),null!=s&&s.dimensions&&(this._dimensions=s.dimensions),this._contentRef.appendChild(this._canvas),this.extensionCloseCallback=this.stop}addButtonsAndTheirEvents(t){const e=Qn.createSVGButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <title>capture</title>\n <path d="M0 16q0 3.264 1.28 6.208t3.392 5.12 5.12 3.424 6.208 1.248 6.208-1.248 5.12-3.424 3.392-5.12 1.28-6.208-1.28-6.208-3.392-5.12-5.088-3.392-6.24-1.28q-3.264 0-6.208 1.28t-5.12 3.392-3.392 5.12-1.28 6.208zM4 16q0-3.264 1.6-6.016t4.384-4.352 6.016-1.632 6.016 1.632 4.384 4.352 1.6 6.016-1.6 6.048-4.384 4.352-6.016 1.6-6.016-1.6-4.384-4.352-1.6-6.048z"></path>\n</svg>\n');e.classList.add("modal-svg-camera-button"),e.children[0].classList.add("modal-svg-camera-icon");const i=this.addCloseButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="M195.2 195.2a64 64 0 0 1 90.496 0L512 421.504 738.304 195.2a64 64 0 0 1 90.496 90.496L602.496 512 828.8 738.304a64 64 0 0 1-90.496 90.496L512 602.496 285.696 828.8a64 64 0 0 1-90.496-90.496L421.504 512 195.2 285.696a64 64 0 0 1 0-90.496z"/>\n</svg>',!0);i.classList.add("modal-svg-close-button"),i.children[0].classList.add("modal-svg-close-icon");const s=Qn.createSVGButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M4.89163 13.2687L9.16582 17.5427L18.7085 8" stroke="#000000" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>');return s.classList.add("modal-svg-submit-button"),this.addButtons(e,s),this.addButtonEvents(e,i,s,t),{captureButton:e,submitButton:s}}addButtonEvents(t,e,i,s){t.onclick=()=>{this.capture()},e.addEventListener("click",this.stop.bind(this)),i.onclick=()=>{const t=this.getFile();t&&Wn.addFilesToType([t],[s]),this.stop(),this.close()}}stop(){this._mediaStream&&this._mediaStream.getTracks().forEach((t=>t.stop())),this._stopped=!0,setTimeout((()=>{this._captureButton.replaceChildren(this._captureIcon),this._captureButton.classList.replace("modal-svg-refresh-button","modal-svg-camera-button");const t=this._canvas.getContext("2d");null==t||t.clearRect(0,0,this._canvas.width,this._canvas.height)}),Qn.MODAL_CLOSE_TIMEOUT_MS)}start(){this._dataURL=void 0,this._submitButton.classList.add("modal-svg-submit-disabled"),this._stopped=!1,navigator.mediaDevices.getUserMedia({video:this._dimensions||!0}).then((t=>{if(this._mediaStream=t,!this.isOpen())return this.stop();const e=document.createElement("video");e.srcObject=t,e.play(),requestAnimationFrame(this.updateCanvas.bind(this,e,this._canvas))})).catch((t=>{console.error(t),this.stop(),this.close()}))}capture(){this._dataURL?(this._captureButton.replaceChildren(this._captureIcon),this._captureButton.classList.replace("modal-svg-refresh-button","modal-svg-camera-button"),this._submitButton.classList.add("modal-svg-submit-disabled"),this._dataURL=void 0):(this._captureButton.replaceChildren(this._refreshIcon),this._captureButton.classList.replace("modal-svg-camera-button","modal-svg-refresh-button"),this._submitButton.classList.remove("modal-svg-submit-disabled"),this._dataURL=this._canvas.toDataURL())}getFile(){if(this._dataURL){const t=atob(this._dataURL.split(",")[1]),e=new Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);const i=new Uint8Array(e),s=new Blob([i],{type:this._format}),n="image/jpeg"===this._format?"jpeg":"png",o=io.getFileName(this._newFilePrefix||"photo",n);return new File([s],o,{type:s.type})}}updateCanvas(t,e){if(!this._stopped){if(!this._dataURL){e.width=t.videoWidth,e.height=t.videoHeight;const i=e.getContext("2d");null==i||i.drawImage(t,0,0,e.width,e.height)}requestAnimationFrame(this.updateCanvas.bind(this,t,e))}}openCameraModal(t){this.displayModalElements(),t.start()}static createCameraModalFunc(t,e,i,s){const n=new lo(t,e,i,s);return n.openCameraModal.bind(n,n)}}class co extends ms{constructor(t,e,i){var s,n,o,r;const a=null==(s=null==i?void 0:i.button)?void 0:s.position,l=(null==(r=null==(o=null==(n=null==i?void 0:i.button)?void 0:n.styles)?void 0:o.text)?void 0:r.content)||"Photo";super(co.createButtonElement(),a,(null==i?void 0:i.button)||{},l);const c=this.createInnerElements(this._customStyles,"dropup-menu"===a);i&&this.addClickEvent(t,e,i.modalContainerStyle,i.files),this.elementRef.classList.add("upload-file-button"),this.elementRef.appendChild(c.styles),this.reapplyStateStyle("styles")}createInnerElements(t,e=!1){return{styles:ds.createInnerElement(this.elementRef,co.createSVGIconElement(),"styles",t,e)}}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSVGIconElement(){const t=$e.createSVGElement('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg">\n <path d="M29 7h-4.599l-2.401-4h-12l-2.4 4h-4.6c-1 0-3 1-3 2.969v16.031c0 1.657 1.5 3 2.792 3h26.271c1.313 0 2.938-1.406 2.938-2.968v-16.032c0-1-1-3-3-3zM30 26.032c0 0.395-0.639 0.947-0.937 0.969h-26.265c-0.232-0.019-0.797-0.47-0.797-1v-16.031c0-0.634 0.851-0.953 1-0.969h5.732l2.4-4h9.802l1.785 3.030 0.55 0.97h5.731c0.705 0 0.99 0.921 1 1v16.032zM16 10c-3.866 0-7 3.134-7 7s3.134 7 7 7 7-3.134 7-7-3.134-7-7-7zM16 22c-2.757 0-5-2.243-5-5s2.243-5 5-5 5 2.243 5 5-2.243 5-5 5z"></path>\n</svg>');return t.id="camera-icon",t}addClickEvent(t,e,i,s){const n=lo.createCameraModalFunc(t,e,i,s);this.elementRef.onclick=n}}class ho{constructor(t,e,i,s){this.elementRef=ho.createPanelElement(t.inputAreaStyle);const n={},o=this.createFileUploadComponents(t,i,s,n),r=new m(t,i,o);t.speechToText&&!n.microphone&&(n.microphone={button:new Un(t,r,e.addNewErrorMessage.bind(e))});const a=new ao(t,r,e,i,o,n);r.submit=a.submitFromInput.bind(a),eo.attach(t,i,r,o,a),t.submitUserMessage=a.programmaticSubmit.bind(a),n.submit={button:a},ho.addElements(this.elementRef,r,n,s,o,t.dropupStyles)}static createPanelElement(t){const e=document.createElement("div");return e.id="input",Object.assign(e.style,t),e}createFileUploadComponents(t,e,i,s){var n,o,r,a;const l=new Wn(this.elementRef,t.attachmentContainerStyle,e.demo);if(ho.createUploadButtons(t,e.fileTypes||{},l,i,s),null!=(n=e.camera)&&n.files){const n=(null==(o=s.images)?void 0:o.fileType)||l.addType(t,e.camera.files,"images");s.camera={button:new co(i,n,e.camera)}}if(null!=(r=e.recordAudio)&&r.files){const i=(null==(a=s.audio)?void 0:a.fileType)||l.addType(t,e.recordAudio.files,"audio");s.microphone={button:new so(i,e.recordAudio)}}return to.isEnabled(l,t.dragAndDrop)&&to.create(i,l,t.dragAndDrop),l}static createUploadButtons(t,e,i,s,n){Object.keys(e).forEach((o=>{const r=o,a=e[r];if(a.files){const e=i.addType(t,a.files,r),{id:o,svgString:l,dropupText:c}=ws[r],h=new Yn(s,e,a,o,l,c);n[r]={button:h,fileType:e}}}))}static addElements(t,e,i,s,n,o){x.addElements(t,e.elementRef);const r=hs.create(),a=ys.addButtons(r,i,s,o);cs.set(e.inputElementRef,r,n.elementRef,a),hs.add(t,r)}}class uo{static createElements(t,e,i){const s=document.createElement("div");s.id="chat-view";const n=new as(t,e,i);e.websocket&&Ce.createConnection(e,n);const o=new ho(t,n,e,s);return x.addElements(s,n.elementRef,o.elementRef),s}static render(t,e,i,s){const n=uo.createElements(t,i,s);e.replaceChildren(n)}}var po=Object.defineProperty,mo=(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&&po(e,i,o),o};class vo extends De{constructor(){super(),this.getMessages=()=>[],this.submitUserMessage=()=>console.warn("submitUserMessage failed - please wait for chat view to render before calling this property."),this.addMessage=()=>console.warn("addMessage failed - please wait for chat view to render before calling this property."),this.focusInput=()=>v.focusFromParentElement(this._elementRef),this.refreshMessages=()=>{},this.clearMessages=()=>{},this.scrollToBottom=()=>{},this.disableSubmitButton=()=>{},this.setPlaceholderText=()=>{},this._hasBeenRendered=!1,this._auxiliaryStyleApplied=!1,this._elementRef=document.createElement("div"),this._elementRef.id="container",this.attachShadow({mode:"open"}).appendChild(this._elementRef),r.apply('#validate-property-key-view{height:100%;position:relative;display:flex;justify-content:center;align-items:center;padding:8px}#loading-validate-key-property{display:inline-block;width:50px;height:50px}#loading-validate-key-property:after{content:" ";display:block;width:38px;height:38px;margin:1px;border-radius:50%;border:5px solid #5fb2ff;border-color:#5fb2ff transparent #5fb2ff transparent;animation:loading-spinner 1.4s linear infinite}#insert-key-view{height:100%;position:relative}#insert-key-contents{text-align:center;position:absolute;top:44%;left:50%;transform:translate(-50%,-50%);width:82%;display:flex;max-width:700px}#insert-key-title{margin-bottom:15px}#insert-key-input-container{margin-right:2.7em;width:calc(100% - 80px)}#insert-key-input{padding:.3em 1.7em .3em .3em;border-width:1px;border-style:solid;border-radius:3px;width:100%;font-size:inherit}.insert-key-input-valid{border-color:gray}.insert-key-input-invalid{border-color:red}#visibility-icon-container{position:relative;float:right;cursor:pointer;-webkit-user-select:none;user-select:none}.visibility-icon{filter:brightness(0) saturate(100%) invert(63%) sepia(1%) saturate(9%) hue-rotate(43deg) brightness(98%) contrast(92%);position:absolute;right:-1.7em;top:-1.43em}#visible-icon{top:-1.4em}.visibility-icon:hover{filter:unset}.visibility-icon>*{pointer-events:none}#start-button{border:1px solid grey;color:#454545;border-radius:4px;width:3em;display:flex;justify-content:center;align-items:center;cursor:pointer;padding:.28em .3em;-webkit-user-select:none;user-select:none;background-color:#fff}#start-button:hover{background-color:#f2f2f2}#start-button:active{background-color:#d2d2d2}#insert-key-help-text-container{width:100%;position:absolute;margin-top:32px;margin-bottom:20px}#insert-key-help-text-contents{width:100%;position:absolute}#insert-key-input-invalid-text{display:block;margin-top:1em;margin-bottom:.5em;color:red}.insert-key-input-help-text{display:block;margin-top:16px}#loading-key{display:inline-block;width:16px;height:16px}#loading-key:after{content:" ";display:block;width:11px;height:11px;margin:1px;border-radius:50%;border:2px solid #0084ff;border-color:#0084ff transparent #0084ff transparent;animation:loading-spinner 1.2s linear infinite}#error-view{color:red;font-size:1.2em;line-height:1.3em;margin-top:-5px;text-align:center;height:100%;display:flex;justify-content:center;align-items:center;padding-left:8px;padding-right:8px}@keyframes loading-spinner{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.intro-panel{position:absolute;display:flex;justify-content:center;right:0;bottom:0;left:0;margin:auto;height:fit-content;top:-2.5em}#internal-intro-panel{width:250px;height:min-content;display:block;border-radius:5px;overflow:auto;border:1px solid rgb(203,203,203);padding:10px;max-height:calc(100% - 6.8em)}#internal-intro-panel>p{margin-block-start:.8em;margin-block-end:.8em}pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}/*!\n Theme: a11y-dark\n Author: @ericwbailey\n Maintainer: @ericwbailey\n\n Based on the Tomorrow Night Eighties theme: https://github.com/isagalaev/highlight.js/blob/master/src/styles/tomorrow-night-eighties.css\n*/.hljs{background:#2b2b2b;color:#f8f8f2}.hljs-comment,.hljs-quote{color:#d4d0ab}.hljs-deletion,.hljs-name,.hljs-regexp,.hljs-selector-class,.hljs-selector-id,.hljs-tag,.hljs-template-variable,.hljs-variable{color:#ffa07a}.hljs-built_in,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-type{color:#f5ab35}.hljs-attribute{color:gold}.hljs-addition,.hljs-bullet,.hljs-string,.hljs-symbol{color:#abe338}.hljs-section,.hljs-title{color:#00e0e0}.hljs-keyword,.hljs-selector-tag{color:#dcc6e0}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}@media screen and (-ms-high-contrast: active){.hljs-addition,.hljs-attribute,.hljs-built_in,.hljs-bullet,.hljs-comment,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-quote,.hljs-string,.hljs-symbol,.hljs-type{color:highlight}.hljs-keyword,.hljs-selector-tag{font-weight:700}}#messages{overflow:auto}.outer-message-container:last-child{margin-bottom:5px}.inner-message-container{display:flex;margin-left:auto;margin-right:auto;width:calc(97.5% - 24px);max-width:100%}.message-bubble{margin-top:10px;word-wrap:break-word;width:fit-content;max-width:60%;border-radius:10px;padding:.42em .55em;height:fit-content;line-height:1.26em}.user-message-text{color:#fff;background-color:#0084ff;margin-right:0;margin-left:auto}.ai-message-text{color:#000;background-color:#e4e6eb;margin-left:0;margin-right:auto}.loading-history-message-full-view{position:absolute;height:70%;width:100%;display:flex;align-items:center}.loading-history-message-small{height:20px;margin-bottom:30px}.loading-history-message-small>div>div{scale:.6}.loading-history-message{margin-top:0;width:100%;max-width:100%;display:flex;justify-content:center;background-color:unset}.loading-history{width:70px}.loading-history div{position:absolute;width:var(--loading-history-width);height:var(--loading-history-height);margin:var(--loading-history-margin);border:var(--loading-history-border) solid;border-radius:50%;animation:loading-spinner 1.2s cubic-bezier(.5,0,.5,1) infinite;border-color:var(--loading-history-color) transparent transparent transparent}.loading-history div:nth-child(1){animation-delay:-.45s}.loading-history div:nth-child(2){animation-delay:-.3s}.loading-history div:nth-child(3){animation-delay:-.15s}.html-message{max-width:unset}.error-message-text{margin:14px auto 10px;background-color:#f4c0c0;color:#474747;text-align:center;max-width:95%}.deep-chat-loading-message-dots-container{width:1em;padding:.6em .75em .6em 1.3em}.loading-message-dots{position:relative;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite linear alternate;animation-delay:.5s}.loading-message-dots:before,.loading-message-dots:after{content:"";display:inline-block;position:absolute;top:0}.loading-message-dots:before{left:-.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite alternate;animation-delay:0s}.loading-message-dots:after{left:.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--loading-message-color);color:var(--loading-message-color);animation:loading-message-dots 1s infinite alternate;animation-delay:1s}@keyframes loading-message-dots{0%{background-color:var(--loading-message-color)}50%,to{background-color:var(--loading-message-color-fade)}}.message-bubble>p:first-child{margin-top:0}.message-bubble>p:last-child{margin-bottom:0}pre{overflow:auto;display:block;word-break:break-all;word-wrap:break-word;border-radius:7px;background:#2b2b2b;color:#f8f8f2;margin-top:.8em;margin-bottom:.8em;padding:.6em;font-size:.9em;line-height:1.5em}.image-message{padding:0;display:flex;background-color:#ddd}.image-message>*,.image-message>*>*{width:100%;border-radius:8px;display:flex}.audio-message{width:60%;max-width:300px;height:2.2em;max-height:54px;padding:0;background-color:unset}.audio-player{width:100%;height:100%}.audio-player-safari{height:fit-content;width:40px}.audio-player-safari-left{float:left}.audio-player-safari-right{float:right}.any-file-message-bubble{padding:1px}.any-file-message-contents{display:flex}.any-file-message-icon-container{width:1.3em;min-width:1.3em;position:relative;border-radius:4px;margin-left:6px;margin-right:2px}.any-file-message-icon{background-color:#fff;border-radius:4px;position:absolute;width:1em;height:1.25em;padding:1px;margin-top:auto;margin-bottom:auto;top:0;bottom:0}.any-file-message-text{padding-top:5px;overflow-wrap:anywhere;padding-bottom:5px;padding-right:7px}.message-bubble>a{color:inherit}.left-item-position{margin-right:10px}.right-item-position{margin-left:10px}.avatar{padding-top:5px;width:1.5em;height:1.5em;border-radius:1px}.avatar-container{margin-top:9px}.name{margin-top:16px;font-size:15px}#drag-and-drop{position:absolute;display:none;z-index:10;height:calc(100% - 10px);width:calc(100% - 10px);background-color:#70c6ff4d;border:5px dashed #6dafff}#file-attachment-container{position:absolute;height:3.6em;width:calc(80% - 4px);top:-2.5em;border-radius:5px;overflow:auto;text-align:left;background-color:#d7d7d73b;padding-left:4px}.file-attachment{width:2.85em;height:2.85em;display:inline-flex;margin-right:.6em;margin-bottom:.44em;margin-top:4px;position:relative;background-color:#fff;border-radius:5px}.image-attachment{width:100%;height:100%;object-fit:cover;border-radius:5px}.border-bound-attachment{width:calc(100% - 2px);height:calc(100% - 2px);border:1px solid #c3c3c3;border-radius:5px;overflow:hidden}.border-bound-attachment-safari{width:calc(100% - 1px);height:calc(100% - 1px)}.audio-attachment-icon-container{cursor:pointer}.audio-attachment-icon-container:hover{background-color:#f8f8f8}.attachment-icon{left:0;right:0;bottom:0;top:2px;margin:auto;position:absolute;width:25px;-webkit-user-select:none;user-select:none}.not-removable-attachment-icon{top:0;right:0;bottom:0;left:0}.play-icon{filter:brightness(0) saturate(100%) invert(17%) sepia(0%) saturate(1392%) hue-rotate(67deg) brightness(98%) contrast(97%)}.stop-icon{filter:brightness(0) saturate(100%) invert(29%) sepia(90%) saturate(1228%) hue-rotate(198deg) brightness(93%) contrast(98%)}.audio-placeholder-text-3-digits{padding-left:.26rem}.audio-placeholder-text-4-digits{padding-left:.1rem}.any-file-attachment{padding:2px 0}.file-attachment-text-container{position:absolute;width:inherit;display:flex;align-items:center;height:100%;top:-1px}.audio-placeholder-text-3-digits-container{padding-top:1px;cursor:default}.any-file-attachment-text{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;padding-left:.13em;margin-left:auto;margin-right:auto}.remove-file-attachment-button{height:1.25em;width:1.25em;border:1px solid #cfcfcf;border-radius:25px;background-color:#fff;top:-4px;right:-5px;position:absolute;display:flex;justify-content:center;cursor:pointer;-webkit-user-select:none;user-select:none}.remove-file-attachment-button:hover{background-color:#e4e4e4}.remove-file-attachment-button:active{background-color:#d7d7d7}.x-icon{color:#4e4e4e;top:-.075em;position:relative;font-size:1.05em}.modal{display:none;flex-direction:column;align-items:center;justify-content:center;position:absolute;width:80%;max-width:420px;max-height:80%;margin:auto;top:0;right:0;bottom:0;left:0;z-index:2}.modal-content{border-top:1px solid rgb(217,217,217);border-left:1px solid rgb(217,217,217);border-right:1px solid rgb(217,217,217);border-top-left-radius:inherit;border-top-right-radius:inherit;background-color:#fff;overflow-y:auto;height:fit-content;max-height:calc(100% - 3.3em);width:100%}.modal-content>p{margin-left:1em;margin-right:1em}.modal-content>ul{margin-right:1em}.modal-button-panel{height:3.3em;border:1px solid;border-color:rgb(223,223,223) rgb(217,217,217) rgb(217,217,217);border-bottom-left-radius:inherit;border-bottom-right-radius:inherit;background-color:#fff;text-align:center;justify-content:center;display:flex;width:100%}.modal-button{min-width:2.5em;text-align:center;color:#fff;border-radius:5px;padding:.4em .4em .3em;height:1.25em;background-color:#3279b2;top:0;bottom:0;cursor:pointer;-webkit-user-select:none;user-select:none;margin:auto .31em}.modal-button:hover{background-color:#276da7}.modal-button:active{background-color:#1b5687}.modal-svg-button{padding:0 0 2px;width:2em;height:1.8em}.modal-svg-button-icon{width:100%;height:100%;filter:brightness(0) saturate(100%) invert(100%) sepia(15%) saturate(4%) hue-rotate(346deg) brightness(101%) contrast(102%)}#modal-background-panel{position:absolute;width:100%;height:100%;background-color:#00000042;z-index:1;display:none}.show-modal-background{animation:fadeInBackground .3s ease-in-out}@keyframes fadeInBackground{0%{opacity:0}to{opacity:1}}.show-modal{animation:fadeInModal .3s ease-in-out}@keyframes fadeInModal{0%{opacity:0;scale:.95}to{opacity:1;scale:1}}.hide-modal-background{animation:fadeOutBackground .2s ease-in-out}@keyframes fadeOutBackground{0%{opacity:1}to{opacity:0}}.hide-modal{animation:fadeOutModal .2s ease-in-out}@keyframes fadeOutModal{0%{opacity:1;scale:1}to{opacity:0;scale:.95}}.modal-camera-content{overflow:hidden;text-align:center;border:unset;height:100%;background-color:#2a2a2a;display:flex;justify-content:center}.camera-modal-canvas{max-width:100%;max-height:100%;margin-top:auto;margin-bottom:auto}.modal-svg-submit-button{background-color:green}.modal-svg-submit-button:hover{background-color:#007500}.modal-svg-submit-button:active{background-color:#006500}.modal-svg-submit-disabled{pointer-events:none;background-color:#747474}.modal-svg-close-button{height:1.56em;padding-top:.37em;padding-bottom:0;background-color:#c13e3e}.modal-svg-close-button:hover{background-color:#b43434}.modal-svg-close-button:active{background-color:#972929}.modal-svg-close-icon{width:80%;height:80%}.modal-svg-camera-button{height:1.6em;padding-top:.38em;padding-bottom:0}.modal-svg-camera-icon{height:76%}.modal-svg-refresh-icon{height:105%}.modal-svg-refresh-button{height:1.66em;padding-top:.11em;padding-bottom:.21em}.input-button-container{position:relative;z-index:1}.inside-right{position:absolute;right:calc(10% + .35em);bottom:.85em}.inside-left{position:absolute;left:calc(10% + .35em);bottom:.85em}.outside-left{position:absolute;right:calc(11px - .55em);bottom:.88em}.outside-right{position:absolute;left:calc(11px - .55em);bottom:.88em}#upload-images-icon{position:absolute;pointer-events:none;width:1.45em;height:1.45em;left:.11em;bottom:.08em;filter:brightness(0) saturate(100%) invert(43%) sepia(0%) saturate(740%) hue-rotate(77deg) brightness(99%) contrast(92%)}#upload-gifs-icon{position:absolute;pointer-events:none;width:1.5em;height:1.48em;left:.07em;bottom:.08em;filter:brightness(0) saturate(100%) invert(49%) sepia(0%) saturate(2586%) hue-rotate(12deg) brightness(93%) contrast(90%)}#upload-audio-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.17em;bottom:.2em;filter:brightness(0) saturate(100%) invert(15%) sepia(0%) saturate(337%) hue-rotate(125deg) brightness(91%) contrast(94%);transform:scaleX(.95)}#camera-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.23em;bottom:.2em;filter:brightness(0) saturate(100%) invert(52%) sepia(0%) saturate(161%) hue-rotate(164deg) brightness(91%) contrast(92%);transform:scaleX(.95)}#upload-mixed-files-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.2em;filter:brightness(0) saturate(100%) invert(53%) sepia(0%) saturate(36%) hue-rotate(74deg) brightness(98%) contrast(93%);transform:scaleX(.95)}#interim-text{color:gray}#microphone-button{padding-top:.5px}.outer-button-container>#microphone-button{padding-bottom:1px}#microphone-icon{position:absolute;pointer-events:none;width:1.21em;height:1.21em;left:.25em;bottom:.25em}.default-microphone-icon{filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%)}.active-microphone-icon{filter:brightness(0) saturate(100%) invert(10%) sepia(97%) saturate(7495%) hue-rotate(0deg) brightness(101%) contrast(107%);border-radius:10px}.command-microphone-icon{filter:brightness(0) saturate(100%) invert(42%) sepia(96%) saturate(1067%) hue-rotate(77deg) brightness(99%) contrast(102%)}.unsupported-microphone{display:none}#submit-icon{height:100%;filter:brightness(0) saturate(100%) invert(32%) sepia(0%) saturate(924%) hue-rotate(46deg) brightness(95%) contrast(99%);width:1.21em}#stop-icon{background-color:#acacac;position:absolute;width:.95em;height:.95em;left:.35em;bottom:.35em;border-radius:2px}.submit-button-enlarged{scale:1.1;margin-right:.3em;margin-left:.3em}.loading-submit-button{position:relative;left:calc(-9990px + .275em);width:.22em;height:.22em;border-radius:5px;background-color:#848484;color:#848484;box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484;animation:loading-submit-button 1.5s infinite linear;bottom:-.75em}@keyframes loading-submit-button{0%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}16.667%{box-shadow:9990px -6px #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}33.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}50%{box-shadow:9990px 0 #848484,calc(9990px + .44em) -6px 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}66.667%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}83.333%{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) -6px 0 0 #848484}to{box-shadow:9990px 0 #848484,calc(9990px + .44em) 0 0 0 #848484,calc(9990px + .8em) 0 0 0 #848484}}.input-button{border-radius:4px;cursor:pointer;margin-bottom:.2em;-webkit-user-select:none;user-select:none}.input-button-svg{width:1.65em;height:1.65em}.input-button:hover{background-color:#9c9c9c2e}.input-button:active{background-color:#9c9c9c5e}.loading-button{cursor:auto}.loading-button:hover{background-color:unset}.text-button{filter:unset!important;display:flex;justify-content:center;align-items:center;margin-left:4px;margin-right:4px;height:1.6em}#text-input-container{background-color:#fff;width:80%;display:flex;border:1px solid #0000001a;border-radius:5px;margin-top:.8em;margin-bottom:.8em;box-shadow:#959da533 0 1px 12px;overflow-y:auto;max-height:200px;position:relative}.text-input-container-left-adjustment{margin-left:1.5em}.text-input-container-right-adjustment{margin-right:1.5em}.text-input-container-left-small-adjustment{margin-left:1.1em}.text-input-container-left-small-adjustment>.outside-left{right:calc(14px - .55em)}.text-input-container-right-small-adjustment{margin-right:1.1em}.text-input-container-right-small-adjustment>.outside-right{left:calc(14px - .55em)}#text-input{text-align:left;outline:none;word-wrap:break-word;line-break:auto}.text-input-styling{padding:.4em .5em;overflow:overlay;width:100%}.text-input-inner-left-adjustment{padding-left:2.2em}.text-input-inner-right-adjustment{padding-right:2em}.text-input-disabled{pointer-events:none;-webkit-user-select:none;user-select:none}[contenteditable]:empty:before{content:attr(deep-chat-placeholder-text);pointer-events:none}[contenteditable][textcolor]:empty:before{color:gray}.outside-right>#dropup-menu,.inside-right>#dropup-menu{right:0}#dropup-icon{position:absolute;pointer-events:none;width:1.16em;height:1.2em;left:.265em;bottom:.43em;filter:brightness(0) saturate(100%) invert(54%) sepia(0%) saturate(724%) hue-rotate(6deg) brightness(92%) contrast(90%)}#dropup-menu{background-color:#fff;position:absolute;transform:translateY(-100%);border-radius:5px;z-index:1;top:-.49em;box-shadow:#0003 -1px 2px 10px,#0000001a 0 2px 4px;cursor:pointer;-webkit-user-select:none;user-select:none}.dropup-menu-item{height:1.4em;padding:.28em .84em .28em .35em;display:flex;position:relative}.dropup-menu-item:first-child{padding-top:.49em;border-top-left-radius:inherit;border-top-right-radius:inherit}.dropup-menu-item:last-child{padding-bottom:.45em;border-bottom-left-radius:inherit;border-bottom-right-radius:inherit}.dropup-menu-item-icon{width:1.39em;position:relative;margin-right:.56em}.dropup-menu-item-icon>svg{bottom:0!important;top:0!important;margin-bottom:auto;margin-top:auto}.dropup-menu-item-text{margin-top:.08em;width:max-content}#input{width:100%;display:inline-flex;text-align:center;margin-left:auto;margin-right:auto;margin-top:auto;position:relative;justify-content:center}#chat-view{height:100%;display:grid;grid-template-columns:100%}::-webkit-scrollbar{width:9px;height:9px}::-webkit-scrollbar-thumb{background-color:#d0d0d0;border-radius:5px}::-webkit-scrollbar-track{background-color:#f2f2f2}.deep-chat-web-model-button{margin-top:10px;margin-bottom:5px;margin-left:1px}:host{all:initial;display:table-cell}#container{height:inherit;width:inherit;overflow:hidden}',this.shadowRoot),setTimeout((()=>{this._hasBeenRendered||this.onRender()}),20)}changeToChatView(){this._activeService&&(this._activeService.validateKeyProperty=!1),this.onRender()}onRender(){n.attemptAppendStyleSheetToHead(this.style),S.processConnect(this),(!this._activeService||this._activeService.demo)&&(this._activeService=ts.create(this)),this.auxiliaryStyle&&!this._auxiliaryStyleApplied&&(r.apply(this.auxiliaryStyle,this.shadowRoot),this._auxiliaryStyleApplied=!0),r.applyDefaultStyleToComponent(this.style,this.chatStyle),S.checkForContainerStyles(this,this._elementRef),this._activeService.key&&this._activeService.validateKeyProperty?e.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):this._activeService instanceof Be&&!this._activeService.key?this._activeService instanceof Be&&Ve.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):(this._childElement??(this._childElement=this.children[0]),uo.render(this,this._elementRef,this._activeService,this._childElement)),this._hasBeenRendered=!0,pe.onRender(this)}disconnectedCallback(){We.chat=void 0}}mo([ss("object")],vo.prototype,"connect"),mo([ss("object")],vo.prototype,"directConnection"),mo([ss("object")],vo.prototype,"webModel"),mo([ss("object")],vo.prototype,"requestBodyLimits"),mo([ss("function")],vo.prototype,"requestInterceptor"),mo([ss("function")],vo.prototype,"responseInterceptor"),mo([ss("function")],vo.prototype,"validateInput"),mo([ss("function")],vo.prototype,"loadHistory"),mo([ss("object")],vo.prototype,"chatStyle"),mo([ss("object")],vo.prototype,"attachmentContainerStyle"),mo([ss("object")],vo.prototype,"dropupStyles"),mo([ss("object")],vo.prototype,"inputAreaStyle"),mo([ss("object")],vo.prototype,"textInput"),mo([ss("object")],vo.prototype,"submitButtonStyles"),mo([ss("string")],vo.prototype,"auxiliaryStyle"),mo([ss("array")],vo.prototype,"history"),mo([ss("object")],vo.prototype,"introMessage"),mo([ss("object")],vo.prototype,"avatars"),mo([ss("object")],vo.prototype,"names"),mo([ss("boolean")],vo.prototype,"displayLoadingBubble"),mo([ss("object")],vo.prototype,"errorMessages"),mo([ss("object")],vo.prototype,"messageStyles"),mo([ss("object")],vo.prototype,"textToSpeech"),mo([ss("object")],vo.prototype,"speechToText"),mo([ss("object")],vo.prototype,"images"),mo([ss("object")],vo.prototype,"gifs"),mo([ss("object")],vo.prototype,"camera"),mo([ss("object")],vo.prototype,"audio"),mo([ss("object")],vo.prototype,"microphone"),mo([ss("object")],vo.prototype,"mixedFiles"),mo([ss("object")],vo.prototype,"dragAndDrop"),mo([ss("object")],vo.prototype,"introPanelStyle"),mo([ss("object")],vo.prototype,"htmlClassUtilities"),mo([ss("function")],vo.prototype,"onMessage"),mo([ss("function")],vo.prototype,"onClearMessages"),mo([ss("function")],vo.prototype,"onComponentRender"),mo([ss("function")],vo.prototype,"onError"),mo([ss("object")],vo.prototype,"demo"),mo([ss("object")],vo.prototype,"_insertKeyViewStyles"),customElements.define("deep-chat",vo);export{vo as DeepChat};