deep-chat-dev 9.0.60 → 9.0.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/custom-elements.json +5204 -5206
- package/dist/deepChat.bundle.js +1 -1
- package/dist/deepChat.d.ts.map +1 -1
- package/dist/deepChat.js +46 -46
- package/dist/types/openAI.d.ts +8 -4
- package/dist/types/openAI.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/deepChat.bundle.js
CHANGED
@@ -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="large-loading-ring"></div>'}static createElements(){const t=document.createElement("div");return t.id="validate-property-key-view",t}static render(i,n,s){const o=e.createElements(),r={onSuccess:n,onFail:t.render.bind(this,i,"Your 'key' has failed authentication"),onLoad:e.onLoad.bind(this,o)};s.key&&s.verifyKey(s.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 n=t.default||{},s=Object.assign(JSON.parse(JSON.stringify({...n,...e})),null==t?void 0:t.hover);return{default:n,hover:s,click:Object.assign(JSON.parse(JSON.stringify({...s,...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 n;const s=i;e.style[s]&&null!=(n=t.default)&&n[s]&&(t.default[i]=e.style[s])}))}static applyToStyleIfNotDefined(t,e){for(const i in e){const n=e[i];""===t[i]&&n&&(t[i]=n)}}}const n=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){i.applyToStyleIfNotDefined(e,t.DEFAULT_COMPONENT_STYLE)}};n.DEFAULT_COMPONENT_STYLE={height:"350px",width:"320px",border:"1px solid #cacaca",fontFamily:"'Inter', sans-serif, Avenir, Helvetica, Arial",fontSize:"0.9rem",backgroundColor:"white",position:"relative",overflow:"hidden"};let s=n;var o=(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))(o||{});let r=class{};r.IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),r.IS_CHROMIUM=window.chrome;const a=class t{static add(e,i,n){void 0!==i&&e.addEventListener("keydown",t.onKeyDown.bind(this,i)),e.oninput=t.onInput.bind(this,i,n)}static onKeyDown(e,i){const n=i.target.textContent;n&&n.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 n=i.target,s=n.textContent||"";void 0!==t&&s.length>t&&(n.textContent=s.substring(0,t),d.focusEndOfInput(n)),null==e||e()}};a.PERMITTED_KEYS=new Set([o.BACKSPACE,o.DELETE,o.ARROW_RIGHT,o.ARROW_LEFT,o.ARROW_DOWN,o.ARROW_UP,o.META,o.CONTROL,o.ENTER]);let c=a;class l{static sanitizePastedTextContent(t){var e,i;t.preventDefault();const n=null==(e=t.clipboardData)?void 0:e.getData("text/plain");null==(i=document.execCommand)||i.call(document,"insertHTML",!1,n)}}const u=class t{constructor(e,i){var n;const s=t.processConfig(i,e.textInput);this.elementRef=t.createContainerElement(null==(n=null==s?void 0:s.styles)?void 0:n.container),this.inputElementRef=this.createInputElement(s),this._config=s,this.elementRef.appendChild(this.inputElementRef),setTimeout((()=>{var t;c.add(this.inputElementRef,null==(t=e.textInput)?void 0:t.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 preventAutomaticScrollUpOnNewLine(t){let e;t.addEventListener("keydown",(()=>{e=window.scrollY})),t.addEventListener("input",(()=>{e!==window.scrollY&&window.scrollTo({top:e})}))}static clear(t){const e=window.scrollY;t.classList.contains("text-input-disabled")||(t.textContent=""),r.IS_CHROMIUM&&window.scrollTo({top:e})}createInputElement(e){var i,n,s;const o=document.createElement("div");return o.id=t.TEXT_INPUT_ID,o.classList.add("text-input-styling","text-input-placeholder"),o.innerText=(null==(i=null==e?void 0:e.placeholder)?void 0:i.text)||"Ask me anything!",r.IS_CHROMIUM&&t.preventAutomaticScrollUpOnNewLine(o),"boolean"==typeof(null==e?void 0:e.disabled)&&!0===e.disabled?(o.contentEditable="false",o.classList.add("text-input-disabled")):(o.contentEditable="true",this.addEventListeners(o,e)),Object.assign(o.style,null==(n=null==e?void 0:e.styles)?void 0:n.text),Object.assign(o.style,null==(s=null==e?void 0:e.placeholder)?void 0:s.style),o}removeTextIfPlaceholder(){var e,n,s,o;this.inputElementRef.classList.contains("text-input-placeholder")&&!this.inputElementRef.classList.contains("text-input-disabled")&&(null!=(e=this._config.placeholder)&&e.style&&(i.unsetStyle(this.inputElementRef,null==(n=this._config.placeholder)?void 0:n.style),Object.assign(this.inputElementRef.style,null==(o=null==(s=this._config)?void 0:s.styles)?void 0:o.text)),t.clear(this.inputElementRef),this.inputElementRef.classList.remove("text-input-placeholder"))}static toggleEditability(t,e){t.contentEditable=e?"true":"false"}addEventListeners(t,e){var i,n,s;t.onfocus=this.onFocus.bind(this,null==(i=null==e?void 0:e.styles)?void 0:i.focus),null!=(n=null==e?void 0:e.styles)&&n.focus&&(t.onblur=this.onBlur.bind(this,e.styles.focus,null==(s=null==e?void 0:e.styles)?void 0:s.container)),t.addEventListener("keydown",this.onKeydown.bind(this)),t.onpaste=l.sanitizePastedTextContent}onFocus(t){r.IS_SAFARI?setTimeout((()=>{this.removeTextIfPlaceholder()})):this.removeTextIfPlaceholder(),Object.assign(this.elementRef.style,t)}onBlur(t,e){i.unsetStyle(this.elementRef,t),e&&Object.assign(this.elementRef.style,e)}static createContainerElement(t){const e=document.createElement("div");return e.id="text-input-container",Object.assign(e.style,t),e}onKeydown(t){var e;t.key===o.ENTER&&!t.ctrlKey&&!t.shiftKey&&(t.preventDefault(),null==(e=this.submit)||e.call(this))}};u.TEXT_INPUT_ID="text-input";let h=u;class d{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(`#${h.TEXT_INPUT_ID}`);e&&d.focusEndOfInput(e)}}function p(t){return t.charAt(0).toUpperCase()+t.slice(1)}const m={INVALID_KEY:"Invalid API Key",CONNECTION_FAILED:"Failed to connect",INVALID_RESPONSE:function(t,e,i,n){const s=`\n${p(e)} message: ${JSON.stringify(t)} \n`,o=i?`${p(e)} message after interceptor: ${function(t){return t&&JSON.stringify(t)}(n)} \n`:"";return`${s+o}Make sure the ${e} message is using the Response format: https://deepchat.dev/docs/connect/#Response \n You can also augment it using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor`},INVALID_STREAM_RESPONSE:"Make sure the events are using the Response format: https://deepchat.dev/docs/connect/#Response \nYou can also augment them using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor"},f=class t{static async tempRemoveContentHeader(e,i,n){if(null==e||!e.headers)throw new Error("Request settings have not been set up");const s=e.headers[t.CONTENT_TYPE];let o;delete e.headers[t.CONTENT_TYPE];try{o=await i(n)}catch(i){throw e.headers[t.CONTENT_TYPE]=s,i}return e.headers[t.CONTENT_TYPE]=s,o}static displayError(t,e,i="Service error, please try again."){if(console.error(e),"object"==typeof e)return 0===Object.keys(e).length?t.addNewErrorMessage("service",i):t.addNewErrorMessage("service",JSON.stringify(e));t.addNewErrorMessage("service",e)}static fetch(t,e,i,n){var s,o;const r={method:(null==(s=t.requestSettings)?void 0:s.method)||"POST",headers:e};return"GET"!==r.method&&(r.body=i?JSON.stringify(n):n),fetch((null==(o=t.requestSettings)?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 n=await(null==(i=t.requestInterceptor)?void 0:i.call(t,e))||e,s=n,o=n;return{body:s.body,headers:s.headers,error:o.error}}static validateResponseFormat(t){return t&&"object"==typeof t&&("string"==typeof t.error||"string"==typeof t.text||"string"==typeof t.html||"object"==typeof t.files)}};f.CONTENT_TYPE="Content-Type";let v=f;function g(t){let e,i,n,s=!1;return function(o){void 0===e?(e=o,i=0,n=-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;){s&&(10===e[i]&&(a=++i),s=!1);let o=-1;for(;i<r&&-1===o;++i)switch(e[i]){case 58:-1===n&&(n=i-a);break;case 13:s=!0;case 10:o=i}if(-1===o)break;t(e.subarray(a,o),n),a=i,n=-1}a===r?e=void 0:0!==a&&(e=e.subarray(a),i-=a)}}var b=globalThis&&globalThis.__rest||function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const y="text/event-stream",w="last-event-id";function x(t,e){var{signal:i,headers:n,onopen:s,onmessage:o,onclose:r,onerror:a,openWhenHidden:c,fetch:l}=e,u=b(e,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise(((e,h)=>{const d=Object.assign({},n);let p;function m(){p.abort(),document.hidden||j()}d.accept||(d.accept=y),c||document.addEventListener("visibilitychange",m);let f=1e3,v=0;function b(){document.removeEventListener("visibilitychange",m),window.clearTimeout(v),p.abort()}null==i||i.addEventListener("abort",(()=>{b(),e()}));const x=l??window.fetch,k=s??M;async function j(){var i;p=new AbortController;try{const i=await x(t,Object.assign(Object.assign({},u),{headers:d,signal:p.signal}));await k(i),await async function(t,e){const i=t.getReader();let n;for(;!(n=await i.read()).done;)e(n.value)}(i.body,g(function(t,e,i){let n={data:"",event:"",id:"",retry:void 0};const s=new TextDecoder;return function(o,r){if(0===o.length)null==i||i(n),n={data:"",event:"",id:"",retry:void 0};else if(r>0){const i=s.decode(o.subarray(0,r)),a=r+(32===o[r+1]?2:1),c=s.decode(o.subarray(a));switch(i){case"data":n.data=n.data?n.data+"\n"+c:c;break;case"event":n.event=c;break;case"id":t(n.id=c);break;case"retry":const i=parseInt(c,10);isNaN(i)||e(n.retry=i)}}}}((t=>{t?d[w]=t:delete d[w]}),(t=>{f=t}),o))),null==r||r(),b(),e()}catch(t){if(!p.signal.aborted)try{const e=null!==(i=null==a?void 0:a(t))&&void 0!==i?i:f;window.clearTimeout(v),v=window.setTimeout(j,e)}catch(t){b(),h(t)}}}j()}))}function M(t){const e=t.headers.get("content-type");if(null==e||!e.startsWith(y))throw new Error(`Expected content-type to be ${y}, Actual: ${e}`)}const k=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,n){const s=t.getResponse(e);setTimeout((async()=>{const t=await(null==n?void 0:n(s))||s;t.error?e.addNewErrorMessage("service",t.error):e.addNewMessage(t,!0),i()}),400)}static requestStream(e,i){setTimeout((()=>{var n;const s=null==(n=t.getResponse(e))?void 0:n.text;S.simulate(e,i,s)}),400)}};k.URL="deep-chat-demo";let j=k;class S{static async request(t,e,i,n=!0){var s,o,r,a,c;const l={body:e,headers:null==(s=t.requestSettings)?void 0:s.headers},{body:u,headers:h,error:d}=await v.processRequestInterceptor(t.deepChat,l),{onOpen:p,onClose:f,abortStream:g}=t.streamHandlers;if(d)return S.onInterceptorError(i,d,f);if(null!=(o=t.requestSettings)&&o.handler)return A.stream(t,u,i);if((null==(r=t.requestSettings)?void 0:r.url)===j.URL)return j.requestStream(i,t.streamHandlers);let b=null;x((null==(a=t.requestSettings)?void 0:a.url)||t.url||"",{method:(null==(c=t.requestSettings)?void 0:c.method)||"POST",headers:h,body:n?JSON.stringify(u):u,openWhenHidden:!0,async onopen(t){if(t.ok)return b=i.addNewStreamedMessage(),p();throw await v.processResponseByType(t)},onmessage(e){var n;if(JSON.stringify(e.data)!==JSON.stringify("[DONE]")){const s=JSON.parse(e.data);null==(n=t.extractResultData)||n.call(t,s).then((t=>{void 0===(null==t?void 0:t.text)?console.error(`Response data: ${e.data} \n ${m.INVALID_STREAM_RESPONSE}`):b&&i.updateStreamedMessage(t.text,b)})).catch((t=>v.displayError(i,t)))}},onerror(t){throw f(),t},onclose(){i.finaliseStreamedMessage(),f()},signal:g.signal}).catch((e=>{var n;null==(n=t.extractResultData)||n.call(t,e).then((()=>{v.displayError(i,e)})).catch((t=>{v.displayError(i,t)}))}))}static onInterceptorError(t,e,i){t.addNewErrorMessage("service",e),null==i||i()}static simulate(t,e,i){const n=e,s=(null==i?void 0:i.split(" "))||[],o=t.addNewStreamedMessage();e.onOpen(),S.populateMessages(o,s,t,n)}static populateMessages(t,e,i,n,s=0){const o=e[s];if(o){i.updateStreamedMessage(`${o} `,t);const r=setTimeout((()=>{S.populateMessages(t,e,i,n,s+1)}),n.simulationInterim||70);n.abortStream.abort=()=>S.abort(r,i,n.onClose)}else i.finaliseStreamedMessage(),n.onClose()}static abort(t,e,i){clearTimeout(t),e.finaliseStreamedMessage(),i()}}class A{static async request(t,e,i){var n,s;let o=!0;const r=A.generateOptionalSignals();null==(s=(n=t.requestSettings).handler)||s.call(n,e,{...r,onResponse:async e=>{var n,s;if(!o)return;o=!1;const r=await(null==(s=(n=t.deepChat).responseInterceptor)?void 0:s.call(n,e))||e;v.validateResponseFormat(r)?"string"==typeof r.error?(console.error(r.error),i.addNewErrorMessage("service",r.error),t.completionsHandlers.onFinish()):t.deepChat.stream&&r.text?S.simulate(i,t.streamHandlers,r.text):(i.addNewMessage(r,!0),t.completionsHandlers.onFinish()):(console.error(m.INVALID_RESPONSE(e,"server",!!t.deepChat.responseInterceptor,r)),i.addNewErrorMessage("service","Error in server message"),t.completionsHandlers.onFinish())}})}static stream(t,e,i){var n,s;let o=!0,r=!1,a=null;t.streamHandlers.abortStream.abort=()=>{i.finaliseStreamedMessage(),t.streamHandlers.onClose(),o=!1};const c=A.generateOptionalSignals();null==(s=(n=t.requestSettings).handler)||s.call(n,e,{...c,onOpen:()=>{r||!o||(a=i.addNewStreamedMessage(),t.streamHandlers.onOpen(),r=!0)},onResponse:e=>{o&&(!e||"object"!=typeof e||"string"!=typeof e.error&&"string"!=typeof e.text?console.error(m.INVALID_RESPONSE(e,"server",!1)):e.error?(console.error(e.error),i.finaliseStreamedMessage(),t.streamHandlers.onClose(),i.addNewErrorMessage("service",e.error),o=!1):e.text&&a&&i.updateStreamedMessage(e.text,a))},onClose:()=>{o&&(i.finaliseStreamedMessage(),t.streamHandlers.onClose(),o=!1)},stopClicked:t.streamHandlers.stopClicked})}static websocket(t,e){var i,n;const s={isOpen:!1,newUserMessage:{listener:()=>{}}};t.websocket=s;const o=A.generateOptionalSignals();null==(n=(i=t.requestSettings).handler)||n.call(i,void 0,{...o,onOpen:()=>{e.removeError(),s.isOpen=!0},onResponse:async i=>{var n,o;if(!s.isOpen)return;const r=await(null==(o=(n=t.deepChat).responseInterceptor)?void 0:o.call(n,i))||i;v.validateResponseFormat(r)?"string"==typeof r.error?(console.error(r.error),e.isLastMessageError()||e.addNewErrorMessage("service",r.error)):t.deepChat.stream?S.simulate(e,t.streamHandlers,r.text):e.addNewMessage(r,!0):(console.error(m.INVALID_RESPONSE(i,"server",!!t.deepChat.responseInterceptor,r)),e.addNewErrorMessage("service","Error in server message"))},onClose:()=>{s.isOpen=!1},newUserMessage:s.newUserMessage})}static generateOptionalSignals(){return{onClose:()=>{},onOpen:()=>{},stopClicked:{listener:()=>{}},newUserMessage:{listener:()=>{}}}}}class T{static async request(t,e,i,n=!0){var s,o,r;const a={body:e,headers:null==(s=t.requestSettings)?void 0:s.headers},{body:c,headers:l,error:u}=await v.processRequestInterceptor(t.deepChat,a),{onFinish:h}=t.completionsHandlers;if(u)return T.onInterceptorError(i,u,h);if(null!=(o=t.requestSettings)&&o.handler)return A.request(t,c,i);if((null==(r=t.requestSettings)?void 0:r.url)===j.URL)return j.request(i,h,t.deepChat.responseInterceptor);let d=!0;const p=v.fetch.bind(this,t,l,n);p(c).then((t=>(d=!!t.ok,t))).then((t=>v.processResponseByType(t))).then((async e=>{var n,s;if(!t.extractResultData)return;const o=await(null==(s=(n=t.deepChat).responseInterceptor)?void 0:s.call(n,e))||e,r=await t.extractResultData(o,p,c);if(!d)throw e;if(!r||"object"!=typeof r)throw Error(m.INVALID_RESPONSE(e,"response",!!t.deepChat.responseInterceptor,o));r.makingAnotherRequest||(t.deepChat.stream&&r.text?S.simulate(i,t.streamHandlers,r.text):(i.addNewMessage(r,!0),h()))})).catch((t=>{v.displayError(i,t),h()}))}static executePollRequest(t,e,i,n){console.log("polling");const{onFinish:s}=t.completionsHandlers;fetch(e,i).then((t=>t.json())).then((async o=>{var r,a;if(!t.extractPollResultData)return;const c=await t.extractPollResultData(await(null==(a=(r=t.deepChat).responseInterceptor)?void 0:a.call(r,o))||o);c.timeoutMS?setTimeout((()=>{T.executePollRequest(t,e,i,n)}),c.timeoutMS):(console.log("finished polling"),n.addNewMessage(c,!0),s())})).catch((t=>{v.displayError(n,t),s()}))}static async poll(t,e,i,n=!0){var s,o,r;const a={body:e,headers:null==(s=t.requestSettings)?void 0:s.headers},{body:c,headers:l,error:u}=await v.processRequestInterceptor(t.deepChat,a);if(u)return T.onInterceptorError(i,u);const h=(null==(o=t.requestSettings)?void 0:o.url)||t.url||"",d={method:(null==(r=t.requestSettings)?void 0:r.method)||"POST",body:n?JSON.stringify(c):c,headers:l};T.executePollRequest(t,h,d,i)}static onInterceptorError(t,e,i){t.addNewErrorMessage("service",e),null==i||i()}static verifyKey(t,e,i,n,s,o,r,a,c){if(""===t)return o(m.INVALID_KEY);r(),fetch(e,{method:n,headers:i,body:c||null}).then((t=>v.processResponseByType(t))).then((e=>{a(e,t,s,o)})).catch((t=>{o(m.CONNECTION_FAILED),console.error(t)}))}}class O{static getCharacterLimitMessages(t,e){var i;let n=0,s=t.length-1;for(;s>=0;s-=1){const o=null==(i=t[s])?void 0:i.text;if(void 0!==o&&(n+=o.length,n>e)){t[s].text=o.substring(0,o.length-(n-e));break}}return t.slice(Math.max(s,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=O.getMaxMessages(t,e)):t=[t[t.length-1]],t=JSON.parse(JSON.stringify(t)),void 0===i?t:O.getCharacterLimitMessages(t,i)}}class C{static setup(t){t.requestSettings.url!==j.URL&&(t.permittedErrorPrefixes=["Connection error","Error in server message"],t.websocket="pending")}static createConnection(t,e){if(!document.body.contains(t.deepChat))return;const i=t.requestSettings.websocket;if(i){if(t.requestSettings.handler)return A.websocket(t,e);try{const n="boolean"!=typeof i?i:void 0,s=new WebSocket(t.requestSettings.url||"",n);t.websocket=s,t.websocket.onopen=()=>{var i,n;e.removeError(),t.websocket&&"object"==typeof t.websocket&&C.assignListeners(t,s,e),null==(n=(i=t.deepChat)._validationHandler)||n.call(i)},t.websocket.onerror=i=>{console.error(i),C.retryConnection(t,e)}}catch(i){console.error(i),C.retryConnection(t,e)}}}static retryConnection(t,e){var i,n;null==(n=(i=t.deepChat)._validationHandler)||n.call(i),document.body.contains(t.deepChat)&&(t.websocket="pending",e.isLastMessageError()||e.addNewErrorMessage("service","Connection error"),setTimeout((()=>{C.createConnection(t,e)}),5e3))}static assignListeners(t,e,i){e.onmessage=async e=>{var n,s;if(t.extractResultData)try{const o=JSON.parse(e.data),r=await(null==(s=(n=t.deepChat).responseInterceptor)?void 0:s.call(n,o))||o,a=await t.extractResultData(r);if(!a||"object"!=typeof a)throw Error(m.INVALID_RESPONSE(o,"server",!!t.deepChat.responseInterceptor,r));t.deepChat.stream&&a.text?S.simulate(i,t.streamHandlers,a.text):i.addNewMessage(a,!0)}catch(t){v.displayError(i,t,"Error in server message")}},e.onclose=()=>{console.error("Connection closed"),i.isLastMessageError()||i.addNewErrorMessage("service","Connection error"),C.createConnection(t,i)}}static async sendWebsocket(t,e,i,n=!0){var s,o;const r=t.websocket;if(!r||"pending"===r)return;const a={body:e,headers:null==(s=t.requestSettings)?void 0:s.headers},{body:c,error:l}=await v.processRequestInterceptor(t.deepChat,a);if(l)return i.addNewErrorMessage("service",l);if(!C.isWebSocket(r))return r.newUserMessage.listener(c);const u=n?JSON.stringify(c):c;if((null==(o=t.requestSettings)?void 0:o.url)===j.URL)return j.request(i,t.completionsHandlers.onFinish,t.deepChat.responseInterceptor);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(u))}static canSendMessage(t){return!t||"pending"!==t&&(C.isWebSocket(t)?void 0!==t.readyState&&t.readyState===t.OPEN:t.isOpen)}static isWebSocket(t){return void 0!==t.send}}class N{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 processInitialMessageFile(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}}var I;function E(t){return(I=I||document.createElement("textarea")).innerHTML="&"+t+";",I.value}var z=Object.prototype.hasOwnProperty;function L(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 P=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function _(t){return t.indexOf("\\")<0?t:t.replace(P,"$1")}function D(t){return!(t>=55296&&t<=57343||t>=64976&&t<=65007||65535==(65535&t)||65534==(65535&t)||t>=0&&t<=8||11===t||t>=14&&t<=31||t>=127&&t<=159||t>1114111)}function R(t){if(t>65535){var e=55296+((t-=65536)>>10),i=56320+(1023&t);return String.fromCharCode(e,i)}return String.fromCharCode(t)}var F=/&([a-z#][a-z0-9]{1,31});/gi,B=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;function J(t,e){var i=0,n=E(e);return e!==n?n:35===e.charCodeAt(0)&&B.test(e)&&D(i="x"===e[1].toLowerCase()?parseInt(e.slice(2),16):parseInt(e.slice(1),10))?R(i):t}function q(t){return t.indexOf("&")<0?t:t.replace(F,J)}var Y=/[&<>"]/,U=/[&<>"]/g,$={"&":"&","<":"<",">":">",'"':"""};function V(t){return $[t]}function Z(t){return Y.test(t)?t.replace(U,V):t}var H={};function G(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?G(t,e+2):e}H.blockquote_open=function(){return"<blockquote>\n"},H.blockquote_close=function(t,e){return"</blockquote>"+K(t,e)},H.code=function(t,e){return t[e].block?"<pre><code>"+Z(t[e].content)+"</code></pre>"+K(t,e):"<code>"+Z(t[e].content)+"</code>"},H.fence=function(t,e,i,n,s){var o,r,a=t[e],c="",l=i.langPrefix;if(a.params){if(r=(o=a.params.split(/\s+/g)).join(" "),function(t,e){return!!t&&z.call(t,e)}(s.rules.fence_custom,o[0]))return s.rules.fence_custom[o[0]](t,e,i,n,s);c=' class="'+l+Z(q(_(r)))+'"'}return"<pre><code"+c+">"+(i.highlight&&i.highlight.apply(i.highlight,[a.content].concat(o))||Z(a.content))+"</code></pre>"+K(t,e)},H.fence_custom={},H.heading_open=function(t,e){return"<h"+t[e].hLevel+">"},H.heading_close=function(t,e){return"</h"+t[e].hLevel+">\n"},H.hr=function(t,e,i){return(i.xhtmlOut?"<hr />":"<hr>")+K(t,e)},H.bullet_list_open=function(){return"<ul>\n"},H.bullet_list_close=function(t,e){return"</ul>"+K(t,e)},H.list_item_open=function(){return"<li>"},H.list_item_close=function(){return"</li>\n"},H.ordered_list_open=function(t,e){var i=t[e];return"<ol"+(i.order>1?' start="'+i.order+'"':"")+">\n"},H.ordered_list_close=function(t,e){return"</ol>"+K(t,e)},H.paragraph_open=function(t,e){return t[e].tight?"":"<p>"},H.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?K(t,e):"")},H.link_open=function(t,e,i){var n=t[e].title?' title="'+Z(q(t[e].title))+'"':"",s=i.linkTarget?' target="'+i.linkTarget+'"':"";return'<a href="'+Z(t[e].href)+'"'+n+s+">"},H.link_close=function(){return"</a>"},H.image=function(t,e,i){var n=' src="'+Z(t[e].src)+'"',s=t[e].title?' title="'+Z(q(t[e].title))+'"':"";return"<img"+n+(' alt="'+(t[e].alt?Z(q(_(t[e].alt))):"")+'"')+s+(i.xhtmlOut?" /":"")+">"},H.table_open=function(){return"<table>\n"},H.table_close=function(){return"</table>\n"},H.thead_open=function(){return"<thead>\n"},H.thead_close=function(){return"</thead>\n"},H.tbody_open=function(){return"<tbody>\n"},H.tbody_close=function(){return"</tbody>\n"},H.tr_open=function(){return"<tr>"},H.tr_close=function(){return"</tr>\n"},H.th_open=function(t,e){var i=t[e];return"<th"+(i.align?' style="text-align:'+i.align+'"':"")+">"},H.th_close=function(){return"</th>"},H.td_open=function(t,e){var i=t[e];return"<td"+(i.align?' style="text-align:'+i.align+'"':"")+">"},H.td_close=function(){return"</td>"},H.strong_open=function(){return"<strong>"},H.strong_close=function(){return"</strong>"},H.em_open=function(){return"<em>"},H.em_close=function(){return"</em>"},H.del_open=function(){return"<del>"},H.del_close=function(){return"</del>"},H.ins_open=function(){return"<ins>"},H.ins_close=function(){return"</ins>"},H.mark_open=function(){return"<mark>"},H.mark_close=function(){return"</mark>"},H.sub=function(t,e){return"<sub>"+Z(t[e].content)+"</sub>"},H.sup=function(t,e){return"<sup>"+Z(t[e].content)+"</sup>"},H.hardbreak=function(t,e,i){return i.xhtmlOut?"<br />\n":"<br>\n"},H.softbreak=function(t,e,i){return i.breaks?i.xhtmlOut?"<br />\n":"<br>\n":"\n"},H.text=function(t,e){return Z(t[e].content)},H.htmlblock=function(t,e){return t[e].content},H.htmltag=function(t,e){return t[e].content},H.abbr_open=function(t,e){return'<abbr title="'+Z(q(t[e].title))+'">'},H.abbr_close=function(){return"</abbr>"},H.footnote_ref=function(t,e){var i=Number(t[e].id+1).toString(),n="fnref"+i;return t[e].subId>0&&(n+=":"+t[e].subId),'<sup class="footnote-ref"><a href="#fn'+i+'" id="'+n+'">['+i+"]</a></sup>"},H.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'},H.footnote_block_close=function(){return"</ol>\n</section>\n"},H.footnote_open=function(t,e){return'<li id="fn'+Number(t[e].id+1).toString()+'" class="footnote-item">'},H.footnote_close=function(){return"</li>\n"},H.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>'},H.dl_open=function(){return"<dl>\n"},H.dt_open=function(){return"<dt>"},H.dd_open=function(){return"<dd>"},H.dl_close=function(){return"</dl>\n"},H.dt_close=function(){return"</dt>\n"},H.dd_close=function(){return"</dd>\n"};var K=H.getBreak=function(t,e){return(e=G(t,e))<t.length&&"list_item_close"===t[e].type?"":"\n"};function Q(){this.rules=L({},H),this.getBreak=H.getBreak}function W(){this.t=[],this.i=null}function X(t,e,i,n,s){this.src=t,this.env=n,this.options=i,this.parser=e,this.tokens=s,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 tt(t,e){var i,n,s,o=-1,r=t.posMax,a=t.pos,c=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===(s=t.src.charCodeAt(t.pos)))i++;else if(93===s&&0===--i){n=!0;break}t.parser.skipToken(t)}return n?(o=t.pos,t.labelUnmatchedScopes=0):t.labelUnmatchedScopes=i-1,t.pos=a,t.isInLabel=c,o}function et(t,e,i,n){var s,o,r,a,c,l;if(42!==t.charCodeAt(0)||91!==t.charCodeAt(1)||-1===t.indexOf("]:")||((o=tt(s=new X(t,e,i,n,[]),1))<0||58!==t.charCodeAt(o+1)))return-1;for(a=s.posMax,r=o+2;r<a&&10!==s.src.charCodeAt(r);r++);return c=t.slice(2,o),0===(l=t.slice(o+2,r).trim()).length?-1:(n.abbreviations||(n.abbreviations={}),typeof n.abbreviations[":"+c]>"u"&&(n.abbreviations[":"+c]=l),r)}function it(t){var e=q(t);try{e=decodeURI(e)}catch{}return encodeURI(e)}function nt(t,e){var i,n,s,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 s=it(_(t.src.slice(o+1,e))),!!t.parser.validateLink(s)&&(t.pos=e+1,t.linkContent=s,!0);92===i&&e+1<r?e+=2:e++}return!1}for(n=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&&++n>1||41===i&&--n<0)break;e++}return!(o===e||(s=_(t.src.slice(o,e)),!t.parser.validateLink(s)))&&(t.linkContent=s,t.pos=e,!0)}function st(t,e){var i,n=e,s=t.posMax,o=t.src.charCodeAt(e);if(34!==o&&39!==o&&40!==o)return!1;for(e++,40===o&&(o=41);e<s;){if((i=t.src.charCodeAt(e))===o)return t.pos=e+1,t.linkContent=_(t.src.slice(n+1,e)),!0;92===i&&e+1<s?e+=2:e++}return!1}function ot(t){return t.trim().replace(/\s+/g," ").toUpperCase()}function rt(t,e,i,n){var s,o,r,a,c,l,u,h,d;if(91!==t.charCodeAt(0)||-1===t.indexOf("]:")||((o=tt(s=new X(t,e,i,n,[]),0))<0||58!==t.charCodeAt(o+1)))return-1;for(a=s.posMax,r=o+2;r<a&&(32===(c=s.src.charCodeAt(r))||10===c);r++);if(!nt(s,r))return-1;for(u=s.linkContent,l=r=s.pos,r+=1;r<a&&(32===(c=s.src.charCodeAt(r))||10===c);r++);for(r<a&&l!==r&&st(s,r)?(h=s.linkContent,r=s.pos):(h="",r=l);r<a&&32===s.src.charCodeAt(r);)r++;return r<a&&10!==s.src.charCodeAt(r)?-1:(d=ot(t.slice(1,o)),typeof n.references[d]>"u"&&(n.references[d]={title:h,href:u}),r)}Q.prototype.renderInline=function(t,e,i){for(var n=this.rules,s=t.length,o=0,r="";s--;)r+=n[t[o].type](t,o++,e,i,this);return r},Q.prototype.render=function(t,e,i){for(var n=this.rules,s=t.length,o=-1,r="";++o<s;)"inline"===t[o].type?r+=this.renderInline(t[o].children,e,i):r+=n[t[o].type](t,o,e,i,this);return r},W.prototype.o=function(t){for(var e=this.t.length,i=-1;e--;)if(this.t[++i].name===t)return i;return-1},W.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))}))}))},W.prototype.at=function(t,e,i){var n=this.o(t),s=i||{};if(-1===n)throw new Error("Parser rule not found: "+t);this.t[n].fn=e,this.t[n].alt=s.alt||[],this.i=null},W.prototype.before=function(t,e,i,n){var s=this.o(t),o=n||{};if(-1===s)throw new Error("Parser rule not found: "+t);this.t.splice(s,0,{name:e,enabled:!0,fn:i,alt:o.alt||[]}),this.i=null},W.prototype.after=function(t,e,i,n){var s=this.o(t),o=n||{};if(-1===s)throw new Error("Parser rule not found: "+t);this.t.splice(s+1,0,{name:e,enabled:!0,fn:i,alt:o.alt||[]}),this.i=null},W.prototype.push=function(t,e,i){var n=i||{};this.t.push({name:t,enabled:!0,fn:e,alt:n.alt||[]}),this.i=null},W.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},W.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},W.prototype.getRules=function(t){return null===this.i&&this.l(),this.i[t]||[]},X.prototype.pushPending=function(){this.tokens.push({type:"text",content:this.pending,level:this.pendingLevel}),this.pending=""},X.prototype.push=function(t){this.pending&&this.pushPending(),this.tokens.push(t),this.pendingLevel=this.level},X.prototype.cacheSet=function(t,e){for(var i=this.cache.length;i<=t;i++)this.cache.push(0);this.cache[t]=e},X.prototype.cacheGet=function(t){return t<this.cache.length?this.cache[t]:0};var at=" \n()[]'\".,!?-";function ct(t){return t.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1")}var lt=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,ut=/\((c|tm|r|p)\)/gi,ht={c:"©",r:"®",p:"§",tm:"™"};function dt(t){return t.indexOf("(")<0?t:t.replace(ut,(function(t,e){return ht[e.toLowerCase()]}))}var pt=/['"]/,mt=/['"]/g,ft=/[-\s()\[\]]/;function vt(t,e){return!(e<0||e>=t.length)&&!ft.test(t[e])}function gt(t,e,i){return t.substr(0,e)+i+t.substr(e+1)}var bt=[["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,n,s,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(n=o[e].content;n.length&&!((s=et(n,t.inline,t.options,t.env))<0);)n=n.slice(s).trim();o[e].content=n,n.length||(o[e-1].tight=!0,o[e+1].tight=!0)}}],["references",function(t){var e,i,n,s,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(n=o[e].content;n.length&&!((s=rt(n,t.inline,t.options,t.env))<0);)n=n.slice(s).trim();o[e].content=n,n.length||(o[e-1].tight=!0,o[e+1].tight=!0)}}],["inline",function(t){var e,i,n,s=t.tokens;for(i=0,n=s.length;i<n;i++)"inline"===(e=s[i]).type&&t.inline.parse(e.content,t.options,t.env,e.children)}],["footnote_tail",function(t){var e,i,n,s,o,r,a,c,l,u=0,h=!1,d={};if(t.env.footnotes&&(t.tokens=t.tokens.filter((function(t){return"footnote_reference_open"===t.type?(h=!0,c=[],l=t.label,!1):"footnote_reference_close"===t.type?(h=!1,d[":"+l]=c,!1):(h&&c.push(t),!h)})),t.env.footnotes.list)){for(r=t.env.footnotes.list,t.tokens.push({type:"footnote_block_open",level:u++}),e=0,i=r.length;e<i;e++){for(t.tokens.push({type:"footnote_open",id:e,level:u++}),r[e].tokens?((a=[]).push({type:"paragraph_open",tight:!1,level:u++}),a.push({type:"inline",content:"",level:u,children:r[e].tokens}),a.push({type:"paragraph_close",tight:!1,level:--u})):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,s=r[e].count>0?r[e].count:1,n=0;n<s;n++)t.tokens.push({type:"footnote_anchor",id:e,subId:n,level:u});o&&t.tokens.push(o),t.tokens.push({type:"footnote_close",level:--u})}t.tokens.push({type:"footnote_block_close",level:--u})}}],["abbr2",function(t){var e,i,n,s,o,r,a,c,l,u,h,d,p=t.tokens;if(t.env.abbreviations)for(t.env.abbrRegExp||(d="(^|["+at.split("").map(ct).join("")+"])("+Object.keys(t.env.abbreviations).map((function(t){return t.substr(1)})).sort((function(t,e){return e.length-t.length})).map(ct).join("|")+")($|["+at.split("").map(ct).join("")+"])",t.env.abbrRegExp=new RegExp(d,"g")),u=t.env.abbrRegExp,i=0,n=p.length;i<n;i++)if("inline"===p[i].type)for(e=(s=p[i].children).length-1;e>=0;e--)if("text"===(o=s[e]).type){for(c=0,r=o.content,u.lastIndex=0,l=o.level,a=[];h=u.exec(r);)u.lastIndex>c&&a.push({type:"text",content:r.slice(c,h.index+h[1].length),level:l}),a.push({type:"abbr_open",title:t.env.abbreviations[":"+h[2]],level:l++}),a.push({type:"text",content:h[2],level:l}),a.push({type:"abbr_close",level:--l}),c=u.lastIndex-h[3].length;a.length&&(c<r.length&&a.push({type:"text",content:r.slice(c),level:l}),p[i].children=s=[].concat(s.slice(0,e),a,s.slice(e+1)))}}],["replacements",function(t){var e,i,n,s,o;if(t.options.typographer)for(o=t.tokens.length-1;o>=0;o--)if("inline"===t.tokens[o].type)for(e=(s=t.tokens[o].children).length-1;e>=0;e--)"text"===(i=s[e]).type&&(n=dt(n=i.content),lt.test(n)&&(n=n.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=n)}],["smartquotes",function(t){var e,i,n,s,o,r,a,c,l,u,h,d,p,m,f,v,g;if(t.options.typographer)for(g=[],f=t.tokens.length-1;f>=0;f--)if("inline"===t.tokens[f].type)for(v=t.tokens[f].children,g.length=0,e=0;e<v.length;e++)if("text"===(i=v[e]).type&&!pt.test(i.text)){for(a=v[e].level,p=g.length-1;p>=0&&!(g[p].level<=a);p--);g.length=p+1,o=0,r=(n=i.content).length;t:for(;o<r&&(mt.lastIndex=o,s=mt.exec(n),s);)if(c=!vt(n,s.index-1),o=s.index+1,m="'"===s[0],(l=!vt(n,o))||c){if(h=!l,d=!c)for(p=g.length-1;p>=0&&(u=g[p],!(g[p].level<a));p--)if(u.single===m&&g[p].level===a){u=g[p],m?(v[u.token].content=gt(v[u.token].content,u.pos,t.options.quotes[2]),i.content=gt(i.content,s.index,t.options.quotes[3])):(v[u.token].content=gt(v[u.token].content,u.pos,t.options.quotes[0]),i.content=gt(i.content,s.index,t.options.quotes[1])),g.length=p;continue t}h?g.push({token:e,pos:s.index,single:m,level:a}):d&&m&&(i.content=gt(i.content,s.index,"’"))}else m&&(i.content=gt(i.content,s.index,"’"))}}]];function yt(){this.options={},this.ruler=new W;for(var t=0;t<bt.length;t++)this.ruler.push(bt[t][0],bt[t][1])}function wt(t,e,i,n,s){var o,r,a,c,l,u,h;for(this.src=t,this.parser=e,this.options=i,this.env=n,this.tokens=s,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="",u=0,h=!1,a=c=u=0,l=(r=this.src).length;c<l;c++){if(o=r.charCodeAt(c),!h){if(32===o){u++;continue}h=!0}(10===o||c===l-1)&&(10!==o&&c++,this.bMarks.push(a),this.eMarks.push(c),this.tShift.push(u),h=!1,u=0,a=c+1)}this.bMarks.push(r.length),this.eMarks.push(r.length),this.tShift.push(0),this.lineMax=this.bMarks.length-1}function xt(t,e){var i,n,s;return(n=t.bMarks[e]+t.tShift[e])>=(s=t.eMarks[e])||42!==(i=t.src.charCodeAt(n++))&&45!==i&&43!==i||n<s&&32!==t.src.charCodeAt(n)?-1:n}function Mt(t,e){var i,n=t.bMarks[e]+t.tShift[e],s=t.eMarks[e];if(n+1>=s||((i=t.src.charCodeAt(n++))<48||i>57))return-1;for(;;){if(n>=s)return-1;if(!((i=t.src.charCodeAt(n++))>=48&&i<=57)){if(41===i||46===i)break;return-1}}return n<s&&32!==t.src.charCodeAt(n)?-1:n}yt.prototype.process=function(t){var e,i,n;for(e=0,i=(n=this.ruler.getRules("")).length;e<i;e++)n[e](t)},wt.prototype.isEmpty=function(t){return this.bMarks[t]+this.tShift[t]>=this.eMarks[t]},wt.prototype.skipEmptyLines=function(t){for(var e=this.lineMax;t<e&&!(this.bMarks[t]+this.tShift[t]<this.eMarks[t]);t++);return t},wt.prototype.skipSpaces=function(t){for(var e=this.src.length;t<e&&32===this.src.charCodeAt(t);t++);return t},wt.prototype.skipChars=function(t,e){for(var i=this.src.length;t<i&&this.src.charCodeAt(t)===e;t++);return t},wt.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},wt.prototype.getLines=function(t,e,i,n){var s,o,r,a,c,l=t;if(t>=e)return"";if(l+1===e)return o=this.bMarks[l]+Math.min(this.tShift[l],i),r=n?this.eMarks[l]+1:this.eMarks[l],this.src.slice(o,r);for(a=new Array(e-t),s=0;l<e;l++,s++)(c=this.tShift[l])>i&&(c=i),c<0&&(c=0),o=this.bMarks[l]+c,r=l+1<e||n?this.eMarks[l]+1:this.eMarks[l],a[s]=this.src.slice(o,r);return a.join("")};var kt={};["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){kt[t]=!0}));var jt=/^<([a-zA-Z]{1,15})[\s\/>]/,St=/^<\/([a-zA-Z]{1,15})[\s>]/;function At(t,e){var i=t.bMarks[e]+t.blkIndent,n=t.eMarks[e];return t.src.substr(i,n-i)}function Tt(t,e){var i,n,s=t.bMarks[e]+t.tShift[e],o=t.eMarks[e];return s>=o||126!==(n=t.src.charCodeAt(s++))&&58!==n||s===(i=t.skipSpaces(s))||i>=o?-1:i}var Ot=[["code",function(t,e,i){var n,s;if(t.tShift[e]-t.blkIndent<4)return!1;for(s=n=e+1;n<i;)if(t.isEmpty(n))n++;else{if(!(t.tShift[n]-t.blkIndent>=4))break;s=++n}return t.line=n,t.tokens.push({type:"code",content:t.getLines(e,s,4+t.blkIndent,!0),block:!0,lines:[e,t.line],level:t.level}),!0}],["fences",function(t,e,i,n){var s,o,r,a,c,l=!1,u=t.bMarks[e]+t.tShift[e],h=t.eMarks[e];if(u+3>h||126!==(s=t.src.charCodeAt(u))&&96!==s||(c=u,(o=(u=t.skipChars(u,s))-c)<3)||(r=t.src.slice(u,h).trim()).indexOf("`")>=0)return!1;if(n)return!0;for(a=e;!(++a>=i||(u=c=t.bMarks[a]+t.tShift[a],h=t.eMarks[a],u<h&&t.tShift[a]<t.blkIndent));)if(!(t.src.charCodeAt(u)!==s||t.tShift[a]-t.blkIndent>=4||(u=t.skipChars(u,s),u-c<o||(u=t.skipSpaces(u),u<h)))){l=!0;break}return o=t.tShift[e],t.line=a+(l?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,n){var s,o,r,a,c,l,u,h,d,p,m,f=t.bMarks[e]+t.tShift[e],v=t.eMarks[e];if(f>v||62!==t.src.charCodeAt(f++)||t.level>=t.options.maxNesting)return!1;if(n)return!0;for(32===t.src.charCodeAt(f)&&f++,c=t.blkIndent,t.blkIndent=0,a=[t.bMarks[e]],t.bMarks[e]=f,o=(f=f<v?t.skipSpaces(f):f)>=v,r=[t.tShift[e]],t.tShift[e]=f-t.bMarks[e],h=t.parser.ruler.getRules("blockquote"),s=e+1;s<i&&!((f=t.bMarks[s]+t.tShift[s])>=(v=t.eMarks[s]));s++)if(62!==t.src.charCodeAt(f++)){if(o)break;for(m=!1,d=0,p=h.length;d<p;d++)if(h[d](t,s,i,!0)){m=!0;break}if(m)break;a.push(t.bMarks[s]),r.push(t.tShift[s]),t.tShift[s]=-1337}else 32===t.src.charCodeAt(f)&&f++,a.push(t.bMarks[s]),t.bMarks[s]=f,o=(f=f<v?t.skipSpaces(f):f)>=v,r.push(t.tShift[s]),t.tShift[s]=f-t.bMarks[s];for(l=t.parentType,t.parentType="blockquote",t.tokens.push({type:"blockquote_open",lines:u=[e,0],level:t.level++}),t.parser.tokenize(t,e,s),t.tokens.push({type:"blockquote_close",level:--t.level}),t.parentType=l,u[1]=t.line,d=0;d<r.length;d++)t.bMarks[d+e]=a[d],t.tShift[d+e]=r[d];return t.blkIndent=c,!0},["paragraph","blockquote","list"]],["hr",function(t,e,i,n){var s,o,r,a=t.bMarks[e],c=t.eMarks[e];if((a+=t.tShift[e])>c||42!==(s=t.src.charCodeAt(a++))&&45!==s&&95!==s)return!1;for(o=1;a<c;){if((r=t.src.charCodeAt(a++))!==s&&32!==r)return!1;r===s&&o++}return!(o<3)&&(n||(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,n){var s,o,r,a,c,l,u,h,d,p,m,f,v,g,b,y,w,x,M,k,j,S=!0;if((h=Mt(t,e))>=0)f=!0;else{if(!((h=xt(t,e))>=0))return!1;f=!1}if(t.level>=t.options.maxNesting)return!1;if(m=t.src.charCodeAt(h-1),n)return!0;for(g=t.tokens.length,f?(u=t.bMarks[e]+t.tShift[e],p=Number(t.src.substr(u,h-u-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++}),s=e,b=!1,x=t.parser.ruler.getRules("list");s<i&&((d=(v=t.skipSpaces(h))>=t.eMarks[s]?1:v-h)>4&&(d=1),d<1&&(d=1),o=h-t.bMarks[s]+d,t.tokens.push({type:"list_item_open",lines:w=[e,0],level:t.level++}),a=t.blkIndent,c=t.tight,r=t.tShift[e],l=t.parentType,t.tShift[e]=v-t.bMarks[e],t.blkIndent=o,t.tight=!0,t.parentType="list",t.parser.tokenize(t,e,i,!0),(!t.tight||b)&&(S=!1),b=t.line-e>1&&t.isEmpty(t.line-1),t.blkIndent=a,t.tShift[e]=r,t.tight=c,t.parentType=l,t.tokens.push({type:"list_item_close",level:--t.level}),s=e=t.line,w[1]=s,v=t.bMarks[e],!(s>=i||t.isEmpty(s)||t.tShift[s]<t.blkIndent));){for(j=!1,M=0,k=x.length;M<k;M++)if(x[M](t,s,i,!0)){j=!0;break}if(j)break;if(f){if((h=Mt(t,s))<0)break}else if((h=xt(t,s))<0)break;if(m!==t.src.charCodeAt(h-1))break}return t.tokens.push({type:f?"ordered_list_close":"bullet_list_close",level:--t.level}),y[1]=s,t.line=s,S&&function(t,e){var i,n,s=t.level+2;for(i=e+2,n=t.tokens.length-2;i<n;i++)t.tokens[i].level===s&&"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,n){var s,o,r,a,c,l=t.bMarks[e]+t.tShift[e],u=t.eMarks[e];if(l+4>u||91!==t.src.charCodeAt(l)||94!==t.src.charCodeAt(l+1)||t.level>=t.options.maxNesting)return!1;for(a=l+2;a<u;a++){if(32===t.src.charCodeAt(a))return!1;if(93===t.src.charCodeAt(a))break}return!(a===l+2||a+1>=u||58!==t.src.charCodeAt(++a))&&(n||(a++,t.env.footnotes||(t.env.footnotes={}),t.env.footnotes.refs||(t.env.footnotes.refs={}),c=t.src.slice(l+2,a-2),t.env.footnotes.refs[":"+c]=-1,t.tokens.push({type:"footnote_reference_open",label:c,level:t.level++}),s=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]=s,t.tokens.push({type:"footnote_reference_close",level:--t.level})),!0)},["paragraph"]],["heading",function(t,e,i,n){var s,o,r,a=t.bMarks[e]+t.tShift[e],c=t.eMarks[e];if(a>=c||(35!==(s=t.src.charCodeAt(a))||a>=c))return!1;for(o=1,s=t.src.charCodeAt(++a);35===s&&a<c&&o<=6;)o++,s=t.src.charCodeAt(++a);return!(o>6||a<c&&32!==s)&&(n||(c=t.skipCharsBack(c,32,a),(r=t.skipCharsBack(c,35,a))>a&&32===t.src.charCodeAt(r-1)&&(c=r),t.line=e+1,t.tokens.push({type:"heading_open",hLevel:o,lines:[e,t.line],level:t.level}),a<c&&t.tokens.push({type:"inline",content:t.src.slice(a,c).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 n,s,o,r=e+1;return!(r>=i||t.tShift[r]<t.blkIndent||t.tShift[r]-t.blkIndent>3||(s=t.bMarks[r]+t.tShift[r],o=t.eMarks[r],s>=o)||(n=t.src.charCodeAt(s),45!==n&&61!==n)||(s=t.skipChars(s,n),s=t.skipSpaces(s),s<o))&&(s=t.bMarks[e]+t.tShift[e],t.line=r+1,t.tokens.push({type:"heading_open",hLevel:61===n?1:2,lines:[e,t.line],level:t.level}),t.tokens.push({type:"inline",content:t.src.slice(s,t.eMarks[e]).trim(),level:t.level+1,lines:[e,t.line-1],children:[]}),t.tokens.push({type:"heading_close",hLevel:61===n?1:2,level:t.level}),!0)}],["htmlblock",function(t,e,i,n){var s,o,r,a=t.bMarks[e],c=t.eMarks[e],l=t.tShift[e];if(a+=l,!t.options.html||l>3||a+2>=c||60!==t.src.charCodeAt(a))return!1;if(33===(s=t.src.charCodeAt(a+1))||63===s){if(n)return!0}else{if(47!==s&&!function(t){var e=32|t;return e>=97&&e<=122}(s))return!1;if(47===s){if(!(o=t.src.slice(a,c).match(St)))return!1}else if(!(o=t.src.slice(a,c).match(jt)))return!1;if(!0!==kt[o[1].toLowerCase()])return!1;if(n)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,n){var s,o,r,a,c,l,u,h,d,p,m;if(e+2>i||(c=e+1,t.tShift[c]<t.blkIndent)||(r=t.bMarks[c]+t.tShift[c])>=t.eMarks[c]||124!==(s=t.src.charCodeAt(r))&&45!==s&&58!==s||(o=At(t,e+1),!/^[-:| ]+$/.test(o))||(l=o.split("|"))<=2)return!1;for(h=[],a=0;a<l.length;a++){if(!(d=l[a].trim())){if(0===a||a===l.length-1)continue;return!1}if(!/^:?-+:?$/.test(d))return!1;58===d.charCodeAt(d.length-1)?h.push(58===d.charCodeAt(0)?"center":"right"):58===d.charCodeAt(0)?h.push("left"):h.push("")}if(-1===(o=At(t,e).trim()).indexOf("|")||(l=o.replace(/^\||\|$/g,"").split("|"),h.length!==l.length))return!1;if(n)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<l.length;a++)t.tokens.push({type:"th_open",align:h[a],lines:[e,e+1],level:t.level++}),t.tokens.push({type:"inline",content:l[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++}),c=e+2;c<i&&!(t.tShift[c]<t.blkIndent||(o=At(t,c).trim(),-1===o.indexOf("|")));c++){for(l=o.replace(/^\||\|$/g,"").split("|"),t.tokens.push({type:"tr_open",level:t.level++}),a=0;a<l.length;a++)t.tokens.push({type:"td_open",align:h[a],level:t.level++}),u=l[a].substring(124===l[a].charCodeAt(0)?1:0,124===l[a].charCodeAt(l[a].length-1)?l[a].length-1:l[a].length).trim(),t.tokens.push({type:"inline",content:u,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]=c,t.line=c,!0},["paragraph"]],["deflist",function(t,e,i,n){var s,o,r,a,c,l,u,h,d,p,m,f,v,g;if(n)return!(t.ddIndent<0)&&Tt(t,e)>=0;if(u=e+1,t.isEmpty(u)&&++u>i||t.tShift[u]<t.blkIndent||(s=Tt(t,u))<0||t.level>=t.options.maxNesting)return!1;l=t.tokens.length,t.tokens.push({type:"dl_open",lines:c=[e,0],level:t.level++}),r=e,o=u;t:for(;;){for(g=!0,v=!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=[u,0],level:t.level++}),f=t.tight,d=t.ddIndent,h=t.blkIndent,m=t.tShift[o],p=t.parentType,t.blkIndent=t.ddIndent=t.tShift[o]+2,t.tShift[o]=s-t.bMarks[o],t.tight=!0,t.parentType="deflist",t.parser.tokenize(t,o,i,!0),(!t.tight||v)&&(g=!1),v=t.line-o>1&&t.isEmpty(t.line-1),t.tShift[o]=m,t.tight=f,t.parentType=p,t.blkIndent=h,t.ddIndent=d,t.tokens.push({type:"dd_close",level:--t.level}),a[1]=u=t.line,u>=i||t.tShift[u]<t.blkIndent)break t;if((s=Tt(t,u))<0)break;o=u}if(u>=i||(r=u,t.isEmpty(r))||t.tShift[r]<t.blkIndent||(o=r+1)>=i||(t.isEmpty(o)&&o++,o>=i)||t.tShift[o]<t.blkIndent||(s=Tt(t,o))<0)break}return t.tokens.push({type:"dl_close",level:--t.level}),c[1]=u,t.line=u,g&&function(t,e){var i,n,s=t.level+2;for(i=e+2,n=t.tokens.length-2;i<n;i++)t.tokens[i].level===s&&"paragraph_open"===t.tokens[i].type&&(t.tokens[i+2].tight=!0,t.tokens[i].tight=!0,i+=2)}(t,l),!0},["paragraph"]],["paragraph",function(t,e){var i,n,s,o,r,a,c=e+1;if(c<(i=t.lineMax)&&!t.isEmpty(c))for(a=t.parser.ruler.getRules("paragraph");c<i&&!t.isEmpty(c);c++)if(!(t.tShift[c]-t.blkIndent>3)){for(s=!1,o=0,r=a.length;o<r;o++)if(a[o](t,c,i,!0)){s=!0;break}if(s)break}return n=t.getLines(e,c,t.blkIndent,!1).trim(),t.line=c,n.length&&(t.tokens.push({type:"paragraph_open",tight:!1,lines:[e,t.line],level:t.level}),t.tokens.push({type:"inline",content:n,level:t.level+1,lines:[e,t.line],children:[]}),t.tokens.push({type:"paragraph_close",tight:!1,level:t.level})),!0}]];function Ct(){this.ruler=new W;for(var t=0;t<Ot.length;t++)this.ruler.push(Ot[t][0],Ot[t][1],{alt:(Ot[t][2]||[]).slice()})}Ct.prototype.tokenize=function(t,e,i){for(var n,s=this.ruler.getRules(""),o=s.length,r=e,a=!1;r<i&&(t.line=r=t.skipEmptyLines(r),!(r>=i||t.tShift[r]<t.blkIndent));){for(n=0;n<o&&!s[n](t,r,i,!1);n++);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 Nt=/[\n\t]/g,It=/\r[\n\u0085]|[\u2424\u2028\u0085]/g,Et=/\u00a0/g;function zt(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}}Ct.prototype.parse=function(t,e,i,n){var s,o=0,r=0;if(!t)return[];(t=(t=t.replace(Et," ")).replace(It,"\n")).indexOf("\t")>=0&&(t=t.replace(Nt,(function(e,i){var n;return 10===t.charCodeAt(i)?(o=i+1,r=0,e):(n=" ".slice((i-o-r)%4),r=i-o+1,n)}))),s=new wt(t,this,e,i,n),this.tokenize(s,s.line,s.lineMax)};for(var Lt=[],Pt=0;Pt<256;Pt++)Lt.push(0);function _t(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}function Dt(t,e){var i,n,s,o=e,r=!0,a=!0,c=t.posMax,l=t.src.charCodeAt(e);for(i=e>0?t.src.charCodeAt(e-1):-1;o<c&&t.src.charCodeAt(o)===l;)o++;return o>=c&&(r=!1),(s=o-e)>=4?r=a=!1:((32===(n=o<c?t.src.charCodeAt(o):-1)||10===n)&&(r=!1),(32===i||10===i)&&(a=!1),95===l&&(_t(i)&&(r=!1),_t(n)&&(a=!1))),{can_open:r,can_close:a,delims:s}}"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach((function(t){Lt[t.charCodeAt(0)]=1}));var Rt=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Ft=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Bt=["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"],Jt=/^<([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])?)*)>/,qt=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;function Yt(t,e){return t=t.source,e=e||"",function i(n,s){return n?(s=s.source||s,t=t.replace(n,s),i):new RegExp(t,e)}}var Ut=Yt(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",/[^"'=<>`\x00-\x20]+/)("single_quoted",/'[^']*'/)("double_quoted",/"[^"]*"/)(),$t=Yt(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",/[a-zA-Z_:][a-zA-Z0-9:._-]*/)("attr_value",Ut)(),Vt=Yt(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",$t)(),Zt=Yt(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",Vt)("close_tag",/<\/[A-Za-z][A-Za-z0-9]*\s*>/)("comment",/<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->/)("processing",/<[?].*?[?]>/)("declaration",/<![A-Z]+\s+[^>]*>/)("cdata",/<!\[CDATA\[[\s\S]*?\]\]>/)();var Ht=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,Gt=/^&([a-z][a-z0-9]{1,31});/i;var Kt=[["text",function(t,e){for(var i=t.pos;i<t.posMax&&!zt(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,n,s=t.pos;if(10!==t.src.charCodeAt(s))return!1;if(i=t.pending.length-1,n=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(s++;s<n&&32===t.src.charCodeAt(s);)s++;return t.pos=s,!0}],["escape",function(t,e){var i,n=t.pos,s=t.posMax;if(92!==t.src.charCodeAt(n))return!1;if(++n<s){if((i=t.src.charCodeAt(n))<256&&0!==Lt[i])return e||(t.pending+=t.src[n]),t.pos+=2,!0;if(10===i){for(e||t.push({type:"hardbreak",level:t.level}),n++;n<s&&32===t.src.charCodeAt(n);)n++;return t.pos=n,!0}}return e||(t.pending+="\\"),t.pos++,!0}],["backticks",function(t,e){var i,n,s,o,r,a=t.pos;if(96!==t.src.charCodeAt(a))return!1;for(i=a,a++,n=t.posMax;a<n&&96===t.src.charCodeAt(a);)a++;for(s=t.src.slice(i,a),o=r=a;-1!==(o=t.src.indexOf("`",r));){for(r=o+1;r<n&&96===t.src.charCodeAt(r);)r++;if(r-o===s.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+=s),t.pos+=s.length,!0}],["del",function(t,e){var i,n,s,o,r,a=t.posMax,c=t.pos;if(126!==t.src.charCodeAt(c)||e||c+4>=a||126!==t.src.charCodeAt(c+1)||t.level>=t.options.maxNesting||(o=c>0?t.src.charCodeAt(c-1):-1,r=t.src.charCodeAt(c+2),126===o)||126===r||32===r||10===r)return!1;for(n=c+2;n<a&&126===t.src.charCodeAt(n);)n++;if(n>c+3)return t.pos+=n-c,e||(t.pending+=t.src.slice(c,n)),!0;for(t.pos=c+2,s=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?s--:32!==r&&10!==r&&s++,s<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=c+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=c,!1)}],["ins",function(t,e){var i,n,s,o,r,a=t.posMax,c=t.pos;if(43!==t.src.charCodeAt(c)||e||c+4>=a||43!==t.src.charCodeAt(c+1)||t.level>=t.options.maxNesting||(o=c>0?t.src.charCodeAt(c-1):-1,r=t.src.charCodeAt(c+2),43===o)||43===r||32===r||10===r)return!1;for(n=c+2;n<a&&43===t.src.charCodeAt(n);)n++;if(n!==c+2)return t.pos+=n-c,e||(t.pending+=t.src.slice(c,n)),!0;for(t.pos=c+2,s=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?s--:32!==r&&10!==r&&s++,s<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=c+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=c,!1)}],["mark",function(t,e){var i,n,s,o,r,a=t.posMax,c=t.pos;if(61!==t.src.charCodeAt(c)||e||c+4>=a||61!==t.src.charCodeAt(c+1)||t.level>=t.options.maxNesting||(o=c>0?t.src.charCodeAt(c-1):-1,r=t.src.charCodeAt(c+2),61===o)||61===r||32===r||10===r)return!1;for(n=c+2;n<a&&61===t.src.charCodeAt(n);)n++;if(n!==c+2)return t.pos+=n-c,e||(t.pending+=t.src.slice(c,n)),!0;for(t.pos=c+2,s=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?s--:32!==r&&10!==r&&s++,s<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=c+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=c,!1)}],["emphasis",function(t,e){var i,n,s,o,r,a,c,l=t.posMax,u=t.pos,h=t.src.charCodeAt(u);if(95!==h&&42!==h||e)return!1;if(i=(c=Dt(t,u)).delims,!c.can_open)return t.pos+=i,e||(t.pending+=t.src.slice(u,t.pos)),!0;if(t.level>=t.options.maxNesting)return!1;for(t.pos=u+i,a=[i];t.pos<l;)if(t.src.charCodeAt(t.pos)!==h)t.parser.skipToken(t);else{if(n=(c=Dt(t,t.pos)).delims,c.can_close){for(o=a.pop(),r=n;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,s=!0;break}t.pos+=n;continue}c.can_open&&a.push(n),t.pos+=n}return s?(t.posMax=t.pos,t.pos=u+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=l,!0):(t.pos=u,!1)}],["sub",function(t,e){var i,n,s=t.posMax,o=t.pos;if(126!==t.src.charCodeAt(o)||e||o+2>=s||t.level>=t.options.maxNesting)return!1;for(t.pos=o+1;t.pos<s;){if(126===t.src.charCodeAt(t.pos)){i=!0;break}t.parser.skipToken(t)}return!i||o+1===t.pos||(n=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:n.replace(Rt,"$1")}),t.pos=t.posMax+1,t.posMax=s,!0)}],["sup",function(t,e){var i,n,s=t.posMax,o=t.pos;if(94!==t.src.charCodeAt(o)||e||o+2>=s||t.level>=t.options.maxNesting)return!1;for(t.pos=o+1;t.pos<s;){if(94===t.src.charCodeAt(t.pos)){i=!0;break}t.parser.skipToken(t)}return!i||o+1===t.pos||(n=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:n.replace(Ft,"$1")}),t.pos=t.posMax+1,t.posMax=s,!0)}],["links",function(t,e){var i,n,s,o,r,a,c,l,u=!1,h=t.pos,d=t.posMax,p=t.pos,m=t.src.charCodeAt(p);if(33===m&&(u=!0,m=t.src.charCodeAt(++p)),91!==m||t.level>=t.options.maxNesting||(i=p+1,(n=tt(t,p))<0))return!1;if((a=n+1)<d&&40===t.src.charCodeAt(a)){for(a++;a<d&&(32===(l=t.src.charCodeAt(a))||10===l);a++);if(a>=d)return!1;for(p=a,nt(t,a)?(o=t.linkContent,a=t.pos):o="",p=a;a<d&&(32===(l=t.src.charCodeAt(a))||10===l);a++);if(a<d&&p!==a&&st(t,a))for(r=t.linkContent,a=t.pos;a<d&&(32===(l=t.src.charCodeAt(a))||10===l);a++);else r="";if(a>=d||41!==t.src.charCodeAt(a))return t.pos=h,!1;a++}else{if(t.linkLevel>0)return!1;for(;a<d&&(32===(l=t.src.charCodeAt(a))||10===l);a++);if(a<d&&91===t.src.charCodeAt(a)&&(p=a+1,(a=tt(t,a))>=0?s=t.src.slice(p,a++):a=p-1),s||(typeof s>"u"&&(a=n+1),s=t.src.slice(i,n)),!(c=t.env.references[ot(s)]))return t.pos=h,!1;o=c.href,r=c.title}return e||(t.pos=i,t.posMax=n,u?t.push({type:"image",src:o,title:r,alt:t.src.substr(i,n-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,n,s,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,n=tt(t,a+1),n<0))&&(e||(t.env.footnotes||(t.env.footnotes={}),t.env.footnotes.list||(t.env.footnotes.list=[]),s=t.env.footnotes.list.length,t.pos=i,t.posMax=n,t.push({type:"footnote_ref",id:s,level:t.level}),t.linkLevel++,o=t.tokens.length,t.parser.tokenize(t),t.env.footnotes.list[s]={tokens:t.tokens.splice(o)},t.linkLevel--),t.pos=n+1,t.posMax=r,!0)}],["footnote_ref",function(t,e){var i,n,s,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(n=a+2;n<r;n++){if(32===t.src.charCodeAt(n)||10===t.src.charCodeAt(n))return!1;if(93===t.src.charCodeAt(n))break}return!(n===a+2||n>=r||(n++,i=t.src.slice(a+2,n-1),typeof t.env.footnotes.refs[":"+i]>"u"))&&(e||(t.env.footnotes.list||(t.env.footnotes.list=[]),t.env.footnotes.refs[":"+i]<0?(s=t.env.footnotes.list.length,t.env.footnotes.list[s]={label:i,count:0},t.env.footnotes.refs[":"+i]=s):s=t.env.footnotes.refs[":"+i],o=t.env.footnotes.list[s].count,t.env.footnotes.list[s].count++,t.push({type:"footnote_ref",id:s,subId:o,level:t.level})),t.pos=n,t.posMax=r,!0)}],["autolink",function(t,e){var i,n,s,o,r,a=t.pos;return!(60!==t.src.charCodeAt(a)||(i=t.src.slice(a),i.indexOf(">")<0))&&((n=i.match(qt))?!(Bt.indexOf(n[1].toLowerCase())<0||(o=n[0].slice(1,-1),r=it(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+=n[0].length,!0):!!(s=i.match(Jt))&&(r=it("mailto:"+(o=s[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+=s[0].length,!0)))}],["htmltag",function(t,e){var i,n,s,o=t.pos;return!(!t.options.html||(s=t.posMax,60!==t.src.charCodeAt(o)||o+2>=s)||(i=t.src.charCodeAt(o+1),33!==i&&63!==i&&47!==i&&!function(t){var e=32|t;return e>=97&&e<=122}(i))||(n=t.src.slice(o).match(Zt),!n))&&(e||t.push({type:"htmltag",content:t.src.slice(o,o+n[0].length),level:t.level}),t.pos+=n[0].length,!0)}],["entity",function(t,e){var i,n,s=t.pos,o=t.posMax;if(38!==t.src.charCodeAt(s))return!1;if(s+1<o)if(35===t.src.charCodeAt(s+1)){if(n=t.src.slice(s).match(Ht))return e||(i="x"===n[1][0].toLowerCase()?parseInt(n[1].slice(1),16):parseInt(n[1],10),t.pending+=D(i)?R(i):R(65533)),t.pos+=n[0].length,!0}else if(n=t.src.slice(s).match(Gt)){var r=E(n[1]);if(n[1]!==r)return e||(t.pending+=r),t.pos+=n[0].length,!0}return e||(t.pending+="&"),t.pos++,!0}]];function Qt(){this.ruler=new W;for(var t=0;t<Kt.length;t++)this.ruler.push(Kt[t][0],Kt[t][1]);this.validateLink=Wt}function Wt(t){var e=t.trim().toLowerCase();return!(-1!==(e=q(e)).indexOf(":")&&-1!==["vbscript","javascript","file","data"].indexOf(e.split(":")[0]))}Qt.prototype.skipToken=function(t){var e,i,n=this.ruler.getRules(""),s=n.length,o=t.pos;if((i=t.cacheGet(o))>0)t.pos=i;else{for(e=0;e<s;e++)if(n[e](t,!0))return void t.cacheSet(o,t.pos);t.pos++,t.cacheSet(o,t.pos)}},Qt.prototype.tokenize=function(t){for(var e,i,n=this.ruler.getRules(""),s=n.length,o=t.posMax;t.pos<o;){for(i=0;i<s&&!(e=n[i](t,!1));i++);if(e){if(t.pos>=o)break}else t.pending+=t.src[t.pos++]}t.pending&&t.pushPending()},Qt.prototype.parse=function(t,e,i,n){var s=new X(t,this,e,i,n);this.tokenize(s)};var Xt={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 te(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 ee(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 Qt,this.block=new Ct,this.core=new yt,this.renderer=new Q,this.ruler=new W,this.options={},this.configure(Xt[t]),this.set(e||{})}ee.prototype.set=function(t){L(this.options,t)},ee.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)}))},ee.prototype.use=function(t,e){return t(this,e),this},ee.prototype.parse=function(t,e){var i=new te(this,t,e);return this.core.process(i),i.tokens},ee.prototype.render=function(t,e){return e=e||{},this.renderer.render(this.parse(t,e),this.options,e)},ee.prototype.parseInline=function(t,e){var i=new te(this,t,e);return i.inlineMode=!0,this.core.process(i),i.tokens},ee.prototype.renderInline=function(t,e){return e=e||{},this.renderer.render(this.parseInline(t,e),this.options,e)};class ie{static createNew(){const t=window.hljs;return new ee(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:!1,langPrefix:"language-",linkTarget:"_blank",typographer:!0}:{highlight:t=>t,linkTarget:"_blank"})}}class ne{static parseConfig(t,e,i,n){var s;const o={files:e};if("object"==typeof n){const{files:e,request:r,button:a}=n;e&&(e.infoModal&&(o.files.infoModal=e.infoModal,null!=(s=e.infoModal)&&s.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||t.headers||t.method||t.url)&&(o.request={headers:(null==r?void 0:r.headers)||t.headers,method:(null==r?void 0:r.method)||t.method,url:(null==r?void 0:r.url)||t.url})}return o}static processMixedFiles(t,e,i){if(i){const n={acceptedFormats:""};t.fileTypes.mixedFiles=ne.parseConfig(t.requestSettings,n,e,i)}}static processMicrophone(t,e,i,n){var s,o,r,a,c,l;const u={acceptedFormats:"audio/*",...(null==(s=t.fileTypes.audio)?void 0:s.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.recordAudio=ne.parseConfig(t.requestSettings,u,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!=(c=t.fileTypes.audio)&&c.files&&((l=t.fileTypes.audio.files).maxNumberOfFiles??(l.maxNumberOfFiles=i.files.maxNumberOfFiles)))):n||(t.fileTypes.audio=ne.parseConfig(t.requestSettings,u,e,i)))}static processAudioConfig(t,e,i,n){if(!i&&!n)return;const s={acceptedFormats:"audio/*",...(null==n?void 0:n.files)||{}};t.fileTypes.audio=ne.parseConfig(t.requestSettings,s,e,i)}static processGifConfig(t,e,i,n){if(!i&&!n)return;const s={acceptedFormats:"image/gif",...(null==n?void 0:n.files)||{}};t.fileTypes.gifs=ne.parseConfig(t.requestSettings,s,e,i)}static processCamera(t,e,i,n){var s,o,r,a;const c={acceptedFormats:"image/*",...(null==(s=t.fileTypes.images)?void 0:s.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.camera=ne.parseConfig(t.requestSettings,c,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))):n||(t.fileTypes.images=ne.parseConfig(t.requestSettings,c,e,i)))}static processImagesConfig(t,e,i,n){if(!i&&!n)return;const s={acceptedFormats:"image/*",...(null==n?void 0:n.files)||{}};t.fileTypes.images=ne.parseConfig(t.requestSettings,s,e,i)}static populateDefaultFileIO(t,e){var i,n;t&&(t.files??(t.files={}),(i=t.files).acceptedFormats??(i.acceptedFormats=e),(n=t.files).maxNumberOfFiles??(n.maxNumberOfFiles=1))}static set(t,e,i){ne.populateDefaultFileIO(null==i?void 0:i.audio,".4a,.mp3,.webm,.mp4,.mpga,.wav,.mpeg,.m4a"),ne.populateDefaultFileIO(null==i?void 0:i.images,".png,.jpg");const n=ie.createNew();ne.processImagesConfig(e,n,t.images,null==i?void 0:i.images),ne.processCamera(e,n,t.camera,t.images),ne.processGifConfig(e,n,t.gifs,null==i?void 0:i.gifs),ne.processAudioConfig(e,n,t.audio,null==i?void 0:i.audio),ne.processMicrophone(e,n,t.microphone,t.audio),ne.processMixedFiles(e,n,t.mixedFiles)}}class se{constructor(t,e,i){var n,s,o,r;this.rawBody={},this.validateConfigKey=!1,this.canSendMessage=se.canSendMessage,this.requestSettings={},this.fileTypes={},this.completionsHandlers={},this.streamHandlers={},this.deepChat=t,this.demo=i,Object.assign(this.rawBody,null==(n=t.request)?void 0:n.additionalBodyProps),this.totalMessagesMaxCharLength=null==(s=null==t?void 0:t.requestBodyLimits)?void 0:s.totalMessagesMaxCharLength,this.maxMessages=null==(o=null==t?void 0:t.requestBodyLimits)?void 0:o.maxMessages,ne.set(t,this,e),t.request&&(this.requestSettings=t.request),this.demo&&((r=this.requestSettings).url??(r.url=j.URL)),this.requestSettings.websocket&&C.setup(this)}static canSendMessage(t,e,i){return!!i||(!(!t||""===t.trim())||!!(e&&e.length>0))}verifyKey(t,e){}static createCustomFormDataBody(t,e,i){const n=new FormData;i.forEach((t=>n.append("files",t))),Object.keys(t).forEach((e=>n.append(e,String(t[e]))));let s=0;e.slice(0,e.length-1).forEach((t=>{n.append(`message${s+=1}`,JSON.stringify(t))}));const o=e[e.length-1];return o.text&&(delete o.files,n.append(`message${s+=1}`,JSON.stringify(o))),n}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){const{stream:n}=this.deepChat;return!n||!this.demo&&"object"==typeof n&&n.simulation?T.request(this,t,e,i):S.request(this,t,e)}async callServiceAPI(t,e,i){var n,s,o,r;const a={messages:e,...this.rawBody};let c=!1;null!=(n=this.requestSettings.headers)&&n["Content-Type"]||((s=this.requestSettings).headers??(s.headers={}),(o=this.requestSettings.headers)["Content-Type"]??(o["Content-Type"]="application/json"),c=!0),await this.request(a,t),c&&(null==(r=this.requestSettings.headers)||delete r["Content-Type"])}async callApiWithFiles(t,e,i,n){const s=se.createCustomFormDataBody(t,i,n),o=this.requestSettings,r=this.getServiceIOByType(n[0]);this.requestSettings=(null==r?void 0:r.request)||this.requestSettings,await this.request(s,e,!1),this.requestSettings=o}async callAPI(t,e){if(!this.requestSettings)throw new Error("Request settings have not been set up");const i=O.processMessages(e.messages,this.maxMessages,this.totalMessagesMaxCharLength);if(this.requestSettings.websocket){const t={messages:i,...this.rawBody};C.sendWebsocket(this,t,e,!1)}else t.files&&!this.isDirectConnection()?this.callApiWithFiles(this.rawBody,e,i,t.files):this.callServiceAPI(e,i,t.files)}async extractResultData(t){if(t.error)throw t.error;return t.result?N.handleResponseProperty(t):t}isDirectConnection(){return!1}}class oe extends se{constructor(t,e,i,n,s){var o;super(t,s),this.insertKeyPlaceholderText="API Key",this.getKeyLink="",Object.assign(this.rawBody,null==(o=t.request)?void 0:o.additionalBodyProps),this.keyVerificationDetails=e,this.buildHeadersFunc=i,n&&this.setApiKeyProperties(n),this.requestSettings=this.buildRequestSettings(this.key||"",t.request)}setApiKeyProperties(t){this.key=t.key,t.validateKeyProperty&&(this.validateConfigKey=t.validateKeyProperty)}buildRequestSettings(t,e){const i=e??{};return i.headers=this.buildHeadersFunc(t),i}keyAuthenticated(t,e){this.requestSettings=this.buildRequestSettings(e,this.requestSettings),this.key=e,t()}verifyKey(t,e){const{url:i,method:n,handleVerificationResult:s,createHeaders:o,body:r}=this.keyVerificationDetails,a=(null==o?void 0:o(t))||this.buildHeadersFunc(t);T.verifyKey(t,i,a,n,this.keyAuthenticated.bind(this,e.onSuccess),e.onFail,e.onLoad,s,r)}isDirectConnection(){return!0}}class re{static waitForPropertiesToBeUpdatedBeforeRender(t){t._propUpdated_=!1,setTimeout((()=>{t._propUpdated_?re.waitForPropertiesToBeUpdatedBeforeRender(t):(t._waitingToRender_=!1,t.onRender())}))}static attemptRender(t){t._propUpdated_=!0,t._waitingToRender_||(t._waitingToRender_=!0,re.waitForPropertiesToBeUpdatedBeforeRender(t))}}const ae=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(n){i=n,e?this[t]=n:re.attemptRender(this)}})}attributeChangedCallback(e,i,n){if(i===n)return;const s=t._attributes_[e](n);this[t._attributeToProperty_[e]]=s}onRender(){}};ae._attributes_={},ae._attributeToProperty_={};let ce=ae;class le{static createSVGElement(t){return(new DOMParser).parseFromString(t,"image/svg+xml").documentElement}}const ue=class t{static changeVisibility(e,i,n,s){s.target.id===t.VISIBLE_ICON_ID?(i.style.display="none",n.style.display="block",e.type="password"):(i.style.display="block",n.style.display="none",e.type="text")}static createIconElement(t,e){const i=le.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 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 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);n.style.display="none",i.appendChild(n);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 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(s),i.onclick=t.changeVisibility.bind(this,e,n,s),i}};ue.VISIBLE_ICON_ID="visible-icon";let he=ue;class de{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 n=document.createElement("div");n.id="insert-key-help-text-contents";const s=de.createFailText();if(n.appendChild(s),t){const e=de.createHelpLink(t);n.appendChild(e)}if(!0===e){const t=de.createCautionText();n.appendChild(t)}return i.appendChild(n),{helpTextContainerElement:i,failTextElement:s}}static onFail(t,e,i,n){t.classList.replace("insert-key-input-valid","insert-key-input-invalid"),i.innerText=n,i.style.display="block",e.innerText="Start",t.classList.remove("loading")}static onLoad(t,e){t.classList.add("loading"),e.innerHTML='<div id="loading-ring"></div>'}static verifyKey(t,e,i){const n=t.value.trim();i.verifyKey(n,e)}static addVerificationEvents(t,e,i,n,s){const r={onSuccess:n,onFail:de.onFail.bind(this,t,e,i),onLoad:de.onLoad.bind(this,t,e)},a=de.verifyKey.bind(this,t,r,s);e.onclick=a,t.onkeydown=e=>{!t.classList.contains("loading")&&e.key===o.ENTER&&a()}}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=de.onInputFocus,e.appendChild(i),e}static createContents(t,e){var i;const n=document.createElement("div");n.id="insert-key-contents";const s=de.createInput(e.insertKeyPlaceholderText),o=s.children[0],r=he.create(o);s.appendChild(r),n.appendChild(s);const a=de.createStartButton(),{helpTextContainerElement:c,failTextElement:l}=de.createHelpTextContainer(e.getKeyLink,null==(i=e.deepChat._insertKeyViewStyles)?void 0:i.displayCautionText);return n.appendChild(a),n.appendChild(c),de.addVerificationEvents(o,a,l,t,e),n}static createElements(t,e){const i=document.createElement("div");i.id="insert-key-view";const n=de.createContents(t,e);return i.appendChild(n),i}static render(t,e,i){const n=de.createElements(e,i);t.replaceChildren(n)}}class pe{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,n){const s=t;Array.isArray(s.error)&&"Error in `parameters`: field required"===s.error[0]?i(e):n(m.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api-inference.huggingface.co/models/gpt2",method:"POST",handleVerificationResult:pe.handleVerificationResult}}}const me=class t extends oe{constructor(e,i,n,s,o,r){super(e,pe.buildKeyVerificationDetails(),pe.buildHeaders,o,r),this.insertKeyPlaceholderText="Hugging Face Token",this.getKeyLink="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}${n}`,this.textInputPlaceholderText=i,"object"==typeof s&&(s.model&&(this.url=`${t.URL_PREFIX}${s.model}`),s.options&&(this.rawBody.options=s.options),s.parameters&&(this.rawBody.parameters=s.parameters))}preprocessBody(t,e,i){const n=JSON.parse(JSON.stringify(t)),s=e[e.length-1].text;if(s)return n.options??(n.options={}),n.options.wait_for_model=!0,{inputs:s,...n}}async callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");const n=this.preprocessBody(this.rawBody,e,i);T.request(this,n,t)}};me.URL_PREFIX="https://api-inference.huggingface.co/models/";let fe=me;class ve extends fe{constructor(t,e,i,n,s,o){super(t,e,i,n,s,o),this.isTextInputDisabled=!0,this.canSendMessage=ve.canSendFile}static canSendFile(t,e){return!(null==e||!e[0])}preprocessBody(t,e,i){return i[0]}async callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");T.poll(this,i[0],t,!1)}}class ge extends ve{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.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 be extends ve{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.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 ye="data:image/png;base64,";class we{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,n){t.message?n(m.INVALID_KEY):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.stability.ai/v1/engines/list",method:"GET",handleVerificationResult:we.handleVerificationResult}}}class xe extends oe{constructor(t,e,i,n,s){super(t,e,i,n,s),this.insertKeyPlaceholderText="Stability AI API Key",this.getKeyLink="https://platform.stability.ai/docs/getting-started/authentication",this.permittedErrorPrefixes=["Incorrect","invalid_"]}}class Me extends xe{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),n=null==i?void 0:i.stabilityAI;super(t,we.buildKeyVerificationDetails(),we.buildHeaders,n,{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 s=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageUpscale;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/image-to-image/upscale`),Me.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=Me.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.requestSettings)throw new Error("Request settings have not been set up");if(!i)throw new Error("Image was not found");const n=this.createFormDataBody(this.rawBody,i[0]);v.tempRemoveContentHeader(this.requestSettings,T.request.bind(this,this,n,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${ye}${t.base64}`,type:"image"})))}}}class ke extends xe{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),n=null==i?void 0:i.stabilityAI;super(t,we.buildKeyVerificationDetails(),we.buildHeaders,n,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.url="https://api.stability.ai/v1/generation/stable-inpainting-512-v2-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 s=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageMasking;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/image-to-image/masking`),void 0!==s.weight&&null!==s.weight&&(this._imageWeight=s.weight),void 0!==s.mask_source&&null!==s.mask_source&&(this._maskSource=s.mask_source),ke.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=ke.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,n){const s=new FormData;return s.append("init_image",e),s.append("mask_source",String(this._maskSource)),s.append("mask_image",i),n&&""!==n&&s.append("text_prompts[0][text]",n),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 n,s;if(!this.requestSettings)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==(s=null==(n=e[e.length-1])?void 0:n.text)?void 0:s.trim(),r=this.createFormDataBody(this.rawBody,i[0],i[1],o);v.tempRemoveContentHeader(this.requestSettings,T.request.bind(this,this,r,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${ye}${t.base64}`,type:"image"})))}}}class je extends ve{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.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 Se extends fe{constructor(t){var e,i,n;super(t,"Once upon a time","gpt2",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.textGeneration,null==(n=t.directConnection)?void 0:n.huggingFace)}async extractResultData(t){if(t.error)throw t.error;return{text:t[0].generated_text||""}}}class Ae extends fe{constructor(t){var e,i,n;const s=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",s,null==(n=t.directConnection)?void 0:n.huggingFace),this.permittedErrorPrefixes=["Authorization header","Error in"],this.context=s.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 Te extends fe{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.huggingFace)}async extractResultData(t){if(t.error)throw t.error;return{text:t[0].summary_text||""}}}class Oe extends fe{constructor(t){var e,i,n;super(t,"Ask me anything!","facebook/blenderbot-400M-distill",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.conversation,null==(n=t.directConnection)?void 0:n.huggingFace),this.maxMessages??(this.maxMessages=-1)}processMessages(t){const e=t.filter((t=>t.text)),i=e[e.length-1].text,n=e.slice(0,e.length-1);if(!i)return;return{past_user_inputs:n.filter((t=>"user"===t.role)).map((t=>t.text)),generated_responses:n.filter((t=>"ai"===t.role)).map((t=>t.text)),mostRecentMessageText:i}}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=this.processMessages(e);if(n)return i.options??(i.options={}),i.options.wait_for_model=!0,{inputs:{past_user_inputs:n.past_user_inputs,generated_responses:n.generated_responses,text:n.mostRecentMessageText},...i}}async extractResultData(t){if(t.error)throw t.error;return{text:t.generated_text||""}}}class Ce extends xe{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),n=i.stabilityAI;super(t,we.buildKeyVerificationDetails(),we.buildHeaders,n,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-5/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 s=null==(e=i.stabilityAI)?void 0:e.imageToImage;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/text-to-image`),void 0!==s.weight&&null!==s.weight&&(this._imageWeight=s.weight),Ce.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=Ce.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 n=new FormData;return n.append("init_image",e),i&&""!==i&&n.append("text_prompts[0][text]",i),void 0!==this._imageWeight&&null!==this._imageWeight&&n.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach((e=>{n.append(e,String(t[e]))})),void 0===n.get("weight")&&n.append("weight",String(1)),n}async callServiceAPI(t,e,i){var n,s;if(!this.requestSettings)throw new Error("Request settings have not been set up");if(!i)throw new Error("Image was not found");const o=null==(s=null==(n=e[e.length-1])?void 0:n.text)?void 0:s.trim(),r=this.createFormDataBody(this.rawBody,i[0],o);v.tempRemoveContentHeader(this.requestSettings,T.request.bind(this,this,r,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${ye}${t.base64}`,type:"image"})))}}}class Ne extends fe{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.huggingFace)}async extractResultData(t){if(t.error)throw t.error;return{text:t[0].translation_text||""}}}class Ie extends xe{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),n=i.stabilityAI;super(t,we.buildKeyVerificationDetails(),we.buildHeaders,n),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-5/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 s=null==(e=i.stabilityAI)?void 0:e.textToImage;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/text-to-image`),void 0!==s.weight&&null!==s.weight&&(this._imageWeight=s.weight),Ie.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=Ie.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)),n={text:e};return this._imageWeight&&(n.weight=this._imageWeight),i.text_prompts=[n],i}async callServiceAPI(t,e){if(!this.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e[e.length-1].text);T.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${ye}${t.base64}`,type:"image"})))}}}class Ee extends fe{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.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){if(t.error)throw t.error;return{text:t[0].sequence||""}}}class ze{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json",accept:"application/json"}}static handleVerificationResult(t,e,i,n){"invalid request: prompt must be at least 1 token long"===t.message?i(e):n(m.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api.cohere.ai/v1/generate",method:"POST",handleVerificationResult:ze.handleVerificationResult,body:JSON.stringify({prompt:""})}}}class Le extends oe{constructor(t,e,i,n,s){super(t,ze.buildKeyVerificationDetails(),ze.buildHeaders,s),this.insertKeyPlaceholderText="Cohere API Key",this.getKeyLink="https://dashboard.cohere.ai/api-keys",this.permittedErrorPrefixes=["invalid"],this.url=e,this.textInputPlaceholderText=i,n&&"object"==typeof n&&Object.assign(this.rawBody,n)}}class Pe extends Le{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=e[e.length-1].text;if(n)return{prompt:n,...i}}async callServiceAPI(t,e){if(!this.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);T.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 _e extends Le{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=e[e.length-1].text;if(n)return{text:n,...i}}async callServiceAPI(t,e){if(!this.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);T.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.summary||""}}}const De=class t{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,n){const s=t;s.error?"invalid_api_key"===s.error.code?n(m.INVALID_KEY):n(m.CONNECTION_FAILED):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.openai.com/v1/models",method:"GET",handleVerificationResult:t.handleVerificationResult}}static async storeFiles(e,i,n){const s=e.requestSettings.headers;if(!s)return;e.url="https://api.openai.com/v1/files";const o=s[v.CONTENT_TYPE];delete s[v.CONTENT_TYPE];const r=n.map((async i=>{const n=new FormData;return n.append("purpose","assistants"),n.append("file",i),new Promise((i=>{i(t.directFetch(e,n,"POST",!1))}))}));try{const t=(await Promise.all(r)).map((t=>t.id));return s[v.CONTENT_TYPE]=o,t}catch(t){throw s[v.CONTENT_TYPE]=o,v.displayError(i,t),e.completionsHandlers.onFinish(),t}}static async directFetch(t,e,i,n=!0){t.requestSettings.method=i;const s=await v.fetch(t,t.requestSettings.headers,n,e).then((t=>v.processResponseByType(t)));if(s.error)throw s.error.message;return s}};De.CONVERSE_MAX_CHAR_LENGTH=13352,De.FILE_MAX_CHAR_LENGTH=1e3;let Re=De;const Fe=class t extends oe{constructor(e){var i,n,s;const{textInput:o}=e,r=JSON.parse(JSON.stringify(e.directConnection)),a=null==r?void 0:r.openAI;super(e,Re.buildKeyVerificationDetails(),Re.buildHeaders,a),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/audio/speech",this.permittedErrorPrefixes=["Invalid"],this._maxCharLength=Re.FILE_MAX_CHAR_LENGTH,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>',null!=o&&o.characterLimit&&(this._maxCharLength=o.characterLimit);const c=null==(i=null==r?void 0:r.openAI)?void 0:i.textToSpeech;"object"==typeof c&&Object.assign(this.rawBody,c),(n=this.rawBody).model??(n.model=t.DEFAULT_MODEL),(s=this.rawBody).voice??(s.voice=t.DEFAULT_VOIDE),this.textInputPlaceholderText="Insert text to generate audio",this.rawBody.response_format="mp3"}preprocessBody(t,e){var i,n;const s=JSON.parse(JSON.stringify(t)),o=null==(n=null==(i=e[e.length-1])?void 0:i.text)?void 0:n.trim();if(o&&""!==o){const t=o.substring(0,this._maxCharLength);s.input=t}return s}async callServiceAPI(t,e){var i;if(null==(i=this.requestSettings)||!i.headers)throw new Error("Request settings have not been set up");this.url=this.requestSettings.url||this.url;const n=this.preprocessBody(this.rawBody,e);T.request(this,n,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"}}};Fe.DEFAULT_MODEL="tts-1",Fe.DEFAULT_VOIDE="alloy";let Be=Fe;const Je=class t extends oe{constructor(e){var i,n;const{textInput:s}=e,o=JSON.parse(JSON.stringify(e.directConnection)),r=null==o?void 0:o.openAI;super(e,Re.buildKeyVerificationDetails(),Re.buildHeaders,r,{audio:{}}),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="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._maxCharLength=Re.FILE_MAX_CHAR_LENGTH,this._service_url=t.AUDIO_TRANSCRIPTIONS_URL,null!=s&&s.characterLimit&&(this._maxCharLength=s.characterLimit);const a=null==(i=null==o?void 0:o.openAI)?void 0:i.audio;"object"==typeof a&&(this.processConfig(a),t.cleanConfig(a),Object.assign(this.rawBody,a)),(n=this.rawBody).model??(n.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,n;const s=JSON.parse(JSON.stringify(t)),o=null==(n=null==(i=e[e.length-1])?void 0:i.text)?void 0:n.trim();if(o&&""!==o){const t=o.substring(0,this._maxCharLength);s.prompt=t}return s}async callServiceAPI(e,i,n){var s;if(null==(s=this.requestSettings)||!s.headers)throw new Error("Request settings have not been set up");if(null==n||!n[0])throw new Error("No file was added");this.url=this.requestSettings.url||this._service_url;const o=this.preprocessBody(this.rawBody,i),r=t.createFormDataBody(o,n[0]);v.tempRemoveContentHeader(this.requestSettings,T.request.bind(this,this,r,e),!1)}async extractResultData(t){if(t.error)throw t.error.message;return{text:t.text}}};Je.AUDIO_TRANSCRIPTIONS_URL="https://api.openai.com/v1/audio/transcriptions",Je.AUDIO_TRANSLATIONS_URL="https://api.openai.com/v1/audio/translations",Je.DEFAULT_MODEL="whisper-1";let qe=Je;class Ye{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,n){t.error?n(m.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:Ye.handleSpeechVerificationResult}}static buildSummarizationHeader(t){return{"Ocp-Apim-Subscription-Key":t,"Content-Type":"application/json"}}static handleLanguageVerificationResult(t,e,i,n){var s;"401"===(null==(s=t.error)?void 0:s.code)?n(m.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:Ye.handleLanguageVerificationResult}}static handleTranslationVerificationResult(t,e,i,n){t.json().then((t=>{Array.isArray(t)||401e3!==t.error.code?i(e):n(m.INVALID_KEY)}))}static buildTranslationKeyVerificationDetails(t){return{url:"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es",method:"POST",createHeaders:e=>Ye.buildTranslationHeaders(t,e),handleVerificationResult:Ye.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 Ue extends oe{constructor(t,e,i,n,s){super(t,Ye.buildLanguageKeyVerificationDetails(i),e,n,s),this.insertKeyPlaceholderText="Azure Language Subscription Key",this.getKeyLink="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",this.permittedErrorPrefixes=["Access"]}}class $e extends Ue{constructor(t){var e,i,n,s;const o=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.summarization,r=null==(n=t.directConnection)?void 0:n.azure;super(t,Ye.buildSummarizationHeader,o.endpoint,r),this.url="",this.textInputPlaceholderText="Insert text to summarize",(s=this.rawBody).language??(s.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.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);T.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"),n={method:"GET",headers:null==(e=this.requestSettings)?void 0:e.headers};T.executePollRequest(this,i,n,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||""}}}const Ve=class t{static generateDefaultBody(t){return{model:t}}static build(e,i){const n=t.generateDefaultBody(e);return i&&"boolean"!=typeof i?Object.assign(n,i):n}};Ve.GPT_COMPLETIONS_DAVINCI_MODEL="text-davinci-003",Ve.GPT_CHAT_TURBO_MODEL="gpt-3.5-turbo";let Ze=Ve;class He extends oe{constructor(t){var e,i;const{directConnection:n,textInput:s}=t,o=null==n?void 0:n.openAI;super(t,Re.buildKeyVerificationDetails(),Re.buildHeaders,o),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/completions",this.permittedErrorPrefixes=["Incorrect"],this._maxCharLength=Re.CONVERSE_MAX_CHAR_LENGTH,this.full_transaction_max_tokens=4e3,this.numberOfCharsPerToken=3.5;const r=null==(e=null==n?void 0:n.openAI)?void 0:e.completions;null!=s&&s.characterLimit&&(this._maxCharLength=s.characterLimit),"object"==typeof r&&Object.assign(this.rawBody,r),(i=this.rawBody).model??(i.model=Ze.GPT_COMPLETIONS_DAVINCI_MODEL)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=e.filter((t=>t.text)),s=n[n.length-1].text;if(!s)return;const o=s.substring(0,this._maxCharLength),r=i.max_tokens||this.full_transaction_max_tokens-o.length/this.numberOfCharsPerToken;return{prompt:o,max_tokens:Math.floor(r),...i}}async callServiceAPI(t,e){if(!this.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);this.deepChat.stream||i.stream?(i.stream=!0,S.request(this,i,t)):T.request(this,i,t)}async extractResultData(t){var e;if(t.error)throw t.error.message;return{text:(null==(e=t.choices[0])?void 0:e.text)||""}}}class Ge{static async poll(t,e){const i={authorization:t,"content-type":"application/json"},n=`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 s;for(;!s;){const t=await(await fetch(n,{headers:i})).json();if("completed"===t.status)s=t;else{if("error"===t.status)throw new Error(`Transcription failed: ${t.error}`);await new Promise((t=>setTimeout(t,3e3)))}}return s}static buildHeaders(t){return{Authorization:t,"Content-Type":"application/octet-stream"}}static handleVerificationResult(t,e,i,n){const s=t;s.error?"invalid_api_key"===s.error.code?n(m.INVALID_KEY):n(m.CONNECTION_FAILED):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.assemblyai.com/v2/upload",method:"POST",handleVerificationResult:Ge.handleVerificationResult}}}class Ke extends oe{constructor(t){var e;const i=null==(e=t.directConnection)?void 0:e.assemblyAI;super(t,Ge.buildKeyVerificationDetails(),Ge.buildHeaders,i,{audio:{}}),this.insertKeyPlaceholderText="AssemblyAI API Key",this.getKeyLink="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=Ke.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])}async callServiceAPI(t,e,i){var n;if(null==(n=this.requestSettings)||!n.headers)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");T.request(this,i[0],t,!1)}async extractResultData(t){var e,i;if(t.error)throw t.error;const n=null==(i=null==(e=this.requestSettings)?void 0:e.headers)?void 0:i.Authorization;return{text:(await Ge.poll(n,t.upload_url)).text}}}class Qe extends oe{constructor(t,e,i,n,s){super(t,Ye.buildSpeechKeyVerificationDetails(i),e,n,s),this.insertKeyPlaceholderText="Azure Speech Subscription Key",this.getKeyLink="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal"}}const We=class t extends Qe{constructor(e){var i,n,s,o,r,a;const c=null==(n=null==(i=e.directConnection)?void 0:i.azure)?void 0:n.textToSpeech,l=null==(s=e.directConnection)?void 0:s.azure;super(e,Ye.buildTextToSpeechHeaders.bind({},(null==c?void 0:c.outputFormat)||"audio-16khz-128kbitrate-mono-mp3"),c.region,l),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,c),(o=this.rawBody).lang??(o.lang="en-US"),(r=this.rawBody).name??(r.name="en-US-JennyNeural"),(a=this.rawBody).gender??(a.gender="Female"),this.url=`https://${c.region}.tts.speech.microsoft.com/cognitiveservices/v1`}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.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);T.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"}]})}}))}};We.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 Xe=We;const ti=class t extends Qe{constructor(e){var i,n,s;const o=null==(n=null==(i=e.directConnection)?void 0:i.azure)?void 0:n.speechToText,r=null==(s=e.directConnection)?void 0:s.azure;super(e,Ye.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 n,s;if(null==(n=this.requestSettings)||!n.headers)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");null!=(s=this.requestSettings)&&s.headers&&(this.requestSettings.headers["Content-Type"]=i[0].name.toLocaleLowerCase().endsWith(".wav")?"audio/wav; codecs=audio/pcm; samplerate=16000":"audio/ogg; codecs=opus"),T.request(this,i[0],t,!1)}async extractResultData(t){if(t.error)throw t.error;return{text:t.DisplayText||""}}};ti.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 ei=ti;class ii extends oe{constructor(t){var e,i,n;const s=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.translation,o=null==(n=t.directConnection)?void 0:n.azure;super(t,Ye.buildTranslationKeyVerificationDetails(s.region),Ye.buildTranslationHeaders.bind({},null==s?void 0:s.region),o),this.insertKeyPlaceholderText="Azure Translate Subscription Key",this.getKeyLink="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=${s.language||"es"}`}preprocessBody(t){const e=t[t.length-1].text;if(e)return[{Text:e}]}async callServiceAPI(t,e){if(!this.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(e);T.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 ni=class t{static getRole(e){return e?t.AI_ROLE:t.USER_ROLE}static getLastElementsByClass(t,e,i){for(let n=t.length-1;n>=0;n-=1){const s=t[n];if(s.bubbleElement.classList.contains(e[0])&&!e.slice(1).find((t=>!s.bubbleElement.classList.contains(t)))){if(!i)return s;if(!i.find((t=>s.bubbleElement.classList.contains(t))))return s}}}static getLastMessage(e,i,n){const s=t.getRole(i);for(let t=e.length-1;t>=0;t-=1)if(e[t].role===s){if(!n)return e[t];if(e[t][n])return e[t]}}};ni.AI_ROLE="ai",ni.USER_ROLE="user";let si=ni;const oi=class t extends oe{constructor(t){var e,i,n,s,o;const r=JSON.parse(JSON.stringify(t.directConnection)),a=r.openAI;super(t,Re.buildKeyVerificationDetails(),Re.buildHeaders,a),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.url="",this.permittedErrorPrefixes=["Incorrect"],this.searchedForThreadId=!1;const c=null==(e=r.openAI)?void 0:e.assistant;if("object"==typeof c){this.rawBody.assistant_id=c.assistant_id;const{function_handler:e}=null==(n=null==(i=t.directConnection)?void 0:i.openAI)?void 0:n.assistant;e&&(this._functionHandler=e)}(s=this.requestSettings).headers??(s.headers={}),(o=this.requestSettings.headers)["OpenAI-Beta"]??(o["OpenAI-Beta"]="assistants=v1"),this.maxMessages=1}processMessages(t,e){const i=this.totalMessagesMaxCharLength||Re.CONVERSE_MAX_CHAR_LENGTH;return O.getCharacterLimitMessages(t,i).map((t=>({content:t.text||"",role:t.role===si.AI_ROLE?"assistant":"user",file_ids:e})))}createNewThreadMessages(t,e,i){const n=JSON.parse(JSON.stringify(t)),s=this.processMessages(e,i);return n.thread={messages:s},n}callService(e,i,n){if(this.sessionId){this.url=`${t.THREAD_PREFIX}/${this.sessionId}/messages`;const s=this.processMessages(i,n)[0];T.request(this,s,e)}else{this.url=`${t.THREAD_PREFIX}/runs`;const s=this.createNewThreadMessages(this.rawBody,i,n);T.request(this,s,e)}this.messages=e}async callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");this.searchedForThreadId||this.searchPreviousMessagesForThreadId(t.messages);const n=i?await Re.storeFiles(this,t,i):void 0;this.requestSettings.method="POST",this.callService(t,e,n)}searchPreviousMessagesForThreadId(t){const e=t.find((t=>t.sessionId));e&&(this.sessionId=e.sessionId),this.searchedForThreadId=!0}async extractResultData(e){var i;if(e.error)throw e.error.message;await this.assignThreadAndRun(e);const n=`${t.THREAD_PREFIX}/${this.sessionId}/runs/${this.run_id}`,s={method:"GET",headers:null==(i=this.requestSettings)?void 0:i.headers};return T.executePollRequest(this,n,s,this.messages),{makingAnotherRequest:!0}}async assignThreadAndRun(e){if(this.sessionId){this.url=`${t.THREAD_PREFIX}/${this.sessionId}/runs`;const e=await Re.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 extractPollResultData(e){var i;const{status:n,required_action:s}=e;if("queued"===n||"in_progress"===n)return{timeoutMS:t.POLLING_TIMEOUT_MS};if("completed"===n&&this.messages)return this.url=`${t.THREAD_PREFIX}/${e.thread_id}/messages`,{text:(await Re.directFetch(this,{},"GET")).data[0].content[0].text.value,sessionId:this.sessionId};const o=null==(i=null==s?void 0:s.submit_tool_outputs)?void 0:i.tool_calls;if("requires_action"===n&&o)return await this.handleTools(o);throw Error(`Thread run status: ${n}`)}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}))),n=(await this._functionHandler(i)).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`,await Re.directFetch(this,{tool_outputs:n},"POST"),{timeoutMS:t.POLLING_TIMEOUT_MS}}};oi.THREAD_PREFIX="https://api.openai.com/v1/threads",oi.POLLING_TIMEOUT_MS=800;let ri=oi;const ai=class t extends oe{constructor(e){var i;const{directConnection:n,textInput:s}=e,o=null==n?void 0:n.openAI;super(e,Re.buildKeyVerificationDetails(),Re.buildHeaders,o,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="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"],this._maxCharLength=Re.FILE_MAX_CHAR_LENGTH,null!=s&&s.characterLimit&&(this._maxCharLength=s.characterLimit);const r=null==(i=null==n?void 0:n.openAI)?void 0:i.images;if(this.camera){const t="object"==typeof r&&r.size?Number.parseInt(r.size):1024;this.camera.files={dimensions:{width:t,height:t}}}"object"==typeof r&&Object.assign(this.rawBody,r),this.canSendMessage=t.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])||!(!t||""===t.trim())}static createFormDataBody(t,e,i){const n=new FormData;return n.append("image",e),i&&n.append("mask",i),Object.keys(t).forEach((e=>{n.append(e,String(t[e]))})),n}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t));if(e&&""!==e){const t=e.substring(0,this._maxCharLength);i.prompt=t}return i}callApiWithImage(e,i,n){var s,o;let r;const a=null==(o=null==(s=i[i.length-1])?void 0:s.text)?void 0:o.trim();if(n[1]||a&&""!==a){this.url=t.IMAGE_EDIT_URL;const e=this.preprocessBody(this.rawBody,a);r=t.createFormDataBody(e,n[0],n[1])}else this.url=t.IMAGE_VARIATIONS_URL,r=t.createFormDataBody(this.rawBody,n[0]);v.tempRemoveContentHeader(this.requestSettings,T.request.bind(this,this,r,e),!1)}async callServiceAPI(e,i,n){var s;if(null==(s=this.requestSettings)||!s.headers)throw new Error("Request settings have not been set up");if(null!=n&&n[0])this.callApiWithImage(e,i,n);else{if(!this.requestSettings)throw new Error("Request settings have not been set up");this.url=t.IMAGE_GENERATION_URL;const n=this.preprocessBody(this.rawBody,i[i.length-1].text);T.request(this,n,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:`${ye}${t.b64_json}`,type:"image"}))}}};ai.IMAGE_GENERATION_URL="https://api.openai.com/v1/images/generations",ai.IMAGE_VARIATIONS_URL="https://api.openai.com/v1/images/variations",ai.IMAGE_EDIT_URL="https://api.openai.com/v1/images/edits";let ci=ai;class li extends oe{constructor(t){var e,i,n,s;const o=JSON.parse(JSON.stringify(t.directConnection)),r=o.openAI;super(t,Re.buildKeyVerificationDetails(),Re.buildHeaders,r),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/chat/completions",this.permittedErrorPrefixes=["Incorrect"],this._systemMessage=li.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=li.generateSystemMessage(a.system_prompt));const{function_handler:e}=null==(n=null==(i=t.directConnection)?void 0:i.openAI)?void 0:n.chat;e&&(this._functionHandler=e),this.cleanConfig(a),Object.assign(this.rawBody,a)}this.maxMessages??(this.maxMessages=-1),(s=this.rawBody).model??(s.model=Ze.GPT_CHAT_TURBO_MODEL)}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)),n=this.totalMessagesMaxCharLength||Re.CONVERSE_MAX_CHAR_LENGTH,s=O.getCharacterLimitMessages(e,n-this._systemMessage.content.length).map((t=>({content:li.getContent(t),role:t.role===si.AI_ROLE?"assistant":"user"})));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.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);this.deepChat.stream||i.stream?(i.stream=!0,S.request(this,i,t)):T.request(this,i,t)}async extractResultData(t,e,i){if(t.error)throw t.error.message;return t.choices[0].delta?{text:t.choices[0].delta.content||""}:t.choices[0].message?t.choices[0].message.tool_calls?this.handleTools(t.choices[0].message,e,i):{text:t.choices[0].message.content}:{text:""}}async handleTools(t,e,i){var n;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 s=JSON.parse(JSON.stringify(i)),o=t.tool_calls.map((t=>({name:t.function.name,arguments:t.function.arguments}))),r=await(null==(n=this._functionHandler)?void 0:n.call(this,o));if(r.text)return{text:r.text};if(s.messages.push(t),Array.isArray(r)){r.forEach(((e,i)=>{var n;const o=null==(n=t.tool_calls)?void 0:n[i];null==s||s.messages.push({role:"tool",tool_call_id:null==o?void 0:o.id,name:null==o?void 0:o.function.name,content:e.response})})),delete s.tools,delete s.tool_choice;const i=await(null==e?void 0:e(s).then((t=>v.processResponseByType(t))));if(i.error)throw i.error.message;return{text:i.choices[0].message.content||""}}throw Error("Response object must contain a FunctionHandlerResponse object")}}class ui extends Le{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),n=null==(e=i.cohere)?void 0:e.chat;super(t,"https://api.cohere.ai/v1/chat","Ask me anything!",n,i.cohere),this.username="USER","object"==typeof n&&(n.user_name&&(this.username=n.user_name),this.cleanConfig(n),Object.assign(this.rawBody,n)),this.maxMessages??(this.maxMessages=-1)}cleanConfig(t){delete t.user_name}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=e.filter((t=>t.text));return i.query=n[n.length-1].text,i.chat_history=n.slice(0,n.length-1).map((t=>({text:t.text,user_name:"ai"===t.role?"CHATBOT":this.username}))),i}async callServiceAPI(t,e){if(!this.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);T.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.text}}}class hi{static create(t){const{directConnection:e,request:i,demo:n}=t;if(e){if(e.openAI)return e.openAI.images?new ci(t):e.openAI.speechToText?new qe(t):e.openAI.textToSpeech?new Be(t):e.openAI.assistant?new ri(t):e.openAI.completions?new He(t):new li(t);if(e.assemblyAI)return new Ke(t);if(e.cohere)return e.cohere.chat?new ui(t):e.cohere.summarization?new _e(t):new Pe(t);if(e.huggingFace)return e.huggingFace.textGeneration?new Se(t):e.huggingFace.summarization?new Te(t):e.huggingFace.translation?new Ne(t):e.huggingFace.fillMask?new Ee(t):e.huggingFace.questionAnswer?new Ae(t):e.huggingFace.audioSpeechRecognition?new je(t):e.huggingFace.audioClassification?new ge(t):e.huggingFace.imageClassification?new be(t):new Oe(t);if(e.azure){if(e.azure.speechToText)return new ei(t);if(e.azure.textToSpeech)return new Xe(t);if(e.azure.summarization)return new $e(t);if(e.azure.translation)return new ii(t)}if(e.stabilityAI)return e.stabilityAI.imageToImage?new Ce(t):e.stabilityAI.imageToImageUpscale?new Me(t):e.stabilityAI.imageToImageMasking?new ke(t):new Ie(t)}return i?new se(t):new se(t,void 0,n||!0)}}const di=class t{static appendStyleSheetToHead(){const e=document.getElementsByTagName("head")[0];if(!Array.from(e.getElementsByTagName("link")).some((e=>e.getAttribute("href")===t.FONT_URL))){const i=document.createElement("link");i.rel="stylesheet",i.href=t.FONT_URL,e.appendChild(i)}}};di.FONT_URL="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap";let pi=di;class mi{}function fi(t){return function(e,i){Object.defineProperty(e,i,{});const n=e.constructor,s=i.toLocaleLowerCase();n._attributes_[s]=mi.attibutes[t],n._attributeToProperty_[s]=i}}mi.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}`)()};class vi{static onNewMessage(t,e,i){const n=JSON.parse(JSON.stringify({message:e,isInitial:i}));t.onNewMessage(n),t.dispatchEvent(new CustomEvent("new-message",{detail:n}))}static onClearMessages(t){t.onClearMessages(),t.dispatchEvent(new CustomEvent("clear-messages"))}static onRender(t){t.onComponentRender(),t.dispatchEvent(new CustomEvent("render"))}}const gi=class t{static addElements(t,...e){e.forEach((e=>t.appendChild(e)))}static isScrollbarAtBottomOfElement(e){const i=e.scrollHeight,n=e.clientHeight;return e.scrollTop>=i-n-t.CODE_SNIPPET_GENERATION_JUMP}static cloneElement(t){const e=t.cloneNode(!0);return t.parentNode.replaceChild(e,t),e}};gi.CODE_SNIPPET_GENERATION_JUMP=.5;let bi=gi;const yi=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 n={};setTimeout((()=>{if("object"==typeof e&&(e.lang&&(n.lang=e.lang),e.pitch&&(n.pitch=e.pitch),e.rate&&(n.rate=e.rate),e.volume&&(n.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&&(n.voice=t)}i(n)}),t.LOAD_VOICES_MS)}};yi.LOAD_VOICES_MS=200;let wi=yi;class xi{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 set(t,e){var i,n,s,o;if(null!=(n=null==(i=null==e?void 0:e.loading)?void 0:i.bubble)&&n.color){const i=xi.colorToHex(null==(o=null==(s=null==e?void 0:e.loading)?void 0:s.bubble)?void 0:o.color);t.style.setProperty("--message-dots-color",i),t.style.setProperty("--message-dots-color-fade",`${i}33`)}else t.style.setProperty("--message-dots-color","#848484"),t.style.setProperty("--message-dots-color-fade","#55555533")}}class Mi{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",Mi.mouseEnter.bind(this,t,e)),t.addEventListener("mouseleave",Mi.mouseLeave.bind(this,t,e)),t.addEventListener("mousedown",Mi.mouseDown.bind(this,t,e)),t.addEventListener("mouseup",Mi.mouseUp.bind(this,t,e))}}class ki{static applyStylesToElement(t,e){const n=i.processStateful(e,{},{});Mi.add(t,n),Object.assign(t.style,n.default)}static applyEventsToElement(t,e){Object.keys(e).forEach((i=>{const n=e[i];n&&t.addEventListener(i,n)}))}static applyClassUtilitiesToElement(t,e){const{events:i,styles:n}=e;i&&ki.applyEventsToElement(t,i),n&&!Ai.doesElementContainDeepChatClass(t)&&ki.applyStylesToElement(t,n)}static applyCustomClassUtilities(t,e){Object.keys(t).forEach((i=>{const n=e.getElementsByClassName(i);Array.from(n).forEach((e=>{t[i]&&ki.applyClassUtilitiesToElement(e,t[i])}))}))}static apply(t,e){Ai.applyDeepChatUtilities(t,t.htmlClassUtilities,e),ki.applyCustomClassUtilities(t.htmlClassUtilities,e)}}const ji={"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"}}}},Si=Object.keys(ji);class Ai{static applySuggestionEvent(t,e){setTimeout((()=>{e.addEventListener("click",(()=>{var i,n;null==(n=t.submitUserMessage)||n.call(t,(null==(i=e.textContent)?void 0:i.trim())||"")}))}))}static isUpdateMessage(t){var e;const i=document.createElement("div");return i.innerHTML=t,null==(e=i.children[0])?void 0:e.classList.contains("deep-chat-update-message")}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 Si.find((e=>t.classList.contains(e)))}static applyEvents(t,e){const i=ji[e].events;Object.keys(i||[]).forEach((e=>{t.addEventListener(e,null==i?void 0:i[e])}))}static getProcessedStyles(t,e,n){const s=Array.from(e.classList).reduce(((e,i)=>{var n;const s=null==(n=t[i])?void 0:n.styles;return s&&t[i].styles&&e.push(s),e}),[]),o=ji[n].styles;if(o){const t=JSON.parse(JSON.stringify(o));t.default&&i.overwriteDefaultWithAlreadyApplied(t,e),s.unshift(t)}const r=i.mergeStatefulStyles(s);return i.processStateful(r,{},{})}static applyDeepChatUtilities(t,e,i){Si.forEach((t=>{const n=i.getElementsByClassName(t);Array.from(n||[]).forEach((i=>{const n=Ai.getProcessedStyles(e,i,t);ki.applyStylesToElement(i,n),Ai.applyEvents(i,t)}))}));const n=i.getElementsByClassName("deep-chat-suggestion-button");Array.from(n).forEach((e=>Ai.applySuggestionEvent(t,e)))}}class Ti{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],n="a"!==e.tagName.toLocaleLowerCase()?e:e.children[0];Object.assign(n.style,i.media)}}static applySideStyles(t,e,i,n){n&&(Ti.applyCustomStylesToElements(t,i,n.shared),e?Ti.applyCustomStylesToElements(t,i,n.ai):Ti.applyCustomStylesToElements(t,i,n.user))}static isMessageSideStyles(t){return!!(t.ai||t.shared||t.user)}static applyCustomStyles(t,e,i,n,s){var o;s&&t.default!==s?Ti.isMessageSideStyles(s)?(Ti.applySideStyles(e,i,n,t.default),Ti.applySideStyles(e,i,n,s)):(Ti.applyCustomStylesToElements(e,n,null==(o=t.default)?void 0:o.shared),Ti.applyCustomStylesToElements(e,n,s)):Ti.applySideStyles(e,i,n,t.default)}static extractParticularSharedStyles(t,e){if(null==e||!e.shared)return;const i=e.shared,n={outerContainer:{},innerContainer:{},bubble:{},media:{}};return t.forEach((t=>{var e,s,o,r;n.outerContainer[t]=(null==(e=i.outerContainer)?void 0:e[t])||"",n.innerContainer[t]=(null==(s=i.innerContainer)?void 0:s[t])||"",n.bubble[t]=(null==(o=i.bubble)?void 0:o[t])||"",n.media[t]=(null==(r=i.media)?void 0:r[t])||""})),n}}class Oi{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=Oi.createIntroPanel(e);return"none"===t.style.display&&(t.style.display="block"),i.appendChild(t),i}createInternalIntroPanel(t,e){const i=Oi.createIntroPanel(e);return i.id="internal-intro-panel",i.innerHTML=t,i}hide(){this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="none",this._isDisplayed=!1)}display(){!this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="",this._isDisplayed=!0)}}const Ci=class t{static addMessage(t,e,i,n){var s;t.elementRef.appendChild(e.outerContainer),t.applyCustomStyles(e,n,!0,null==(s=t.messageStyles)?void 0:s[i]),t.elementRef.scrollTop=t.elementRef.scrollHeight}static wrapInLink(t,e){const i=document.createElement("a");return i.href=e,i.target="_blank",i.appendChild(t),i}static processContent(e,i){return!i||i.startsWith("data")?e:t.wrapInLink(e,i)}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}}};Ci.DEFAULT_FILE_NAME="file";let Ni=Ci;class Ii{static addElement(t,e){t.elementRef.appendChild(e),t.elementRef.scrollTop=t.elementRef.scrollHeight}static createElements(t,e,i){const n=t.createNewMessageElement("",i);return n.bubbleElement.classList.add("html-message"),n.bubbleElement.innerHTML=e,n}static updateLastAIMessage(t,e,i){const n=si.getLastElementsByClass(i,["ai-message-text","html-message"],["loading-message-text"]);if(!n)return!1;n&&(n.bubbleElement.innerHTML=e);const s=si.getLastMessage(t,!0,"html");return s&&(s.html=e),!0}static add(t,e,i,n){var s;if(Ai.isUpdateMessage(e)&&Ii.updateLastAIMessage(t.messages,e,n))return;const o=Ii.createElements(t,e,i);return 0===e.trim().length&&_i.editEmptyMessageElement(o.bubbleElement),ki.apply(t,o.outerContainer),t.applyCustomStyles(o,i,!1,null==(s=t.messageStyles)?void 0:s.html),Ii.addElement(t,o.outerContainer),o}}class Ei{static getText(t,e){var i,n;if(!t.directConnection&&!t.request&&!t.demo)return"Connect to any API using the [request](https://deepchat.dev/docs/connect#Request)\n property or choose any one of the preconfigured APIs via\n the [directConnection](https://deepchat.dev/docs/directConnection/#directConnection) property.\n \n To get started checkout the [Start](https://deepchat.dev/start) page and\n live code [examples](https://deepchat.dev/examples/frameworks).\n \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.";const o=null==(n=t.directConnection.openAI)?void 0:n.assistant;if("boolean"==typeof o||o&&!o.assistant_id)return"Please define the `assistant_id` property inside the openAI [assistant](https://deepchat.dev/docs/directConnection/openAI#Assistant) object."}else if(t.request&&!t.request.url&&!t.request.handler)return"Please define a `url` or a `handler` property inside the [request](https://deepchat.dev/docs/connect#Request) object.";return null}}class zi{static createImage(t,e){const i=new Image;return i.src=t.src,Ni.scrollDownOnImageLoad(i.src,e),Ni.processContent(i,i.src)}static async addNewImageMessage(t,e,i){const n=zi.createImage(e,t.elementRef),s=t.createNewMessageElement("",i);s.bubbleElement.appendChild(n),s.bubbleElement.classList.add("image-message"),Ni.addMessage(t,s,"image",i)}static createAudioElement(t,e){const i=document.createElement("audio");return i.src=t.src,i.classList.add("audio-player"),i.controls=!0,r.IS_SAFARI&&(i.classList.add("audio-player-safari"),i.classList.add(e?"audio-player-safari-left":"audio-player-safari-right")),i}static addNewAudioMessage(t,e,i){const n=zi.createAudioElement(e,i),s=t.createNewMessageElement("",i);s.bubbleElement.appendChild(n),s.bubbleElement.classList.add("audio-message"),Ni.addMessage(t,s,"audio",i)}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 n=le.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>');n.classList.add("any-file-message-icon"),i.appendChild(n);const s=document.createElement("div");return s.classList.add("any-file-message-text"),s.textContent=t.name||Ni.DEFAULT_FILE_NAME,e.appendChild(i),e.appendChild(s),Ni.processContent(e,t.src)}static addNewAnyFileMessage(t,e,i){const n=t.createNewMessageElement("",i),s=zi.createAnyFile(e);n.bubbleElement.classList.add("any-file-message-bubble"),n.bubbleElement.appendChild(s),Ni.addMessage(t,n,"file",i)}static addMessages(t,e,i){e.forEach((e=>{var n,s;"audio"===e.type||null!=(n=e.src)&&n.startsWith("data:audio")?zi.addNewAudioMessage(t,e,i):"image"===e.type||null!=(s=e.src)&&s.startsWith("data:image")?zi.addNewImageMessage(t,e,i):zi.addNewAnyFileMessage(t,e,i)}))}}class Li{static applyCustomStylesToElements(t,e,i){Object.assign(t.style,i.container),Object.assign(e.style,i.avatar)}static applyCustomStyles(t,e,i,n){var s,o,r;null!=(s=i.default)&&s.styles&&Li.applyCustomStylesToElements(t,e,i.default.styles),n?null!=(o=i.ai)&&o.styles&&Li.applyCustomStylesToElements(t,e,i.ai.styles):null!=(r=i.user)&&r.styles&&Li.applyCustomStylesToElements(t,e,i.user.styles)}static createAvatar(t,e){var i,n,s,o;const r=document.createElement("img");r.src=t?(null==(i=null==e?void 0:e.ai)?void 0:i.src)||(null==(n=null==e?void 0:e.default)?void 0:n.src)||"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8c3ZnIGZpbGw9IiMwMDAwMDAiIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIAoJCXZpZXdCb3g9IjAgMCAzMiAzMiIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+Cgk8cGF0aCBkPSJNMjMsMzAuMzZIOWMtMi40MDQsMC00LjM2LTEuOTU2LTQuMzYtNC4zNlYxNWMwLTIuNDA0LDEuOTU2LTQuMzYsNC4zNi00LjM2aDMuNjU5CgkJYzAuMTY3LTEuNTY2LDEuNDE1LTIuODEzLDIuOTgxLTIuOTgxVjUuMzMzYy0xLjEzMS0wLjE3NC0yLTEuMTU0LTItMi4zMzNjMC0xLjMwMSwxLjA1OS0yLjM2LDIuMzYtMi4zNgoJCWMxLjMwMiwwLDIuMzYsMS4wNTksMi4zNiwyLjM2YzAsMS4xNzktMC44NjksMi4xNTktMiwyLjMzM1Y3LjY2YzEuNTY2LDAuMTY3LDIuODE0LDEuNDE1LDIuOTgxLDIuOTgxSDIzCgkJYzIuNDA0LDAsNC4zNiwxLjk1Niw0LjM2LDQuMzZ2MTFDMjcuMzYsMjguNDA0LDI1LjQwNCwzMC4zNiwyMywzMC4zNnogTTksMTEuMzZjLTIuMDA3LDAtMy42NCwxLjYzMy0zLjY0LDMuNjR2MTEKCQljMCwyLjAwNywxLjYzMywzLjY0LDMuNjQsMy42NGgxNGMyLjAwNywwLDMuNjQtMS42MzMsMy42NC0zLjY0VjE1YzAtMi4wMDctMS42MzMtMy42NC0zLjY0LTMuNjRIOXogTTEzLjM4NCwxMC42NGg1LjIzMQoJCUMxOC40MzksOS4zNTQsMTcuMzM0LDguMzYsMTYsOC4zNkMxNC42NjcsOC4zNiwxMy41NjEsOS4zNTQsMTMuMzg0LDEwLjY0eiBNMTYsMS4zNmMtMC45MDQsMC0xLjY0LDAuNzM2LTEuNjQsMS42NAoJCVMxNS4wOTYsNC42NCwxNiw0LjY0YzAuOTA0LDAsMS42NC0wLjczNiwxLjY0LTEuNjRTMTYuOTA0LDEuMzYsMTYsMS4zNnogTTIwLDI3LjM2aC04Yy0xLjMwMSwwLTIuMzYtMS4wNTktMi4zNi0yLjM2CgkJczEuMDU5LTIuMzYsMi4zNi0yLjM2aDhjMS4zMDIsMCwyLjM2LDEuMDU5LDIuMzYsMi4zNlMyMS4zMDIsMjcuMzYsMjAsMjcuMzZ6IE0xMiwyMy4zNmMtMC45MDQsMC0xLjY0LDAuNzM1LTEuNjQsMS42NAoJCXMwLjczNiwxLjY0LDEuNjQsMS42NGg4YzAuOTA0LDAsMS42NC0wLjczNSwxLjY0LTEuNjRzLTAuNzM1LTEuNjQtMS42NC0xLjY0SDEyeiBNMzEsMjMuODZoLTJjLTAuMTk5LDAtMC4zNi0wLjE2MS0wLjM2LTAuMzZWMTUKCQljMC0wLjE5OSwwLjE2MS0wLjM2LDAuMzYtMC4zNmgyYzAuMTk5LDAsMC4zNiwwLjE2MSwwLjM2LDAuMzZ2OC41QzMxLjM2LDIzLjY5OSwzMS4xOTksMjMuODYsMzEsMjMuODZ6IE0yOS4zNiwyMy4xNGgxLjI3OXYtNy43OAoJCUgyOS4zNlYyMy4xNHogTTMsMjMuODZIMWMtMC4xOTksMC0wLjM2LTAuMTYxLTAuMzYtMC4zNlYxNWMwLTAuMTk5LDAuMTYxLTAuMzYsMC4zNi0wLjM2aDJjMC4xOTksMCwwLjM2LDAuMTYxLDAuMzYsMC4zNnY4LjUKCQlDMy4zNiwyMy42OTksMy4xOTksMjMuODYsMywyMy44NnogTTEuMzYsMjMuMTRoMS4yOHYtNy43OEgxLjM2VjIzLjE0eiBNMjAsMjAuMzZjLTEuMzAyLDAtMi4zNi0xLjA1OS0yLjM2LTIuMzYKCQlzMS4wNTktMi4zNiwyLjM2LTIuMzZzMi4zNiwxLjA1OSwyLjM2LDIuMzZDMjIuMzYsMTkuMzAyLDIxLjMwMiwyMC4zNiwyMCwyMC4zNnogTTIwLDE2LjM2Yy0wLjkwNCwwLTEuNjQsMC43MzYtMS42NCwxLjY0CgkJczAuNzM1LDEuNjQsMS42NCwxLjY0czEuNjQtMC43MzUsMS42NC0xLjY0UzIwLjkwNCwxNi4zNiwyMCwxNi4zNnogTTEyLDIwLjM2Yy0xLjMwMSwwLTIuMzYtMS4wNTktMi4zNi0yLjM2czEuMDU5LTIuMzYsMi4zNi0yLjM2CgkJczIuMzYsMS4wNTksMi4zNiwyLjM2QzE0LjM2LDE5LjMwMiwxMy4zMDEsMjAuMzYsMTIsMjAuMzZ6IE0xMiwxNi4zNmMtMC45MDQsMC0xLjY0LDAuNzM2LTEuNjQsMS42NHMwLjczNiwxLjY0LDEuNjQsMS42NAoJCXMxLjY0LTAuNzM1LDEuNjQtMS42NFMxMi45MDQsMTYuMzYsMTIsMTYuMzZ6Ii8+Cgk8cmVjdCBzdHlsZT0iZmlsbDpub25lOyIgd2lkdGg9IjMyIiBoZWlnaHQ9IjMyIi8+Cjwvc3ZnPg==":(null==(s=null==e?void 0:e.user)?void 0:s.src)||(null==(o=null==e?void 0:e.default)?void 0:o.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==",r.classList.add("avatar");const a=document.createElement("div");return a.classList.add("avatar-container"),a.appendChild(r),e&&Li.applyCustomStyles(a,r,e,t),a}static getPosition(t,e){var i,n,s,o,r,a;let c=t?null==(n=null==(i=null==e?void 0:e.ai)?void 0:i.styles)?void 0:n.position:null==(o=null==(s=null==e?void 0:e.user)?void 0:s.styles)?void 0:o.position;return c??(c=null==(a=null==(r=null==e?void 0:e.default)?void 0:r.styles)?void 0:a.position),c??(c=t?"left":"right"),c}static add(t,e,i){const n="boolean"==typeof i?void 0:i,s=Li.createAvatar(e,n),o=Li.getPosition(e,n);s.classList.add("left"===o?"left-item-position":"right-item-position"),t.insertAdjacentElement("left"===o?"beforebegin":"afterend",s)}}class Pi{static getPosition(t,e){var i,n,s;let o=t?null==(i=null==e?void 0:e.ai)?void 0:i.position:null==(n=null==e?void 0:e.user)?void 0:n.position;return o||(o=null==(s=null==e?void 0:e.default)?void 0:s.position),o||(o=t?"left":"right"),o}static applyStyle(t,e,i){var n,s,o;Object.assign(t.style,null==(n=i.default)?void 0:n.style,e?null==(s=i.ai)?void 0:s.style:null==(o=i.user)?void 0:o.style)}static getNameText(t,e){var i,n,s,o;return t?(null==(i=e.ai)?void 0:i.text)||(null==(n=e.default)?void 0:n.text)||"AI":(null==(s=e.user)?void 0:s.text)||(null==(o=e.default)?void 0:o.text)||"User"}static createName(t,e){const i=document.createElement("div");return i.classList.add("name"),i.textContent=Pi.getNameText(t,e),Pi.applyStyle(i,t,e),i}static add(t,e,i){const n="boolean"==typeof i?{}:i,s=Pi.createName(e,n),o=Pi.getPosition(e,n);s.classList.add("left"===o?"left-item-position":"right-item-position"),t.insertAdjacentElement("left"===o?"beforebegin":"afterend",s)}}class _i{constructor(t,e,i){var n,s;this._messageElementRefs=[],this._textElementsToText=[],this._streamedText="",this.htmlClassUtilities={},this.messages=[];const{permittedErrorPrefixes:o,introPanelMarkUp:r,demo:a}=e;this._remarkable=ie.createNew(),this.elementRef=_i.createContainerElement(),this.messageStyles=t.messageStyles,this._avatars=t.avatars,this._names=t.names,this._errorMessageOverrides=null==(n=t.errorMessages)?void 0:n.overrides,t.htmlClassUtilities&&(this.htmlClassUtilities=t.htmlClassUtilities),this._onNewMessage=vi.onNewMessage.bind(this,t),this._onClearMessages=vi.onClearMessages.bind(this,t),this._displayLoadingMessage=_i.getDisplayLoadingMessage(t,e),this._permittedErrorPrefixes=o,this.addSetupMessageIfNeeded(t,e),this.populateIntroPanel(i,r,t.introPanelStyle),t.introMessage&&this.addIntroductoryMessage(t.introMessage),t.initialMessages&&this.populateInitialMessages(t.initialMessages),this._displayServiceErrorMessages=null==(s=t.errorMessages)?void 0:s.displayServiceErrorMessages,t.getMessages=()=>JSON.parse(JSON.stringify(this.messages)),t.clearMessages=this.clearMessages.bind(this,e),t.refreshMessages=this.refreshTextMessages.bind(this),t.scrollToBottom=this.scrollToBottom.bind(this),a&&this.prepareDemo(a),t.textToSpeech&&wi.processConfig(t.textToSpeech,(t=>{this._textToSpeech=t})),setTimeout((()=>{this.submitUserMessage=t.submitUserMessage}))}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())}static createContainerElement(){const t=document.createElement("div");return t.id="messages",t}addSetupMessageIfNeeded(t,e){const i=Ei.getText(t,e);if(i){const t=this.createAndAppendNewMessageElement(i,!0);this.applyCustomStyles(t,!0,!1)}}addIntroductoryMessage(t){var e,i,n,s;if(t&&(this._introMessage=t),null!=(e=this._introMessage)&&e.text){const t=this.createAndAppendNewMessageElement(this._introMessage.text,!0);this.applyCustomStyles(t,!0,!1,null==(i=this.messageStyles)?void 0:i.intro)}else if(null!=(n=this._introMessage)&&n.html){const t=Ii.add(this,this._introMessage.html,!0,this._messageElementRefs);this.applyCustomStyles(t,!0,!1,null==(s=this.messageStyles)?void 0:s.intro)}}populateInitialMessages(t){t.forEach((t=>{N.processInitialMessageFile(t),this.addNewMessage(t,t.role===si.AI_ROLE,!0)})),setTimeout((()=>this.scrollToBottom()))}applyCustomStyles(t,e,i,n){t&&this.messageStyles&&Ti.applyCustomStyles(this.messageStyles,t,e,i,n)}addInnerContainerElements(t,e,i){return t.classList.add("message-bubble",i?"ai-message-text":"user-message-text"),t.innerHTML=this._remarkable.render(e),0===t.innerText.trim().length&&(t.innerText=e),this._avatars&&Li.add(t,i,this._avatars),this._names&&Pi.add(t,i,this._names),{bubbleElement:t}}static createMessageContent(t,e){const i={role:si.getRole(t)},{text:n,files:s,html:o,sessionId:r}=e;return n&&(i.text=n),s&&(i.files=s),o&&(i.html=o),1===Object.keys(i).length&&(i.text=""),r&&(i.sessionId=r),i}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}}createMessageElements(t,e){const i=_i.createBaseElements(),{outerContainer:n,innerContainer:s,bubbleElement:o}=i;return n.appendChild(s),this.addInnerContainerElements(o,t,e),this._messageElementRefs.push(i),i}static isTemporaryElement(t){return(null==t?void 0:t.bubbleElement.classList.contains("loading-message-text"))||Ai.isElementTemporary(t)}createNewMessageElement(t,e){var i;null==(i=this._introPanel)||i.hide();const n=this._messageElementRefs[this._messageElementRefs.length-1];return _i.isTemporaryElement(n)&&(n.outerContainer.remove(),this._messageElementRefs.pop()),this.createMessageElements(t,e)}createAndAppendNewMessageElement(t,e){const i=this.createNewMessageElement(t,e);return this.elementRef.appendChild(i.outerContainer),this.scrollToBottom(),i}static editEmptyMessageElement(t){t.textContent=".",t.style.color="#00000000"}addNewTextMessage(t,e){const i=this.createAndAppendNewMessageElement(t,e);return this.applyCustomStyles(i,e,!1),0===t.trim().length&&_i.editEmptyMessageElement(i.bubbleElement),this._textElementsToText.push([i,t]),i}addNewMessage(t,e,i=!1){let n=!0;const s=_i.createMessageContent(e,t);if(void 0!==s.text&&null!==t.text&&(this.addNewTextMessage(s.text,e),!i&&this._textToSpeech&&e&&wi.speak(s.text,this._textToSpeech)),s.files&&Array.isArray(s.files)&&zi.addMessages(this,s.files,e),void 0!==s.html&&null!==s.html){const t=Ii.add(this,s.html,e,this._messageElementRefs);Ai.isElementTemporary(t)&&delete s.html,n=!!t}this.updateStateOnMessage(s,n,i)}updateStateOnMessage(t,e,i=!1){e&&this.messages.push(t),this.sendClientUpdate(t,i)}sendClientUpdate(t,e=!1){var i;null==(i=this._onNewMessage)||i.call(this,JSON.parse(JSON.stringify(t)),e)}removeMessageOnError(){const t=this._messageElementRefs[this._messageElementRefs.length-1],e=null==t?void 0:t.bubbleElement;(null!=e&&e.classList.contains("streamed-message")&&""===e.textContent||_i.isTemporaryElement(t))&&(t.outerContainer.remove(),this._messageElementRefs.pop())}addNewErrorMessage(t,e){var i,n,s,o;this.removeMessageOnError();const r=_i.createBaseElements(),{outerContainer:a,bubbleElement:c}=r;c.classList.add("error-message-text");const l=this.getPermittedMessage(e)||(null==(i=this._errorMessageOverrides)?void 0:i[t])||(null==(n=this._errorMessageOverrides)?void 0:n.default)||"Error, please try again.";c.innerHTML=l;const u=Ti.extractParticularSharedStyles(["fontSize","fontFamily"],null==(s=this.messageStyles)?void 0:s.default);Ti.applyCustomStylesToElements(r,!1,u),Ti.applyCustomStylesToElements(r,!1,null==(o=this.messageStyles)?void 0:o.error),this.elementRef.appendChild(a),this.scrollToBottom(),this._textToSpeech&&wi.speak(l,this._textToSpeech),this._streamedText=""}static checkPermittedErrorPrefixes(t,e){for(let i=0;i<t.length;i+=1)if(e.startsWith(t[i]))return e}getPermittedMessage(t){if(t){if(this._displayServiceErrorMessages)return t;if("string"==typeof t&&this._permittedErrorPrefixes){const e=_i.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,t);if(e)return e}else if(Array.isArray(t)&&this._permittedErrorPrefixes)for(let e=0;e<t.length;e+=1){const i=_i.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,t[e]);if(i)return i}}}getLastMessageElement(){return this.elementRef.children[this.elementRef.children.length-1]}getLastMessageBubbleElement(){var t,e,i;return Array.from((null==(i=null==(e=null==(t=this.getLastMessageElement())?void 0:t.children)?void 0:e[0])?void 0:i.children)||[]).find((t=>t.classList.contains("message-bubble")))}isLastMessageError(){var t;return null==(t=this.getLastMessageBubbleElement())?void 0:t.classList.contains("error-message-text")}removeError(){this.isLastMessageError()&&this.getLastMessageElement().remove()}addLoadingMessage(){var t;if(!this._displayLoadingMessage)return;const e=this.createMessageElements("",!0),{outerContainer:i,bubbleElement:n}=e;n.classList.add("loading-message-text");const s=document.createElement("div");s.classList.add("dots-flashing"),n.appendChild(s),this.applyCustomStyles(e,!0,!1,null==(t=this.messageStyles)?void 0:t.loading),xi.set(n,this.messageStyles),this.elementRef.appendChild(i),this.scrollToBottom()}addNewStreamedMessage(){const{bubbleElement:t}=this.addNewTextMessage("",!0),e=_i.createMessageContent(!0,{text:""});return this.messages.push(e),t.classList.add("streamed-message"),this.scrollToBottom(),t}updateStreamedMessage(t,e){var i,n,s,o,r;const a=bi.isScrollbarAtBottomOfElement(this.elementRef);if(0!==t.trim().length){const t=null==(i=this.messageStyles)?void 0:i.default;e.style.color=(null==(s=null==(n=null==t?void 0:t.ai)?void 0:n.bubble)?void 0:s.color)||(null==(r=null==(o=null==t?void 0:t.shared)?void 0:o.bubble)?void 0:r.color)||""}this._streamedText+=t,this._textElementsToText[this._textElementsToText.length-1][1]=this._streamedText,e.innerHTML=this._remarkable.render(this._streamedText),a&&this.scrollToBottom()}finaliseStreamedMessage(){var t;null!=(t=this.getLastMessageBubbleElement())&&t.classList.contains("streamed-message")&&(this._textElementsToText[this._textElementsToText.length-1][1]=this._streamedText,this.messages[this.messages.length-1].text=this._streamedText,this.sendClientUpdate(_i.createMessageContent(!0,{text:this._streamedText}),!1),this._textToSpeech&&wi.speak(this._streamedText,this._textToSpeech),this._streamedText="")}populateIntroPanel(t,e,i){(t||e)&&(this._introPanel=new Oi(t,e,i),this._introPanel._elementRef&&(ki.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})}}else{const i=t.file.name||Ni.DEFAULT_FILE_NAME;e({name:i,type:"any"})}})))))}clearMessages(t,e){var i,n;const s=[];this._messageElementRefs.forEach((t=>{const e=t.bubbleElement.classList;e.contains("loading-message-text")||e.contains("streamed-message")?s.push(t):t.outerContainer.remove()})),Array.from(this.elementRef.children).forEach((t=>{var e;const i=null==(e=t.children[0])?void 0:e.children[0];null!=i&&i.classList.contains("error-message-text")&&t.remove()})),this._messageElementRefs=s,!1!==e&&(null!=(i=this._introPanel)&&i._elementRef&&this._introPanel.display(),this.addIntroductoryMessage()),this.messages.splice(0,this.messages.length),this._textElementsToText.splice(0,this._textElementsToText.length),null==(n=this._onClearMessages)||n.call(this),delete t.sessionId}scrollToBottom(){this.elementRef.scrollTop=this.elementRef.scrollHeight}refreshTextMessages(){this._remarkable=ie.createNew(),this._textElementsToText.forEach((t=>{t[0].bubbleElement.innerHTML=this._remarkable.render(t[1])}))}}const Di=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,n){0===n["outside-right"].length&&n["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===n["outside-left"].length&&n["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,n){if(!(n["inside-left"].length>0||n["inside-right"].length>0)){if(0===n["outside-right"].length&&n["outside-left"].length>0)return e[0].classList.add(t.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),n["outside-left"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")));if(0===n["outside-left"].length&&n["outside-right"].length>0)return e[3].classList.add(t.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),n["outside-right"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")))}}static set(e,i,n,s){!!t.adjustOutsideSubmit(i,n,s)||t.adjustForOutsideButton(i,n,s),t.adjustInputPadding(e,s)}};Di.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS="text-input-container-left-adjustment",Di.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS="text-input-container-right-adjustment",Di.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS="text-input-container-left-small-adjustment",Di.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS="text-input-container-right-small-adjustment";let Ri=Di;class Fi{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 n=Fi.getContainerIndex(i);t[n].appendChild(e),3===n&&e.classList.add("outside-right")}}const Bi=["camera","gifs","images","audio","mixedFiles","submit","microphone"];class Ji{static createTextElement(t){const e=document.createElement("div");return e.classList.add("text-button"),e.innerText=t,e}static createElement(t,e){return e?Ji.createTextElement(t):le.createSVGElement(t)}static createCustomElement(t,e){var i,n,s,o;const r=null==e?void 0:e[t];return null!=(i=null==r?void 0:r.text)&&i.content?Ji.createElement(null==(n=null==r?void 0:r.text)?void 0:n.content,!0):null!=(s=null==r?void 0:r.svg)&&s.content?Ji.createElement(null==(o=null==r?void 0:r.svg)?void 0:o.content,!1):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 n;return i&&(n=Ji.createCustomElement(e,i)),Ji.processElement(t,n),n}static create(t,e,i){const n={};if(!i)return Ji.processElement(t),n;const s=Ji.createSpecificStateElement(t,e[0],i);n[e[0]]=s;let o=s;return e.slice(1).forEach((t=>{o=Ji.createCustomElement(t,i)||o,n[t]=o})),n}}class qi{static unsetAllCSS(t,e){var n,s;e.container&&i.unsetAllCSSMouseStates(t,e.container),null!=(n=e.svg)&&n.styles&&i.unsetAllCSSMouseStates(t.children[0],e.svg.styles),null!=(s=e.text)&&s.styles&&i.unsetAllCSSMouseStates(t.children[0],e.text.styles)}static unsetActionCSS(t,e){var n,s;e.container&&i.unsetActivityCSSMouseStates(t,e.container),null!=(n=e.svg)&&n.styles&&i.unsetActivityCSSMouseStates(t.children[0],e.svg.styles),null!=(s=e.text)&&s.styles&&i.unsetActivityCSSMouseStates(t.children[0],e.text.styles)}static setElementsCSS(t,e,i){var n,s,o,r,a;Object.assign(t.style,null==(n=e.container)?void 0:n[i]),Object.assign(t.children[0].style,null==(o=null==(s=e.svg)?void 0:s.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){qi.setElementsCSS(t,e,"default"),"default"!==i&&(qi.setElementsCSS(t,e,"hover"),"hover"!==i&&qi.setElementsCSS(t,e,"click"))}}class Yi{constructor(t,e,i,n){this._mouseState={state:"default"},this.elementRef=t,this._customStyles=i,this.position=e,this.dropupText=n}buttonMouseLeave(t){this._mouseState.state="default",t&&(qi.unsetAllCSS(this.elementRef,t),qi.setElementsCSS(this.elementRef,t,"default"))}buttonMouseEnter(t){this._mouseState.state="hover",t&&qi.setElementsCSS(this.elementRef,t,"hover")}buttonMouseUp(t){t&&qi.unsetActionCSS(this.elementRef,t),this.buttonMouseEnter(t)}buttonMouseDown(t){this._mouseState.state="click",t&&qi.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],n=i&&this._customStyles[i];n&&qi.unsetActionCSS(this.elementRef,n)}}reapplyStateStyle(t,e){if(!this._customStyles)return;e&&this.unsetCustomStateStyles(e);const i=this._customStyles[t];i&&qi.setElementCssUpToState(this.elementRef,i,this._mouseState.state),this.setEvents(i)}}class Ui{static focusItemWhenOnEdge(t,e){const i=e?t.children[0]:t.children[t.children.length-1];Ui.focusSiblingItem(i,t,e,!0)}static focusSiblingItem(t,e,i,n=!1){const s=n?t:t[i?"nextSibling":"previousSibling"];s?(t.dispatchEvent(new MouseEvent("mouseleave")),s.dispatchEvent(new MouseEvent("mouseenter"))):(t.dispatchEvent(new MouseEvent("mouseleave")),Ui.focusItemWhenOnEdge(e,i))}}class $i{static addItemEvents(t,e,i,n){Mi.add(e,n),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,n){const s=t.children[0];s.classList.contains("text-button")?e.appendChild($i.createItemText(s.textContent,null==n?void 0:n.text)):(e.appendChild($i.createItemIcon(t,null==n?void 0:n.iconContainer)),e.appendChild($i.createItemText(i,null==n?void 0:n.text)))}static createItem(t,e,n){var s;const{elementRef:o,dropupText:r}=e,a=document.createElement("div");Object.assign(a.style,null==(s=null==n?void 0:n.item)?void 0:s.default),$i.populateItem(o,a,r,n),a.classList.add("dropup-menu-item");const c=i.processStateful((null==n?void 0:n.item)||{},{backgroundColor:"#f3f3f3"},{backgroundColor:"#ebebeb"});return $i.addItemEvents(t,a,o,c),a}}class Vi{constructor(t,e){var i;this._isOpen=!0,this._styles=e,this.elementRef=Vi.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=$i.createItem(this,t,this._styles);this.elementRef.appendChild(e)}addWindowEvents(t){window.addEventListener("click",(e=>{var i;t.parentElement!==(null==(i=e.target.shadowRoot)?void 0:i.children[0])&&this.close()})),window.addEventListener("keydown",(t=>{var e,i,n;this._isOpen&&(t.key===o.ESCAPE?(this.close(),null==(e=this.highlightedItem)||e.dispatchEvent(new MouseEvent("mouseleave"))):t.key===o.ENTER?(null==(i=this.highlightedItem)||i.click(),null==(n=this.highlightedItem)||n.dispatchEvent(new MouseEvent("mouseleave"))):t.key===o.ARROW_DOWN?Ui.focusSiblingItem(this.highlightedItem||this.elementRef.children[this.elementRef.children.length-1],this.elementRef,!0):t.key===o.ARROW_UP&&Ui.focusSiblingItem(this.highlightedItem||this.elementRef.children[0],this.elementRef,!1))}))}}class Zi extends Yi{constructor(t,e){var i;super(Zi.createButtonElement(),void 0,{styles:null==(i=null==e?void 0:e.button)?void 0:i.styles});const n=this.createInnerElements(this._customStyles);this._menu=new Vi(t,null==e?void 0:e.menu),this.addClickEvent(),this.buttonContainer=Zi.createButtonContainer(),this.elementRef.appendChild(n.styles),this.buttonContainer.appendChild(this.elementRef),this.elementRef.classList.add("dropup-icon","upload-file-button"),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(Zi.createSVGIconElement(),"styles",t)}}createInnerElement(t,e,i){return Ji.createSpecificStateElement(this.elementRef,e,i)||t}static createSVGIconElement(){const t=le.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>');return t.id="dropup-icon",t}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,n;return null!=(i=null==e?void 0:e.button)&&i.position?null==(n=null==e?void 0:e.button)?void 0:n.position:t["outside-left"].length>0&&0===t["outside-right"].length?"outside-right":"outside-left"}}class Hi{static addToDropup(t,e,i,n){const s=new Zi(i,n);Bi.forEach((t=>{const i=e["dropup-menu"].findIndex((e=>e.buttonType===t)),n=e["dropup-menu"][i];n&&(s.addItem(n.button),e["dropup-menu"].splice(i,1))}));const o=Zi.getPosition(e,n);Fi.addButton(t,s.buttonContainer,o),e[o].push({})}static addToSideContainer(t,e){["inside-left","inside-right","outside-left","outside-right"].forEach((i=>{const n=i;e[n].forEach((e=>{Fi.addButton(t,e.button.elementRef,n)}))}))}static setPosition(t,e,i){const n={...t[e],buttonType:e};i.push(n),delete t[e]}static createPositionsObj(){return{"dropup-menu":[],"outside-left":[],"inside-left":[],"inside-right":[],"outside-right":[]}}static generatePositions(t){const e=Hi.createPositionsObj();Object.keys(t).forEach((i=>{var n;const s=null==(n=t[i])?void 0:n.button.position;s&&Hi.setPosition(t,i,e[s])})),0===e["inside-right"].length&&t.submit&&Hi.setPosition(t,"submit",e["inside-right"]),0===e["outside-right"].length&&(t.submit?Hi.setPosition(t,"submit",e["outside-right"]):t.microphone?Hi.setPosition(t,"microphone",e["outside-right"]):t.camera&&Hi.setPosition(t,"camera",e["outside-right"])),t.submit&&Hi.setPosition(t,"submit",0===e["outside-left"].length?e["outside-left"]:e["inside-right"]),t.microphone&&Hi.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?Bi.forEach((i=>{t[i]&&e["dropup-menu"].push({...t[i],buttonType:i})})):1===i.length&&Hi.setPosition(t,i[0],0===e["outside-right"].length?e["outside-right"]:e["outside-left"]),e}static addButtons(t,e,i,n){const s=Hi.generatePositions(e);return Hi.addToSideContainer(t,s),s["dropup-menu"].length>0&&Hi.addToDropup(t,s,i,n),s}}const Gi={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 Ki{constructor(t,e,i,n){this._attachments=[],this._fileCountLimit=99,this._acceptedFormat="",e.maxNumberOfFiles&&(this._fileCountLimit=e.maxNumberOfFiles),this._toggleContainerDisplay=i,this._fileAttachmentsContainerRef=n,e.acceptedFormats&&(this._acceptedFormat=e.acceptedFormats),setTimeout((()=>{this._validationHandler=t._validationHandler}))}attemptAddFile(t,e){return!!Ki.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 n=i[e].trim();if(t.type===n)return!0;if(n.startsWith(".")){const e=n.slice(1);if(t.name.endsWith(e))return!0}else{if(t.name.endsWith(n))return!0;if(n.endsWith("/*")&&t.type.startsWith(n.slice(0,-2)))return!0}}return!1}addAttachmentBasedOnType(t,e,i){if(t.type.startsWith("image")){const n=Ki.createImageAttachment(e);this.addFileAttachment(t,"image",n,i)}else if(t.type.startsWith("audio")){const n=Xi.createAudioAttachment(e);this.addFileAttachment(t,"audio",n,i)}else{const e=Ki.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"),r.IS_SAFARI&&e.classList.add("border-bound-attachment-safari");const i=document.createElement("div");i.classList.add("any-file-attachment-text");const n=document.createElement("div");return n.classList.add("file-attachment-text-container"),n.appendChild(i),i.textContent=t,e.appendChild(n),e}addFileAttachment(t,e,i,n){var s;const o=Ki.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 n&&(r.removeButton=this.createRemoveAttachmentButton(r),o.appendChild(r.removeButton)),this._toggleContainerDisplay(!0),this._attachments.push(r),this._fileAttachmentsContainerRef.scrollTop=this._fileAttachmentsContainerRef.scrollHeight,null==(s=this._validationHandler)||s.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)),n=this._attachments[i].attachmentContainerElement;this._attachments.splice(i,1),Xi.stopAttachmentPlayback(n),n.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 Qi='<?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>',Wi=class t extends Ki{constructor(t,e,i,n){super(t,e,i,n)}static createAudioContainer(){const t=document.createElement("div");return t.classList.add("border-bound-attachment","audio-attachment-icon-container"),r.IS_SAFARI&&t.classList.add("border-bound-attachment-safari"),t}static addAudioElements(t,e){const i=t.parentElement?bi.cloneElement(t):t,n=document.createElement("audio");n.src=e;const s=le.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>');s.classList.add("attachment-icon","play-icon");const o=le.createSVGElement(Qi);o.classList.add("attachment-icon","stop-icon"),i.replaceChildren(s),n.onplay=()=>{i.replaceChildren(o)},n.onpause=()=>{i.replaceChildren(s),n.currentTime=0},n.onended=()=>{i.replaceChildren(s)},i.onclick=()=>{n.paused?n.play():n.pause()}}static createAudioAttachment(e){const i=t.createAudioContainer();return t.addAudioElements(i,e),i}createTimer(e,i){let n=0;const s=void 0!==i&&i<t.TIMER_LIMIT_S?i:t.TIMER_LIMIT_S;return setInterval((()=>{var t;n+=1,n===s&&(null==(t=this.stopPlaceholderCallback)||t.call(this),this.clearTimer()),600===n&&e.classList.add("audio-placeholder-text-4-digits");const i=Math.floor(n/60),o=(n%60).toString().padStart(2,"0");e.textContent=`${i}:${o}`}),1e3)}createPlaceholderAudioAttachment(e){const i=t.createAudioContainer(),n=document.createElement("div");n.classList.add("audio-placeholder-text-3-digits");const s=document.createElement("div");s.classList.add("file-attachment-text-container","audio-placeholder-text-3-digits-container"),s.appendChild(n);const o=le.createSVGElement(Qi);return o.classList.add("attachment-icon","stop-icon","not-removable-attachment-icon"),n.textContent="0:00",this._activePlaceholderTimer=this.createTimer(n,e),i.appendChild(s),this.addPlaceholderAudioAttachmentEvents(i,o,s),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 n=this._activePlaceholderAttachment;n&&(n.file=e,t.addAudioElements(n.attachmentContainerElement.children[0],i),n.removeButton=this.createRemoveAttachmentButton(n),n.attachmentContainerElement.appendChild(n.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,n;null!=(n=null==(i=null==(e=t.children[0])?void 0:e.children)?void 0:i[0])&&n.classList.contains("stop-icon")&&t.children[0].click()}};Wi.TIMER_LIMIT_S=5999;let Xi=Wi;class tn{static create(t,e,i,n,s){return"audio"===s?new Xi(t,e,i,n):new Ki(t,e,i,n)}}class en{constructor(t,e,i){this._fileAttachmentsTypes=[],this.elementRef=this.createAttachmentContainer();const n="object"==typeof i&&!!i.displayFileAttachmentContainer;this.toggleContainerDisplay(n),t.appendChild(this.elementRef),e&&Object.assign(this.elementRef.style,e)}addType(t,e,i){const n=tn.create(t,e,this.toggleContainerDisplay.bind(this),this.elementRef,i);return this._fileAttachmentsTypes.push(n),n}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 n=0;n<e.length&&!e[n].attemptAddFile(t,i.target.result);n+=1);}}))}addFilesToAnyType(t){en.addFilesToType(t,this._fileAttachmentsTypes)}removeAllFiles(){this._fileAttachmentsTypes.forEach((t=>t.removeAllAttachments())),this.elementRef.replaceChildren(),this.toggleContainerDisplay(!1)}getNumberOfTypes(){return this._fileAttachmentsTypes.length}}const nn=class t{constructor(e,i,n){this._isOpen=!1,this._contentRef=t.createModalContent(i,null==n?void 0:n.backgroundColor),this._buttonPanel=t.createButtonPanel(null==n?void 0:n.backgroundColor),this._elementRef=t.createContainer(this._contentRef,n),this._elementRef.appendChild(this._buttonPanel),e.appendChild(this._elementRef),this._backgroundPanelRef=t.createDarkBackgroundPanel(),e.appendChild(this._backgroundPanelRef),this.addWindowEvents()}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=le.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,n){const s=i?t.createSVGButton(e):t.createTextButton(e);return this.addButtons(s),s.onclick=()=>{this.close(),setTimeout((()=>{null==n||n()}),140)},s}static createTextModalFunc(e,i,n){var s;if("object"==typeof i&&null!=(s=i.files)&&s.infoModal){const s=new t(e,["modal-content"],i.files.infoModal.containerStyle);return s.addCloseButton("OK",!1,n),s.openTextModal.bind(s,i.infoModalTextMarkUp||"")}}addWindowEvents(){window.addEventListener("keydown",(t=>{var e,i;this._isOpen&&(t.key===o.ESCAPE?(this.close(),null==(e=this.extensionCloseCallback)||e.call(this)):t.key===o.ENTER&&(this.close(),null==(i=this.extensionCloseCallback)||i.call(this)))}))}};nn.MODAL_CLOSE_TIMEOUT_MS=190;let sn=nn;class on extends Yi{constructor(t,e,i,n,s,o){var r,a,c,l,u,h;super(on.createButtonElement(),null==(r=i.button)?void 0:r.position,i.button,o);const d=this.createInnerElements(n,s,this._customStyles);this._inputElement=on.createInputElement(null==(a=null==i?void 0:i.files)?void 0:a.acceptedFormats),this.addClickEvent(t,i),this.elementRef.replaceChildren(d.styles),this.reapplyStateStyle("styles"),this._fileAttachmentsType=e,this._openModalOnce=!1===(null==(l=null==(c=i.files)?void 0:c.infoModal)?void 0:l.openModalOnce)||null==(h=null==(u=i.files)?void 0:u.infoModal)?void 0:h.openModalOnce}createInnerElements(t,e,i){const n=on.createSVGIconElement(t,e);return{styles:this.createInnerElement(n,"styles",i)}}triggerImportPrompt(t){t.onchange=this.import.bind(this,t),t.click()}import(t){en.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}createInnerElement(t,e,i){return Ji.createSpecificStateElement(this.elementRef,e,i)||t}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button","upload-file-button"),t}static createSVGIconElement(t,e){const i=le.createSVGElement(e);return i.id=t,i}addClickEvent(t,e){const i=this.triggerImportPrompt.bind(this,this._inputElement),n=sn.createTextModalFunc(t,e,i);this.elementRef.onclick=this.click.bind(this,n)}click(t){!t||void 0!==this._openModalOnce&&!0!==this._openModalOnce?this.triggerImportPrompt(this._inputElement):(t(),!0===this._openModalOnce&&(this._openModalOnce=!1))}}class rn{static create(t,e,i){const n=rn.createElement(i);rn.addEvents(n,t,e),t.appendChild(n)}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(),rn.display(t)},t.ondragleave=e=>{e.preventDefault(),rn.hide(t)},t.ondragover=t=>{t.preventDefault()},t.ondrop=e=>{e.preventDefault(),rn.uploadFile(i,e),rn.hide(t)}}static uploadFile(t,e){var i;const n=null==(i=e.dataTransfer)?void 0:i.files;n&&t.addFilesToAnyType(Array.from(n))}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 an{static async useValidationFunc(t,e,i,n,s){const o=e.inputElementRef,r=o.classList.contains("text-input-placeholder")?"":o.textContent;await i.completePlaceholders();const a=i.getAllFileData(),c=t(r,null==a?void 0:a.map((t=>t.file)),s);return c?n.changeToSubmitIcon():n.changeToDisabledIcon(),c}static validateWebsocket(t,e){return!(t.websocket&&!C.canSendMessage(t.websocket))||(e.changeToDisabledIcon(),!1)}static attach(t,e,i,n,s){const o=t.validateInput||N.processValidateInput(t);t._validationHandler=async(t=!1)=>{if(s.status.loadingActive||s.status.requestInProgress||!0===e.isSubmitProgrammaticallyDisabled||!an.validateWebsocket(e,s))return!1;const r=o||e.canSendMessage;return r?an.useValidationFunc(r,i,n,s,t):null}}}class cn extends Yi{constructor(t){"dropup-menu"===(null==t?void 0:t.position)&&(t.position="outside-right"),super(cn.createMicrophoneElement(),null==t?void 0:t.position,t),this.isActive=!1,this._innerElements=this.createInnerElements(this._customStyles),this.changeToDefault()}createInnerElements(t){const e=cn.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 Ji.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=le.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 ln={},un={},hn={},dn={},pn={};Object.defineProperty(pn,"u",{value:!0}),pn.Text=void 0;class mn{static capitalize(t){return t.replace(mn.FIRST_CHAR_REGEX,(t=>t.toUpperCase()))}static lineBreak(t){return t.replace(mn.DOUBLE_LINE,"<p></p>").replace(mn.ONE_LINE,"<br>")}static isCharDefined(t){return void 0!==t&&" "!==t&&" "!==t&&"\n"!==t&&""!==t}static breakupIntoWordsArr(t){return t.split(/(\W+)/)}}pn.Text=mn,mn.FIRST_CHAR_REGEX=/\S/,mn.DOUBLE_LINE=/\n\n/g,mn.ONE_LINE=/\n/g,Object.defineProperty(dn,"u",{value:!0}),dn.Translate=void 0;const fn=pn;dn.Translate=class{static translate(t,e){const i=fn.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(hn,"u",{value:!0}),hn.WebSpeechTranscript=void 0;const vn=dn;hn.WebSpeechTranscript=class{static extract(t,e,i){let n="";for(let s=t.resultIndex;s<t.results.length;++s){let o=t.results[s][0].transcript;i&&(o=vn.Translate.translate(o,i)),t.results[s].isFinal?e+=o:n+=o}return{interimTranscript:n,finalTranscript:e,newText:n||e}}static extractSafari(t,e,i){let n="";for(let e=t.resultIndex;e<t.results.length;++e){let s=t.results[e][0].transcript;i&&(s=vn.Translate.translate(s,i)),n+=s}return{interimTranscript:"",finalTranscript:n,newText:n}}};var gn={};Object.defineProperty(gn,"u",{value:!0}),gn.Browser=void 0;class bn{}gn.Browser=bn,bn.IS_SAFARI=()=>(void 0===bn._IS_SAFARI&&(bn._IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),bn._IS_SAFARI);var yn={},wn={};Object.defineProperty(wn,"u",{value:!0}),wn.EventListeners=void 0;class xn{static getElementIfFocusedOnAvailable(t,e){return Array.isArray(t)?t.find((t=>e===t)):e===t?t:void 0}static keyDownWindow(t){t.element&&xn.getElementIfFocusedOnAvailable(t.element,document.activeElement)&&(null!==xn.KEY_DOWN_TIMEOUT&&clearTimeout(xn.KEY_DOWN_TIMEOUT),xn.KEY_DOWN_TIMEOUT=setTimeout((()=>{xn.KEY_DOWN_TIMEOUT=null,this.resetRecording(t)}),500))}static mouseDownWindow(t,e){this.mouseDownElement=xn.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=xn.mouseDownWindow.bind(t,e.element),document.addEventListener("mousedown",t.mouseDownEvent),t.mouseUpEvent=xn.mouseUpWindow.bind(t,e),document.addEventListener("mouseup",t.mouseUpEvent),t.keyDownEvent=xn.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)}}wn.EventListeners=xn,xn.KEY_DOWN_TIMEOUT=null;var Mn={};Object.defineProperty(Mn,"u",{value:!0}),Mn.PreResultUtils=void 0;Mn.PreResultUtils=class{static process(t,e,i,n,s){const o=null==n?void 0:n(e,i);return!!o&&(setTimeout((()=>{o.restart?t.resetRecording(s):o.stop&&t.stop()})),(o.stop||o.restart)&&o.removeNewText)}};var kn={},jn={};Object.defineProperty(jn,"u",{value:!0}),jn.AutoScroll=void 0;class Sn{static changeStateIfNeeded(t,e){e&&!t.isCursorAtEnd&&(t.endPadding="",t.scrollingSpan.innerHTML=" ")}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&&Sn.isElementOverflown(e)}}jn.AutoScroll=Sn;var An={};Object.defineProperty(An,"u",{value:!0}),An.Elements=void 0;An.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 Tn={};Object.defineProperty(Tn,"u",{value:!0}),Tn.Cursor=void 0;class On{static setOffsetForGeneric(t,e,i=0){let n=0;for(let s=0;s<t.childNodes.length;s+=1){const o=t.childNodes[s];if(o.childNodes.length>0){const t=On.setOffsetForGeneric(o,e,i);if(-1===t)return-1;i+=t}else if(null!==o.textContent){if(i+o.textContent.length>e){const n=document.createRange();n.setStart(o,e-i),n.collapse(!0);const s=window.getSelection();return null==s||s.removeAllRanges(),null==s||s.addRange(n),t.focus(),-1}i+=o.textContent.length,n+=o.textContent.length}}return n}static focusEndOfGeneric(t){const e=document.createRange();e.selectNodeContents(t),e.collapse(!1);const i=window.getSelection();i&&(i.removeAllRanges(),i.addRange(e))}static setOffsetForSafariGeneric(t,e){const i=window.getSelection();if(i){const n=On.getGenericElementCursorOffset(t,i,!0);console.log(n),setTimeout((()=>{}),100),On.setOffsetForGeneric(t,n+e)}}static setOffsetForPrimitive(t,e,i){i&&t.blur(),t.setSelectionRange(e,e),t.focus()}static getGenericElementCursorOffset(t,e,i){let n=0;if(e.rangeCount>0){const s=e.getRangeAt(0),o=s.cloneRange();o.selectNodeContents(t),i?o.setEnd(s.startContainer,s.startOffset):o.setEnd(s.endContainer,s.endOffset),n=o.toString().length}return n}}Tn.Cursor=On,Object.defineProperty(kn,"u",{value:!0}),kn.CommandUtils=void 0;const Cn=jn,Nn=An,In=gn,En=Tn,zn=pn;class Ln{static processCommand(t,e){return(!e||!e.caseSensitive)&&(t=t.toLowerCase()),!1===(null==e?void 0:e.substrings)?zn.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 n=t[i];return e[i]="string"==typeof n?Ln.processCommand(n,t.settings):n,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,n){Ln.toggleCommandModeOff(t),Nn.Elements.isPrimitiveElement(n)?(n.value=i,t.isTargetInShadow||En.Cursor.setOffsetForPrimitive(n,i.length,!0),In.Browser.IS_SAFARI()&&t.autoScroll&&Cn.AutoScroll.scrollSafariPrimitiveToEnd(n)):(n.textContent=i,t.isTargetInShadow||En.Cursor.focusEndOfGeneric(n),setTimeout((()=>Cn.AutoScroll.scrollGeneric(t,n)))),t.resetRecording(e)}static checkIfMatchesSubstring(t,e){return e.includes(t)}static checkIfMatchesWord(t,e,i){const n=t;for(let t=i.length-1;t>=0;t-=1){let e=t,s=n.length-1;for(;i[e]===n[s]&&s>=0;)e-=1,s-=1;if(s<0)return!0}return!1}static execCommand(t,e,i,n,s){var o,r,a;const c=t.commands;if(!c||!n||!i)return;const l=!0===(null===(o=c.settings)||void 0===o?void 0:o.caseSensitive)?e:e.toLowerCase(),u=zn.Text.breakupIntoWordsArr(l),h=!1===(null===(r=c.settings)||void 0===r?void 0:r.substrings)?Ln.checkIfMatchesWord:Ln.checkIfMatchesSubstring;if(c.commandMode&&h(c.commandMode,l,u))return t.setInterimColorToFinal(),setTimeout((()=>Ln.toggleCommandModeOn(t))),{doNotProcessTranscription:!1};if(!c.commandMode||t.isWaitingForCommand){if(c.stop&&h(c.stop,l,u))return Ln.toggleCommandModeOff(t),setTimeout((()=>t.stop())),{doNotProcessTranscription:!1};if(c.pause&&h(c.pause,l,u))return Ln.toggleCommandModeOff(t),t.setInterimColorToFinal(),setTimeout((()=>{var e;t.isPaused=!0,null===(e=t.onPauseTrigger)||void 0===e||e.call(t,!0)})),{doNotProcessTranscription:!1};if(c.resume&&h(c.resume,l,u))return t.isPaused=!1,null===(a=t.onPauseTrigger)||void 0===a||a.call(t,!1),Ln.toggleCommandModeOff(t),t.resetRecording(i),{doNotProcessTranscription:!0};if(c.reset&&h(c.reset,l,u))return void 0!==s&&Ln.setText(t,i,s,n),{doNotProcessTranscription:!0};if(c.removeAllText&&h(c.removeAllText,l,u))return Ln.setText(t,i,"",n),{doNotProcessTranscription:!0}}}}kn.CommandUtils=Ln;var Pn={};Object.defineProperty(Pn,"u",{value:!0}),Pn.Highlight=void 0;const _n=An,Dn=Tn;class Rn{static setStateForPrimitive(t,e){let i,n;null!==e.selectionStart&&(i=e.selectionStart),null!==e.selectionEnd&&(n=e.selectionEnd),t.isHighlighted=i!==n}static setStateForGeneric(t,e){const i=window.getSelection();if(null!=i&&i.focusNode){const n=Dn.Cursor.getGenericElementCursorOffset(e,i,!0),s=Dn.Cursor.getGenericElementCursorOffset(e,i,!1);t.isHighlighted=n!==s}}static setState(t,e){document.activeElement===e&&(_n.Elements.isPrimitiveElement(e)?Rn.setStateForPrimitive(t,e):Rn.setStateForGeneric(t,e))}static removeForGeneric(t,e){const i=window.getSelection();if(i){const n=Dn.Cursor.getGenericElementCursorOffset(e,i,!0);i.deleteFromDocument(),Dn.Cursor.setOffsetForGeneric(e,n),t.isHighlighted=!1}}static removeForPrimitive(t,e){const i=e.selectionStart,n=e.selectionEnd,s=e.value;if(i&&n){const o=s.substring(0,i)+s.substring(n);e.value=o,Dn.Cursor.setOffsetForPrimitive(e,i,t.autoScroll)}t.isHighlighted=!1}}Pn.Highlight=Rn;var Fn={};Object.defineProperty(Fn,"u",{value:!0}),Fn.Padding=void 0;const Bn=An,Jn=Tn,qn=pn;class Yn{static setStateForPrimitiveElement(t,e){if(document.activeElement===e&&null!==e.selectionStart){const i=e.selectionStart,n=e.value[i-1],s=null===e.selectionEnd?i:e.selectionEnd,o=e.value[s];return qn.Text.isCharDefined(n)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),qn.Text.isCharDefined(o)&&(t.endPadding=" ",t.numberOfSpacesAfterNewText=1),void(t.isCursorAtEnd=e.value.length===s)}const i=e.value[e.value.length-1];qn.Text.isCharDefined(i)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),t.isCursorAtEnd=!0}static setStateForGenericElement(t,e){var i,n,s;if(document.activeElement===e){const o=window.getSelection();if(null!=o&&o.focusNode){const r=Jn.Cursor.getGenericElementCursorOffset(e,o,!0),a=null===(i=e.textContent)||void 0===i?void 0:i[r-1],c=Jn.Cursor.getGenericElementCursorOffset(e,o,!1),l=null===(n=e.textContent)||void 0===n?void 0:n[c];return qn.Text.isCharDefined(a)&&(t.startPadding=" "),qn.Text.isCharDefined(l)&&(t.endPadding=" "),void(t.isCursorAtEnd=(null===(s=e.textContent)||void 0===s?void 0:s.length)===c)}}const o=e.innerText.charAt(e.innerText.length-1);qn.Text.isCharDefined(o)&&(t.startPadding=" "),t.isCursorAtEnd=!0}static setState(t,e){Bn.Elements.isPrimitiveElement(e)?Yn.setStateForPrimitiveElement(t,e):Yn.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)}}Fn.Padding=Yn,Object.defineProperty(yn,"u",{value:!0}),yn.Speech=void 0;const Un=wn,$n=Mn,Vn=kn,Zn=jn,Hn=Pn,Gn=An,Kn=Fn,Qn=gn,Wn=Tn,Xn=pn;yn.Speech=class{constructor(){this.finalTranscript="",this.interimSpan=Gn.Elements.createInterimSpan(),this.finalSpan=Gn.Elements.createGenericSpan(),this.scrollingSpan=Gn.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(Un.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,Gn.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=Vn.CommandUtils.process(this._options.commands))}prepare(t){Kn.Padding.setState(this,t),Hn.Highlight.setState(this,t),this.isTargetInShadow=Gn.Elements.isInsideShadowDOM(t),Gn.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 n;const s=Xn.Text.capitalize(e);if(this.finalTranscript===s&&""===t)return;$n.PreResultUtils.process(this,i,""===t,this._onPreResult,this._options)&&(t="",i="");const o=this.commands&&Vn.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===(n=this._onResult)||void 0===n||n.call(this,i,""===t),this.finalTranscript=s,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&&Hn.Highlight.removeForPrimitive(this,t),this.primitiveTextRecorded||Kn.Padding.adjustStateAfterRecodingPrimitiveElement(this,t),i&&Kn.Padding.adjustSateForNoTextPrimitiveElement(this);const n=this.startPadding+this.finalTranscript+e;if(t.value=n+this.endPadding,!this.isTargetInShadow){const e=n.length+this.numberOfSpacesAfterNewText;Wn.Cursor.setOffsetForPrimitive(t,e,this.autoScroll)}this.autoScroll&&Qn.Browser.IS_SAFARI()&&this.isCursorAtEnd&&Zn.AutoScroll.scrollSafariPrimitiveToEnd(t)}updateGenericElement(t,e,i){this.isHighlighted&&Hn.Highlight.removeForGeneric(this,t),this.spansPopulated||Gn.Elements.appendSpans(this,t);const n=(i?"":this.startPadding)+Xn.Text.lineBreak(this.finalTranscript);this.finalSpan.innerHTML=n;const s=Zn.AutoScroll.isRequired(this.autoScroll,t);Zn.AutoScroll.changeStateIfNeeded(this,s);const o=Xn.Text.lineBreak(e)+(i?"":this.endPadding);this.interimSpan.innerHTML=o,Qn.Browser.IS_SAFARI()&&this.insertInCursorLocation&&Wn.Cursor.setOffsetForSafariGeneric(t,n.length+o.length),s&&Zn.AutoScroll.scrollGeneric(this,t),i&&(this.scrollingSpan.innerHTML="")}finalise(t){this._genericElement&&(t?(this.finalSpan=Gn.Elements.createGenericSpan(),this.setInterimColorToFinal(),this.interimSpan=Gn.Elements.createInterimSpan(),this.scrollingSpan=Gn.Elements.createGenericSpan()):this._genericElement.textContent=this._genericElement.textContent,this.spansPopulated=!1),Un.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(un,"u",{value:!0}),un.WebSpeech=void 0;const ts=hn,es=gn,is=yn;class ns extends is.Speech{constructor(){super()}start(t){var e;void 0===this._extractText&&(this._extractText=es.Browser.IS_SAFARI()?ts.WebSpeechTranscript.extractSafari:ts.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!!ns.getAPI()||(this.error("Speech Recognition is unsupported"),!1)}instantiateService(t){var e,i;const n=ns.getAPI();this._service=new n,this._service.continuous=!0,this._service.interimResults=null===(e=null==t?void 0:t.displayInterimResults)||void 0===e||e,this._service.lang=(null===(i=null==t?void 0:t.language)||void 0===i?void 0:i.trim())||"en-US",this.setEvents()}setEvents(){this._service&&(this._service.onstart=()=>{this.setStateOnStart()},this._service.onerror=t=>{es.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:n}=this._extractText(t,this.finalTranscript,this._translations);this.updateElements(e,i,n)}})}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()}}un.WebSpeech=ns;var ss={};Object.defineProperty(ss,"u",{value:!0}),ss.GlobalState=void 0;class os{static doubleClickDetector(){return!!os.doubleClickPending||(os.doubleClickPending=!0,setTimeout((()=>{os.doubleClickPending=!1}),300),!1)}}ss.GlobalState=os,os.doubleClickPending=!1;var rs={},as={};Object.defineProperty(as,"u",{value:!0}),as.PreventConnectionStop=void 0;as.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 cs={},ls={};Object.defineProperty(ls,"u",{value:!0}),ls.README_URL=void 0,ls.README_URL="https://github.com/OvidijusParsiunas/speech-to-element",Object.defineProperty(cs,"u",{value:!0}),cs.AzureSpeechConfig=void 0;const us=ls;class hs{static validateOptions(t,e){return e?e.subscriptionKey||e.token||e.retrieveToken?!!e.region||(t(`Please define a 'region' property - more info: ${us.README_URL}`),!1):(t(`Please define a 'subscriptionKey', 'token' or 'retrieveToken' property - more info: ${us.README_URL}`),!1):(t(`Please provide subscription details - more info: ${us.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 hs.getNewSpeechConfig(t,e);return i&&hs.process(i,e),i}}cs.AzureSpeechConfig=hs;var ds={};Object.defineProperty(ds,"u",{value:!0}),ds.StopTimeout=void 0;class ps{static set(t){t.stopTimeout=setTimeout((()=>t.stop()),t.stopTimeoutMS)}static reset(t,e){t.stopTimeoutMS=e||ps.DEFAULT_MS,t.stopTimeout&&clearTimeout(t.stopTimeout),ps.set(t)}}ds.StopTimeout=ps,ps.DEFAULT_MS=2e4;var ms={};Object.defineProperty(ms,"u",{value:!0}),ms.AzureTranscript=void 0;const fs=dn;ms.AzureTranscript=class{static extract(t,e,i,n){return n&&(t=fs.Translate.translate(t,n)),i?{interimTranscript:"",finalTranscript:e+t,newText:t}:{interimTranscript:t,finalTranscript:e,newText:t}}},Object.defineProperty(rs,"u",{value:!0}),rs.Azure=void 0;const vs=as,gs=cs,bs=ds,ys=ms,ws=yn;class xs extends ws.Speech{constructor(){super(...arguments),this._newTextPadding=""}start(t,e){this._newTextPadding="",void 0===this.stopTimeout&&bs.StopTimeout.reset(this,null==t?void 0:t.stopAfterSilenceMs),this.prepareBeforeStart(t),this.startAsync(t),e||vs.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 xs.getAPI()?gs.AzureSpeechConfig.validateOptions(this.error.bind(this),t):(this.moduleNotFound(),!1)}async instantiateService(t){const e=xs.getAPI(),i=e.AudioConfig.fromDefaultMicrophoneInput(),n=await gs.AzureSpeechConfig.get(e.SpeechConfig,t);if(n){const s=new e.SpeechRecognizer(n,i);this.setEvents(s),this._service=s,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:n,newText:s}=ys.AzureTranscript.extract(this._newTextPadding+e.result.text,this.finalTranscript,!1,this._translations);bs.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(i,n,s)}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:n}=ys.AzureTranscript.extract(this._newTextPadding+i.text,this.finalTranscript,!0,this._translations);bs.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(t,e,n),""!==e&&(this._newTextPadding=" ")}}}onCanceled(t,e){e.reason===window.SpeechSDK.CancellationReason.Error&&this.error(e.errorDetails)}onSessionStarted(){vs.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()}}rs.Azure=xs,Object.defineProperty(ln,"u",{value:!0});const Ms=un,ks=kn,js=ss,Ss=rs;class As{static toggle(t,e){var i,n;const s=t.toLocaleLowerCase().trim();null!==(i=js.GlobalState.service)&&void 0!==i&&i.recognizing?this.stop():"webspeech"===s?As.startWebSpeech(e):"azure"===s?As.startAzure(e):(console.error("service not found - must be either 'webspeech' or 'azure'"),null===(n=null==e?void 0:e.onError)||void 0===n||n.call(e,"service not found - must be either 'webspeech' or 'azure'"))}static startWebSpeech(t){As.stop()||(js.GlobalState.service=new Ms.WebSpeech,js.GlobalState.service.start(t))}static isWebSpeechSupported(){return!!Ms.WebSpeech.getAPI()}static startAzure(t){var e;As.stop()||null!==(e=js.GlobalState.service)&&void 0!==e&&e.cannotBeStopped||(js.GlobalState.service=new Ss.Azure,js.GlobalState.service.start(t))}static stop(){var t;return!!js.GlobalState.doubleClickDetector()||(!(null===(t=js.GlobalState.service)||void 0===t)&&t.recognizing&&js.GlobalState.service.stop(),!1)}static endCommandMode(){js.GlobalState.service&&ks.CommandUtils.toggleCommandModeOff(js.GlobalState.service)}}var Ts=ln.default=As;class Os extends cn{constructor(t,e,i){var n;super("object"==typeof t.speechToText?null==(n=t.speechToText)?void 0:n.button:{});const{serviceName:s,processedConfig:o}=Os.processConfiguration(e,t.speechToText);if(this._addErrorMessage=i,"webspeech"!==s||Ts.isWebSpeechSupported()){const i=!t.textInput||!t.textInput.disabled;this.elementRef.onclick=this.buttonClick.bind(this,e,i,s,o)}else this.changeToUnsupported()}static processConfiguration(t,e){var i;const n="object"==typeof e?e:{},s="object"==typeof n.webSpeech?n.webSpeech:{},o=n.azure||{},r={displayInterimResults:n.displayInterimResults??void 0,textColor:n.textColor??void 0,translations:n.translations??void 0,commands:n.commands??void 0,...s,...o},a=null==(i=n.commands)?void 0:i.submit;return a&&(r.onPreResult=e=>e.toLowerCase().includes(a)?(setTimeout((()=>{var e;return null==(e=t.submit)?void 0:e.call(t)})),Ts.endCommandMode(),{restart:!0,removeNewText:!0}):null),{serviceName:Os.getServiceName(n),processedConfig:r}}static getServiceName(t){return t.webSpeech?"webspeech":t.azure?"azure":"webspeech"}buttonClick(t,e,i,n){t.removeTextIfPlaceholder(),Ts.toggle(i,{insertInCursorLocation:!1,element:e?t.inputElementRef:void 0,onError:this.onError.bind(this),onStart:this.changeToActive.bind(this),onStop:this.changeToDefault.bind(this),onCommandModeTrigger:this.onCommandModeTrigger.bind(this),...n})}onCommandModeTrigger(t){t?this.changeToCommandMode():this.changeToActive()}onError(){this._addErrorMessage("speechToText","speech input error")}}class Cs{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 Ns extends cn{constructor(t,e){var i,n;super(e.button),this._waitingForBrowserApproval=!1,this._audioType=t,this._extension=(null==(i=e.files)?void 0:i.format)||"mp3",this._maxDurationSeconds=null==(n=e.files)?void 0:n.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=Cs.getFileName(this._newFilePrefix||"audio",this._extension),n=new File([e],i,{type:e.type}),s=new FileReader;s.readAsDataURL(n),s.onload=t=>{this._audioType.completePlaceholderAttachment(n,t.target.result)}}}class Is{static setPropertyValueIfDoesNotExist(t,e,i){const n=e[0];1===e.length?t[n]??(t[n]=i):(t[n]??(t[n]={}),e.shift(),Is.setPropertyValueIfDoesNotExist(t[n],e,i))}static setPropertyValue(t,e,i){const n=e[0];1===e.length?t[n]=i:(t[n]??(t[n]={}),e.shift(),Is.setPropertyValue(t[n],e,i))}static getObjectValue(t,e){const i=t[e[0]];return void 0===i||1===e.length?i:Is.getObjectValue(i,e.slice(1))}static overwritePropertyObjectFromAnother(t,e,i){const n=Is.getObjectValue(e,i);if(n){const e={...n,...Is.getObjectValue(t,i)||{}};Is.setPropertyValue(t,i,e)}}}class Es{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]||{}));Is.overwritePropertyObjectFromAnother(i,t.submit,["container","default"]),Is.overwritePropertyObjectFromAnother(i,t.submit,["text","styles","default"]),Is.overwritePropertyObjectFromAnother(i,t.submit,["svg","styles","default"]),t[e]=i}static setUpDisabledButton(t){Is.setPropertyValueIfDoesNotExist(t,["submit","container","default","backgroundColor"],""),Is.setPropertyValueIfDoesNotExist(t,["disabled","container","default","backgroundColor"],"unset"),Is.setPropertyValueIfDoesNotExist(t.submit,["svg","styles","default","filter"],""),Is.setPropertyValueIfDoesNotExist(t.disabled,["svg","styles","default","filter"],"brightness(0) saturate(100%) invert(70%) sepia(0%) saturate(5564%) hue-rotate(207deg) brightness(100%) contrast(97%)"),Es.overwriteDefaultStyleWithSubmit(t,"disabled")}static process(t){const e=JSON.parse(JSON.stringify(t||{}));return Es.overwriteDefaultStyleWithSubmit(e,"loading"),Es.overwriteDefaultStyleWithSubmit(e,"stop"),null!=t&&t.alwaysEnabled||Es.setUpDisabledButton(e),e}}const zs=class t extends Yi{constructor(e,i,n,s,o){const r=Es.process(e.submitButtonStyles);super(t.createButtonContainerElement(),null==r?void 0:r.position,r),this._isSVGLoadingIconOverriden=!1,this.status={requestInProgress:!1,loadingActive:!1},this._messages=n,this._inputElementRef=i,this._fileAttachments=o,this._innerElements=this.createInnerElements(),this._abortStream=new AbortController,this._stopClicked={listener:()=>{}},this._serviceIO=s,this._alwaysEnabled=!(null==r||!r.alwaysEnabled),e.disableSubmitButton=this.disableSubmitButton.bind(this,s),this.attemptOverwriteLoadingStyle(e),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:n}=Ji.create(this.elementRef,["submit","loading","stop"],this._customStyles),s=e||t.createSubmitIconElement();return{submit:s,loading:i||t.createLoadingIconElement(),stop:n||t.createStopIconElement(),disabled:this.createDisabledIconElement(s)}}static createButtonContainerElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSubmitIconElement(){const t=le.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("dots-jumping"),t}static createStopIconElement(){const t=document.createElement("div");return t.id="stop-icon",t}createDisabledIconElement(t){return Ji.createCustomElement("disabled",this._customStyles)||t.cloneNode(!0)}attemptOverwriteLoadingStyle(t){var e,i,n,s,o,r,a,c,l;if(!(null!=(i=null==(e=this._customStyles)?void 0:e.submit)&&i.svg||null!=(o=null==(s=null==(n=this._customStyles)?void 0:n.loading)?void 0:s.svg)&&o.content||null!=(c=null==(a=null==(r=this._customStyles)?void 0:r.loading)?void 0:a.text)&&c.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==(l=t.shadowRoot)||l.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.deepChat;"object"==typeof e&&"number"==typeof e.simulation&&(this._serviceIO.streamHandlers.simulationInterim=e.simulation)}resetSubmit(t){this.status.requestInProgress=!1,this.status.loadingActive=!1,t()}submitFromInput(){var t;if(this._inputElementRef.classList.contains("text-input-placeholder"))this.submit(!1,"");else{const e=null==(t=this._inputElementRef.textContent)?void 0:t.trim();this.submit(!1,e)}}async submit(t,e){var i,n;let s,o;if(t||(await this._fileAttachments.completePlaceholders(),s=this._fileAttachments.getAllFileData(),o=null==s?void 0:s.map((t=>t.file))),!1===await(null==(i=this._validationHandler)?void 0:i.call(this,t)))return;this.changeToLoadingIcon(),await this.addNewMessages(e,s),this._messages.addLoadingMessage(),t||h.clear(this._inputElementRef);const r={text:""===e?void 0:e,files:o};await this._serviceIO.callAPI(r,this._messages),t||null==(n=this._fileAttachments)||n.removeAllFiles()}async addNewMessages(t,e){const i={};""!==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,!1)}stopStream(){var t;this._abortStream.abort(),null==(t=this._stopClicked)||t.listener()}changeToStopIcon(){this.elementRef.classList.remove(t.LOADING_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),Es.resetSubmit(this,this.status.loadingActive),this.elementRef.onclick=this.submitFromInput.bind(this))}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))}};zs.SUBMIT_CLASS="submit-button",zs.LOADING_CLASS="loading-button",zs.DISABLED_CLASS="disabled-button";let Ls=zs;class Ps extends sn{constructor(t,e,i,n){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:s,submitButton:o}=this.addButtonsAndTheirEvents(e);this._captureButton=s,this._submitButton=o,this._captureIcon=this._captureButton.children[0],this._refreshIcon=le.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==n?void 0:n.format)&&(this._format="image/jpeg"),null!=n&&n.dimensions&&(this._dimensions=n.dimensions),this._contentRef.appendChild(this._canvas),this.extensionCloseCallback=this.stop}addButtonsAndTheirEvents(t){const e=sn.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 n=sn.createSVGButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M4.89163 13.2687L9.16582 17.5427L18.7085 8" stroke="#000000" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>');return n.classList.add("modal-svg-submit-button"),this.addButtons(e,n),this.addButtonEvents(e,i,n,t),{captureButton:e,submitButton:n}}addButtonEvents(t,e,i,n){t.onclick=()=>{this.capture()},e.addEventListener("click",this.stop.bind(this)),i.onclick=()=>{const t=this.getFile();t&&en.addFilesToType([t],[n]),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)}),sn.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),n=new Blob([i],{type:this._format}),s="image/jpeg"===this._format?"jpeg":"png",o=Cs.getFileName(this._newFilePrefix||"photo",s);return new File([n],o,{type:n.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,n){const s=new Ps(t,e,i,n);return s.openCameraModal.bind(s,s)}}class _s extends Yi{constructor(t,e,i){var n;super(_s.createButtonElement(),null==(n=null==i?void 0:i.button)?void 0:n.position,(null==i?void 0:i.button)||{},"Photo");const s=this.createInnerElements(this._customStyles);i&&this.addClickEvent(t,e,i.modalContainerStyle,i.files),this.elementRef.classList.add("upload-file-button"),this.elementRef.appendChild(s.styles),this.reapplyStateStyle("styles")}createInnerElements(t){return{styles:this.createInnerElement(_s.createSVGIconElement(),"styles",t)}}createInnerElement(t,e,i){return Ji.createSpecificStateElement(this.elementRef,e,i)||t}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSVGIconElement(){const t=le.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,n){const s=Ps.createCameraModalFunc(t,e,i,n);this.elementRef.onclick=s}}class Ds{constructor(t,e,i,n){this.elementRef=Ds.createPanelElement(t.inputAreaStyle);const s=new h(t,i),o={},r=this.createFileUploadComponents(t,i,n,o);t.speechToText&&!o.microphone&&(o.microphone={button:new Os(t,s,e.addNewErrorMessage.bind(e))});const a=new Ls(t,s.inputElementRef,e,i,r);s.submit=a.submitFromInput.bind(a),an.attach(t,i,s,r,a),t.submitUserMessage=a.submit.bind(a,!0),o.submit={button:a},Ds.addElements(this.elementRef,s,o,n,r,t.dropupStyles)}static createPanelElement(t){const e=document.createElement("div");return e.id="input",Object.assign(e.style,t),e}createFileUploadComponents(t,e,i,n){var s,o,r,a;const c=new en(this.elementRef,t.attachmentContainerStyle,e.demo);if(Ds.createUploadButtons(t,e.fileTypes||{},c,i,n),null!=(s=e.camera)&&s.files){const s=(null==(o=n.images)?void 0:o.fileType)||c.addType(t,e.camera.files,"images");n.camera={button:new _s(i,s,e.camera)}}if(null!=(r=e.recordAudio)&&r.files){const i=(null==(a=n.audio)?void 0:a.fileType)||c.addType(t,e.recordAudio.files,"audio");n.microphone={button:new Ns(i,e.recordAudio)}}return rn.isEnabled(c,t.dragAndDrop)&&rn.create(i,c,t.dragAndDrop),c}static createUploadButtons(t,e,i,n,s){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:c,dropupText:l}=Gi[r],u=new on(n,e,a,o,c,l);s[r]={button:u,fileType:e}}}))}static addElements(t,e,i,n,s,o){bi.addElements(t,e.elementRef);const r=Fi.create(),a=Hi.addButtons(r,i,n,o);Ri.set(e.inputElementRef,r,s.elementRef,a),Fi.add(t,r)}}class Rs{static createElements(t,e,i){const n=document.createElement("div");n.id="chat-view";const s=new _i(t,e,i);e.websocket&&C.createConnection(e,s);const o=new Ds(t,s,e,n);return bi.addElements(n,s.elementRef,o.elementRef),n}static render(t,e,i,n){const s=Rs.createElements(t,i,n);e.replaceChildren(s)}}var Fs=Object.defineProperty,Bs=Object.getOwnPropertyDescriptor,Js=(t,e,i,n)=>{for(var s,o=n>1?void 0:n?Bs(e,i):e,r=t.length-1;r>=0;r--)(s=t[r])&&(o=(n?s(e,i,o):s(o))||o);return n&&o&&Fs(e,i,o),o};class qs extends ce{constructor(){super(),this.directConnection={openAI:{assistant:{assistant_id:"asst_Zwv7fGXUGVT8yGurausdsBnc",function_handler:t=>(console.log(t),t.map((t=>this.getCurrentWeather2(t.arguments))))},key:"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"}},this.mixedFiles=!0,this.getMessages=()=>[],this.submitUserMessage=()=>console.warn("submitUserMessage failed - please wait for chat view to render before calling this property."),this.focusInput=()=>d.focusFromParentElement(this._elementRef),this.refreshMessages=()=>{},this.clearMessages=()=>{},this.scrollToBottom=()=>{},this.disableSubmitButton=()=>{},this.onNewMessage=()=>{},this.onClearMessages=()=>{},this.onComponentRender=()=>{},this._hasBeenRendered=!1,this._auxiliaryStyleApplied=!1,pi.appendStyleSheetToHead(),this._elementRef=document.createElement("div"),this._elementRef.id="container",this.attachShadow({mode:"open"}).appendChild(this._elementRef),s.apply('#validate-property-key-view{height:100%;position:relative;display:flex;justify-content:center;align-items:center;padding:8px}#large-loading-ring{display:inline-block;width:50px;height:50px}#large-loading-ring:after{content:" ";display:block;width:38px;height:38px;margin:1px;border-radius:50%;border:5px solid #5fb2ff;border-color:#5fb2ff transparent #5fb2ff transparent;animation:large-loading-ring 1.4s linear infinite}@keyframes large-loading-ring{0%{transform:rotate(0)}to{transform:rotate(360deg)}}#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-ring{display:inline-block;width:16px;height:16px}#loading-ring: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-ring 1.2s linear infinite}@keyframes loading-ring{0%{transform:rotate(0)}to{transform:rotate(360deg)}}#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}.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}.html-message{max-width:unset}.error-message-text{margin:14px auto 10px;background-color:#f4c0c0;color:#474747;text-align:center;max-width:95%}.loading-message-text{width:1em;padding:.6em .75em .6em 1.3em}.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}.dots-jumping{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:dots-jumping 1.5s infinite linear;bottom:-.7em}@keyframes dots-jumping{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}}.dots-flashing{position:relative;width:.45em;height:.45em;border-radius:5px;background-color:var(--message-dots-color);color:var(--message-dots-color);animation:dots-flashing 1s infinite linear alternate;animation-delay:.5s}.dots-flashing:before,.dots-flashing:after{content:"";display:inline-block;position:absolute;top:0}.dots-flashing:before{left:-.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--message-dots-color);color:var(--message-dots-color);animation:dots-flashing 1s infinite alternate;animation-delay:0s}.dots-flashing:after{left:.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--message-dots-color);color:var(--message-dots-color);animation:dots-flashing 1s infinite alternate;animation-delay:1s}@keyframes dots-flashing{0%{background-color:var(--message-dots-color)}50%,to{background-color:var(--message-dots-color-fade)}}.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}.text-input-placeholder{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}:host{all:initial;display:table-cell}#container{height:inherit;width:inherit;overflow:hidden}\n',this.shadowRoot),setTimeout((()=>{this._hasBeenRendered||this.onRender()}),20)}getCurrentWeather(t){return(t=t.toLowerCase()).includes("tokyo")?JSON.stringify({location:t,temperature:"10",unit:"celsius"}):t.includes("san francisco")?JSON.stringify({location:t,temperature:"72",unit:"fahrenheit"}):JSON.stringify({location:t,temperature:"22",unit:"celsius"})}getCurrentWeather2(t){return console.log("location"),console.log(t),(t=t.toLowerCase()).includes("tokyo")?"Good":t.includes("san francisco")?"Mild":"Very Hot"}changeToChatView(){this._activeService&&(this._activeService.validateConfigKey=!1),this.onRender()}onRender(){this._activeService??(this._activeService=hi.create(this)),this._activeService&&(this.auxiliaryStyle&&!this._auxiliaryStyleApplied&&(s.apply(this.auxiliaryStyle,this.shadowRoot),this._auxiliaryStyleApplied=!0),s.applyDefaultStyleToComponent(this.style),N.checkForContainerStyles(this,this._elementRef),this._activeService.key&&this._activeService.validateConfigKey?e.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):this._activeService instanceof oe&&!this._activeService.key?this._activeService instanceof oe&&de.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):(this._childElement??(this._childElement=this.children[0]),Rs.render(this,this._elementRef,this._activeService,this._childElement)),this._hasBeenRendered=!0,vi.onRender(this))}}Js([fi("object")],qs.prototype,"directConnection",2),Js([fi("object")],qs.prototype,"request",2),Js([fi("object")],qs.prototype,"stream",2),Js([fi("object")],qs.prototype,"requestBodyLimits",2),Js([fi("function")],qs.prototype,"requestInterceptor",2),Js([fi("function")],qs.prototype,"responseInterceptor",2),Js([fi("function")],qs.prototype,"validateInput",2),Js([fi("object")],qs.prototype,"attachmentContainerStyle",2),Js([fi("object")],qs.prototype,"dropupStyles",2),Js([fi("object")],qs.prototype,"inputAreaStyle",2),Js([fi("object")],qs.prototype,"textInput",2),Js([fi("object")],qs.prototype,"submitButtonStyles",2),Js([fi("string")],qs.prototype,"auxiliaryStyle",2),Js([fi("array")],qs.prototype,"initialMessages",2),Js([fi("object")],qs.prototype,"introMessage",2),Js([fi("object")],qs.prototype,"avatars",2),Js([fi("object")],qs.prototype,"names",2),Js([fi("boolean")],qs.prototype,"displayLoadingBubble",2),Js([fi("object")],qs.prototype,"errorMessages",2),Js([fi("object")],qs.prototype,"messageStyles",2),Js([fi("object")],qs.prototype,"textToSpeech",2),Js([fi("object")],qs.prototype,"speechToText",2),Js([fi("object")],qs.prototype,"images",2),Js([fi("object")],qs.prototype,"gifs",2),Js([fi("object")],qs.prototype,"camera",2),Js([fi("object")],qs.prototype,"audio",2),Js([fi("object")],qs.prototype,"microphone",2),Js([fi("object")],qs.prototype,"mixedFiles",2),Js([fi("object")],qs.prototype,"dragAndDrop",2),Js([fi("object")],qs.prototype,"introPanelStyle",2),Js([fi("object")],qs.prototype,"htmlClassUtilities",2),Js([fi("function")],qs.prototype,"onNewMessage",2),Js([fi("function")],qs.prototype,"onClearMessages",2),Js([fi("function")],qs.prototype,"onComponentRender",2),Js([fi("object")],qs.prototype,"demo",2),Js([fi("object")],qs.prototype,"_insertKeyViewStyles",2),customElements.define("deep-chat",qs);export{qs 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="large-loading-ring"></div>'}static createElements(){const t=document.createElement("div");return t.id="validate-property-key-view",t}static render(i,n,s){const o=e.createElements(),r={onSuccess:n,onFail:t.render.bind(this,i,"Your 'key' has failed authentication"),onLoad:e.onLoad.bind(this,o)};s.key&&s.verifyKey(s.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 n=t.default||{},s=Object.assign(JSON.parse(JSON.stringify({...n,...e})),null==t?void 0:t.hover);return{default:n,hover:s,click:Object.assign(JSON.parse(JSON.stringify({...s,...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 n;const s=i;e.style[s]&&null!=(n=t.default)&&n[s]&&(t.default[i]=e.style[s])}))}static applyToStyleIfNotDefined(t,e){for(const i in e){const n=e[i];""===t[i]&&n&&(t[i]=n)}}}const n=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){i.applyToStyleIfNotDefined(e,t.DEFAULT_COMPONENT_STYLE)}};n.DEFAULT_COMPONENT_STYLE={height:"350px",width:"320px",border:"1px solid #cacaca",fontFamily:"'Inter', sans-serif, Avenir, Helvetica, Arial",fontSize:"0.9rem",backgroundColor:"white",position:"relative",overflow:"hidden"};let s=n;var o=(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))(o||{});let r=class{};r.IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),r.IS_CHROMIUM=window.chrome;const a=class t{static add(e,i,n){void 0!==i&&e.addEventListener("keydown",t.onKeyDown.bind(this,i)),e.oninput=t.onInput.bind(this,i,n)}static onKeyDown(e,i){const n=i.target.textContent;n&&n.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 n=i.target,s=n.textContent||"";void 0!==t&&s.length>t&&(n.textContent=s.substring(0,t),d.focusEndOfInput(n)),null==e||e()}};a.PERMITTED_KEYS=new Set([o.BACKSPACE,o.DELETE,o.ARROW_RIGHT,o.ARROW_LEFT,o.ARROW_DOWN,o.ARROW_UP,o.META,o.CONTROL,o.ENTER]);let c=a;class l{static sanitizePastedTextContent(t){var e,i;t.preventDefault();const n=null==(e=t.clipboardData)?void 0:e.getData("text/plain");null==(i=document.execCommand)||i.call(document,"insertHTML",!1,n)}}const u=class t{constructor(e,i){var n;const s=t.processConfig(i,e.textInput);this.elementRef=t.createContainerElement(null==(n=null==s?void 0:s.styles)?void 0:n.container),this.inputElementRef=this.createInputElement(s),this._config=s,this.elementRef.appendChild(this.inputElementRef),setTimeout((()=>{var t;c.add(this.inputElementRef,null==(t=e.textInput)?void 0:t.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 preventAutomaticScrollUpOnNewLine(t){let e;t.addEventListener("keydown",(()=>{e=window.scrollY})),t.addEventListener("input",(()=>{e!==window.scrollY&&window.scrollTo({top:e})}))}static clear(t){const e=window.scrollY;t.classList.contains("text-input-disabled")||(t.textContent=""),r.IS_CHROMIUM&&window.scrollTo({top:e})}createInputElement(e){var i,n,s;const o=document.createElement("div");return o.id=t.TEXT_INPUT_ID,o.classList.add("text-input-styling","text-input-placeholder"),o.innerText=(null==(i=null==e?void 0:e.placeholder)?void 0:i.text)||"Ask me anything!",r.IS_CHROMIUM&&t.preventAutomaticScrollUpOnNewLine(o),"boolean"==typeof(null==e?void 0:e.disabled)&&!0===e.disabled?(o.contentEditable="false",o.classList.add("text-input-disabled")):(o.contentEditable="true",this.addEventListeners(o,e)),Object.assign(o.style,null==(n=null==e?void 0:e.styles)?void 0:n.text),Object.assign(o.style,null==(s=null==e?void 0:e.placeholder)?void 0:s.style),o}removeTextIfPlaceholder(){var e,n,s,o;this.inputElementRef.classList.contains("text-input-placeholder")&&!this.inputElementRef.classList.contains("text-input-disabled")&&(null!=(e=this._config.placeholder)&&e.style&&(i.unsetStyle(this.inputElementRef,null==(n=this._config.placeholder)?void 0:n.style),Object.assign(this.inputElementRef.style,null==(o=null==(s=this._config)?void 0:s.styles)?void 0:o.text)),t.clear(this.inputElementRef),this.inputElementRef.classList.remove("text-input-placeholder"))}static toggleEditability(t,e){t.contentEditable=e?"true":"false"}addEventListeners(t,e){var i,n,s;t.onfocus=this.onFocus.bind(this,null==(i=null==e?void 0:e.styles)?void 0:i.focus),null!=(n=null==e?void 0:e.styles)&&n.focus&&(t.onblur=this.onBlur.bind(this,e.styles.focus,null==(s=null==e?void 0:e.styles)?void 0:s.container)),t.addEventListener("keydown",this.onKeydown.bind(this)),t.onpaste=l.sanitizePastedTextContent}onFocus(t){r.IS_SAFARI?setTimeout((()=>{this.removeTextIfPlaceholder()})):this.removeTextIfPlaceholder(),Object.assign(this.elementRef.style,t)}onBlur(t,e){i.unsetStyle(this.elementRef,t),e&&Object.assign(this.elementRef.style,e)}static createContainerElement(t){const e=document.createElement("div");return e.id="text-input-container",Object.assign(e.style,t),e}onKeydown(t){var e;t.key===o.ENTER&&!t.ctrlKey&&!t.shiftKey&&(t.preventDefault(),null==(e=this.submit)||e.call(this))}};u.TEXT_INPUT_ID="text-input";let h=u;class d{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(`#${h.TEXT_INPUT_ID}`);e&&d.focusEndOfInput(e)}}function p(t){return t.charAt(0).toUpperCase()+t.slice(1)}const m={INVALID_KEY:"Invalid API Key",CONNECTION_FAILED:"Failed to connect",INVALID_RESPONSE:function(t,e,i,n){const s=`\n${p(e)} message: ${JSON.stringify(t)} \n`,o=i?`${p(e)} message after interceptor: ${function(t){return t&&JSON.stringify(t)}(n)} \n`:"";return`${s+o}Make sure the ${e} message is using the Response format: https://deepchat.dev/docs/connect/#Response \n You can also augment it using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor`},INVALID_STREAM_RESPONSE:"Make sure the events are using the Response format: https://deepchat.dev/docs/connect/#Response \nYou can also augment them using the responseInterceptor property: https://deepchat.dev/docs/interceptors#responseInterceptor"},f=class t{static async tempRemoveContentHeader(e,i,n){if(null==e||!e.headers)throw new Error("Request settings have not been set up");const s=e.headers[t.CONTENT_TYPE];let o;delete e.headers[t.CONTENT_TYPE];try{o=await i(n)}catch(i){throw e.headers[t.CONTENT_TYPE]=s,i}return e.headers[t.CONTENT_TYPE]=s,o}static displayError(t,e,i="Service error, please try again."){if(console.error(e),"object"==typeof e)return 0===Object.keys(e).length?t.addNewErrorMessage("service",i):t.addNewErrorMessage("service",JSON.stringify(e));t.addNewErrorMessage("service",e)}static fetch(t,e,i,n){var s,o;const r={method:(null==(s=t.requestSettings)?void 0:s.method)||"POST",headers:e};return"GET"!==r.method&&(r.body=i?JSON.stringify(n):n),fetch((null==(o=t.requestSettings)?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 n=await(null==(i=t.requestInterceptor)?void 0:i.call(t,e))||e,s=n,o=n;return{body:s.body,headers:s.headers,error:o.error}}static validateResponseFormat(t){return t&&"object"==typeof t&&("string"==typeof t.error||"string"==typeof t.text||"string"==typeof t.html||"object"==typeof t.files)}};f.CONTENT_TYPE="Content-Type";let v=f;function g(t){let e,i,n,s=!1;return function(o){void 0===e?(e=o,i=0,n=-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;){s&&(10===e[i]&&(a=++i),s=!1);let o=-1;for(;i<r&&-1===o;++i)switch(e[i]){case 58:-1===n&&(n=i-a);break;case 13:s=!0;case 10:o=i}if(-1===o)break;t(e.subarray(a,o),n),a=i,n=-1}a===r?e=void 0:0!==a&&(e=e.subarray(a),i-=a)}}var b=globalThis&&globalThis.__rest||function(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i};const y="text/event-stream",w="last-event-id";function x(t,e){var{signal:i,headers:n,onopen:s,onmessage:o,onclose:r,onerror:a,openWhenHidden:c,fetch:l}=e,u=b(e,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise(((e,h)=>{const d=Object.assign({},n);let p;function m(){p.abort(),document.hidden||j()}d.accept||(d.accept=y),c||document.addEventListener("visibilitychange",m);let f=1e3,v=0;function b(){document.removeEventListener("visibilitychange",m),window.clearTimeout(v),p.abort()}null==i||i.addEventListener("abort",(()=>{b(),e()}));const x=l??window.fetch,k=s??M;async function j(){var i;p=new AbortController;try{const i=await x(t,Object.assign(Object.assign({},u),{headers:d,signal:p.signal}));await k(i),await async function(t,e){const i=t.getReader();let n;for(;!(n=await i.read()).done;)e(n.value)}(i.body,g(function(t,e,i){let n={data:"",event:"",id:"",retry:void 0};const s=new TextDecoder;return function(o,r){if(0===o.length)null==i||i(n),n={data:"",event:"",id:"",retry:void 0};else if(r>0){const i=s.decode(o.subarray(0,r)),a=r+(32===o[r+1]?2:1),c=s.decode(o.subarray(a));switch(i){case"data":n.data=n.data?n.data+"\n"+c:c;break;case"event":n.event=c;break;case"id":t(n.id=c);break;case"retry":const i=parseInt(c,10);isNaN(i)||e(n.retry=i)}}}}((t=>{t?d[w]=t:delete d[w]}),(t=>{f=t}),o))),null==r||r(),b(),e()}catch(t){if(!p.signal.aborted)try{const e=null!==(i=null==a?void 0:a(t))&&void 0!==i?i:f;window.clearTimeout(v),v=window.setTimeout(j,e)}catch(t){b(),h(t)}}}j()}))}function M(t){const e=t.headers.get("content-type");if(null==e||!e.startsWith(y))throw new Error(`Expected content-type to be ${y}, Actual: ${e}`)}const k=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,n){const s=t.getResponse(e);setTimeout((async()=>{const t=await(null==n?void 0:n(s))||s;t.error?e.addNewErrorMessage("service",t.error):e.addNewMessage(t,!0),i()}),400)}static requestStream(e,i){setTimeout((()=>{var n;const s=null==(n=t.getResponse(e))?void 0:n.text;S.simulate(e,i,s)}),400)}};k.URL="deep-chat-demo";let j=k;class S{static async request(t,e,i,n=!0){var s,o,r,a,c;const l={body:e,headers:null==(s=t.requestSettings)?void 0:s.headers},{body:u,headers:h,error:d}=await v.processRequestInterceptor(t.deepChat,l),{onOpen:p,onClose:f,abortStream:g}=t.streamHandlers;if(d)return S.onInterceptorError(i,d,f);if(null!=(o=t.requestSettings)&&o.handler)return A.stream(t,u,i);if((null==(r=t.requestSettings)?void 0:r.url)===j.URL)return j.requestStream(i,t.streamHandlers);let b=null;x((null==(a=t.requestSettings)?void 0:a.url)||t.url||"",{method:(null==(c=t.requestSettings)?void 0:c.method)||"POST",headers:h,body:n?JSON.stringify(u):u,openWhenHidden:!0,async onopen(t){if(t.ok)return b=i.addNewStreamedMessage(),p();throw await v.processResponseByType(t)},onmessage(e){var n;if(JSON.stringify(e.data)!==JSON.stringify("[DONE]")){const s=JSON.parse(e.data);null==(n=t.extractResultData)||n.call(t,s).then((t=>{void 0===(null==t?void 0:t.text)?console.error(`Response data: ${e.data} \n ${m.INVALID_STREAM_RESPONSE}`):b&&i.updateStreamedMessage(t.text,b)})).catch((t=>v.displayError(i,t)))}},onerror(t){throw f(),t},onclose(){i.finaliseStreamedMessage(),f()},signal:g.signal}).catch((e=>{var n;null==(n=t.extractResultData)||n.call(t,e).then((()=>{v.displayError(i,e)})).catch((t=>{v.displayError(i,t)}))}))}static onInterceptorError(t,e,i){t.addNewErrorMessage("service",e),null==i||i()}static simulate(t,e,i){const n=e,s=(null==i?void 0:i.split(" "))||[],o=t.addNewStreamedMessage();e.onOpen(),S.populateMessages(o,s,t,n)}static populateMessages(t,e,i,n,s=0){const o=e[s];if(o){i.updateStreamedMessage(`${o} `,t);const r=setTimeout((()=>{S.populateMessages(t,e,i,n,s+1)}),n.simulationInterim||70);n.abortStream.abort=()=>S.abort(r,i,n.onClose)}else i.finaliseStreamedMessage(),n.onClose()}static abort(t,e,i){clearTimeout(t),e.finaliseStreamedMessage(),i()}}class A{static async request(t,e,i){var n,s;let o=!0;const r=A.generateOptionalSignals();null==(s=(n=t.requestSettings).handler)||s.call(n,e,{...r,onResponse:async e=>{var n,s;if(!o)return;o=!1;const r=await(null==(s=(n=t.deepChat).responseInterceptor)?void 0:s.call(n,e))||e;v.validateResponseFormat(r)?"string"==typeof r.error?(console.error(r.error),i.addNewErrorMessage("service",r.error),t.completionsHandlers.onFinish()):t.deepChat.stream&&r.text?S.simulate(i,t.streamHandlers,r.text):(i.addNewMessage(r,!0),t.completionsHandlers.onFinish()):(console.error(m.INVALID_RESPONSE(e,"server",!!t.deepChat.responseInterceptor,r)),i.addNewErrorMessage("service","Error in server message"),t.completionsHandlers.onFinish())}})}static stream(t,e,i){var n,s;let o=!0,r=!1,a=null;t.streamHandlers.abortStream.abort=()=>{i.finaliseStreamedMessage(),t.streamHandlers.onClose(),o=!1};const c=A.generateOptionalSignals();null==(s=(n=t.requestSettings).handler)||s.call(n,e,{...c,onOpen:()=>{r||!o||(a=i.addNewStreamedMessage(),t.streamHandlers.onOpen(),r=!0)},onResponse:e=>{o&&(!e||"object"!=typeof e||"string"!=typeof e.error&&"string"!=typeof e.text?console.error(m.INVALID_RESPONSE(e,"server",!1)):e.error?(console.error(e.error),i.finaliseStreamedMessage(),t.streamHandlers.onClose(),i.addNewErrorMessage("service",e.error),o=!1):e.text&&a&&i.updateStreamedMessage(e.text,a))},onClose:()=>{o&&(i.finaliseStreamedMessage(),t.streamHandlers.onClose(),o=!1)},stopClicked:t.streamHandlers.stopClicked})}static websocket(t,e){var i,n;const s={isOpen:!1,newUserMessage:{listener:()=>{}}};t.websocket=s;const o=A.generateOptionalSignals();null==(n=(i=t.requestSettings).handler)||n.call(i,void 0,{...o,onOpen:()=>{e.removeError(),s.isOpen=!0},onResponse:async i=>{var n,o;if(!s.isOpen)return;const r=await(null==(o=(n=t.deepChat).responseInterceptor)?void 0:o.call(n,i))||i;v.validateResponseFormat(r)?"string"==typeof r.error?(console.error(r.error),e.isLastMessageError()||e.addNewErrorMessage("service",r.error)):t.deepChat.stream?S.simulate(e,t.streamHandlers,r.text):e.addNewMessage(r,!0):(console.error(m.INVALID_RESPONSE(i,"server",!!t.deepChat.responseInterceptor,r)),e.addNewErrorMessage("service","Error in server message"))},onClose:()=>{s.isOpen=!1},newUserMessage:s.newUserMessage})}static generateOptionalSignals(){return{onClose:()=>{},onOpen:()=>{},stopClicked:{listener:()=>{}},newUserMessage:{listener:()=>{}}}}}class T{static async request(t,e,i,n=!0){var s,o,r;const a={body:e,headers:null==(s=t.requestSettings)?void 0:s.headers},{body:c,headers:l,error:u}=await v.processRequestInterceptor(t.deepChat,a),{onFinish:h}=t.completionsHandlers;if(u)return T.onInterceptorError(i,u,h);if(null!=(o=t.requestSettings)&&o.handler)return A.request(t,c,i);if((null==(r=t.requestSettings)?void 0:r.url)===j.URL)return j.request(i,h,t.deepChat.responseInterceptor);let d=!0;const p=v.fetch.bind(this,t,l,n);p(c).then((t=>(d=!!t.ok,t))).then((t=>v.processResponseByType(t))).then((async e=>{var n,s;if(!t.extractResultData)return;const o=await(null==(s=(n=t.deepChat).responseInterceptor)?void 0:s.call(n,e))||e,r=await t.extractResultData(o,p,c);if(!d)throw e;if(!r||"object"!=typeof r)throw Error(m.INVALID_RESPONSE(e,"response",!!t.deepChat.responseInterceptor,o));r.makingAnotherRequest||(t.deepChat.stream&&r.text?S.simulate(i,t.streamHandlers,r.text):(i.addNewMessage(r,!0),h()))})).catch((t=>{v.displayError(i,t),h()}))}static executePollRequest(t,e,i,n){console.log("polling");const{onFinish:s}=t.completionsHandlers;fetch(e,i).then((t=>t.json())).then((async o=>{var r,a;if(!t.extractPollResultData)return;const c=await t.extractPollResultData(await(null==(a=(r=t.deepChat).responseInterceptor)?void 0:a.call(r,o))||o);c.timeoutMS?setTimeout((()=>{T.executePollRequest(t,e,i,n)}),c.timeoutMS):(console.log("finished polling"),n.addNewMessage(c,!0),s())})).catch((t=>{v.displayError(n,t),s()}))}static async poll(t,e,i,n=!0){var s,o,r;const a={body:e,headers:null==(s=t.requestSettings)?void 0:s.headers},{body:c,headers:l,error:u}=await v.processRequestInterceptor(t.deepChat,a);if(u)return T.onInterceptorError(i,u);const h=(null==(o=t.requestSettings)?void 0:o.url)||t.url||"",d={method:(null==(r=t.requestSettings)?void 0:r.method)||"POST",body:n?JSON.stringify(c):c,headers:l};T.executePollRequest(t,h,d,i)}static onInterceptorError(t,e,i){t.addNewErrorMessage("service",e),null==i||i()}static verifyKey(t,e,i,n,s,o,r,a,c){if(""===t)return o(m.INVALID_KEY);r(),fetch(e,{method:n,headers:i,body:c||null}).then((t=>v.processResponseByType(t))).then((e=>{a(e,t,s,o)})).catch((t=>{o(m.CONNECTION_FAILED),console.error(t)}))}}class O{static getCharacterLimitMessages(t,e){var i;let n=0,s=t.length-1;for(;s>=0;s-=1){const o=null==(i=t[s])?void 0:i.text;if(void 0!==o&&(n+=o.length,n>e)){t[s].text=o.substring(0,o.length-(n-e));break}}return t.slice(Math.max(s,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=O.getMaxMessages(t,e)):t=[t[t.length-1]],t=JSON.parse(JSON.stringify(t)),void 0===i?t:O.getCharacterLimitMessages(t,i)}}class C{static setup(t){t.requestSettings.url!==j.URL&&(t.permittedErrorPrefixes=["Connection error","Error in server message"],t.websocket="pending")}static createConnection(t,e){if(!document.body.contains(t.deepChat))return;const i=t.requestSettings.websocket;if(i){if(t.requestSettings.handler)return A.websocket(t,e);try{const n="boolean"!=typeof i?i:void 0,s=new WebSocket(t.requestSettings.url||"",n);t.websocket=s,t.websocket.onopen=()=>{var i,n;e.removeError(),t.websocket&&"object"==typeof t.websocket&&C.assignListeners(t,s,e),null==(n=(i=t.deepChat)._validationHandler)||n.call(i)},t.websocket.onerror=i=>{console.error(i),C.retryConnection(t,e)}}catch(i){console.error(i),C.retryConnection(t,e)}}}static retryConnection(t,e){var i,n;null==(n=(i=t.deepChat)._validationHandler)||n.call(i),document.body.contains(t.deepChat)&&(t.websocket="pending",e.isLastMessageError()||e.addNewErrorMessage("service","Connection error"),setTimeout((()=>{C.createConnection(t,e)}),5e3))}static assignListeners(t,e,i){e.onmessage=async e=>{var n,s;if(t.extractResultData)try{const o=JSON.parse(e.data),r=await(null==(s=(n=t.deepChat).responseInterceptor)?void 0:s.call(n,o))||o,a=await t.extractResultData(r);if(!a||"object"!=typeof a)throw Error(m.INVALID_RESPONSE(o,"server",!!t.deepChat.responseInterceptor,r));t.deepChat.stream&&a.text?S.simulate(i,t.streamHandlers,a.text):i.addNewMessage(a,!0)}catch(t){v.displayError(i,t,"Error in server message")}},e.onclose=()=>{console.error("Connection closed"),i.isLastMessageError()||i.addNewErrorMessage("service","Connection error"),C.createConnection(t,i)}}static async sendWebsocket(t,e,i,n=!0){var s,o;const r=t.websocket;if(!r||"pending"===r)return;const a={body:e,headers:null==(s=t.requestSettings)?void 0:s.headers},{body:c,error:l}=await v.processRequestInterceptor(t.deepChat,a);if(l)return i.addNewErrorMessage("service",l);if(!C.isWebSocket(r))return r.newUserMessage.listener(c);const u=n?JSON.stringify(c):c;if((null==(o=t.requestSettings)?void 0:o.url)===j.URL)return j.request(i,t.completionsHandlers.onFinish,t.deepChat.responseInterceptor);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(u))}static canSendMessage(t){return!t||"pending"!==t&&(C.isWebSocket(t)?void 0!==t.readyState&&t.readyState===t.OPEN:t.isOpen)}static isWebSocket(t){return void 0!==t.send}}class N{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 processInitialMessageFile(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}}var I;function E(t){return(I=I||document.createElement("textarea")).innerHTML="&"+t+";",I.value}var z=Object.prototype.hasOwnProperty;function L(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 P=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;function D(t){return t.indexOf("\\")<0?t:t.replace(P,"$1")}function _(t){return!(t>=55296&&t<=57343||t>=64976&&t<=65007||65535==(65535&t)||65534==(65535&t)||t>=0&&t<=8||11===t||t>=14&&t<=31||t>=127&&t<=159||t>1114111)}function R(t){if(t>65535){var e=55296+((t-=65536)>>10),i=56320+(1023&t);return String.fromCharCode(e,i)}return String.fromCharCode(t)}var F=/&([a-z#][a-z0-9]{1,31});/gi,B=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;function J(t,e){var i=0,n=E(e);return e!==n?n:35===e.charCodeAt(0)&&B.test(e)&&_(i="x"===e[1].toLowerCase()?parseInt(e.slice(2),16):parseInt(e.slice(1),10))?R(i):t}function q(t){return t.indexOf("&")<0?t:t.replace(F,J)}var Y=/[&<>"]/,$=/[&<>"]/g,U={"&":"&","<":"<",">":">",'"':"""};function V(t){return U[t]}function Z(t){return Y.test(t)?t.replace($,V):t}var H={};function G(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?G(t,e+2):e}H.blockquote_open=function(){return"<blockquote>\n"},H.blockquote_close=function(t,e){return"</blockquote>"+K(t,e)},H.code=function(t,e){return t[e].block?"<pre><code>"+Z(t[e].content)+"</code></pre>"+K(t,e):"<code>"+Z(t[e].content)+"</code>"},H.fence=function(t,e,i,n,s){var o,r,a=t[e],c="",l=i.langPrefix;if(a.params){if(r=(o=a.params.split(/\s+/g)).join(" "),function(t,e){return!!t&&z.call(t,e)}(s.rules.fence_custom,o[0]))return s.rules.fence_custom[o[0]](t,e,i,n,s);c=' class="'+l+Z(q(D(r)))+'"'}return"<pre><code"+c+">"+(i.highlight&&i.highlight.apply(i.highlight,[a.content].concat(o))||Z(a.content))+"</code></pre>"+K(t,e)},H.fence_custom={},H.heading_open=function(t,e){return"<h"+t[e].hLevel+">"},H.heading_close=function(t,e){return"</h"+t[e].hLevel+">\n"},H.hr=function(t,e,i){return(i.xhtmlOut?"<hr />":"<hr>")+K(t,e)},H.bullet_list_open=function(){return"<ul>\n"},H.bullet_list_close=function(t,e){return"</ul>"+K(t,e)},H.list_item_open=function(){return"<li>"},H.list_item_close=function(){return"</li>\n"},H.ordered_list_open=function(t,e){var i=t[e];return"<ol"+(i.order>1?' start="'+i.order+'"':"")+">\n"},H.ordered_list_close=function(t,e){return"</ol>"+K(t,e)},H.paragraph_open=function(t,e){return t[e].tight?"":"<p>"},H.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?K(t,e):"")},H.link_open=function(t,e,i){var n=t[e].title?' title="'+Z(q(t[e].title))+'"':"",s=i.linkTarget?' target="'+i.linkTarget+'"':"";return'<a href="'+Z(t[e].href)+'"'+n+s+">"},H.link_close=function(){return"</a>"},H.image=function(t,e,i){var n=' src="'+Z(t[e].src)+'"',s=t[e].title?' title="'+Z(q(t[e].title))+'"':"";return"<img"+n+(' alt="'+(t[e].alt?Z(q(D(t[e].alt))):"")+'"')+s+(i.xhtmlOut?" /":"")+">"},H.table_open=function(){return"<table>\n"},H.table_close=function(){return"</table>\n"},H.thead_open=function(){return"<thead>\n"},H.thead_close=function(){return"</thead>\n"},H.tbody_open=function(){return"<tbody>\n"},H.tbody_close=function(){return"</tbody>\n"},H.tr_open=function(){return"<tr>"},H.tr_close=function(){return"</tr>\n"},H.th_open=function(t,e){var i=t[e];return"<th"+(i.align?' style="text-align:'+i.align+'"':"")+">"},H.th_close=function(){return"</th>"},H.td_open=function(t,e){var i=t[e];return"<td"+(i.align?' style="text-align:'+i.align+'"':"")+">"},H.td_close=function(){return"</td>"},H.strong_open=function(){return"<strong>"},H.strong_close=function(){return"</strong>"},H.em_open=function(){return"<em>"},H.em_close=function(){return"</em>"},H.del_open=function(){return"<del>"},H.del_close=function(){return"</del>"},H.ins_open=function(){return"<ins>"},H.ins_close=function(){return"</ins>"},H.mark_open=function(){return"<mark>"},H.mark_close=function(){return"</mark>"},H.sub=function(t,e){return"<sub>"+Z(t[e].content)+"</sub>"},H.sup=function(t,e){return"<sup>"+Z(t[e].content)+"</sup>"},H.hardbreak=function(t,e,i){return i.xhtmlOut?"<br />\n":"<br>\n"},H.softbreak=function(t,e,i){return i.breaks?i.xhtmlOut?"<br />\n":"<br>\n":"\n"},H.text=function(t,e){return Z(t[e].content)},H.htmlblock=function(t,e){return t[e].content},H.htmltag=function(t,e){return t[e].content},H.abbr_open=function(t,e){return'<abbr title="'+Z(q(t[e].title))+'">'},H.abbr_close=function(){return"</abbr>"},H.footnote_ref=function(t,e){var i=Number(t[e].id+1).toString(),n="fnref"+i;return t[e].subId>0&&(n+=":"+t[e].subId),'<sup class="footnote-ref"><a href="#fn'+i+'" id="'+n+'">['+i+"]</a></sup>"},H.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'},H.footnote_block_close=function(){return"</ol>\n</section>\n"},H.footnote_open=function(t,e){return'<li id="fn'+Number(t[e].id+1).toString()+'" class="footnote-item">'},H.footnote_close=function(){return"</li>\n"},H.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>'},H.dl_open=function(){return"<dl>\n"},H.dt_open=function(){return"<dt>"},H.dd_open=function(){return"<dd>"},H.dl_close=function(){return"</dl>\n"},H.dt_close=function(){return"</dt>\n"},H.dd_close=function(){return"</dd>\n"};var K=H.getBreak=function(t,e){return(e=G(t,e))<t.length&&"list_item_close"===t[e].type?"":"\n"};function Q(){this.rules=L({},H),this.getBreak=H.getBreak}function W(){this.t=[],this.i=null}function X(t,e,i,n,s){this.src=t,this.env=n,this.options=i,this.parser=e,this.tokens=s,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 tt(t,e){var i,n,s,o=-1,r=t.posMax,a=t.pos,c=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===(s=t.src.charCodeAt(t.pos)))i++;else if(93===s&&0===--i){n=!0;break}t.parser.skipToken(t)}return n?(o=t.pos,t.labelUnmatchedScopes=0):t.labelUnmatchedScopes=i-1,t.pos=a,t.isInLabel=c,o}function et(t,e,i,n){var s,o,r,a,c,l;if(42!==t.charCodeAt(0)||91!==t.charCodeAt(1)||-1===t.indexOf("]:")||((o=tt(s=new X(t,e,i,n,[]),1))<0||58!==t.charCodeAt(o+1)))return-1;for(a=s.posMax,r=o+2;r<a&&10!==s.src.charCodeAt(r);r++);return c=t.slice(2,o),0===(l=t.slice(o+2,r).trim()).length?-1:(n.abbreviations||(n.abbreviations={}),typeof n.abbreviations[":"+c]>"u"&&(n.abbreviations[":"+c]=l),r)}function it(t){var e=q(t);try{e=decodeURI(e)}catch{}return encodeURI(e)}function nt(t,e){var i,n,s,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 s=it(D(t.src.slice(o+1,e))),!!t.parser.validateLink(s)&&(t.pos=e+1,t.linkContent=s,!0);92===i&&e+1<r?e+=2:e++}return!1}for(n=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&&++n>1||41===i&&--n<0)break;e++}return!(o===e||(s=D(t.src.slice(o,e)),!t.parser.validateLink(s)))&&(t.linkContent=s,t.pos=e,!0)}function st(t,e){var i,n=e,s=t.posMax,o=t.src.charCodeAt(e);if(34!==o&&39!==o&&40!==o)return!1;for(e++,40===o&&(o=41);e<s;){if((i=t.src.charCodeAt(e))===o)return t.pos=e+1,t.linkContent=D(t.src.slice(n+1,e)),!0;92===i&&e+1<s?e+=2:e++}return!1}function ot(t){return t.trim().replace(/\s+/g," ").toUpperCase()}function rt(t,e,i,n){var s,o,r,a,c,l,u,h,d;if(91!==t.charCodeAt(0)||-1===t.indexOf("]:")||((o=tt(s=new X(t,e,i,n,[]),0))<0||58!==t.charCodeAt(o+1)))return-1;for(a=s.posMax,r=o+2;r<a&&(32===(c=s.src.charCodeAt(r))||10===c);r++);if(!nt(s,r))return-1;for(u=s.linkContent,l=r=s.pos,r+=1;r<a&&(32===(c=s.src.charCodeAt(r))||10===c);r++);for(r<a&&l!==r&&st(s,r)?(h=s.linkContent,r=s.pos):(h="",r=l);r<a&&32===s.src.charCodeAt(r);)r++;return r<a&&10!==s.src.charCodeAt(r)?-1:(d=ot(t.slice(1,o)),typeof n.references[d]>"u"&&(n.references[d]={title:h,href:u}),r)}Q.prototype.renderInline=function(t,e,i){for(var n=this.rules,s=t.length,o=0,r="";s--;)r+=n[t[o].type](t,o++,e,i,this);return r},Q.prototype.render=function(t,e,i){for(var n=this.rules,s=t.length,o=-1,r="";++o<s;)"inline"===t[o].type?r+=this.renderInline(t[o].children,e,i):r+=n[t[o].type](t,o,e,i,this);return r},W.prototype.o=function(t){for(var e=this.t.length,i=-1;e--;)if(this.t[++i].name===t)return i;return-1},W.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))}))}))},W.prototype.at=function(t,e,i){var n=this.o(t),s=i||{};if(-1===n)throw new Error("Parser rule not found: "+t);this.t[n].fn=e,this.t[n].alt=s.alt||[],this.i=null},W.prototype.before=function(t,e,i,n){var s=this.o(t),o=n||{};if(-1===s)throw new Error("Parser rule not found: "+t);this.t.splice(s,0,{name:e,enabled:!0,fn:i,alt:o.alt||[]}),this.i=null},W.prototype.after=function(t,e,i,n){var s=this.o(t),o=n||{};if(-1===s)throw new Error("Parser rule not found: "+t);this.t.splice(s+1,0,{name:e,enabled:!0,fn:i,alt:o.alt||[]}),this.i=null},W.prototype.push=function(t,e,i){var n=i||{};this.t.push({name:t,enabled:!0,fn:e,alt:n.alt||[]}),this.i=null},W.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},W.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},W.prototype.getRules=function(t){return null===this.i&&this.l(),this.i[t]||[]},X.prototype.pushPending=function(){this.tokens.push({type:"text",content:this.pending,level:this.pendingLevel}),this.pending=""},X.prototype.push=function(t){this.pending&&this.pushPending(),this.tokens.push(t),this.pendingLevel=this.level},X.prototype.cacheSet=function(t,e){for(var i=this.cache.length;i<=t;i++)this.cache.push(0);this.cache[t]=e},X.prototype.cacheGet=function(t){return t<this.cache.length?this.cache[t]:0};var at=" \n()[]'\".,!?-";function ct(t){return t.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1")}var lt=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,ut=/\((c|tm|r|p)\)/gi,ht={c:"©",r:"®",p:"§",tm:"™"};function dt(t){return t.indexOf("(")<0?t:t.replace(ut,(function(t,e){return ht[e.toLowerCase()]}))}var pt=/['"]/,mt=/['"]/g,ft=/[-\s()\[\]]/;function vt(t,e){return!(e<0||e>=t.length)&&!ft.test(t[e])}function gt(t,e,i){return t.substr(0,e)+i+t.substr(e+1)}var bt=[["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,n,s,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(n=o[e].content;n.length&&!((s=et(n,t.inline,t.options,t.env))<0);)n=n.slice(s).trim();o[e].content=n,n.length||(o[e-1].tight=!0,o[e+1].tight=!0)}}],["references",function(t){var e,i,n,s,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(n=o[e].content;n.length&&!((s=rt(n,t.inline,t.options,t.env))<0);)n=n.slice(s).trim();o[e].content=n,n.length||(o[e-1].tight=!0,o[e+1].tight=!0)}}],["inline",function(t){var e,i,n,s=t.tokens;for(i=0,n=s.length;i<n;i++)"inline"===(e=s[i]).type&&t.inline.parse(e.content,t.options,t.env,e.children)}],["footnote_tail",function(t){var e,i,n,s,o,r,a,c,l,u=0,h=!1,d={};if(t.env.footnotes&&(t.tokens=t.tokens.filter((function(t){return"footnote_reference_open"===t.type?(h=!0,c=[],l=t.label,!1):"footnote_reference_close"===t.type?(h=!1,d[":"+l]=c,!1):(h&&c.push(t),!h)})),t.env.footnotes.list)){for(r=t.env.footnotes.list,t.tokens.push({type:"footnote_block_open",level:u++}),e=0,i=r.length;e<i;e++){for(t.tokens.push({type:"footnote_open",id:e,level:u++}),r[e].tokens?((a=[]).push({type:"paragraph_open",tight:!1,level:u++}),a.push({type:"inline",content:"",level:u,children:r[e].tokens}),a.push({type:"paragraph_close",tight:!1,level:--u})):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,s=r[e].count>0?r[e].count:1,n=0;n<s;n++)t.tokens.push({type:"footnote_anchor",id:e,subId:n,level:u});o&&t.tokens.push(o),t.tokens.push({type:"footnote_close",level:--u})}t.tokens.push({type:"footnote_block_close",level:--u})}}],["abbr2",function(t){var e,i,n,s,o,r,a,c,l,u,h,d,p=t.tokens;if(t.env.abbreviations)for(t.env.abbrRegExp||(d="(^|["+at.split("").map(ct).join("")+"])("+Object.keys(t.env.abbreviations).map((function(t){return t.substr(1)})).sort((function(t,e){return e.length-t.length})).map(ct).join("|")+")($|["+at.split("").map(ct).join("")+"])",t.env.abbrRegExp=new RegExp(d,"g")),u=t.env.abbrRegExp,i=0,n=p.length;i<n;i++)if("inline"===p[i].type)for(e=(s=p[i].children).length-1;e>=0;e--)if("text"===(o=s[e]).type){for(c=0,r=o.content,u.lastIndex=0,l=o.level,a=[];h=u.exec(r);)u.lastIndex>c&&a.push({type:"text",content:r.slice(c,h.index+h[1].length),level:l}),a.push({type:"abbr_open",title:t.env.abbreviations[":"+h[2]],level:l++}),a.push({type:"text",content:h[2],level:l}),a.push({type:"abbr_close",level:--l}),c=u.lastIndex-h[3].length;a.length&&(c<r.length&&a.push({type:"text",content:r.slice(c),level:l}),p[i].children=s=[].concat(s.slice(0,e),a,s.slice(e+1)))}}],["replacements",function(t){var e,i,n,s,o;if(t.options.typographer)for(o=t.tokens.length-1;o>=0;o--)if("inline"===t.tokens[o].type)for(e=(s=t.tokens[o].children).length-1;e>=0;e--)"text"===(i=s[e]).type&&(n=dt(n=i.content),lt.test(n)&&(n=n.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=n)}],["smartquotes",function(t){var e,i,n,s,o,r,a,c,l,u,h,d,p,m,f,v,g;if(t.options.typographer)for(g=[],f=t.tokens.length-1;f>=0;f--)if("inline"===t.tokens[f].type)for(v=t.tokens[f].children,g.length=0,e=0;e<v.length;e++)if("text"===(i=v[e]).type&&!pt.test(i.text)){for(a=v[e].level,p=g.length-1;p>=0&&!(g[p].level<=a);p--);g.length=p+1,o=0,r=(n=i.content).length;t:for(;o<r&&(mt.lastIndex=o,s=mt.exec(n),s);)if(c=!vt(n,s.index-1),o=s.index+1,m="'"===s[0],(l=!vt(n,o))||c){if(h=!l,d=!c)for(p=g.length-1;p>=0&&(u=g[p],!(g[p].level<a));p--)if(u.single===m&&g[p].level===a){u=g[p],m?(v[u.token].content=gt(v[u.token].content,u.pos,t.options.quotes[2]),i.content=gt(i.content,s.index,t.options.quotes[3])):(v[u.token].content=gt(v[u.token].content,u.pos,t.options.quotes[0]),i.content=gt(i.content,s.index,t.options.quotes[1])),g.length=p;continue t}h?g.push({token:e,pos:s.index,single:m,level:a}):d&&m&&(i.content=gt(i.content,s.index,"’"))}else m&&(i.content=gt(i.content,s.index,"’"))}}]];function yt(){this.options={},this.ruler=new W;for(var t=0;t<bt.length;t++)this.ruler.push(bt[t][0],bt[t][1])}function wt(t,e,i,n,s){var o,r,a,c,l,u,h;for(this.src=t,this.parser=e,this.options=i,this.env=n,this.tokens=s,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="",u=0,h=!1,a=c=u=0,l=(r=this.src).length;c<l;c++){if(o=r.charCodeAt(c),!h){if(32===o){u++;continue}h=!0}(10===o||c===l-1)&&(10!==o&&c++,this.bMarks.push(a),this.eMarks.push(c),this.tShift.push(u),h=!1,u=0,a=c+1)}this.bMarks.push(r.length),this.eMarks.push(r.length),this.tShift.push(0),this.lineMax=this.bMarks.length-1}function xt(t,e){var i,n,s;return(n=t.bMarks[e]+t.tShift[e])>=(s=t.eMarks[e])||42!==(i=t.src.charCodeAt(n++))&&45!==i&&43!==i||n<s&&32!==t.src.charCodeAt(n)?-1:n}function Mt(t,e){var i,n=t.bMarks[e]+t.tShift[e],s=t.eMarks[e];if(n+1>=s||((i=t.src.charCodeAt(n++))<48||i>57))return-1;for(;;){if(n>=s)return-1;if(!((i=t.src.charCodeAt(n++))>=48&&i<=57)){if(41===i||46===i)break;return-1}}return n<s&&32!==t.src.charCodeAt(n)?-1:n}yt.prototype.process=function(t){var e,i,n;for(e=0,i=(n=this.ruler.getRules("")).length;e<i;e++)n[e](t)},wt.prototype.isEmpty=function(t){return this.bMarks[t]+this.tShift[t]>=this.eMarks[t]},wt.prototype.skipEmptyLines=function(t){for(var e=this.lineMax;t<e&&!(this.bMarks[t]+this.tShift[t]<this.eMarks[t]);t++);return t},wt.prototype.skipSpaces=function(t){for(var e=this.src.length;t<e&&32===this.src.charCodeAt(t);t++);return t},wt.prototype.skipChars=function(t,e){for(var i=this.src.length;t<i&&this.src.charCodeAt(t)===e;t++);return t},wt.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},wt.prototype.getLines=function(t,e,i,n){var s,o,r,a,c,l=t;if(t>=e)return"";if(l+1===e)return o=this.bMarks[l]+Math.min(this.tShift[l],i),r=n?this.eMarks[l]+1:this.eMarks[l],this.src.slice(o,r);for(a=new Array(e-t),s=0;l<e;l++,s++)(c=this.tShift[l])>i&&(c=i),c<0&&(c=0),o=this.bMarks[l]+c,r=l+1<e||n?this.eMarks[l]+1:this.eMarks[l],a[s]=this.src.slice(o,r);return a.join("")};var kt={};["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){kt[t]=!0}));var jt=/^<([a-zA-Z]{1,15})[\s\/>]/,St=/^<\/([a-zA-Z]{1,15})[\s>]/;function At(t,e){var i=t.bMarks[e]+t.blkIndent,n=t.eMarks[e];return t.src.substr(i,n-i)}function Tt(t,e){var i,n,s=t.bMarks[e]+t.tShift[e],o=t.eMarks[e];return s>=o||126!==(n=t.src.charCodeAt(s++))&&58!==n||s===(i=t.skipSpaces(s))||i>=o?-1:i}var Ot=[["code",function(t,e,i){var n,s;if(t.tShift[e]-t.blkIndent<4)return!1;for(s=n=e+1;n<i;)if(t.isEmpty(n))n++;else{if(!(t.tShift[n]-t.blkIndent>=4))break;s=++n}return t.line=n,t.tokens.push({type:"code",content:t.getLines(e,s,4+t.blkIndent,!0),block:!0,lines:[e,t.line],level:t.level}),!0}],["fences",function(t,e,i,n){var s,o,r,a,c,l=!1,u=t.bMarks[e]+t.tShift[e],h=t.eMarks[e];if(u+3>h||126!==(s=t.src.charCodeAt(u))&&96!==s||(c=u,(o=(u=t.skipChars(u,s))-c)<3)||(r=t.src.slice(u,h).trim()).indexOf("`")>=0)return!1;if(n)return!0;for(a=e;!(++a>=i||(u=c=t.bMarks[a]+t.tShift[a],h=t.eMarks[a],u<h&&t.tShift[a]<t.blkIndent));)if(!(t.src.charCodeAt(u)!==s||t.tShift[a]-t.blkIndent>=4||(u=t.skipChars(u,s),u-c<o||(u=t.skipSpaces(u),u<h)))){l=!0;break}return o=t.tShift[e],t.line=a+(l?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,n){var s,o,r,a,c,l,u,h,d,p,m,f=t.bMarks[e]+t.tShift[e],v=t.eMarks[e];if(f>v||62!==t.src.charCodeAt(f++)||t.level>=t.options.maxNesting)return!1;if(n)return!0;for(32===t.src.charCodeAt(f)&&f++,c=t.blkIndent,t.blkIndent=0,a=[t.bMarks[e]],t.bMarks[e]=f,o=(f=f<v?t.skipSpaces(f):f)>=v,r=[t.tShift[e]],t.tShift[e]=f-t.bMarks[e],h=t.parser.ruler.getRules("blockquote"),s=e+1;s<i&&!((f=t.bMarks[s]+t.tShift[s])>=(v=t.eMarks[s]));s++)if(62!==t.src.charCodeAt(f++)){if(o)break;for(m=!1,d=0,p=h.length;d<p;d++)if(h[d](t,s,i,!0)){m=!0;break}if(m)break;a.push(t.bMarks[s]),r.push(t.tShift[s]),t.tShift[s]=-1337}else 32===t.src.charCodeAt(f)&&f++,a.push(t.bMarks[s]),t.bMarks[s]=f,o=(f=f<v?t.skipSpaces(f):f)>=v,r.push(t.tShift[s]),t.tShift[s]=f-t.bMarks[s];for(l=t.parentType,t.parentType="blockquote",t.tokens.push({type:"blockquote_open",lines:u=[e,0],level:t.level++}),t.parser.tokenize(t,e,s),t.tokens.push({type:"blockquote_close",level:--t.level}),t.parentType=l,u[1]=t.line,d=0;d<r.length;d++)t.bMarks[d+e]=a[d],t.tShift[d+e]=r[d];return t.blkIndent=c,!0},["paragraph","blockquote","list"]],["hr",function(t,e,i,n){var s,o,r,a=t.bMarks[e],c=t.eMarks[e];if((a+=t.tShift[e])>c||42!==(s=t.src.charCodeAt(a++))&&45!==s&&95!==s)return!1;for(o=1;a<c;){if((r=t.src.charCodeAt(a++))!==s&&32!==r)return!1;r===s&&o++}return!(o<3)&&(n||(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,n){var s,o,r,a,c,l,u,h,d,p,m,f,v,g,b,y,w,x,M,k,j,S=!0;if((h=Mt(t,e))>=0)f=!0;else{if(!((h=xt(t,e))>=0))return!1;f=!1}if(t.level>=t.options.maxNesting)return!1;if(m=t.src.charCodeAt(h-1),n)return!0;for(g=t.tokens.length,f?(u=t.bMarks[e]+t.tShift[e],p=Number(t.src.substr(u,h-u-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++}),s=e,b=!1,x=t.parser.ruler.getRules("list");s<i&&((d=(v=t.skipSpaces(h))>=t.eMarks[s]?1:v-h)>4&&(d=1),d<1&&(d=1),o=h-t.bMarks[s]+d,t.tokens.push({type:"list_item_open",lines:w=[e,0],level:t.level++}),a=t.blkIndent,c=t.tight,r=t.tShift[e],l=t.parentType,t.tShift[e]=v-t.bMarks[e],t.blkIndent=o,t.tight=!0,t.parentType="list",t.parser.tokenize(t,e,i,!0),(!t.tight||b)&&(S=!1),b=t.line-e>1&&t.isEmpty(t.line-1),t.blkIndent=a,t.tShift[e]=r,t.tight=c,t.parentType=l,t.tokens.push({type:"list_item_close",level:--t.level}),s=e=t.line,w[1]=s,v=t.bMarks[e],!(s>=i||t.isEmpty(s)||t.tShift[s]<t.blkIndent));){for(j=!1,M=0,k=x.length;M<k;M++)if(x[M](t,s,i,!0)){j=!0;break}if(j)break;if(f){if((h=Mt(t,s))<0)break}else if((h=xt(t,s))<0)break;if(m!==t.src.charCodeAt(h-1))break}return t.tokens.push({type:f?"ordered_list_close":"bullet_list_close",level:--t.level}),y[1]=s,t.line=s,S&&function(t,e){var i,n,s=t.level+2;for(i=e+2,n=t.tokens.length-2;i<n;i++)t.tokens[i].level===s&&"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,n){var s,o,r,a,c,l=t.bMarks[e]+t.tShift[e],u=t.eMarks[e];if(l+4>u||91!==t.src.charCodeAt(l)||94!==t.src.charCodeAt(l+1)||t.level>=t.options.maxNesting)return!1;for(a=l+2;a<u;a++){if(32===t.src.charCodeAt(a))return!1;if(93===t.src.charCodeAt(a))break}return!(a===l+2||a+1>=u||58!==t.src.charCodeAt(++a))&&(n||(a++,t.env.footnotes||(t.env.footnotes={}),t.env.footnotes.refs||(t.env.footnotes.refs={}),c=t.src.slice(l+2,a-2),t.env.footnotes.refs[":"+c]=-1,t.tokens.push({type:"footnote_reference_open",label:c,level:t.level++}),s=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]=s,t.tokens.push({type:"footnote_reference_close",level:--t.level})),!0)},["paragraph"]],["heading",function(t,e,i,n){var s,o,r,a=t.bMarks[e]+t.tShift[e],c=t.eMarks[e];if(a>=c||(35!==(s=t.src.charCodeAt(a))||a>=c))return!1;for(o=1,s=t.src.charCodeAt(++a);35===s&&a<c&&o<=6;)o++,s=t.src.charCodeAt(++a);return!(o>6||a<c&&32!==s)&&(n||(c=t.skipCharsBack(c,32,a),(r=t.skipCharsBack(c,35,a))>a&&32===t.src.charCodeAt(r-1)&&(c=r),t.line=e+1,t.tokens.push({type:"heading_open",hLevel:o,lines:[e,t.line],level:t.level}),a<c&&t.tokens.push({type:"inline",content:t.src.slice(a,c).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 n,s,o,r=e+1;return!(r>=i||t.tShift[r]<t.blkIndent||t.tShift[r]-t.blkIndent>3||(s=t.bMarks[r]+t.tShift[r],o=t.eMarks[r],s>=o)||(n=t.src.charCodeAt(s),45!==n&&61!==n)||(s=t.skipChars(s,n),s=t.skipSpaces(s),s<o))&&(s=t.bMarks[e]+t.tShift[e],t.line=r+1,t.tokens.push({type:"heading_open",hLevel:61===n?1:2,lines:[e,t.line],level:t.level}),t.tokens.push({type:"inline",content:t.src.slice(s,t.eMarks[e]).trim(),level:t.level+1,lines:[e,t.line-1],children:[]}),t.tokens.push({type:"heading_close",hLevel:61===n?1:2,level:t.level}),!0)}],["htmlblock",function(t,e,i,n){var s,o,r,a=t.bMarks[e],c=t.eMarks[e],l=t.tShift[e];if(a+=l,!t.options.html||l>3||a+2>=c||60!==t.src.charCodeAt(a))return!1;if(33===(s=t.src.charCodeAt(a+1))||63===s){if(n)return!0}else{if(47!==s&&!function(t){var e=32|t;return e>=97&&e<=122}(s))return!1;if(47===s){if(!(o=t.src.slice(a,c).match(St)))return!1}else if(!(o=t.src.slice(a,c).match(jt)))return!1;if(!0!==kt[o[1].toLowerCase()])return!1;if(n)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,n){var s,o,r,a,c,l,u,h,d,p,m;if(e+2>i||(c=e+1,t.tShift[c]<t.blkIndent)||(r=t.bMarks[c]+t.tShift[c])>=t.eMarks[c]||124!==(s=t.src.charCodeAt(r))&&45!==s&&58!==s||(o=At(t,e+1),!/^[-:| ]+$/.test(o))||(l=o.split("|"))<=2)return!1;for(h=[],a=0;a<l.length;a++){if(!(d=l[a].trim())){if(0===a||a===l.length-1)continue;return!1}if(!/^:?-+:?$/.test(d))return!1;58===d.charCodeAt(d.length-1)?h.push(58===d.charCodeAt(0)?"center":"right"):58===d.charCodeAt(0)?h.push("left"):h.push("")}if(-1===(o=At(t,e).trim()).indexOf("|")||(l=o.replace(/^\||\|$/g,"").split("|"),h.length!==l.length))return!1;if(n)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<l.length;a++)t.tokens.push({type:"th_open",align:h[a],lines:[e,e+1],level:t.level++}),t.tokens.push({type:"inline",content:l[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++}),c=e+2;c<i&&!(t.tShift[c]<t.blkIndent||(o=At(t,c).trim(),-1===o.indexOf("|")));c++){for(l=o.replace(/^\||\|$/g,"").split("|"),t.tokens.push({type:"tr_open",level:t.level++}),a=0;a<l.length;a++)t.tokens.push({type:"td_open",align:h[a],level:t.level++}),u=l[a].substring(124===l[a].charCodeAt(0)?1:0,124===l[a].charCodeAt(l[a].length-1)?l[a].length-1:l[a].length).trim(),t.tokens.push({type:"inline",content:u,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]=c,t.line=c,!0},["paragraph"]],["deflist",function(t,e,i,n){var s,o,r,a,c,l,u,h,d,p,m,f,v,g;if(n)return!(t.ddIndent<0)&&Tt(t,e)>=0;if(u=e+1,t.isEmpty(u)&&++u>i||t.tShift[u]<t.blkIndent||(s=Tt(t,u))<0||t.level>=t.options.maxNesting)return!1;l=t.tokens.length,t.tokens.push({type:"dl_open",lines:c=[e,0],level:t.level++}),r=e,o=u;t:for(;;){for(g=!0,v=!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=[u,0],level:t.level++}),f=t.tight,d=t.ddIndent,h=t.blkIndent,m=t.tShift[o],p=t.parentType,t.blkIndent=t.ddIndent=t.tShift[o]+2,t.tShift[o]=s-t.bMarks[o],t.tight=!0,t.parentType="deflist",t.parser.tokenize(t,o,i,!0),(!t.tight||v)&&(g=!1),v=t.line-o>1&&t.isEmpty(t.line-1),t.tShift[o]=m,t.tight=f,t.parentType=p,t.blkIndent=h,t.ddIndent=d,t.tokens.push({type:"dd_close",level:--t.level}),a[1]=u=t.line,u>=i||t.tShift[u]<t.blkIndent)break t;if((s=Tt(t,u))<0)break;o=u}if(u>=i||(r=u,t.isEmpty(r))||t.tShift[r]<t.blkIndent||(o=r+1)>=i||(t.isEmpty(o)&&o++,o>=i)||t.tShift[o]<t.blkIndent||(s=Tt(t,o))<0)break}return t.tokens.push({type:"dl_close",level:--t.level}),c[1]=u,t.line=u,g&&function(t,e){var i,n,s=t.level+2;for(i=e+2,n=t.tokens.length-2;i<n;i++)t.tokens[i].level===s&&"paragraph_open"===t.tokens[i].type&&(t.tokens[i+2].tight=!0,t.tokens[i].tight=!0,i+=2)}(t,l),!0},["paragraph"]],["paragraph",function(t,e){var i,n,s,o,r,a,c=e+1;if(c<(i=t.lineMax)&&!t.isEmpty(c))for(a=t.parser.ruler.getRules("paragraph");c<i&&!t.isEmpty(c);c++)if(!(t.tShift[c]-t.blkIndent>3)){for(s=!1,o=0,r=a.length;o<r;o++)if(a[o](t,c,i,!0)){s=!0;break}if(s)break}return n=t.getLines(e,c,t.blkIndent,!1).trim(),t.line=c,n.length&&(t.tokens.push({type:"paragraph_open",tight:!1,lines:[e,t.line],level:t.level}),t.tokens.push({type:"inline",content:n,level:t.level+1,lines:[e,t.line],children:[]}),t.tokens.push({type:"paragraph_close",tight:!1,level:t.level})),!0}]];function Ct(){this.ruler=new W;for(var t=0;t<Ot.length;t++)this.ruler.push(Ot[t][0],Ot[t][1],{alt:(Ot[t][2]||[]).slice()})}Ct.prototype.tokenize=function(t,e,i){for(var n,s=this.ruler.getRules(""),o=s.length,r=e,a=!1;r<i&&(t.line=r=t.skipEmptyLines(r),!(r>=i||t.tShift[r]<t.blkIndent));){for(n=0;n<o&&!s[n](t,r,i,!1);n++);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 Nt=/[\n\t]/g,It=/\r[\n\u0085]|[\u2424\u2028\u0085]/g,Et=/\u00a0/g;function zt(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}}Ct.prototype.parse=function(t,e,i,n){var s,o=0,r=0;if(!t)return[];(t=(t=t.replace(Et," ")).replace(It,"\n")).indexOf("\t")>=0&&(t=t.replace(Nt,(function(e,i){var n;return 10===t.charCodeAt(i)?(o=i+1,r=0,e):(n=" ".slice((i-o-r)%4),r=i-o+1,n)}))),s=new wt(t,this,e,i,n),this.tokenize(s,s.line,s.lineMax)};for(var Lt=[],Pt=0;Pt<256;Pt++)Lt.push(0);function Dt(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122}function _t(t,e){var i,n,s,o=e,r=!0,a=!0,c=t.posMax,l=t.src.charCodeAt(e);for(i=e>0?t.src.charCodeAt(e-1):-1;o<c&&t.src.charCodeAt(o)===l;)o++;return o>=c&&(r=!1),(s=o-e)>=4?r=a=!1:((32===(n=o<c?t.src.charCodeAt(o):-1)||10===n)&&(r=!1),(32===i||10===i)&&(a=!1),95===l&&(Dt(i)&&(r=!1),Dt(n)&&(a=!1))),{can_open:r,can_close:a,delims:s}}"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach((function(t){Lt[t.charCodeAt(0)]=1}));var Rt=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Ft=/\\([ \\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g;var Bt=["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"],Jt=/^<([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])?)*)>/,qt=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;function Yt(t,e){return t=t.source,e=e||"",function i(n,s){return n?(s=s.source||s,t=t.replace(n,s),i):new RegExp(t,e)}}var $t=Yt(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",/[^"'=<>`\x00-\x20]+/)("single_quoted",/'[^']*'/)("double_quoted",/"[^"]*"/)(),Ut=Yt(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",/[a-zA-Z_:][a-zA-Z0-9:._-]*/)("attr_value",$t)(),Vt=Yt(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",Ut)(),Zt=Yt(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",Vt)("close_tag",/<\/[A-Za-z][A-Za-z0-9]*\s*>/)("comment",/<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->/)("processing",/<[?].*?[?]>/)("declaration",/<![A-Z]+\s+[^>]*>/)("cdata",/<!\[CDATA\[[\s\S]*?\]\]>/)();var Ht=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,Gt=/^&([a-z][a-z0-9]{1,31});/i;var Kt=[["text",function(t,e){for(var i=t.pos;i<t.posMax&&!zt(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,n,s=t.pos;if(10!==t.src.charCodeAt(s))return!1;if(i=t.pending.length-1,n=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(s++;s<n&&32===t.src.charCodeAt(s);)s++;return t.pos=s,!0}],["escape",function(t,e){var i,n=t.pos,s=t.posMax;if(92!==t.src.charCodeAt(n))return!1;if(++n<s){if((i=t.src.charCodeAt(n))<256&&0!==Lt[i])return e||(t.pending+=t.src[n]),t.pos+=2,!0;if(10===i){for(e||t.push({type:"hardbreak",level:t.level}),n++;n<s&&32===t.src.charCodeAt(n);)n++;return t.pos=n,!0}}return e||(t.pending+="\\"),t.pos++,!0}],["backticks",function(t,e){var i,n,s,o,r,a=t.pos;if(96!==t.src.charCodeAt(a))return!1;for(i=a,a++,n=t.posMax;a<n&&96===t.src.charCodeAt(a);)a++;for(s=t.src.slice(i,a),o=r=a;-1!==(o=t.src.indexOf("`",r));){for(r=o+1;r<n&&96===t.src.charCodeAt(r);)r++;if(r-o===s.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+=s),t.pos+=s.length,!0}],["del",function(t,e){var i,n,s,o,r,a=t.posMax,c=t.pos;if(126!==t.src.charCodeAt(c)||e||c+4>=a||126!==t.src.charCodeAt(c+1)||t.level>=t.options.maxNesting||(o=c>0?t.src.charCodeAt(c-1):-1,r=t.src.charCodeAt(c+2),126===o)||126===r||32===r||10===r)return!1;for(n=c+2;n<a&&126===t.src.charCodeAt(n);)n++;if(n>c+3)return t.pos+=n-c,e||(t.pending+=t.src.slice(c,n)),!0;for(t.pos=c+2,s=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?s--:32!==r&&10!==r&&s++,s<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=c+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=c,!1)}],["ins",function(t,e){var i,n,s,o,r,a=t.posMax,c=t.pos;if(43!==t.src.charCodeAt(c)||e||c+4>=a||43!==t.src.charCodeAt(c+1)||t.level>=t.options.maxNesting||(o=c>0?t.src.charCodeAt(c-1):-1,r=t.src.charCodeAt(c+2),43===o)||43===r||32===r||10===r)return!1;for(n=c+2;n<a&&43===t.src.charCodeAt(n);)n++;if(n!==c+2)return t.pos+=n-c,e||(t.pending+=t.src.slice(c,n)),!0;for(t.pos=c+2,s=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?s--:32!==r&&10!==r&&s++,s<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=c+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=c,!1)}],["mark",function(t,e){var i,n,s,o,r,a=t.posMax,c=t.pos;if(61!==t.src.charCodeAt(c)||e||c+4>=a||61!==t.src.charCodeAt(c+1)||t.level>=t.options.maxNesting||(o=c>0?t.src.charCodeAt(c-1):-1,r=t.src.charCodeAt(c+2),61===o)||61===r||32===r||10===r)return!1;for(n=c+2;n<a&&61===t.src.charCodeAt(n);)n++;if(n!==c+2)return t.pos+=n-c,e||(t.pending+=t.src.slice(c,n)),!0;for(t.pos=c+2,s=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?s--:32!==r&&10!==r&&s++,s<=0))){i=!0;break}t.parser.skipToken(t)}return i?(t.posMax=t.pos,t.pos=c+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=c,!1)}],["emphasis",function(t,e){var i,n,s,o,r,a,c,l=t.posMax,u=t.pos,h=t.src.charCodeAt(u);if(95!==h&&42!==h||e)return!1;if(i=(c=_t(t,u)).delims,!c.can_open)return t.pos+=i,e||(t.pending+=t.src.slice(u,t.pos)),!0;if(t.level>=t.options.maxNesting)return!1;for(t.pos=u+i,a=[i];t.pos<l;)if(t.src.charCodeAt(t.pos)!==h)t.parser.skipToken(t);else{if(n=(c=_t(t,t.pos)).delims,c.can_close){for(o=a.pop(),r=n;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,s=!0;break}t.pos+=n;continue}c.can_open&&a.push(n),t.pos+=n}return s?(t.posMax=t.pos,t.pos=u+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=l,!0):(t.pos=u,!1)}],["sub",function(t,e){var i,n,s=t.posMax,o=t.pos;if(126!==t.src.charCodeAt(o)||e||o+2>=s||t.level>=t.options.maxNesting)return!1;for(t.pos=o+1;t.pos<s;){if(126===t.src.charCodeAt(t.pos)){i=!0;break}t.parser.skipToken(t)}return!i||o+1===t.pos||(n=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:n.replace(Rt,"$1")}),t.pos=t.posMax+1,t.posMax=s,!0)}],["sup",function(t,e){var i,n,s=t.posMax,o=t.pos;if(94!==t.src.charCodeAt(o)||e||o+2>=s||t.level>=t.options.maxNesting)return!1;for(t.pos=o+1;t.pos<s;){if(94===t.src.charCodeAt(t.pos)){i=!0;break}t.parser.skipToken(t)}return!i||o+1===t.pos||(n=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:n.replace(Ft,"$1")}),t.pos=t.posMax+1,t.posMax=s,!0)}],["links",function(t,e){var i,n,s,o,r,a,c,l,u=!1,h=t.pos,d=t.posMax,p=t.pos,m=t.src.charCodeAt(p);if(33===m&&(u=!0,m=t.src.charCodeAt(++p)),91!==m||t.level>=t.options.maxNesting||(i=p+1,(n=tt(t,p))<0))return!1;if((a=n+1)<d&&40===t.src.charCodeAt(a)){for(a++;a<d&&(32===(l=t.src.charCodeAt(a))||10===l);a++);if(a>=d)return!1;for(p=a,nt(t,a)?(o=t.linkContent,a=t.pos):o="",p=a;a<d&&(32===(l=t.src.charCodeAt(a))||10===l);a++);if(a<d&&p!==a&&st(t,a))for(r=t.linkContent,a=t.pos;a<d&&(32===(l=t.src.charCodeAt(a))||10===l);a++);else r="";if(a>=d||41!==t.src.charCodeAt(a))return t.pos=h,!1;a++}else{if(t.linkLevel>0)return!1;for(;a<d&&(32===(l=t.src.charCodeAt(a))||10===l);a++);if(a<d&&91===t.src.charCodeAt(a)&&(p=a+1,(a=tt(t,a))>=0?s=t.src.slice(p,a++):a=p-1),s||(typeof s>"u"&&(a=n+1),s=t.src.slice(i,n)),!(c=t.env.references[ot(s)]))return t.pos=h,!1;o=c.href,r=c.title}return e||(t.pos=i,t.posMax=n,u?t.push({type:"image",src:o,title:r,alt:t.src.substr(i,n-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,n,s,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,n=tt(t,a+1),n<0))&&(e||(t.env.footnotes||(t.env.footnotes={}),t.env.footnotes.list||(t.env.footnotes.list=[]),s=t.env.footnotes.list.length,t.pos=i,t.posMax=n,t.push({type:"footnote_ref",id:s,level:t.level}),t.linkLevel++,o=t.tokens.length,t.parser.tokenize(t),t.env.footnotes.list[s]={tokens:t.tokens.splice(o)},t.linkLevel--),t.pos=n+1,t.posMax=r,!0)}],["footnote_ref",function(t,e){var i,n,s,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(n=a+2;n<r;n++){if(32===t.src.charCodeAt(n)||10===t.src.charCodeAt(n))return!1;if(93===t.src.charCodeAt(n))break}return!(n===a+2||n>=r||(n++,i=t.src.slice(a+2,n-1),typeof t.env.footnotes.refs[":"+i]>"u"))&&(e||(t.env.footnotes.list||(t.env.footnotes.list=[]),t.env.footnotes.refs[":"+i]<0?(s=t.env.footnotes.list.length,t.env.footnotes.list[s]={label:i,count:0},t.env.footnotes.refs[":"+i]=s):s=t.env.footnotes.refs[":"+i],o=t.env.footnotes.list[s].count,t.env.footnotes.list[s].count++,t.push({type:"footnote_ref",id:s,subId:o,level:t.level})),t.pos=n,t.posMax=r,!0)}],["autolink",function(t,e){var i,n,s,o,r,a=t.pos;return!(60!==t.src.charCodeAt(a)||(i=t.src.slice(a),i.indexOf(">")<0))&&((n=i.match(qt))?!(Bt.indexOf(n[1].toLowerCase())<0||(o=n[0].slice(1,-1),r=it(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+=n[0].length,!0):!!(s=i.match(Jt))&&(r=it("mailto:"+(o=s[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+=s[0].length,!0)))}],["htmltag",function(t,e){var i,n,s,o=t.pos;return!(!t.options.html||(s=t.posMax,60!==t.src.charCodeAt(o)||o+2>=s)||(i=t.src.charCodeAt(o+1),33!==i&&63!==i&&47!==i&&!function(t){var e=32|t;return e>=97&&e<=122}(i))||(n=t.src.slice(o).match(Zt),!n))&&(e||t.push({type:"htmltag",content:t.src.slice(o,o+n[0].length),level:t.level}),t.pos+=n[0].length,!0)}],["entity",function(t,e){var i,n,s=t.pos,o=t.posMax;if(38!==t.src.charCodeAt(s))return!1;if(s+1<o)if(35===t.src.charCodeAt(s+1)){if(n=t.src.slice(s).match(Ht))return e||(i="x"===n[1][0].toLowerCase()?parseInt(n[1].slice(1),16):parseInt(n[1],10),t.pending+=_(i)?R(i):R(65533)),t.pos+=n[0].length,!0}else if(n=t.src.slice(s).match(Gt)){var r=E(n[1]);if(n[1]!==r)return e||(t.pending+=r),t.pos+=n[0].length,!0}return e||(t.pending+="&"),t.pos++,!0}]];function Qt(){this.ruler=new W;for(var t=0;t<Kt.length;t++)this.ruler.push(Kt[t][0],Kt[t][1]);this.validateLink=Wt}function Wt(t){var e=t.trim().toLowerCase();return!(-1!==(e=q(e)).indexOf(":")&&-1!==["vbscript","javascript","file","data"].indexOf(e.split(":")[0]))}Qt.prototype.skipToken=function(t){var e,i,n=this.ruler.getRules(""),s=n.length,o=t.pos;if((i=t.cacheGet(o))>0)t.pos=i;else{for(e=0;e<s;e++)if(n[e](t,!0))return void t.cacheSet(o,t.pos);t.pos++,t.cacheSet(o,t.pos)}},Qt.prototype.tokenize=function(t){for(var e,i,n=this.ruler.getRules(""),s=n.length,o=t.posMax;t.pos<o;){for(i=0;i<s&&!(e=n[i](t,!1));i++);if(e){if(t.pos>=o)break}else t.pending+=t.src[t.pos++]}t.pending&&t.pushPending()},Qt.prototype.parse=function(t,e,i,n){var s=new X(t,this,e,i,n);this.tokenize(s)};var Xt={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 te(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 ee(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 Qt,this.block=new Ct,this.core=new yt,this.renderer=new Q,this.ruler=new W,this.options={},this.configure(Xt[t]),this.set(e||{})}ee.prototype.set=function(t){L(this.options,t)},ee.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)}))},ee.prototype.use=function(t,e){return t(this,e),this},ee.prototype.parse=function(t,e){var i=new te(this,t,e);return this.core.process(i),i.tokens},ee.prototype.render=function(t,e){return e=e||{},this.renderer.render(this.parse(t,e),this.options,e)},ee.prototype.parseInline=function(t,e){var i=new te(this,t,e);return i.inlineMode=!0,this.core.process(i),i.tokens},ee.prototype.renderInline=function(t,e){return e=e||{},this.renderer.render(this.parseInline(t,e),this.options,e)};class ie{static createNew(){const t=window.hljs;return new ee(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:!1,langPrefix:"language-",linkTarget:"_blank",typographer:!0}:{highlight:t=>t,linkTarget:"_blank"})}}class ne{static parseConfig(t,e,i,n){var s;const o={files:e};if("object"==typeof n){const{files:e,request:r,button:a}=n;e&&(e.infoModal&&(o.files.infoModal=e.infoModal,null!=(s=e.infoModal)&&s.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||t.headers||t.method||t.url)&&(o.request={headers:(null==r?void 0:r.headers)||t.headers,method:(null==r?void 0:r.method)||t.method,url:(null==r?void 0:r.url)||t.url})}return o}static processMixedFiles(t,e,i){if(i){const n={acceptedFormats:""};t.fileTypes.mixedFiles=ne.parseConfig(t.requestSettings,n,e,i)}}static processMicrophone(t,e,i,n){var s,o,r,a,c,l;const u={acceptedFormats:"audio/*",...(null==(s=t.fileTypes.audio)?void 0:s.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.recordAudio=ne.parseConfig(t.requestSettings,u,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!=(c=t.fileTypes.audio)&&c.files&&((l=t.fileTypes.audio.files).maxNumberOfFiles??(l.maxNumberOfFiles=i.files.maxNumberOfFiles)))):n||(t.fileTypes.audio=ne.parseConfig(t.requestSettings,u,e,i)))}static processAudioConfig(t,e,i,n){if(!i&&!n)return;const s={acceptedFormats:"audio/*",...(null==n?void 0:n.files)||{}};t.fileTypes.audio=ne.parseConfig(t.requestSettings,s,e,i)}static processGifConfig(t,e,i,n){if(!i&&!n)return;const s={acceptedFormats:"image/gif",...(null==n?void 0:n.files)||{}};t.fileTypes.gifs=ne.parseConfig(t.requestSettings,s,e,i)}static processCamera(t,e,i,n){var s,o,r,a;const c={acceptedFormats:"image/*",...(null==(s=t.fileTypes.images)?void 0:s.files)||{}};i&&(void 0!==navigator.mediaDevices.getUserMedia?(t.camera=ne.parseConfig(t.requestSettings,c,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))):n||(t.fileTypes.images=ne.parseConfig(t.requestSettings,c,e,i)))}static processImagesConfig(t,e,i,n){if(!i&&!n)return;const s={acceptedFormats:"image/*",...(null==n?void 0:n.files)||{}};t.fileTypes.images=ne.parseConfig(t.requestSettings,s,e,i)}static populateDefaultFileIO(t,e){var i,n;t&&(t.files??(t.files={}),(i=t.files).acceptedFormats??(i.acceptedFormats=e),(n=t.files).maxNumberOfFiles??(n.maxNumberOfFiles=1))}static set(t,e,i){ne.populateDefaultFileIO(null==i?void 0:i.audio,".4a,.mp3,.webm,.mp4,.mpga,.wav,.mpeg,.m4a"),ne.populateDefaultFileIO(null==i?void 0:i.images,".png,.jpg");const n=ie.createNew();ne.processImagesConfig(e,n,t.images,null==i?void 0:i.images),ne.processCamera(e,n,t.camera,t.images),ne.processGifConfig(e,n,t.gifs,null==i?void 0:i.gifs),ne.processAudioConfig(e,n,t.audio,null==i?void 0:i.audio),ne.processMicrophone(e,n,t.microphone,t.audio),ne.processMixedFiles(e,n,t.mixedFiles)}}class se{constructor(t,e,i){var n,s,o,r;this.rawBody={},this.validateConfigKey=!1,this.canSendMessage=se.canSendMessage,this.requestSettings={},this.fileTypes={},this.completionsHandlers={},this.streamHandlers={},this.deepChat=t,this.demo=i,Object.assign(this.rawBody,null==(n=t.request)?void 0:n.additionalBodyProps),this.totalMessagesMaxCharLength=null==(s=null==t?void 0:t.requestBodyLimits)?void 0:s.totalMessagesMaxCharLength,this.maxMessages=null==(o=null==t?void 0:t.requestBodyLimits)?void 0:o.maxMessages,ne.set(t,this,e),t.request&&(this.requestSettings=t.request),this.demo&&((r=this.requestSettings).url??(r.url=j.URL)),this.requestSettings.websocket&&C.setup(this)}static canSendMessage(t,e,i){return!!i||(!(!t||""===t.trim())||!!(e&&e.length>0))}verifyKey(t,e){}static createCustomFormDataBody(t,e,i){const n=new FormData;i.forEach((t=>n.append("files",t))),Object.keys(t).forEach((e=>n.append(e,String(t[e]))));let s=0;e.slice(0,e.length-1).forEach((t=>{n.append(`message${s+=1}`,JSON.stringify(t))}));const o=e[e.length-1];return o.text&&(delete o.files,n.append(`message${s+=1}`,JSON.stringify(o))),n}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){const{stream:n}=this.deepChat;return!n||!this.demo&&"object"==typeof n&&n.simulation?T.request(this,t,e,i):S.request(this,t,e)}async callServiceAPI(t,e,i){var n,s,o,r;const a={messages:e,...this.rawBody};let c=!1;null!=(n=this.requestSettings.headers)&&n["Content-Type"]||((s=this.requestSettings).headers??(s.headers={}),(o=this.requestSettings.headers)["Content-Type"]??(o["Content-Type"]="application/json"),c=!0),await this.request(a,t),c&&(null==(r=this.requestSettings.headers)||delete r["Content-Type"])}async callApiWithFiles(t,e,i,n){const s=se.createCustomFormDataBody(t,i,n),o=this.requestSettings,r=this.getServiceIOByType(n[0]);this.requestSettings=(null==r?void 0:r.request)||this.requestSettings,await this.request(s,e,!1),this.requestSettings=o}async callAPI(t,e){if(!this.requestSettings)throw new Error("Request settings have not been set up");const i=O.processMessages(e.messages,this.maxMessages,this.totalMessagesMaxCharLength);if(this.requestSettings.websocket){const t={messages:i,...this.rawBody};C.sendWebsocket(this,t,e,!1)}else t.files&&!this.isDirectConnection()?this.callApiWithFiles(this.rawBody,e,i,t.files):this.callServiceAPI(e,i,t.files)}async extractResultData(t){if(t.error)throw t.error;return t.result?N.handleResponseProperty(t):t}isDirectConnection(){return!1}}class oe extends se{constructor(t,e,i,n,s){var o;super(t,s),this.insertKeyPlaceholderText="API Key",this.getKeyLink="",Object.assign(this.rawBody,null==(o=t.request)?void 0:o.additionalBodyProps),this.keyVerificationDetails=e,this.buildHeadersFunc=i,n&&this.setApiKeyProperties(n),this.requestSettings=this.buildRequestSettings(this.key||"",t.request)}setApiKeyProperties(t){this.key=t.key,t.validateKeyProperty&&(this.validateConfigKey=t.validateKeyProperty)}buildRequestSettings(t,e){const i=e??{};return i.headers=this.buildHeadersFunc(t),i}keyAuthenticated(t,e){this.requestSettings=this.buildRequestSettings(e,this.requestSettings),this.key=e,t()}verifyKey(t,e){const{url:i,method:n,handleVerificationResult:s,createHeaders:o,body:r}=this.keyVerificationDetails,a=(null==o?void 0:o(t))||this.buildHeadersFunc(t);T.verifyKey(t,i,a,n,this.keyAuthenticated.bind(this,e.onSuccess),e.onFail,e.onLoad,s,r)}isDirectConnection(){return!0}}class re{static waitForPropertiesToBeUpdatedBeforeRender(t){t._propUpdated_=!1,setTimeout((()=>{t._propUpdated_?re.waitForPropertiesToBeUpdatedBeforeRender(t):(t._waitingToRender_=!1,t.onRender())}))}static attemptRender(t){t._propUpdated_=!0,t._waitingToRender_||(t._waitingToRender_=!0,re.waitForPropertiesToBeUpdatedBeforeRender(t))}}const ae=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(n){i=n,e?this[t]=n:re.attemptRender(this)}})}attributeChangedCallback(e,i,n){if(i===n)return;const s=t._attributes_[e](n);this[t._attributeToProperty_[e]]=s}onRender(){}};ae._attributes_={},ae._attributeToProperty_={};let ce=ae;class le{static createSVGElement(t){return(new DOMParser).parseFromString(t,"image/svg+xml").documentElement}}const ue=class t{static changeVisibility(e,i,n,s){s.target.id===t.VISIBLE_ICON_ID?(i.style.display="none",n.style.display="block",e.type="password"):(i.style.display="block",n.style.display="none",e.type="text")}static createIconElement(t,e){const i=le.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 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 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);n.style.display="none",i.appendChild(n);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 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(s),i.onclick=t.changeVisibility.bind(this,e,n,s),i}};ue.VISIBLE_ICON_ID="visible-icon";let he=ue;class de{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 n=document.createElement("div");n.id="insert-key-help-text-contents";const s=de.createFailText();if(n.appendChild(s),t){const e=de.createHelpLink(t);n.appendChild(e)}if(!0===e){const t=de.createCautionText();n.appendChild(t)}return i.appendChild(n),{helpTextContainerElement:i,failTextElement:s}}static onFail(t,e,i,n){t.classList.replace("insert-key-input-valid","insert-key-input-invalid"),i.innerText=n,i.style.display="block",e.innerText="Start",t.classList.remove("loading")}static onLoad(t,e){t.classList.add("loading"),e.innerHTML='<div id="loading-ring"></div>'}static verifyKey(t,e,i){const n=t.value.trim();i.verifyKey(n,e)}static addVerificationEvents(t,e,i,n,s){const r={onSuccess:n,onFail:de.onFail.bind(this,t,e,i),onLoad:de.onLoad.bind(this,t,e)},a=de.verifyKey.bind(this,t,r,s);e.onclick=a,t.onkeydown=e=>{!t.classList.contains("loading")&&e.key===o.ENTER&&a()}}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=de.onInputFocus,e.appendChild(i),e}static createContents(t,e){var i;const n=document.createElement("div");n.id="insert-key-contents";const s=de.createInput(e.insertKeyPlaceholderText),o=s.children[0],r=he.create(o);s.appendChild(r),n.appendChild(s);const a=de.createStartButton(),{helpTextContainerElement:c,failTextElement:l}=de.createHelpTextContainer(e.getKeyLink,null==(i=e.deepChat._insertKeyViewStyles)?void 0:i.displayCautionText);return n.appendChild(a),n.appendChild(c),de.addVerificationEvents(o,a,l,t,e),n}static createElements(t,e){const i=document.createElement("div");i.id="insert-key-view";const n=de.createContents(t,e);return i.appendChild(n),i}static render(t,e,i){const n=de.createElements(e,i);t.replaceChildren(n)}}class pe{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,n){const s=t;Array.isArray(s.error)&&"Error in `parameters`: field required"===s.error[0]?i(e):n(m.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api-inference.huggingface.co/models/gpt2",method:"POST",handleVerificationResult:pe.handleVerificationResult}}}const me=class t extends oe{constructor(e,i,n,s,o,r){super(e,pe.buildKeyVerificationDetails(),pe.buildHeaders,o,r),this.insertKeyPlaceholderText="Hugging Face Token",this.getKeyLink="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}${n}`,this.textInputPlaceholderText=i,"object"==typeof s&&(s.model&&(this.url=`${t.URL_PREFIX}${s.model}`),s.options&&(this.rawBody.options=s.options),s.parameters&&(this.rawBody.parameters=s.parameters))}preprocessBody(t,e,i){const n=JSON.parse(JSON.stringify(t)),s=e[e.length-1].text;if(s)return n.options??(n.options={}),n.options.wait_for_model=!0,{inputs:s,...n}}async callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");const n=this.preprocessBody(this.rawBody,e,i);T.request(this,n,t)}};me.URL_PREFIX="https://api-inference.huggingface.co/models/";let fe=me;class ve extends fe{constructor(t,e,i,n,s,o){super(t,e,i,n,s,o),this.isTextInputDisabled=!0,this.canSendMessage=ve.canSendFile}static canSendFile(t,e){return!(null==e||!e[0])}preprocessBody(t,e,i){return i[0]}async callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");T.poll(this,i[0],t,!1)}}class ge extends ve{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.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 be extends ve{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.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 ye="data:image/png;base64,";class we{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,n){t.message?n(m.INVALID_KEY):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.stability.ai/v1/engines/list",method:"GET",handleVerificationResult:we.handleVerificationResult}}}class xe extends oe{constructor(t,e,i,n,s){super(t,e,i,n,s),this.insertKeyPlaceholderText="Stability AI API Key",this.getKeyLink="https://platform.stability.ai/docs/getting-started/authentication",this.permittedErrorPrefixes=["Incorrect","invalid_"]}}class Me extends xe{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),n=null==i?void 0:i.stabilityAI;super(t,we.buildKeyVerificationDetails(),we.buildHeaders,n,{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 s=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageUpscale;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/image-to-image/upscale`),Me.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=Me.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.requestSettings)throw new Error("Request settings have not been set up");if(!i)throw new Error("Image was not found");const n=this.createFormDataBody(this.rawBody,i[0]);v.tempRemoveContentHeader(this.requestSettings,T.request.bind(this,this,n,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${ye}${t.base64}`,type:"image"})))}}}class ke extends xe{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),n=null==i?void 0:i.stabilityAI;super(t,we.buildKeyVerificationDetails(),we.buildHeaders,n,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.url="https://api.stability.ai/v1/generation/stable-inpainting-512-v2-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 s=null==(e=null==i?void 0:i.stabilityAI)?void 0:e.imageToImageMasking;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/image-to-image/masking`),void 0!==s.weight&&null!==s.weight&&(this._imageWeight=s.weight),void 0!==s.mask_source&&null!==s.mask_source&&(this._maskSource=s.mask_source),ke.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=ke.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,n){const s=new FormData;return s.append("init_image",e),s.append("mask_source",String(this._maskSource)),s.append("mask_image",i),n&&""!==n&&s.append("text_prompts[0][text]",n),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 n,s;if(!this.requestSettings)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==(s=null==(n=e[e.length-1])?void 0:n.text)?void 0:s.trim(),r=this.createFormDataBody(this.rawBody,i[0],i[1],o);v.tempRemoveContentHeader(this.requestSettings,T.request.bind(this,this,r,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${ye}${t.base64}`,type:"image"})))}}}class je extends ve{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.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 Se extends fe{constructor(t){var e,i,n;super(t,"Once upon a time","gpt2",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.textGeneration,null==(n=t.directConnection)?void 0:n.huggingFace)}async extractResultData(t){if(t.error)throw t.error;return{text:t[0].generated_text||""}}}class Ae extends fe{constructor(t){var e,i,n;const s=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",s,null==(n=t.directConnection)?void 0:n.huggingFace),this.permittedErrorPrefixes=["Authorization header","Error in"],this.context=s.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 Te extends fe{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.huggingFace)}async extractResultData(t){if(t.error)throw t.error;return{text:t[0].summary_text||""}}}class Oe extends fe{constructor(t){var e,i,n;super(t,"Ask me anything!","facebook/blenderbot-400M-distill",null==(i=null==(e=t.directConnection)?void 0:e.huggingFace)?void 0:i.conversation,null==(n=t.directConnection)?void 0:n.huggingFace),this.maxMessages??(this.maxMessages=-1)}processMessages(t){const e=t.filter((t=>t.text)),i=e[e.length-1].text,n=e.slice(0,e.length-1);if(!i)return;return{past_user_inputs:n.filter((t=>"user"===t.role)).map((t=>t.text)),generated_responses:n.filter((t=>"ai"===t.role)).map((t=>t.text)),mostRecentMessageText:i}}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=this.processMessages(e);if(n)return i.options??(i.options={}),i.options.wait_for_model=!0,{inputs:{past_user_inputs:n.past_user_inputs,generated_responses:n.generated_responses,text:n.mostRecentMessageText},...i}}async extractResultData(t){if(t.error)throw t.error;return{text:t.generated_text||""}}}class Ce extends xe{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),n=i.stabilityAI;super(t,we.buildKeyVerificationDetails(),we.buildHeaders,n,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:1}}}),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-5/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 s=null==(e=i.stabilityAI)?void 0:e.imageToImage;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/text-to-image`),void 0!==s.weight&&null!==s.weight&&(this._imageWeight=s.weight),Ce.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=Ce.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 n=new FormData;return n.append("init_image",e),i&&""!==i&&n.append("text_prompts[0][text]",i),void 0!==this._imageWeight&&null!==this._imageWeight&&n.append("text_prompts[0][weight]",String(this._imageWeight)),Object.keys(t).forEach((e=>{n.append(e,String(t[e]))})),void 0===n.get("weight")&&n.append("weight",String(1)),n}async callServiceAPI(t,e,i){var n,s;if(!this.requestSettings)throw new Error("Request settings have not been set up");if(!i)throw new Error("Image was not found");const o=null==(s=null==(n=e[e.length-1])?void 0:n.text)?void 0:s.trim(),r=this.createFormDataBody(this.rawBody,i[0],o);v.tempRemoveContentHeader(this.requestSettings,T.request.bind(this,this,r,t),!1)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${ye}${t.base64}`,type:"image"})))}}}class Ne extends fe{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.huggingFace)}async extractResultData(t){if(t.error)throw t.error;return{text:t[0].translation_text||""}}}class Ie extends xe{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),n=i.stabilityAI;super(t,we.buildKeyVerificationDetails(),we.buildHeaders,n),this.url="https://api.stability.ai/v1/generation/stable-diffusion-v1-5/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 s=null==(e=i.stabilityAI)?void 0:e.textToImage;"object"==typeof s&&(s.engine_id&&(this.url=`https://api.stability.ai/v1/generation/${s.engine_id}/text-to-image`),void 0!==s.weight&&null!==s.weight&&(this._imageWeight=s.weight),Ie.cleanConfig(s),Object.assign(this.rawBody,s)),this.canSendMessage=Ie.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)),n={text:e};return this._imageWeight&&(n.weight=this._imageWeight),i.text_prompts=[n],i}async callServiceAPI(t,e){if(!this.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e[e.length-1].text);T.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{files:t.artifacts.map((t=>({src:`${ye}${t.base64}`,type:"image"})))}}}class Ee extends fe{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.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){if(t.error)throw t.error;return{text:t[0].sequence||""}}}class ze{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json",accept:"application/json"}}static handleVerificationResult(t,e,i,n){"invalid request: prompt must be at least 1 token long"===t.message?i(e):n(m.INVALID_KEY)}static buildKeyVerificationDetails(){return{url:"https://api.cohere.ai/v1/generate",method:"POST",handleVerificationResult:ze.handleVerificationResult,body:JSON.stringify({prompt:""})}}}class Le extends oe{constructor(t,e,i,n,s){super(t,ze.buildKeyVerificationDetails(),ze.buildHeaders,s),this.insertKeyPlaceholderText="Cohere API Key",this.getKeyLink="https://dashboard.cohere.ai/api-keys",this.permittedErrorPrefixes=["invalid"],this.url=e,this.textInputPlaceholderText=i,n&&"object"==typeof n&&Object.assign(this.rawBody,n)}}class Pe extends Le{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=e[e.length-1].text;if(n)return{prompt:n,...i}}async callServiceAPI(t,e){if(!this.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);T.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 De extends Le{constructor(t){var e,i,n;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==(n=t.directConnection)?void 0:n.cohere)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=e[e.length-1].text;if(n)return{text:n,...i}}async callServiceAPI(t,e){if(!this.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);T.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.summary||""}}}const _e=class t{static buildHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static handleVerificationResult(t,e,i,n){const s=t;s.error?"invalid_api_key"===s.error.code?n(m.INVALID_KEY):n(m.CONNECTION_FAILED):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.openai.com/v1/models",method:"GET",handleVerificationResult:t.handleVerificationResult}}static async storeFiles(e,i,n){const s=e.requestSettings.headers;if(!s)return;e.url="https://api.openai.com/v1/files";const o=s[v.CONTENT_TYPE];delete s[v.CONTENT_TYPE];const r=n.map((async i=>{const n=new FormData;return n.append("purpose","assistants"),n.append("file",i),new Promise((i=>{i(t.directFetch(e,n,"POST",!1))}))}));try{const t=(await Promise.all(r)).map((t=>t.id));return s[v.CONTENT_TYPE]=o,t}catch(t){throw s[v.CONTENT_TYPE]=o,v.displayError(i,t),e.completionsHandlers.onFinish(),t}}static async directFetch(t,e,i,n=!0){t.requestSettings.method=i;const s=await v.fetch(t,t.requestSettings.headers,n,e).then((t=>v.processResponseByType(t)));if(s.error)throw s.error.message;return s}};_e.CONVERSE_MAX_CHAR_LENGTH=13352,_e.FILE_MAX_CHAR_LENGTH=1e3;let Re=_e;const Fe=class t extends oe{constructor(e){var i,n,s;const{textInput:o}=e,r=JSON.parse(JSON.stringify(e.directConnection)),a=null==r?void 0:r.openAI;super(e,Re.buildKeyVerificationDetails(),Re.buildHeaders,a),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/audio/speech",this.permittedErrorPrefixes=["Invalid"],this._maxCharLength=Re.FILE_MAX_CHAR_LENGTH,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>',null!=o&&o.characterLimit&&(this._maxCharLength=o.characterLimit);const c=null==(i=null==r?void 0:r.openAI)?void 0:i.textToSpeech;"object"==typeof c&&Object.assign(this.rawBody,c),(n=this.rawBody).model??(n.model=t.DEFAULT_MODEL),(s=this.rawBody).voice??(s.voice=t.DEFAULT_VOIDE),this.textInputPlaceholderText="Insert text to generate audio",this.rawBody.response_format="mp3"}preprocessBody(t,e){var i,n;const s=JSON.parse(JSON.stringify(t)),o=null==(n=null==(i=e[e.length-1])?void 0:i.text)?void 0:n.trim();if(o&&""!==o){const t=o.substring(0,this._maxCharLength);s.input=t}return s}async callServiceAPI(t,e){var i;if(null==(i=this.requestSettings)||!i.headers)throw new Error("Request settings have not been set up");this.url=this.requestSettings.url||this.url;const n=this.preprocessBody(this.rawBody,e);T.request(this,n,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"}}};Fe.DEFAULT_MODEL="tts-1",Fe.DEFAULT_VOIDE="alloy";let Be=Fe;const Je=class t extends oe{constructor(e){var i,n;const{textInput:s}=e,o=JSON.parse(JSON.stringify(e.directConnection)),r=null==o?void 0:o.openAI;super(e,Re.buildKeyVerificationDetails(),Re.buildHeaders,r,{audio:{}}),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="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._maxCharLength=Re.FILE_MAX_CHAR_LENGTH,this._service_url=t.AUDIO_TRANSCRIPTIONS_URL,null!=s&&s.characterLimit&&(this._maxCharLength=s.characterLimit);const a=null==(i=null==o?void 0:o.openAI)?void 0:i.audio;"object"==typeof a&&(this.processConfig(a),t.cleanConfig(a),Object.assign(this.rawBody,a)),(n=this.rawBody).model??(n.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,n;const s=JSON.parse(JSON.stringify(t)),o=null==(n=null==(i=e[e.length-1])?void 0:i.text)?void 0:n.trim();if(o&&""!==o){const t=o.substring(0,this._maxCharLength);s.prompt=t}return s}async callServiceAPI(e,i,n){var s;if(null==(s=this.requestSettings)||!s.headers)throw new Error("Request settings have not been set up");if(null==n||!n[0])throw new Error("No file was added");this.url=this.requestSettings.url||this._service_url;const o=this.preprocessBody(this.rawBody,i),r=t.createFormDataBody(o,n[0]);v.tempRemoveContentHeader(this.requestSettings,T.request.bind(this,this,r,e),!1)}async extractResultData(t){if(t.error)throw t.error.message;return{text:t.text}}};Je.AUDIO_TRANSCRIPTIONS_URL="https://api.openai.com/v1/audio/transcriptions",Je.AUDIO_TRANSLATIONS_URL="https://api.openai.com/v1/audio/translations",Je.DEFAULT_MODEL="whisper-1";let qe=Je;class Ye{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,n){t.error?n(m.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:Ye.handleSpeechVerificationResult}}static buildSummarizationHeader(t){return{"Ocp-Apim-Subscription-Key":t,"Content-Type":"application/json"}}static handleLanguageVerificationResult(t,e,i,n){var s;"401"===(null==(s=t.error)?void 0:s.code)?n(m.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:Ye.handleLanguageVerificationResult}}static handleTranslationVerificationResult(t,e,i,n){t.json().then((t=>{Array.isArray(t)||401e3!==t.error.code?i(e):n(m.INVALID_KEY)}))}static buildTranslationKeyVerificationDetails(t){return{url:"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es",method:"POST",createHeaders:e=>Ye.buildTranslationHeaders(t,e),handleVerificationResult:Ye.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 $e extends oe{constructor(t,e,i,n,s){super(t,Ye.buildLanguageKeyVerificationDetails(i),e,n,s),this.insertKeyPlaceholderText="Azure Language Subscription Key",this.getKeyLink="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal",this.permittedErrorPrefixes=["Access"]}}class Ue extends $e{constructor(t){var e,i,n,s;const o=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.summarization,r=null==(n=t.directConnection)?void 0:n.azure;super(t,Ye.buildSummarizationHeader,o.endpoint,r),this.url="",this.textInputPlaceholderText="Insert text to summarize",(s=this.rawBody).language??(s.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.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);T.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"),n={method:"GET",headers:null==(e=this.requestSettings)?void 0:e.headers};T.executePollRequest(this,i,n,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||""}}}const Ve=class t{static generateDefaultBody(t){return{model:t}}static build(e,i){const n=t.generateDefaultBody(e);return i&&"boolean"!=typeof i?Object.assign(n,i):n}};Ve.GPT_COMPLETIONS_DAVINCI_MODEL="text-davinci-003",Ve.GPT_CHAT_TURBO_MODEL="gpt-3.5-turbo";let Ze=Ve;class He extends oe{constructor(t){var e,i;const{directConnection:n,textInput:s}=t,o=null==n?void 0:n.openAI;super(t,Re.buildKeyVerificationDetails(),Re.buildHeaders,o),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/completions",this.permittedErrorPrefixes=["Incorrect"],this._maxCharLength=Re.CONVERSE_MAX_CHAR_LENGTH,this.full_transaction_max_tokens=4e3,this.numberOfCharsPerToken=3.5;const r=null==(e=null==n?void 0:n.openAI)?void 0:e.completions;null!=s&&s.characterLimit&&(this._maxCharLength=s.characterLimit),"object"==typeof r&&Object.assign(this.rawBody,r),(i=this.rawBody).model??(i.model=Ze.GPT_COMPLETIONS_DAVINCI_MODEL)}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=e.filter((t=>t.text)),s=n[n.length-1].text;if(!s)return;const o=s.substring(0,this._maxCharLength),r=i.max_tokens||this.full_transaction_max_tokens-o.length/this.numberOfCharsPerToken;return{prompt:o,max_tokens:Math.floor(r),...i}}async callServiceAPI(t,e){if(!this.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);this.deepChat.stream||i.stream?(i.stream=!0,S.request(this,i,t)):T.request(this,i,t)}async extractResultData(t){var e;if(t.error)throw t.error.message;return{text:(null==(e=t.choices[0])?void 0:e.text)||""}}}class Ge{static async poll(t,e){const i={authorization:t,"content-type":"application/json"},n=`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 s;for(;!s;){const t=await(await fetch(n,{headers:i})).json();if("completed"===t.status)s=t;else{if("error"===t.status)throw new Error(`Transcription failed: ${t.error}`);await new Promise((t=>setTimeout(t,3e3)))}}return s}static buildHeaders(t){return{Authorization:t,"Content-Type":"application/octet-stream"}}static handleVerificationResult(t,e,i,n){const s=t;s.error?"invalid_api_key"===s.error.code?n(m.INVALID_KEY):n(m.CONNECTION_FAILED):i(e)}static buildKeyVerificationDetails(){return{url:"https://api.assemblyai.com/v2/upload",method:"POST",handleVerificationResult:Ge.handleVerificationResult}}}class Ke extends oe{constructor(t){var e;const i=null==(e=t.directConnection)?void 0:e.assemblyAI;super(t,Ge.buildKeyVerificationDetails(),Ge.buildHeaders,i,{audio:{}}),this.insertKeyPlaceholderText="AssemblyAI API Key",this.getKeyLink="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=Ke.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])}async callServiceAPI(t,e,i){var n;if(null==(n=this.requestSettings)||!n.headers)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");T.request(this,i[0],t,!1)}async extractResultData(t){var e,i;if(t.error)throw t.error;const n=null==(i=null==(e=this.requestSettings)?void 0:e.headers)?void 0:i.Authorization;return{text:(await Ge.poll(n,t.upload_url)).text}}}class Qe extends oe{constructor(t,e,i,n,s){super(t,Ye.buildSpeechKeyVerificationDetails(i),e,n,s),this.insertKeyPlaceholderText="Azure Speech Subscription Key",this.getKeyLink="https://learn.microsoft.com/en-us/azure/api-management/api-management-subscriptions#create-and-manage-subscriptions-in-azure-portal"}}const We=class t extends Qe{constructor(e){var i,n,s,o,r,a;const c=null==(n=null==(i=e.directConnection)?void 0:i.azure)?void 0:n.textToSpeech,l=null==(s=e.directConnection)?void 0:s.azure;super(e,Ye.buildTextToSpeechHeaders.bind({},(null==c?void 0:c.outputFormat)||"audio-16khz-128kbitrate-mono-mp3"),c.region,l),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,c),(o=this.rawBody).lang??(o.lang="en-US"),(r=this.rawBody).name??(r.name="en-US-JennyNeural"),(a=this.rawBody).gender??(a.gender="Female"),this.url=`https://${c.region}.tts.speech.microsoft.com/cognitiveservices/v1`}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.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);T.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"}]})}}))}};We.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 Xe=We;const ti=class t extends Qe{constructor(e){var i,n,s;const o=null==(n=null==(i=e.directConnection)?void 0:i.azure)?void 0:n.speechToText,r=null==(s=e.directConnection)?void 0:s.azure;super(e,Ye.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 n,s;if(null==(n=this.requestSettings)||!n.headers)throw new Error("Request settings have not been set up");if(null==i||!i[0])throw new Error("No file was added");null!=(s=this.requestSettings)&&s.headers&&(this.requestSettings.headers["Content-Type"]=i[0].name.toLocaleLowerCase().endsWith(".wav")?"audio/wav; codecs=audio/pcm; samplerate=16000":"audio/ogg; codecs=opus"),T.request(this,i[0],t,!1)}async extractResultData(t){if(t.error)throw t.error;return{text:t.DisplayText||""}}};ti.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 ei=ti;class ii extends oe{constructor(t){var e,i,n;const s=null==(i=null==(e=t.directConnection)?void 0:e.azure)?void 0:i.translation,o=null==(n=t.directConnection)?void 0:n.azure;super(t,Ye.buildTranslationKeyVerificationDetails(s.region),Ye.buildTranslationHeaders.bind({},null==s?void 0:s.region),o),this.insertKeyPlaceholderText="Azure Translate Subscription Key",this.getKeyLink="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=${s.language||"es"}`}preprocessBody(t){const e=t[t.length-1].text;if(e)return[{Text:e}]}async callServiceAPI(t,e){if(!this.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(e);T.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 ni=class t{static getRole(e){return e?t.AI_ROLE:t.USER_ROLE}static getLastElementsByClass(t,e,i){for(let n=t.length-1;n>=0;n-=1){const s=t[n];if(s.bubbleElement.classList.contains(e[0])&&!e.slice(1).find((t=>!s.bubbleElement.classList.contains(t)))){if(!i)return s;if(!i.find((t=>s.bubbleElement.classList.contains(t))))return s}}}static getLastMessage(e,i,n){const s=t.getRole(i);for(let t=e.length-1;t>=0;t-=1)if(e[t].role===s){if(!n)return e[t];if(e[t][n])return e[t]}}};ni.AI_ROLE="ai",ni.USER_ROLE="user";let si=ni;const oi=class t extends oe{constructor(t){var e,i,n,s,o;const r=JSON.parse(JSON.stringify(t.directConnection)),a=r.openAI;super(t,Re.buildKeyVerificationDetails(),Re.buildHeaders,a),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.url="",this.permittedErrorPrefixes=["Incorrect"],this.searchedForThreadId=!1;const c=null==(e=r.openAI)?void 0:e.assistant;if("object"==typeof c){this.rawBody.assistant_id=c.assistant_id;const{function_handler:e}=null==(n=null==(i=t.directConnection)?void 0:i.openAI)?void 0:n.assistant;e&&(this._functionHandler=e)}(s=this.requestSettings).headers??(s.headers={}),(o=this.requestSettings.headers)["OpenAI-Beta"]??(o["OpenAI-Beta"]="assistants=v1"),this.maxMessages=1}processMessages(t,e){const i=this.totalMessagesMaxCharLength||Re.CONVERSE_MAX_CHAR_LENGTH;return O.getCharacterLimitMessages(t,i).map((t=>({content:t.text||"",role:t.role===si.AI_ROLE?"assistant":"user",file_ids:e})))}createNewThreadMessages(t,e,i){const n=JSON.parse(JSON.stringify(t)),s=this.processMessages(e,i);return n.thread={messages:s},n}callService(e,i,n){if(this.sessionId){this.url=`${t.THREAD_PREFIX}/${this.sessionId}/messages`;const s=this.processMessages(i,n)[0];T.request(this,s,e)}else{this.url=`${t.THREAD_PREFIX}/runs`;const s=this.createNewThreadMessages(this.rawBody,i,n);T.request(this,s,e)}this.messages=e}async callServiceAPI(t,e,i){if(!this.requestSettings)throw new Error("Request settings have not been set up");this.searchedForThreadId||this.searchPreviousMessagesForThreadId(t.messages);const n=i?await Re.storeFiles(this,t,i):void 0;this.requestSettings.method="POST",this.callService(t,e,n)}searchPreviousMessagesForThreadId(t){const e=t.find((t=>t.sessionId));e&&(this.sessionId=e.sessionId),this.searchedForThreadId=!0}async extractResultData(e){var i;if(e.error)throw e.error.message;await this.assignThreadAndRun(e);const n=`${t.THREAD_PREFIX}/${this.sessionId}/runs/${this.run_id}`,s={method:"GET",headers:null==(i=this.requestSettings)?void 0:i.headers};return T.executePollRequest(this,n,s,this.messages),{makingAnotherRequest:!0}}async assignThreadAndRun(e){if(this.sessionId){this.url=`${t.THREAD_PREFIX}/${this.sessionId}/runs`;const e=await Re.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 extractPollResultData(e){var i;const{status:n,required_action:s}=e;if("queued"===n||"in_progress"===n)return{timeoutMS:t.POLLING_TIMEOUT_MS};if("completed"===n&&this.messages)return this.url=`${t.THREAD_PREFIX}/${e.thread_id}/messages`,{text:(await Re.directFetch(this,{},"GET")).data[0].content[0].text.value,sessionId:this.sessionId};const o=null==(i=null==s?void 0:s.submit_tool_outputs)?void 0:i.tool_calls;if("requires_action"===n&&o)return await this.handleTools(o);throw Error(`Thread run status: ${n}`)}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}))),n=(await this._functionHandler(i)).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`,await Re.directFetch(this,{tool_outputs:n},"POST"),{timeoutMS:t.POLLING_TIMEOUT_MS}}};oi.THREAD_PREFIX="https://api.openai.com/v1/threads",oi.POLLING_TIMEOUT_MS=800;let ri=oi;const ai=class t extends oe{constructor(e){var i;const{directConnection:n,textInput:s}=e,o=null==n?void 0:n.openAI;super(e,Re.buildKeyVerificationDetails(),Re.buildHeaders,o,{images:{files:{acceptedFormats:".png",maxNumberOfFiles:2}}}),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="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"],this._maxCharLength=Re.FILE_MAX_CHAR_LENGTH,null!=s&&s.characterLimit&&(this._maxCharLength=s.characterLimit);const r=null==(i=null==n?void 0:n.openAI)?void 0:i.images;if(this.camera){const t="object"==typeof r&&r.size?Number.parseInt(r.size):1024;this.camera.files={dimensions:{width:t,height:t}}}"object"==typeof r&&Object.assign(this.rawBody,r),this.canSendMessage=t.canFileSendMessage}static canFileSendMessage(t,e){return!(null==e||!e[0])||!(!t||""===t.trim())}static createFormDataBody(t,e,i){const n=new FormData;return n.append("image",e),i&&n.append("mask",i),Object.keys(t).forEach((e=>{n.append(e,String(t[e]))})),n}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t));if(e&&""!==e){const t=e.substring(0,this._maxCharLength);i.prompt=t}return i}callApiWithImage(e,i,n){var s,o;let r;const a=null==(o=null==(s=i[i.length-1])?void 0:s.text)?void 0:o.trim();if(n[1]||a&&""!==a){this.url=t.IMAGE_EDIT_URL;const e=this.preprocessBody(this.rawBody,a);r=t.createFormDataBody(e,n[0],n[1])}else this.url=t.IMAGE_VARIATIONS_URL,r=t.createFormDataBody(this.rawBody,n[0]);v.tempRemoveContentHeader(this.requestSettings,T.request.bind(this,this,r,e),!1)}async callServiceAPI(e,i,n){var s;if(null==(s=this.requestSettings)||!s.headers)throw new Error("Request settings have not been set up");if(null!=n&&n[0])this.callApiWithImage(e,i,n);else{if(!this.requestSettings)throw new Error("Request settings have not been set up");this.url=t.IMAGE_GENERATION_URL;const n=this.preprocessBody(this.rawBody,i[i.length-1].text);T.request(this,n,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:`${ye}${t.b64_json}`,type:"image"}))}}};ai.IMAGE_GENERATION_URL="https://api.openai.com/v1/images/generations",ai.IMAGE_VARIATIONS_URL="https://api.openai.com/v1/images/variations",ai.IMAGE_EDIT_URL="https://api.openai.com/v1/images/edits";let ci=ai;class li extends oe{constructor(t){var e,i,n,s;const o=JSON.parse(JSON.stringify(t.directConnection)),r=o.openAI;super(t,Re.buildKeyVerificationDetails(),Re.buildHeaders,r),this.insertKeyPlaceholderText="OpenAI API Key",this.getKeyLink="https://platform.openai.com/account/api-keys",this.url="https://api.openai.com/v1/chat/completions",this.permittedErrorPrefixes=["Incorrect"],this._systemMessage=li.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=li.generateSystemMessage(a.system_prompt));const{function_handler:e}=null==(n=null==(i=t.directConnection)?void 0:i.openAI)?void 0:n.chat;e&&(this._functionHandler=e),this.cleanConfig(a),Object.assign(this.rawBody,a)}this.maxMessages??(this.maxMessages=-1),(s=this.rawBody).model??(s.model=Ze.GPT_CHAT_TURBO_MODEL)}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)),n=this.totalMessagesMaxCharLength||Re.CONVERSE_MAX_CHAR_LENGTH,s=O.getCharacterLimitMessages(e,n-this._systemMessage.content.length).map((t=>({content:li.getContent(t),role:t.role===si.AI_ROLE?"assistant":"user"})));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.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);this.deepChat.stream||i.stream?(i.stream=!0,S.request(this,i,t)):T.request(this,i,t)}async extractResultData(t,e,i){if(t.error)throw t.error.message;return t.choices[0].delta?{text:t.choices[0].delta.content||""}:t.choices[0].message?t.choices[0].message.tool_calls?this.handleTools(t.choices[0].message,e,i):{text:t.choices[0].message.content}:{text:""}}async handleTools(t,e,i){var n;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 s=JSON.parse(JSON.stringify(i)),o=t.tool_calls.map((t=>({name:t.function.name,arguments:t.function.arguments}))),r=await(null==(n=this._functionHandler)?void 0:n.call(this,o));if(r.text)return{text:r.text};if(s.messages.push(t),Array.isArray(r)){r.forEach(((e,i)=>{var n;const o=null==(n=t.tool_calls)?void 0:n[i];null==s||s.messages.push({role:"tool",tool_call_id:null==o?void 0:o.id,name:null==o?void 0:o.function.name,content:e.response})})),delete s.tools,delete s.tool_choice;const i=await(null==e?void 0:e(s).then((t=>v.processResponseByType(t))));if(i.error)throw i.error.message;return{text:i.choices[0].message.content||""}}throw Error("Response object must contain a FunctionHandlerResponse object")}}class ui extends Le{constructor(t){var e;const i=JSON.parse(JSON.stringify(t.directConnection)),n=null==(e=i.cohere)?void 0:e.chat;super(t,"https://api.cohere.ai/v1/chat","Ask me anything!",n,i.cohere),this.username="USER","object"==typeof n&&(n.user_name&&(this.username=n.user_name),this.cleanConfig(n),Object.assign(this.rawBody,n)),this.maxMessages??(this.maxMessages=-1)}cleanConfig(t){delete t.user_name}preprocessBody(t,e){const i=JSON.parse(JSON.stringify(t)),n=e.filter((t=>t.text));return i.query=n[n.length-1].text,i.chat_history=n.slice(0,n.length-1).map((t=>({text:t.text,user_name:"ai"===t.role?"CHATBOT":this.username}))),i}async callServiceAPI(t,e){if(!this.requestSettings)throw new Error("Request settings have not been set up");const i=this.preprocessBody(this.rawBody,e);T.request(this,i,t)}async extractResultData(t){if(t.message)throw t.message;return{text:t.text}}}class hi{static create(t){const{directConnection:e,request:i,demo:n}=t;if(e){if(e.openAI)return e.openAI.images?new ci(t):e.openAI.speechToText?new qe(t):e.openAI.textToSpeech?new Be(t):e.openAI.assistant?new ri(t):e.openAI.completions?new He(t):new li(t);if(e.assemblyAI)return new Ke(t);if(e.cohere)return e.cohere.chat?new ui(t):e.cohere.summarization?new De(t):new Pe(t);if(e.huggingFace)return e.huggingFace.textGeneration?new Se(t):e.huggingFace.summarization?new Te(t):e.huggingFace.translation?new Ne(t):e.huggingFace.fillMask?new Ee(t):e.huggingFace.questionAnswer?new Ae(t):e.huggingFace.audioSpeechRecognition?new je(t):e.huggingFace.audioClassification?new ge(t):e.huggingFace.imageClassification?new be(t):new Oe(t);if(e.azure){if(e.azure.speechToText)return new ei(t);if(e.azure.textToSpeech)return new Xe(t);if(e.azure.summarization)return new Ue(t);if(e.azure.translation)return new ii(t)}if(e.stabilityAI)return e.stabilityAI.imageToImage?new Ce(t):e.stabilityAI.imageToImageUpscale?new Me(t):e.stabilityAI.imageToImageMasking?new ke(t):new Ie(t)}return i?new se(t):new se(t,void 0,n||!0)}}const di=class t{static appendStyleSheetToHead(){const e=document.getElementsByTagName("head")[0];if(!Array.from(e.getElementsByTagName("link")).some((e=>e.getAttribute("href")===t.FONT_URL))){const i=document.createElement("link");i.rel="stylesheet",i.href=t.FONT_URL,e.appendChild(i)}}};di.FONT_URL="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap";let pi=di;class mi{}function fi(t){return function(e,i){Object.defineProperty(e,i,{});const n=e.constructor,s=i.toLocaleLowerCase();n._attributes_[s]=mi.attibutes[t],n._attributeToProperty_[s]=i}}mi.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}`)()};class vi{static onNewMessage(t,e,i){const n=JSON.parse(JSON.stringify({message:e,isInitial:i}));t.onNewMessage(n),t.dispatchEvent(new CustomEvent("new-message",{detail:n}))}static onClearMessages(t){t.onClearMessages(),t.dispatchEvent(new CustomEvent("clear-messages"))}static onRender(t){t.onComponentRender(),t.dispatchEvent(new CustomEvent("render"))}}const gi=class t{static addElements(t,...e){e.forEach((e=>t.appendChild(e)))}static isScrollbarAtBottomOfElement(e){const i=e.scrollHeight,n=e.clientHeight;return e.scrollTop>=i-n-t.CODE_SNIPPET_GENERATION_JUMP}static cloneElement(t){const e=t.cloneNode(!0);return t.parentNode.replaceChild(e,t),e}};gi.CODE_SNIPPET_GENERATION_JUMP=.5;let bi=gi;const yi=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 n={};setTimeout((()=>{if("object"==typeof e&&(e.lang&&(n.lang=e.lang),e.pitch&&(n.pitch=e.pitch),e.rate&&(n.rate=e.rate),e.volume&&(n.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&&(n.voice=t)}i(n)}),t.LOAD_VOICES_MS)}};yi.LOAD_VOICES_MS=200;let wi=yi;class xi{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 set(t,e){var i,n,s,o;if(null!=(n=null==(i=null==e?void 0:e.loading)?void 0:i.bubble)&&n.color){const i=xi.colorToHex(null==(o=null==(s=null==e?void 0:e.loading)?void 0:s.bubble)?void 0:o.color);t.style.setProperty("--message-dots-color",i),t.style.setProperty("--message-dots-color-fade",`${i}33`)}else t.style.setProperty("--message-dots-color","#848484"),t.style.setProperty("--message-dots-color-fade","#55555533")}}class Mi{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",Mi.mouseEnter.bind(this,t,e)),t.addEventListener("mouseleave",Mi.mouseLeave.bind(this,t,e)),t.addEventListener("mousedown",Mi.mouseDown.bind(this,t,e)),t.addEventListener("mouseup",Mi.mouseUp.bind(this,t,e))}}class ki{static applyStylesToElement(t,e){const n=i.processStateful(e,{},{});Mi.add(t,n),Object.assign(t.style,n.default)}static applyEventsToElement(t,e){Object.keys(e).forEach((i=>{const n=e[i];n&&t.addEventListener(i,n)}))}static applyClassUtilitiesToElement(t,e){const{events:i,styles:n}=e;i&&ki.applyEventsToElement(t,i),n&&!Ai.doesElementContainDeepChatClass(t)&&ki.applyStylesToElement(t,n)}static applyCustomClassUtilities(t,e){Object.keys(t).forEach((i=>{const n=e.getElementsByClassName(i);Array.from(n).forEach((e=>{t[i]&&ki.applyClassUtilitiesToElement(e,t[i])}))}))}static apply(t,e){Ai.applyDeepChatUtilities(t,t.htmlClassUtilities,e),ki.applyCustomClassUtilities(t.htmlClassUtilities,e)}}const ji={"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"}}}},Si=Object.keys(ji);class Ai{static applySuggestionEvent(t,e){setTimeout((()=>{e.addEventListener("click",(()=>{var i,n;null==(n=t.submitUserMessage)||n.call(t,(null==(i=e.textContent)?void 0:i.trim())||"")}))}))}static isUpdateMessage(t){var e;const i=document.createElement("div");return i.innerHTML=t,null==(e=i.children[0])?void 0:e.classList.contains("deep-chat-update-message")}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 Si.find((e=>t.classList.contains(e)))}static applyEvents(t,e){const i=ji[e].events;Object.keys(i||[]).forEach((e=>{t.addEventListener(e,null==i?void 0:i[e])}))}static getProcessedStyles(t,e,n){const s=Array.from(e.classList).reduce(((e,i)=>{var n;const s=null==(n=t[i])?void 0:n.styles;return s&&t[i].styles&&e.push(s),e}),[]),o=ji[n].styles;if(o){const t=JSON.parse(JSON.stringify(o));t.default&&i.overwriteDefaultWithAlreadyApplied(t,e),s.unshift(t)}const r=i.mergeStatefulStyles(s);return i.processStateful(r,{},{})}static applyDeepChatUtilities(t,e,i){Si.forEach((t=>{const n=i.getElementsByClassName(t);Array.from(n||[]).forEach((i=>{const n=Ai.getProcessedStyles(e,i,t);ki.applyStylesToElement(i,n),Ai.applyEvents(i,t)}))}));const n=i.getElementsByClassName("deep-chat-suggestion-button");Array.from(n).forEach((e=>Ai.applySuggestionEvent(t,e)))}}class Ti{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],n="a"!==e.tagName.toLocaleLowerCase()?e:e.children[0];Object.assign(n.style,i.media)}}static applySideStyles(t,e,i,n){n&&(Ti.applyCustomStylesToElements(t,i,n.shared),e?Ti.applyCustomStylesToElements(t,i,n.ai):Ti.applyCustomStylesToElements(t,i,n.user))}static isMessageSideStyles(t){return!!(t.ai||t.shared||t.user)}static applyCustomStyles(t,e,i,n,s){var o;s&&t.default!==s?Ti.isMessageSideStyles(s)?(Ti.applySideStyles(e,i,n,t.default),Ti.applySideStyles(e,i,n,s)):(Ti.applyCustomStylesToElements(e,n,null==(o=t.default)?void 0:o.shared),Ti.applyCustomStylesToElements(e,n,s)):Ti.applySideStyles(e,i,n,t.default)}static extractParticularSharedStyles(t,e){if(null==e||!e.shared)return;const i=e.shared,n={outerContainer:{},innerContainer:{},bubble:{},media:{}};return t.forEach((t=>{var e,s,o,r;n.outerContainer[t]=(null==(e=i.outerContainer)?void 0:e[t])||"",n.innerContainer[t]=(null==(s=i.innerContainer)?void 0:s[t])||"",n.bubble[t]=(null==(o=i.bubble)?void 0:o[t])||"",n.media[t]=(null==(r=i.media)?void 0:r[t])||""})),n}}class Oi{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=Oi.createIntroPanel(e);return"none"===t.style.display&&(t.style.display="block"),i.appendChild(t),i}createInternalIntroPanel(t,e){const i=Oi.createIntroPanel(e);return i.id="internal-intro-panel",i.innerHTML=t,i}hide(){this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="none",this._isDisplayed=!1)}display(){!this._isDisplayed&&this._elementRef&&(this._elementRef.style.display="",this._isDisplayed=!0)}}const Ci=class t{static addMessage(t,e,i,n){var s;t.elementRef.appendChild(e.outerContainer),t.applyCustomStyles(e,n,!0,null==(s=t.messageStyles)?void 0:s[i]),t.elementRef.scrollTop=t.elementRef.scrollHeight}static wrapInLink(t,e){const i=document.createElement("a");return i.href=e,i.target="_blank",i.appendChild(t),i}static processContent(e,i){return!i||i.startsWith("data")?e:t.wrapInLink(e,i)}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}}};Ci.DEFAULT_FILE_NAME="file";let Ni=Ci;class Ii{static addElement(t,e){t.elementRef.appendChild(e),t.elementRef.scrollTop=t.elementRef.scrollHeight}static createElements(t,e,i){const n=t.createNewMessageElement("",i);return n.bubbleElement.classList.add("html-message"),n.bubbleElement.innerHTML=e,n}static updateLastAIMessage(t,e,i){const n=si.getLastElementsByClass(i,["ai-message-text","html-message"],["loading-message-text"]);if(!n)return!1;n&&(n.bubbleElement.innerHTML=e);const s=si.getLastMessage(t,!0,"html");return s&&(s.html=e),!0}static add(t,e,i,n){var s;if(Ai.isUpdateMessage(e)&&Ii.updateLastAIMessage(t.messages,e,n))return;const o=Ii.createElements(t,e,i);return 0===e.trim().length&&Di.editEmptyMessageElement(o.bubbleElement),ki.apply(t,o.outerContainer),t.applyCustomStyles(o,i,!1,null==(s=t.messageStyles)?void 0:s.html),Ii.addElement(t,o.outerContainer),o}}class Ei{static getText(t,e){var i,n;if(!t.directConnection&&!t.request&&!t.demo)return"Connect to any API using the [request](https://deepchat.dev/docs/connect#Request)\n property or choose any one of the preconfigured APIs via\n the [directConnection](https://deepchat.dev/docs/directConnection/#directConnection) property.\n \n To get started checkout the [Start](https://deepchat.dev/start) page and\n live code [examples](https://deepchat.dev/examples/frameworks).\n \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.";const o=null==(n=t.directConnection.openAI)?void 0:n.assistant;if("boolean"==typeof o||o&&!o.assistant_id)return"Please define the `assistant_id` property inside the openAI [assistant](https://deepchat.dev/docs/directConnection/openAI#Assistant) object."}else if(t.request&&!t.request.url&&!t.request.handler)return"Please define a `url` or a `handler` property inside the [request](https://deepchat.dev/docs/connect#Request) object.";return null}}class zi{static createImage(t,e){const i=new Image;return i.src=t.src,Ni.scrollDownOnImageLoad(i.src,e),Ni.processContent(i,i.src)}static async addNewImageMessage(t,e,i){const n=zi.createImage(e,t.elementRef),s=t.createNewMessageElement("",i);s.bubbleElement.appendChild(n),s.bubbleElement.classList.add("image-message"),Ni.addMessage(t,s,"image",i)}static createAudioElement(t,e){const i=document.createElement("audio");return i.src=t.src,i.classList.add("audio-player"),i.controls=!0,r.IS_SAFARI&&(i.classList.add("audio-player-safari"),i.classList.add(e?"audio-player-safari-left":"audio-player-safari-right")),i}static addNewAudioMessage(t,e,i){const n=zi.createAudioElement(e,i),s=t.createNewMessageElement("",i);s.bubbleElement.appendChild(n),s.bubbleElement.classList.add("audio-message"),Ni.addMessage(t,s,"audio",i)}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 n=le.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>');n.classList.add("any-file-message-icon"),i.appendChild(n);const s=document.createElement("div");return s.classList.add("any-file-message-text"),s.textContent=t.name||Ni.DEFAULT_FILE_NAME,e.appendChild(i),e.appendChild(s),Ni.processContent(e,t.src)}static addNewAnyFileMessage(t,e,i){const n=t.createNewMessageElement("",i),s=zi.createAnyFile(e);n.bubbleElement.classList.add("any-file-message-bubble"),n.bubbleElement.appendChild(s),Ni.addMessage(t,n,"file",i)}static addMessages(t,e,i){e.forEach((e=>{var n,s;"audio"===e.type||null!=(n=e.src)&&n.startsWith("data:audio")?zi.addNewAudioMessage(t,e,i):"image"===e.type||null!=(s=e.src)&&s.startsWith("data:image")?zi.addNewImageMessage(t,e,i):zi.addNewAnyFileMessage(t,e,i)}))}}class Li{static applyCustomStylesToElements(t,e,i){Object.assign(t.style,i.container),Object.assign(e.style,i.avatar)}static applyCustomStyles(t,e,i,n){var s,o,r;null!=(s=i.default)&&s.styles&&Li.applyCustomStylesToElements(t,e,i.default.styles),n?null!=(o=i.ai)&&o.styles&&Li.applyCustomStylesToElements(t,e,i.ai.styles):null!=(r=i.user)&&r.styles&&Li.applyCustomStylesToElements(t,e,i.user.styles)}static createAvatar(t,e){var i,n,s,o;const r=document.createElement("img");r.src=t?(null==(i=null==e?void 0:e.ai)?void 0:i.src)||(null==(n=null==e?void 0:e.default)?void 0:n.src)||"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8c3ZnIGZpbGw9IiMwMDAwMDAiIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIAoJCXZpZXdCb3g9IjAgMCAzMiAzMiIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+Cgk8cGF0aCBkPSJNMjMsMzAuMzZIOWMtMi40MDQsMC00LjM2LTEuOTU2LTQuMzYtNC4zNlYxNWMwLTIuNDA0LDEuOTU2LTQuMzYsNC4zNi00LjM2aDMuNjU5CgkJYzAuMTY3LTEuNTY2LDEuNDE1LTIuODEzLDIuOTgxLTIuOTgxVjUuMzMzYy0xLjEzMS0wLjE3NC0yLTEuMTU0LTItMi4zMzNjMC0xLjMwMSwxLjA1OS0yLjM2LDIuMzYtMi4zNgoJCWMxLjMwMiwwLDIuMzYsMS4wNTksMi4zNiwyLjM2YzAsMS4xNzktMC44NjksMi4xNTktMiwyLjMzM1Y3LjY2YzEuNTY2LDAuMTY3LDIuODE0LDEuNDE1LDIuOTgxLDIuOTgxSDIzCgkJYzIuNDA0LDAsNC4zNiwxLjk1Niw0LjM2LDQuMzZ2MTFDMjcuMzYsMjguNDA0LDI1LjQwNCwzMC4zNiwyMywzMC4zNnogTTksMTEuMzZjLTIuMDA3LDAtMy42NCwxLjYzMy0zLjY0LDMuNjR2MTEKCQljMCwyLjAwNywxLjYzMywzLjY0LDMuNjQsMy42NGgxNGMyLjAwNywwLDMuNjQtMS42MzMsMy42NC0zLjY0VjE1YzAtMi4wMDctMS42MzMtMy42NC0zLjY0LTMuNjRIOXogTTEzLjM4NCwxMC42NGg1LjIzMQoJCUMxOC40MzksOS4zNTQsMTcuMzM0LDguMzYsMTYsOC4zNkMxNC42NjcsOC4zNiwxMy41NjEsOS4zNTQsMTMuMzg0LDEwLjY0eiBNMTYsMS4zNmMtMC45MDQsMC0xLjY0LDAuNzM2LTEuNjQsMS42NAoJCVMxNS4wOTYsNC42NCwxNiw0LjY0YzAuOTA0LDAsMS42NC0wLjczNiwxLjY0LTEuNjRTMTYuOTA0LDEuMzYsMTYsMS4zNnogTTIwLDI3LjM2aC04Yy0xLjMwMSwwLTIuMzYtMS4wNTktMi4zNi0yLjM2CgkJczEuMDU5LTIuMzYsMi4zNi0yLjM2aDhjMS4zMDIsMCwyLjM2LDEuMDU5LDIuMzYsMi4zNlMyMS4zMDIsMjcuMzYsMjAsMjcuMzZ6IE0xMiwyMy4zNmMtMC45MDQsMC0xLjY0LDAuNzM1LTEuNjQsMS42NAoJCXMwLjczNiwxLjY0LDEuNjQsMS42NGg4YzAuOTA0LDAsMS42NC0wLjczNSwxLjY0LTEuNjRzLTAuNzM1LTEuNjQtMS42NC0xLjY0SDEyeiBNMzEsMjMuODZoLTJjLTAuMTk5LDAtMC4zNi0wLjE2MS0wLjM2LTAuMzZWMTUKCQljMC0wLjE5OSwwLjE2MS0wLjM2LDAuMzYtMC4zNmgyYzAuMTk5LDAsMC4zNiwwLjE2MSwwLjM2LDAuMzZ2OC41QzMxLjM2LDIzLjY5OSwzMS4xOTksMjMuODYsMzEsMjMuODZ6IE0yOS4zNiwyMy4xNGgxLjI3OXYtNy43OAoJCUgyOS4zNlYyMy4xNHogTTMsMjMuODZIMWMtMC4xOTksMC0wLjM2LTAuMTYxLTAuMzYtMC4zNlYxNWMwLTAuMTk5LDAuMTYxLTAuMzYsMC4zNi0wLjM2aDJjMC4xOTksMCwwLjM2LDAuMTYxLDAuMzYsMC4zNnY4LjUKCQlDMy4zNiwyMy42OTksMy4xOTksMjMuODYsMywyMy44NnogTTEuMzYsMjMuMTRoMS4yOHYtNy43OEgxLjM2VjIzLjE0eiBNMjAsMjAuMzZjLTEuMzAyLDAtMi4zNi0xLjA1OS0yLjM2LTIuMzYKCQlzMS4wNTktMi4zNiwyLjM2LTIuMzZzMi4zNiwxLjA1OSwyLjM2LDIuMzZDMjIuMzYsMTkuMzAyLDIxLjMwMiwyMC4zNiwyMCwyMC4zNnogTTIwLDE2LjM2Yy0wLjkwNCwwLTEuNjQsMC43MzYtMS42NCwxLjY0CgkJczAuNzM1LDEuNjQsMS42NCwxLjY0czEuNjQtMC43MzUsMS42NC0xLjY0UzIwLjkwNCwxNi4zNiwyMCwxNi4zNnogTTEyLDIwLjM2Yy0xLjMwMSwwLTIuMzYtMS4wNTktMi4zNi0yLjM2czEuMDU5LTIuMzYsMi4zNi0yLjM2CgkJczIuMzYsMS4wNTksMi4zNiwyLjM2QzE0LjM2LDE5LjMwMiwxMy4zMDEsMjAuMzYsMTIsMjAuMzZ6IE0xMiwxNi4zNmMtMC45MDQsMC0xLjY0LDAuNzM2LTEuNjQsMS42NHMwLjczNiwxLjY0LDEuNjQsMS42NAoJCXMxLjY0LTAuNzM1LDEuNjQtMS42NFMxMi45MDQsMTYuMzYsMTIsMTYuMzZ6Ii8+Cgk8cmVjdCBzdHlsZT0iZmlsbDpub25lOyIgd2lkdGg9IjMyIiBoZWlnaHQ9IjMyIi8+Cjwvc3ZnPg==":(null==(s=null==e?void 0:e.user)?void 0:s.src)||(null==(o=null==e?void 0:e.default)?void 0:o.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==",r.classList.add("avatar");const a=document.createElement("div");return a.classList.add("avatar-container"),a.appendChild(r),e&&Li.applyCustomStyles(a,r,e,t),a}static getPosition(t,e){var i,n,s,o,r,a;let c=t?null==(n=null==(i=null==e?void 0:e.ai)?void 0:i.styles)?void 0:n.position:null==(o=null==(s=null==e?void 0:e.user)?void 0:s.styles)?void 0:o.position;return c??(c=null==(a=null==(r=null==e?void 0:e.default)?void 0:r.styles)?void 0:a.position),c??(c=t?"left":"right"),c}static add(t,e,i){const n="boolean"==typeof i?void 0:i,s=Li.createAvatar(e,n),o=Li.getPosition(e,n);s.classList.add("left"===o?"left-item-position":"right-item-position"),t.insertAdjacentElement("left"===o?"beforebegin":"afterend",s)}}class Pi{static getPosition(t,e){var i,n,s;let o=t?null==(i=null==e?void 0:e.ai)?void 0:i.position:null==(n=null==e?void 0:e.user)?void 0:n.position;return o||(o=null==(s=null==e?void 0:e.default)?void 0:s.position),o||(o=t?"left":"right"),o}static applyStyle(t,e,i){var n,s,o;Object.assign(t.style,null==(n=i.default)?void 0:n.style,e?null==(s=i.ai)?void 0:s.style:null==(o=i.user)?void 0:o.style)}static getNameText(t,e){var i,n,s,o;return t?(null==(i=e.ai)?void 0:i.text)||(null==(n=e.default)?void 0:n.text)||"AI":(null==(s=e.user)?void 0:s.text)||(null==(o=e.default)?void 0:o.text)||"User"}static createName(t,e){const i=document.createElement("div");return i.classList.add("name"),i.textContent=Pi.getNameText(t,e),Pi.applyStyle(i,t,e),i}static add(t,e,i){const n="boolean"==typeof i?{}:i,s=Pi.createName(e,n),o=Pi.getPosition(e,n);s.classList.add("left"===o?"left-item-position":"right-item-position"),t.insertAdjacentElement("left"===o?"beforebegin":"afterend",s)}}class Di{constructor(t,e,i){var n,s;this._messageElementRefs=[],this._textElementsToText=[],this._streamedText="",this.htmlClassUtilities={},this.messages=[];const{permittedErrorPrefixes:o,introPanelMarkUp:r,demo:a}=e;this._remarkable=ie.createNew(),this.elementRef=Di.createContainerElement(),this.messageStyles=t.messageStyles,this._avatars=t.avatars,this._names=t.names,this._errorMessageOverrides=null==(n=t.errorMessages)?void 0:n.overrides,t.htmlClassUtilities&&(this.htmlClassUtilities=t.htmlClassUtilities),this._onNewMessage=vi.onNewMessage.bind(this,t),this._onClearMessages=vi.onClearMessages.bind(this,t),this._displayLoadingMessage=Di.getDisplayLoadingMessage(t,e),this._permittedErrorPrefixes=o,this.addSetupMessageIfNeeded(t,e),this.populateIntroPanel(i,r,t.introPanelStyle),t.introMessage&&this.addIntroductoryMessage(t.introMessage),t.initialMessages&&this.populateInitialMessages(t.initialMessages),this._displayServiceErrorMessages=null==(s=t.errorMessages)?void 0:s.displayServiceErrorMessages,t.getMessages=()=>JSON.parse(JSON.stringify(this.messages)),t.clearMessages=this.clearMessages.bind(this,e),t.refreshMessages=this.refreshTextMessages.bind(this),t.scrollToBottom=this.scrollToBottom.bind(this),a&&this.prepareDemo(a),t.textToSpeech&&wi.processConfig(t.textToSpeech,(t=>{this._textToSpeech=t})),setTimeout((()=>{this.submitUserMessage=t.submitUserMessage}))}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())}static createContainerElement(){const t=document.createElement("div");return t.id="messages",t}addSetupMessageIfNeeded(t,e){const i=Ei.getText(t,e);if(i){const t=this.createAndAppendNewMessageElement(i,!0);this.applyCustomStyles(t,!0,!1)}}addIntroductoryMessage(t){var e,i,n,s;if(t&&(this._introMessage=t),null!=(e=this._introMessage)&&e.text){const t=this.createAndAppendNewMessageElement(this._introMessage.text,!0);this.applyCustomStyles(t,!0,!1,null==(i=this.messageStyles)?void 0:i.intro)}else if(null!=(n=this._introMessage)&&n.html){const t=Ii.add(this,this._introMessage.html,!0,this._messageElementRefs);this.applyCustomStyles(t,!0,!1,null==(s=this.messageStyles)?void 0:s.intro)}}populateInitialMessages(t){t.forEach((t=>{N.processInitialMessageFile(t),this.addNewMessage(t,t.role===si.AI_ROLE,!0)})),setTimeout((()=>this.scrollToBottom()))}applyCustomStyles(t,e,i,n){t&&this.messageStyles&&Ti.applyCustomStyles(this.messageStyles,t,e,i,n)}addInnerContainerElements(t,e,i){return t.classList.add("message-bubble",i?"ai-message-text":"user-message-text"),t.innerHTML=this._remarkable.render(e),0===t.innerText.trim().length&&(t.innerText=e),this._avatars&&Li.add(t,i,this._avatars),this._names&&Pi.add(t,i,this._names),{bubbleElement:t}}static createMessageContent(t,e){const i={role:si.getRole(t)},{text:n,files:s,html:o,sessionId:r}=e;return n&&(i.text=n),s&&(i.files=s),o&&(i.html=o),1===Object.keys(i).length&&(i.text=""),r&&(i.sessionId=r),i}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}}createMessageElements(t,e){const i=Di.createBaseElements(),{outerContainer:n,innerContainer:s,bubbleElement:o}=i;return n.appendChild(s),this.addInnerContainerElements(o,t,e),this._messageElementRefs.push(i),i}static isTemporaryElement(t){return(null==t?void 0:t.bubbleElement.classList.contains("loading-message-text"))||Ai.isElementTemporary(t)}createNewMessageElement(t,e){var i;null==(i=this._introPanel)||i.hide();const n=this._messageElementRefs[this._messageElementRefs.length-1];return Di.isTemporaryElement(n)&&(n.outerContainer.remove(),this._messageElementRefs.pop()),this.createMessageElements(t,e)}createAndAppendNewMessageElement(t,e){const i=this.createNewMessageElement(t,e);return this.elementRef.appendChild(i.outerContainer),this.scrollToBottom(),i}static editEmptyMessageElement(t){t.textContent=".",t.style.color="#00000000"}addNewTextMessage(t,e){const i=this.createAndAppendNewMessageElement(t,e);return this.applyCustomStyles(i,e,!1),0===t.trim().length&&Di.editEmptyMessageElement(i.bubbleElement),this._textElementsToText.push([i,t]),i}addNewMessage(t,e,i=!1){let n=!0;const s=Di.createMessageContent(e,t);if(void 0!==s.text&&null!==t.text&&(this.addNewTextMessage(s.text,e),!i&&this._textToSpeech&&e&&wi.speak(s.text,this._textToSpeech)),s.files&&Array.isArray(s.files)&&zi.addMessages(this,s.files,e),void 0!==s.html&&null!==s.html){const t=Ii.add(this,s.html,e,this._messageElementRefs);Ai.isElementTemporary(t)&&delete s.html,n=!!t}this.updateStateOnMessage(s,n,i)}updateStateOnMessage(t,e,i=!1){e&&this.messages.push(t),this.sendClientUpdate(t,i)}sendClientUpdate(t,e=!1){var i;null==(i=this._onNewMessage)||i.call(this,JSON.parse(JSON.stringify(t)),e)}removeMessageOnError(){const t=this._messageElementRefs[this._messageElementRefs.length-1],e=null==t?void 0:t.bubbleElement;(null!=e&&e.classList.contains("streamed-message")&&""===e.textContent||Di.isTemporaryElement(t))&&(t.outerContainer.remove(),this._messageElementRefs.pop())}addNewErrorMessage(t,e){var i,n,s,o;this.removeMessageOnError();const r=Di.createBaseElements(),{outerContainer:a,bubbleElement:c}=r;c.classList.add("error-message-text");const l=this.getPermittedMessage(e)||(null==(i=this._errorMessageOverrides)?void 0:i[t])||(null==(n=this._errorMessageOverrides)?void 0:n.default)||"Error, please try again.";c.innerHTML=l;const u=Ti.extractParticularSharedStyles(["fontSize","fontFamily"],null==(s=this.messageStyles)?void 0:s.default);Ti.applyCustomStylesToElements(r,!1,u),Ti.applyCustomStylesToElements(r,!1,null==(o=this.messageStyles)?void 0:o.error),this.elementRef.appendChild(a),this.scrollToBottom(),this._textToSpeech&&wi.speak(l,this._textToSpeech),this._streamedText=""}static checkPermittedErrorPrefixes(t,e){for(let i=0;i<t.length;i+=1)if(e.startsWith(t[i]))return e}getPermittedMessage(t){if(t){if(this._displayServiceErrorMessages)return t;if("string"==typeof t&&this._permittedErrorPrefixes){const e=Di.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,t);if(e)return e}else if(Array.isArray(t)&&this._permittedErrorPrefixes)for(let e=0;e<t.length;e+=1){const i=Di.checkPermittedErrorPrefixes(this._permittedErrorPrefixes,t[e]);if(i)return i}}}getLastMessageElement(){return this.elementRef.children[this.elementRef.children.length-1]}getLastMessageBubbleElement(){var t,e,i;return Array.from((null==(i=null==(e=null==(t=this.getLastMessageElement())?void 0:t.children)?void 0:e[0])?void 0:i.children)||[]).find((t=>t.classList.contains("message-bubble")))}isLastMessageError(){var t;return null==(t=this.getLastMessageBubbleElement())?void 0:t.classList.contains("error-message-text")}removeError(){this.isLastMessageError()&&this.getLastMessageElement().remove()}addLoadingMessage(){var t;if(!this._displayLoadingMessage)return;const e=this.createMessageElements("",!0),{outerContainer:i,bubbleElement:n}=e;n.classList.add("loading-message-text");const s=document.createElement("div");s.classList.add("dots-flashing"),n.appendChild(s),this.applyCustomStyles(e,!0,!1,null==(t=this.messageStyles)?void 0:t.loading),xi.set(n,this.messageStyles),this.elementRef.appendChild(i),this.scrollToBottom()}addNewStreamedMessage(){const{bubbleElement:t}=this.addNewTextMessage("",!0),e=Di.createMessageContent(!0,{text:""});return this.messages.push(e),t.classList.add("streamed-message"),this.scrollToBottom(),t}updateStreamedMessage(t,e){var i,n,s,o,r;const a=bi.isScrollbarAtBottomOfElement(this.elementRef);if(0!==t.trim().length){const t=null==(i=this.messageStyles)?void 0:i.default;e.style.color=(null==(s=null==(n=null==t?void 0:t.ai)?void 0:n.bubble)?void 0:s.color)||(null==(r=null==(o=null==t?void 0:t.shared)?void 0:o.bubble)?void 0:r.color)||""}this._streamedText+=t,this._textElementsToText[this._textElementsToText.length-1][1]=this._streamedText,e.innerHTML=this._remarkable.render(this._streamedText),a&&this.scrollToBottom()}finaliseStreamedMessage(){var t;null!=(t=this.getLastMessageBubbleElement())&&t.classList.contains("streamed-message")&&(this._textElementsToText[this._textElementsToText.length-1][1]=this._streamedText,this.messages[this.messages.length-1].text=this._streamedText,this.sendClientUpdate(Di.createMessageContent(!0,{text:this._streamedText}),!1),this._textToSpeech&&wi.speak(this._streamedText,this._textToSpeech),this._streamedText="")}populateIntroPanel(t,e,i){(t||e)&&(this._introPanel=new Oi(t,e,i),this._introPanel._elementRef&&(ki.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})}}else{const i=t.file.name||Ni.DEFAULT_FILE_NAME;e({name:i,type:"any"})}})))))}clearMessages(t,e){var i,n;const s=[];this._messageElementRefs.forEach((t=>{const e=t.bubbleElement.classList;e.contains("loading-message-text")||e.contains("streamed-message")?s.push(t):t.outerContainer.remove()})),Array.from(this.elementRef.children).forEach((t=>{var e;const i=null==(e=t.children[0])?void 0:e.children[0];null!=i&&i.classList.contains("error-message-text")&&t.remove()})),this._messageElementRefs=s,!1!==e&&(null!=(i=this._introPanel)&&i._elementRef&&this._introPanel.display(),this.addIntroductoryMessage()),this.messages.splice(0,this.messages.length),this._textElementsToText.splice(0,this._textElementsToText.length),null==(n=this._onClearMessages)||n.call(this),delete t.sessionId}scrollToBottom(){this.elementRef.scrollTop=this.elementRef.scrollHeight}refreshTextMessages(){this._remarkable=ie.createNew(),this._textElementsToText.forEach((t=>{t[0].bubbleElement.innerHTML=this._remarkable.render(t[1])}))}}const _i=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,n){0===n["outside-right"].length&&n["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===n["outside-left"].length&&n["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,n){if(!(n["inside-left"].length>0||n["inside-right"].length>0)){if(0===n["outside-right"].length&&n["outside-left"].length>0)return e[0].classList.add(t.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS),n["outside-left"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")));if(0===n["outside-left"].length&&n["outside-right"].length>0)return e[3].classList.add(t.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),i.classList.add(t.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS),n["outside-right"].map((t=>t.button.elementRef.classList.add("submit-button-enlarged")))}}static set(e,i,n,s){!!t.adjustOutsideSubmit(i,n,s)||t.adjustForOutsideButton(i,n,s),t.adjustInputPadding(e,s)}};_i.INPUT_OUTSIDE_LEFT_ADJUSTMENT_CLASS="text-input-container-left-adjustment",_i.INPUT_OUTSIDE_RIGHT_ADJUSTMENT_CLASS="text-input-container-right-adjustment",_i.INPUT_OUTSIDE_LEFT_SMALL_ADJUSTMENT_CLASS="text-input-container-left-small-adjustment",_i.INPUT_OUTSIDE_RIGHT_SMALL_ADJUSTMENT_CLASS="text-input-container-right-small-adjustment";let Ri=_i;class Fi{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 n=Fi.getContainerIndex(i);t[n].appendChild(e),3===n&&e.classList.add("outside-right")}}const Bi=["camera","gifs","images","audio","mixedFiles","submit","microphone"];class Ji{static createTextElement(t){const e=document.createElement("div");return e.classList.add("text-button"),e.innerText=t,e}static createElement(t,e){return e?Ji.createTextElement(t):le.createSVGElement(t)}static createCustomElement(t,e){var i,n,s,o;const r=null==e?void 0:e[t];return null!=(i=null==r?void 0:r.text)&&i.content?Ji.createElement(null==(n=null==r?void 0:r.text)?void 0:n.content,!0):null!=(s=null==r?void 0:r.svg)&&s.content?Ji.createElement(null==(o=null==r?void 0:r.svg)?void 0:o.content,!1):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 n;return i&&(n=Ji.createCustomElement(e,i)),Ji.processElement(t,n),n}static create(t,e,i){const n={};if(!i)return Ji.processElement(t),n;const s=Ji.createSpecificStateElement(t,e[0],i);n[e[0]]=s;let o=s;return e.slice(1).forEach((t=>{o=Ji.createCustomElement(t,i)||o,n[t]=o})),n}}class qi{static unsetAllCSS(t,e){var n,s;e.container&&i.unsetAllCSSMouseStates(t,e.container),null!=(n=e.svg)&&n.styles&&i.unsetAllCSSMouseStates(t.children[0],e.svg.styles),null!=(s=e.text)&&s.styles&&i.unsetAllCSSMouseStates(t.children[0],e.text.styles)}static unsetActionCSS(t,e){var n,s;e.container&&i.unsetActivityCSSMouseStates(t,e.container),null!=(n=e.svg)&&n.styles&&i.unsetActivityCSSMouseStates(t.children[0],e.svg.styles),null!=(s=e.text)&&s.styles&&i.unsetActivityCSSMouseStates(t.children[0],e.text.styles)}static setElementsCSS(t,e,i){var n,s,o,r,a;Object.assign(t.style,null==(n=e.container)?void 0:n[i]),Object.assign(t.children[0].style,null==(o=null==(s=e.svg)?void 0:s.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){qi.setElementsCSS(t,e,"default"),"default"!==i&&(qi.setElementsCSS(t,e,"hover"),"hover"!==i&&qi.setElementsCSS(t,e,"click"))}}class Yi{constructor(t,e,i,n){this._mouseState={state:"default"},this.elementRef=t,this._customStyles=i,this.position=e,this.dropupText=n}buttonMouseLeave(t){this._mouseState.state="default",t&&(qi.unsetAllCSS(this.elementRef,t),qi.setElementsCSS(this.elementRef,t,"default"))}buttonMouseEnter(t){this._mouseState.state="hover",t&&qi.setElementsCSS(this.elementRef,t,"hover")}buttonMouseUp(t){t&&qi.unsetActionCSS(this.elementRef,t),this.buttonMouseEnter(t)}buttonMouseDown(t){this._mouseState.state="click",t&&qi.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],n=i&&this._customStyles[i];n&&qi.unsetActionCSS(this.elementRef,n)}}reapplyStateStyle(t,e){if(!this._customStyles)return;e&&this.unsetCustomStateStyles(e);const i=this._customStyles[t];i&&qi.setElementCssUpToState(this.elementRef,i,this._mouseState.state),this.setEvents(i)}}class $i{static focusItemWhenOnEdge(t,e){const i=e?t.children[0]:t.children[t.children.length-1];$i.focusSiblingItem(i,t,e,!0)}static focusSiblingItem(t,e,i,n=!1){const s=n?t:t[i?"nextSibling":"previousSibling"];s?(t.dispatchEvent(new MouseEvent("mouseleave")),s.dispatchEvent(new MouseEvent("mouseenter"))):(t.dispatchEvent(new MouseEvent("mouseleave")),$i.focusItemWhenOnEdge(e,i))}}class Ui{static addItemEvents(t,e,i,n){Mi.add(e,n),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,n){const s=t.children[0];s.classList.contains("text-button")?e.appendChild(Ui.createItemText(s.textContent,null==n?void 0:n.text)):(e.appendChild(Ui.createItemIcon(t,null==n?void 0:n.iconContainer)),e.appendChild(Ui.createItemText(i,null==n?void 0:n.text)))}static createItem(t,e,n){var s;const{elementRef:o,dropupText:r}=e,a=document.createElement("div");Object.assign(a.style,null==(s=null==n?void 0:n.item)?void 0:s.default),Ui.populateItem(o,a,r,n),a.classList.add("dropup-menu-item");const c=i.processStateful((null==n?void 0:n.item)||{},{backgroundColor:"#f3f3f3"},{backgroundColor:"#ebebeb"});return Ui.addItemEvents(t,a,o,c),a}}class Vi{constructor(t,e){var i;this._isOpen=!0,this._styles=e,this.elementRef=Vi.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=Ui.createItem(this,t,this._styles);this.elementRef.appendChild(e)}addWindowEvents(t){window.addEventListener("click",(e=>{var i;t.parentElement!==(null==(i=e.target.shadowRoot)?void 0:i.children[0])&&this.close()})),window.addEventListener("keydown",(t=>{var e,i,n;this._isOpen&&(t.key===o.ESCAPE?(this.close(),null==(e=this.highlightedItem)||e.dispatchEvent(new MouseEvent("mouseleave"))):t.key===o.ENTER?(null==(i=this.highlightedItem)||i.click(),null==(n=this.highlightedItem)||n.dispatchEvent(new MouseEvent("mouseleave"))):t.key===o.ARROW_DOWN?$i.focusSiblingItem(this.highlightedItem||this.elementRef.children[this.elementRef.children.length-1],this.elementRef,!0):t.key===o.ARROW_UP&&$i.focusSiblingItem(this.highlightedItem||this.elementRef.children[0],this.elementRef,!1))}))}}class Zi extends Yi{constructor(t,e){var i;super(Zi.createButtonElement(),void 0,{styles:null==(i=null==e?void 0:e.button)?void 0:i.styles});const n=this.createInnerElements(this._customStyles);this._menu=new Vi(t,null==e?void 0:e.menu),this.addClickEvent(),this.buttonContainer=Zi.createButtonContainer(),this.elementRef.appendChild(n.styles),this.buttonContainer.appendChild(this.elementRef),this.elementRef.classList.add("dropup-icon","upload-file-button"),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(Zi.createSVGIconElement(),"styles",t)}}createInnerElement(t,e,i){return Ji.createSpecificStateElement(this.elementRef,e,i)||t}static createSVGIconElement(){const t=le.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>');return t.id="dropup-icon",t}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,n;return null!=(i=null==e?void 0:e.button)&&i.position?null==(n=null==e?void 0:e.button)?void 0:n.position:t["outside-left"].length>0&&0===t["outside-right"].length?"outside-right":"outside-left"}}class Hi{static addToDropup(t,e,i,n){const s=new Zi(i,n);Bi.forEach((t=>{const i=e["dropup-menu"].findIndex((e=>e.buttonType===t)),n=e["dropup-menu"][i];n&&(s.addItem(n.button),e["dropup-menu"].splice(i,1))}));const o=Zi.getPosition(e,n);Fi.addButton(t,s.buttonContainer,o),e[o].push({})}static addToSideContainer(t,e){["inside-left","inside-right","outside-left","outside-right"].forEach((i=>{const n=i;e[n].forEach((e=>{Fi.addButton(t,e.button.elementRef,n)}))}))}static setPosition(t,e,i){const n={...t[e],buttonType:e};i.push(n),delete t[e]}static createPositionsObj(){return{"dropup-menu":[],"outside-left":[],"inside-left":[],"inside-right":[],"outside-right":[]}}static generatePositions(t){const e=Hi.createPositionsObj();Object.keys(t).forEach((i=>{var n;const s=null==(n=t[i])?void 0:n.button.position;s&&Hi.setPosition(t,i,e[s])})),0===e["inside-right"].length&&t.submit&&Hi.setPosition(t,"submit",e["inside-right"]),0===e["outside-right"].length&&(t.submit?Hi.setPosition(t,"submit",e["outside-right"]):t.microphone?Hi.setPosition(t,"microphone",e["outside-right"]):t.camera&&Hi.setPosition(t,"camera",e["outside-right"])),t.submit&&Hi.setPosition(t,"submit",0===e["outside-left"].length?e["outside-left"]:e["inside-right"]),t.microphone&&Hi.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?Bi.forEach((i=>{t[i]&&e["dropup-menu"].push({...t[i],buttonType:i})})):1===i.length&&Hi.setPosition(t,i[0],0===e["outside-right"].length?e["outside-right"]:e["outside-left"]),e}static addButtons(t,e,i,n){const s=Hi.generatePositions(e);return Hi.addToSideContainer(t,s),s["dropup-menu"].length>0&&Hi.addToDropup(t,s,i,n),s}}const Gi={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 Ki{constructor(t,e,i,n){this._attachments=[],this._fileCountLimit=99,this._acceptedFormat="",e.maxNumberOfFiles&&(this._fileCountLimit=e.maxNumberOfFiles),this._toggleContainerDisplay=i,this._fileAttachmentsContainerRef=n,e.acceptedFormats&&(this._acceptedFormat=e.acceptedFormats),setTimeout((()=>{this._validationHandler=t._validationHandler}))}attemptAddFile(t,e){return!!Ki.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 n=i[e].trim();if(t.type===n)return!0;if(n.startsWith(".")){const e=n.slice(1);if(t.name.endsWith(e))return!0}else{if(t.name.endsWith(n))return!0;if(n.endsWith("/*")&&t.type.startsWith(n.slice(0,-2)))return!0}}return!1}addAttachmentBasedOnType(t,e,i){if(t.type.startsWith("image")){const n=Ki.createImageAttachment(e);this.addFileAttachment(t,"image",n,i)}else if(t.type.startsWith("audio")){const n=Xi.createAudioAttachment(e);this.addFileAttachment(t,"audio",n,i)}else{const e=Ki.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"),r.IS_SAFARI&&e.classList.add("border-bound-attachment-safari");const i=document.createElement("div");i.classList.add("any-file-attachment-text");const n=document.createElement("div");return n.classList.add("file-attachment-text-container"),n.appendChild(i),i.textContent=t,e.appendChild(n),e}addFileAttachment(t,e,i,n){var s;const o=Ki.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 n&&(r.removeButton=this.createRemoveAttachmentButton(r),o.appendChild(r.removeButton)),this._toggleContainerDisplay(!0),this._attachments.push(r),this._fileAttachmentsContainerRef.scrollTop=this._fileAttachmentsContainerRef.scrollHeight,null==(s=this._validationHandler)||s.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)),n=this._attachments[i].attachmentContainerElement;this._attachments.splice(i,1),Xi.stopAttachmentPlayback(n),n.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 Qi='<?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>',Wi=class t extends Ki{constructor(t,e,i,n){super(t,e,i,n)}static createAudioContainer(){const t=document.createElement("div");return t.classList.add("border-bound-attachment","audio-attachment-icon-container"),r.IS_SAFARI&&t.classList.add("border-bound-attachment-safari"),t}static addAudioElements(t,e){const i=t.parentElement?bi.cloneElement(t):t,n=document.createElement("audio");n.src=e;const s=le.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>');s.classList.add("attachment-icon","play-icon");const o=le.createSVGElement(Qi);o.classList.add("attachment-icon","stop-icon"),i.replaceChildren(s),n.onplay=()=>{i.replaceChildren(o)},n.onpause=()=>{i.replaceChildren(s),n.currentTime=0},n.onended=()=>{i.replaceChildren(s)},i.onclick=()=>{n.paused?n.play():n.pause()}}static createAudioAttachment(e){const i=t.createAudioContainer();return t.addAudioElements(i,e),i}createTimer(e,i){let n=0;const s=void 0!==i&&i<t.TIMER_LIMIT_S?i:t.TIMER_LIMIT_S;return setInterval((()=>{var t;n+=1,n===s&&(null==(t=this.stopPlaceholderCallback)||t.call(this),this.clearTimer()),600===n&&e.classList.add("audio-placeholder-text-4-digits");const i=Math.floor(n/60),o=(n%60).toString().padStart(2,"0");e.textContent=`${i}:${o}`}),1e3)}createPlaceholderAudioAttachment(e){const i=t.createAudioContainer(),n=document.createElement("div");n.classList.add("audio-placeholder-text-3-digits");const s=document.createElement("div");s.classList.add("file-attachment-text-container","audio-placeholder-text-3-digits-container"),s.appendChild(n);const o=le.createSVGElement(Qi);return o.classList.add("attachment-icon","stop-icon","not-removable-attachment-icon"),n.textContent="0:00",this._activePlaceholderTimer=this.createTimer(n,e),i.appendChild(s),this.addPlaceholderAudioAttachmentEvents(i,o,s),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 n=this._activePlaceholderAttachment;n&&(n.file=e,t.addAudioElements(n.attachmentContainerElement.children[0],i),n.removeButton=this.createRemoveAttachmentButton(n),n.attachmentContainerElement.appendChild(n.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,n;null!=(n=null==(i=null==(e=t.children[0])?void 0:e.children)?void 0:i[0])&&n.classList.contains("stop-icon")&&t.children[0].click()}};Wi.TIMER_LIMIT_S=5999;let Xi=Wi;class tn{static create(t,e,i,n,s){return"audio"===s?new Xi(t,e,i,n):new Ki(t,e,i,n)}}class en{constructor(t,e,i){this._fileAttachmentsTypes=[],this.elementRef=this.createAttachmentContainer();const n="object"==typeof i&&!!i.displayFileAttachmentContainer;this.toggleContainerDisplay(n),t.appendChild(this.elementRef),e&&Object.assign(this.elementRef.style,e)}addType(t,e,i){const n=tn.create(t,e,this.toggleContainerDisplay.bind(this),this.elementRef,i);return this._fileAttachmentsTypes.push(n),n}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 n=0;n<e.length&&!e[n].attemptAddFile(t,i.target.result);n+=1);}}))}addFilesToAnyType(t){en.addFilesToType(t,this._fileAttachmentsTypes)}removeAllFiles(){this._fileAttachmentsTypes.forEach((t=>t.removeAllAttachments())),this.elementRef.replaceChildren(),this.toggleContainerDisplay(!1)}getNumberOfTypes(){return this._fileAttachmentsTypes.length}}const nn=class t{constructor(e,i,n){this._isOpen=!1,this._contentRef=t.createModalContent(i,null==n?void 0:n.backgroundColor),this._buttonPanel=t.createButtonPanel(null==n?void 0:n.backgroundColor),this._elementRef=t.createContainer(this._contentRef,n),this._elementRef.appendChild(this._buttonPanel),e.appendChild(this._elementRef),this._backgroundPanelRef=t.createDarkBackgroundPanel(),e.appendChild(this._backgroundPanelRef),this.addWindowEvents()}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=le.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,n){const s=i?t.createSVGButton(e):t.createTextButton(e);return this.addButtons(s),s.onclick=()=>{this.close(),setTimeout((()=>{null==n||n()}),140)},s}static createTextModalFunc(e,i,n){var s;if("object"==typeof i&&null!=(s=i.files)&&s.infoModal){const s=new t(e,["modal-content"],i.files.infoModal.containerStyle);return s.addCloseButton("OK",!1,n),s.openTextModal.bind(s,i.infoModalTextMarkUp||"")}}addWindowEvents(){window.addEventListener("keydown",(t=>{var e,i;this._isOpen&&(t.key===o.ESCAPE?(this.close(),null==(e=this.extensionCloseCallback)||e.call(this)):t.key===o.ENTER&&(this.close(),null==(i=this.extensionCloseCallback)||i.call(this)))}))}};nn.MODAL_CLOSE_TIMEOUT_MS=190;let sn=nn;class on extends Yi{constructor(t,e,i,n,s,o){var r,a,c,l,u,h;super(on.createButtonElement(),null==(r=i.button)?void 0:r.position,i.button,o);const d=this.createInnerElements(n,s,this._customStyles);this._inputElement=on.createInputElement(null==(a=null==i?void 0:i.files)?void 0:a.acceptedFormats),this.addClickEvent(t,i),this.elementRef.replaceChildren(d.styles),this.reapplyStateStyle("styles"),this._fileAttachmentsType=e,this._openModalOnce=!1===(null==(l=null==(c=i.files)?void 0:c.infoModal)?void 0:l.openModalOnce)||null==(h=null==(u=i.files)?void 0:u.infoModal)?void 0:h.openModalOnce}createInnerElements(t,e,i){const n=on.createSVGIconElement(t,e);return{styles:this.createInnerElement(n,"styles",i)}}triggerImportPrompt(t){t.onchange=this.import.bind(this,t),t.click()}import(t){en.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}createInnerElement(t,e,i){return Ji.createSpecificStateElement(this.elementRef,e,i)||t}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button","upload-file-button"),t}static createSVGIconElement(t,e){const i=le.createSVGElement(e);return i.id=t,i}addClickEvent(t,e){const i=this.triggerImportPrompt.bind(this,this._inputElement),n=sn.createTextModalFunc(t,e,i);this.elementRef.onclick=this.click.bind(this,n)}click(t){!t||void 0!==this._openModalOnce&&!0!==this._openModalOnce?this.triggerImportPrompt(this._inputElement):(t(),!0===this._openModalOnce&&(this._openModalOnce=!1))}}class rn{static create(t,e,i){const n=rn.createElement(i);rn.addEvents(n,t,e),t.appendChild(n)}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(),rn.display(t)},t.ondragleave=e=>{e.preventDefault(),rn.hide(t)},t.ondragover=t=>{t.preventDefault()},t.ondrop=e=>{e.preventDefault(),rn.uploadFile(i,e),rn.hide(t)}}static uploadFile(t,e){var i;const n=null==(i=e.dataTransfer)?void 0:i.files;n&&t.addFilesToAnyType(Array.from(n))}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 an{static async useValidationFunc(t,e,i,n,s){const o=e.inputElementRef,r=o.classList.contains("text-input-placeholder")?"":o.textContent;await i.completePlaceholders();const a=i.getAllFileData(),c=t(r,null==a?void 0:a.map((t=>t.file)),s);return c?n.changeToSubmitIcon():n.changeToDisabledIcon(),c}static validateWebsocket(t,e){return!(t.websocket&&!C.canSendMessage(t.websocket))||(e.changeToDisabledIcon(),!1)}static attach(t,e,i,n,s){const o=t.validateInput||N.processValidateInput(t);t._validationHandler=async(t=!1)=>{if(s.status.loadingActive||s.status.requestInProgress||!0===e.isSubmitProgrammaticallyDisabled||!an.validateWebsocket(e,s))return!1;const r=o||e.canSendMessage;return r?an.useValidationFunc(r,i,n,s,t):null}}}class cn extends Yi{constructor(t){"dropup-menu"===(null==t?void 0:t.position)&&(t.position="outside-right"),super(cn.createMicrophoneElement(),null==t?void 0:t.position,t),this.isActive=!1,this._innerElements=this.createInnerElements(this._customStyles),this.changeToDefault()}createInnerElements(t){const e=cn.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 Ji.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=le.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 ln={},un={},hn={},dn={},pn={};Object.defineProperty(pn,"u",{value:!0}),pn.Text=void 0;class mn{static capitalize(t){return t.replace(mn.FIRST_CHAR_REGEX,(t=>t.toUpperCase()))}static lineBreak(t){return t.replace(mn.DOUBLE_LINE,"<p></p>").replace(mn.ONE_LINE,"<br>")}static isCharDefined(t){return void 0!==t&&" "!==t&&" "!==t&&"\n"!==t&&""!==t}static breakupIntoWordsArr(t){return t.split(/(\W+)/)}}pn.Text=mn,mn.FIRST_CHAR_REGEX=/\S/,mn.DOUBLE_LINE=/\n\n/g,mn.ONE_LINE=/\n/g,Object.defineProperty(dn,"u",{value:!0}),dn.Translate=void 0;const fn=pn;dn.Translate=class{static translate(t,e){const i=fn.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(hn,"u",{value:!0}),hn.WebSpeechTranscript=void 0;const vn=dn;hn.WebSpeechTranscript=class{static extract(t,e,i){let n="";for(let s=t.resultIndex;s<t.results.length;++s){let o=t.results[s][0].transcript;i&&(o=vn.Translate.translate(o,i)),t.results[s].isFinal?e+=o:n+=o}return{interimTranscript:n,finalTranscript:e,newText:n||e}}static extractSafari(t,e,i){let n="";for(let e=t.resultIndex;e<t.results.length;++e){let s=t.results[e][0].transcript;i&&(s=vn.Translate.translate(s,i)),n+=s}return{interimTranscript:"",finalTranscript:n,newText:n}}};var gn={};Object.defineProperty(gn,"u",{value:!0}),gn.Browser=void 0;class bn{}gn.Browser=bn,bn.IS_SAFARI=()=>(void 0===bn._IS_SAFARI&&(bn._IS_SAFARI=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),bn._IS_SAFARI);var yn={},wn={};Object.defineProperty(wn,"u",{value:!0}),wn.EventListeners=void 0;class xn{static getElementIfFocusedOnAvailable(t,e){return Array.isArray(t)?t.find((t=>e===t)):e===t?t:void 0}static keyDownWindow(t){t.element&&xn.getElementIfFocusedOnAvailable(t.element,document.activeElement)&&(null!==xn.KEY_DOWN_TIMEOUT&&clearTimeout(xn.KEY_DOWN_TIMEOUT),xn.KEY_DOWN_TIMEOUT=setTimeout((()=>{xn.KEY_DOWN_TIMEOUT=null,this.resetRecording(t)}),500))}static mouseDownWindow(t,e){this.mouseDownElement=xn.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=xn.mouseDownWindow.bind(t,e.element),document.addEventListener("mousedown",t.mouseDownEvent),t.mouseUpEvent=xn.mouseUpWindow.bind(t,e),document.addEventListener("mouseup",t.mouseUpEvent),t.keyDownEvent=xn.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)}}wn.EventListeners=xn,xn.KEY_DOWN_TIMEOUT=null;var Mn={};Object.defineProperty(Mn,"u",{value:!0}),Mn.PreResultUtils=void 0;Mn.PreResultUtils=class{static process(t,e,i,n,s){const o=null==n?void 0:n(e,i);return!!o&&(setTimeout((()=>{o.restart?t.resetRecording(s):o.stop&&t.stop()})),(o.stop||o.restart)&&o.removeNewText)}};var kn={},jn={};Object.defineProperty(jn,"u",{value:!0}),jn.AutoScroll=void 0;class Sn{static changeStateIfNeeded(t,e){e&&!t.isCursorAtEnd&&(t.endPadding="",t.scrollingSpan.innerHTML=" ")}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&&Sn.isElementOverflown(e)}}jn.AutoScroll=Sn;var An={};Object.defineProperty(An,"u",{value:!0}),An.Elements=void 0;An.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 Tn={};Object.defineProperty(Tn,"u",{value:!0}),Tn.Cursor=void 0;class On{static setOffsetForGeneric(t,e,i=0){let n=0;for(let s=0;s<t.childNodes.length;s+=1){const o=t.childNodes[s];if(o.childNodes.length>0){const t=On.setOffsetForGeneric(o,e,i);if(-1===t)return-1;i+=t}else if(null!==o.textContent){if(i+o.textContent.length>e){const n=document.createRange();n.setStart(o,e-i),n.collapse(!0);const s=window.getSelection();return null==s||s.removeAllRanges(),null==s||s.addRange(n),t.focus(),-1}i+=o.textContent.length,n+=o.textContent.length}}return n}static focusEndOfGeneric(t){const e=document.createRange();e.selectNodeContents(t),e.collapse(!1);const i=window.getSelection();i&&(i.removeAllRanges(),i.addRange(e))}static setOffsetForSafariGeneric(t,e){const i=window.getSelection();if(i){const n=On.getGenericElementCursorOffset(t,i,!0);console.log(n),setTimeout((()=>{}),100),On.setOffsetForGeneric(t,n+e)}}static setOffsetForPrimitive(t,e,i){i&&t.blur(),t.setSelectionRange(e,e),t.focus()}static getGenericElementCursorOffset(t,e,i){let n=0;if(e.rangeCount>0){const s=e.getRangeAt(0),o=s.cloneRange();o.selectNodeContents(t),i?o.setEnd(s.startContainer,s.startOffset):o.setEnd(s.endContainer,s.endOffset),n=o.toString().length}return n}}Tn.Cursor=On,Object.defineProperty(kn,"u",{value:!0}),kn.CommandUtils=void 0;const Cn=jn,Nn=An,In=gn,En=Tn,zn=pn;class Ln{static processCommand(t,e){return(!e||!e.caseSensitive)&&(t=t.toLowerCase()),!1===(null==e?void 0:e.substrings)?zn.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 n=t[i];return e[i]="string"==typeof n?Ln.processCommand(n,t.settings):n,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,n){Ln.toggleCommandModeOff(t),Nn.Elements.isPrimitiveElement(n)?(n.value=i,t.isTargetInShadow||En.Cursor.setOffsetForPrimitive(n,i.length,!0),In.Browser.IS_SAFARI()&&t.autoScroll&&Cn.AutoScroll.scrollSafariPrimitiveToEnd(n)):(n.textContent=i,t.isTargetInShadow||En.Cursor.focusEndOfGeneric(n),setTimeout((()=>Cn.AutoScroll.scrollGeneric(t,n)))),t.resetRecording(e)}static checkIfMatchesSubstring(t,e){return e.includes(t)}static checkIfMatchesWord(t,e,i){const n=t;for(let t=i.length-1;t>=0;t-=1){let e=t,s=n.length-1;for(;i[e]===n[s]&&s>=0;)e-=1,s-=1;if(s<0)return!0}return!1}static execCommand(t,e,i,n,s){var o,r,a;const c=t.commands;if(!c||!n||!i)return;const l=!0===(null===(o=c.settings)||void 0===o?void 0:o.caseSensitive)?e:e.toLowerCase(),u=zn.Text.breakupIntoWordsArr(l),h=!1===(null===(r=c.settings)||void 0===r?void 0:r.substrings)?Ln.checkIfMatchesWord:Ln.checkIfMatchesSubstring;if(c.commandMode&&h(c.commandMode,l,u))return t.setInterimColorToFinal(),setTimeout((()=>Ln.toggleCommandModeOn(t))),{doNotProcessTranscription:!1};if(!c.commandMode||t.isWaitingForCommand){if(c.stop&&h(c.stop,l,u))return Ln.toggleCommandModeOff(t),setTimeout((()=>t.stop())),{doNotProcessTranscription:!1};if(c.pause&&h(c.pause,l,u))return Ln.toggleCommandModeOff(t),t.setInterimColorToFinal(),setTimeout((()=>{var e;t.isPaused=!0,null===(e=t.onPauseTrigger)||void 0===e||e.call(t,!0)})),{doNotProcessTranscription:!1};if(c.resume&&h(c.resume,l,u))return t.isPaused=!1,null===(a=t.onPauseTrigger)||void 0===a||a.call(t,!1),Ln.toggleCommandModeOff(t),t.resetRecording(i),{doNotProcessTranscription:!0};if(c.reset&&h(c.reset,l,u))return void 0!==s&&Ln.setText(t,i,s,n),{doNotProcessTranscription:!0};if(c.removeAllText&&h(c.removeAllText,l,u))return Ln.setText(t,i,"",n),{doNotProcessTranscription:!0}}}}kn.CommandUtils=Ln;var Pn={};Object.defineProperty(Pn,"u",{value:!0}),Pn.Highlight=void 0;const Dn=An,_n=Tn;class Rn{static setStateForPrimitive(t,e){let i,n;null!==e.selectionStart&&(i=e.selectionStart),null!==e.selectionEnd&&(n=e.selectionEnd),t.isHighlighted=i!==n}static setStateForGeneric(t,e){const i=window.getSelection();if(null!=i&&i.focusNode){const n=_n.Cursor.getGenericElementCursorOffset(e,i,!0),s=_n.Cursor.getGenericElementCursorOffset(e,i,!1);t.isHighlighted=n!==s}}static setState(t,e){document.activeElement===e&&(Dn.Elements.isPrimitiveElement(e)?Rn.setStateForPrimitive(t,e):Rn.setStateForGeneric(t,e))}static removeForGeneric(t,e){const i=window.getSelection();if(i){const n=_n.Cursor.getGenericElementCursorOffset(e,i,!0);i.deleteFromDocument(),_n.Cursor.setOffsetForGeneric(e,n),t.isHighlighted=!1}}static removeForPrimitive(t,e){const i=e.selectionStart,n=e.selectionEnd,s=e.value;if(i&&n){const o=s.substring(0,i)+s.substring(n);e.value=o,_n.Cursor.setOffsetForPrimitive(e,i,t.autoScroll)}t.isHighlighted=!1}}Pn.Highlight=Rn;var Fn={};Object.defineProperty(Fn,"u",{value:!0}),Fn.Padding=void 0;const Bn=An,Jn=Tn,qn=pn;class Yn{static setStateForPrimitiveElement(t,e){if(document.activeElement===e&&null!==e.selectionStart){const i=e.selectionStart,n=e.value[i-1],s=null===e.selectionEnd?i:e.selectionEnd,o=e.value[s];return qn.Text.isCharDefined(n)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),qn.Text.isCharDefined(o)&&(t.endPadding=" ",t.numberOfSpacesAfterNewText=1),void(t.isCursorAtEnd=e.value.length===s)}const i=e.value[e.value.length-1];qn.Text.isCharDefined(i)&&(t.startPadding=" ",t.numberOfSpacesBeforeNewText=1),t.isCursorAtEnd=!0}static setStateForGenericElement(t,e){var i,n,s;if(document.activeElement===e){const o=window.getSelection();if(null!=o&&o.focusNode){const r=Jn.Cursor.getGenericElementCursorOffset(e,o,!0),a=null===(i=e.textContent)||void 0===i?void 0:i[r-1],c=Jn.Cursor.getGenericElementCursorOffset(e,o,!1),l=null===(n=e.textContent)||void 0===n?void 0:n[c];return qn.Text.isCharDefined(a)&&(t.startPadding=" "),qn.Text.isCharDefined(l)&&(t.endPadding=" "),void(t.isCursorAtEnd=(null===(s=e.textContent)||void 0===s?void 0:s.length)===c)}}const o=e.innerText.charAt(e.innerText.length-1);qn.Text.isCharDefined(o)&&(t.startPadding=" "),t.isCursorAtEnd=!0}static setState(t,e){Bn.Elements.isPrimitiveElement(e)?Yn.setStateForPrimitiveElement(t,e):Yn.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)}}Fn.Padding=Yn,Object.defineProperty(yn,"u",{value:!0}),yn.Speech=void 0;const $n=wn,Un=Mn,Vn=kn,Zn=jn,Hn=Pn,Gn=An,Kn=Fn,Qn=gn,Wn=Tn,Xn=pn;yn.Speech=class{constructor(){this.finalTranscript="",this.interimSpan=Gn.Elements.createInterimSpan(),this.finalSpan=Gn.Elements.createGenericSpan(),this.scrollingSpan=Gn.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($n.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,Gn.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=Vn.CommandUtils.process(this._options.commands))}prepare(t){Kn.Padding.setState(this,t),Hn.Highlight.setState(this,t),this.isTargetInShadow=Gn.Elements.isInsideShadowDOM(t),Gn.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 n;const s=Xn.Text.capitalize(e);if(this.finalTranscript===s&&""===t)return;Un.PreResultUtils.process(this,i,""===t,this._onPreResult,this._options)&&(t="",i="");const o=this.commands&&Vn.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===(n=this._onResult)||void 0===n||n.call(this,i,""===t),this.finalTranscript=s,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&&Hn.Highlight.removeForPrimitive(this,t),this.primitiveTextRecorded||Kn.Padding.adjustStateAfterRecodingPrimitiveElement(this,t),i&&Kn.Padding.adjustSateForNoTextPrimitiveElement(this);const n=this.startPadding+this.finalTranscript+e;if(t.value=n+this.endPadding,!this.isTargetInShadow){const e=n.length+this.numberOfSpacesAfterNewText;Wn.Cursor.setOffsetForPrimitive(t,e,this.autoScroll)}this.autoScroll&&Qn.Browser.IS_SAFARI()&&this.isCursorAtEnd&&Zn.AutoScroll.scrollSafariPrimitiveToEnd(t)}updateGenericElement(t,e,i){this.isHighlighted&&Hn.Highlight.removeForGeneric(this,t),this.spansPopulated||Gn.Elements.appendSpans(this,t);const n=(i?"":this.startPadding)+Xn.Text.lineBreak(this.finalTranscript);this.finalSpan.innerHTML=n;const s=Zn.AutoScroll.isRequired(this.autoScroll,t);Zn.AutoScroll.changeStateIfNeeded(this,s);const o=Xn.Text.lineBreak(e)+(i?"":this.endPadding);this.interimSpan.innerHTML=o,Qn.Browser.IS_SAFARI()&&this.insertInCursorLocation&&Wn.Cursor.setOffsetForSafariGeneric(t,n.length+o.length),s&&Zn.AutoScroll.scrollGeneric(this,t),i&&(this.scrollingSpan.innerHTML="")}finalise(t){this._genericElement&&(t?(this.finalSpan=Gn.Elements.createGenericSpan(),this.setInterimColorToFinal(),this.interimSpan=Gn.Elements.createInterimSpan(),this.scrollingSpan=Gn.Elements.createGenericSpan()):this._genericElement.textContent=this._genericElement.textContent,this.spansPopulated=!1),$n.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(un,"u",{value:!0}),un.WebSpeech=void 0;const ts=hn,es=gn,is=yn;class ns extends is.Speech{constructor(){super()}start(t){var e;void 0===this._extractText&&(this._extractText=es.Browser.IS_SAFARI()?ts.WebSpeechTranscript.extractSafari:ts.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!!ns.getAPI()||(this.error("Speech Recognition is unsupported"),!1)}instantiateService(t){var e,i;const n=ns.getAPI();this._service=new n,this._service.continuous=!0,this._service.interimResults=null===(e=null==t?void 0:t.displayInterimResults)||void 0===e||e,this._service.lang=(null===(i=null==t?void 0:t.language)||void 0===i?void 0:i.trim())||"en-US",this.setEvents()}setEvents(){this._service&&(this._service.onstart=()=>{this.setStateOnStart()},this._service.onerror=t=>{es.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:n}=this._extractText(t,this.finalTranscript,this._translations);this.updateElements(e,i,n)}})}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()}}un.WebSpeech=ns;var ss={};Object.defineProperty(ss,"u",{value:!0}),ss.GlobalState=void 0;class os{static doubleClickDetector(){return!!os.doubleClickPending||(os.doubleClickPending=!0,setTimeout((()=>{os.doubleClickPending=!1}),300),!1)}}ss.GlobalState=os,os.doubleClickPending=!1;var rs={},as={};Object.defineProperty(as,"u",{value:!0}),as.PreventConnectionStop=void 0;as.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 cs={},ls={};Object.defineProperty(ls,"u",{value:!0}),ls.README_URL=void 0,ls.README_URL="https://github.com/OvidijusParsiunas/speech-to-element",Object.defineProperty(cs,"u",{value:!0}),cs.AzureSpeechConfig=void 0;const us=ls;class hs{static validateOptions(t,e){return e?e.subscriptionKey||e.token||e.retrieveToken?!!e.region||(t(`Please define a 'region' property - more info: ${us.README_URL}`),!1):(t(`Please define a 'subscriptionKey', 'token' or 'retrieveToken' property - more info: ${us.README_URL}`),!1):(t(`Please provide subscription details - more info: ${us.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 hs.getNewSpeechConfig(t,e);return i&&hs.process(i,e),i}}cs.AzureSpeechConfig=hs;var ds={};Object.defineProperty(ds,"u",{value:!0}),ds.StopTimeout=void 0;class ps{static set(t){t.stopTimeout=setTimeout((()=>t.stop()),t.stopTimeoutMS)}static reset(t,e){t.stopTimeoutMS=e||ps.DEFAULT_MS,t.stopTimeout&&clearTimeout(t.stopTimeout),ps.set(t)}}ds.StopTimeout=ps,ps.DEFAULT_MS=2e4;var ms={};Object.defineProperty(ms,"u",{value:!0}),ms.AzureTranscript=void 0;const fs=dn;ms.AzureTranscript=class{static extract(t,e,i,n){return n&&(t=fs.Translate.translate(t,n)),i?{interimTranscript:"",finalTranscript:e+t,newText:t}:{interimTranscript:t,finalTranscript:e,newText:t}}},Object.defineProperty(rs,"u",{value:!0}),rs.Azure=void 0;const vs=as,gs=cs,bs=ds,ys=ms,ws=yn;class xs extends ws.Speech{constructor(){super(...arguments),this._newTextPadding=""}start(t,e){this._newTextPadding="",void 0===this.stopTimeout&&bs.StopTimeout.reset(this,null==t?void 0:t.stopAfterSilenceMs),this.prepareBeforeStart(t),this.startAsync(t),e||vs.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 xs.getAPI()?gs.AzureSpeechConfig.validateOptions(this.error.bind(this),t):(this.moduleNotFound(),!1)}async instantiateService(t){const e=xs.getAPI(),i=e.AudioConfig.fromDefaultMicrophoneInput(),n=await gs.AzureSpeechConfig.get(e.SpeechConfig,t);if(n){const s=new e.SpeechRecognizer(n,i);this.setEvents(s),this._service=s,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:n,newText:s}=ys.AzureTranscript.extract(this._newTextPadding+e.result.text,this.finalTranscript,!1,this._translations);bs.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(i,n,s)}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:n}=ys.AzureTranscript.extract(this._newTextPadding+i.text,this.finalTranscript,!0,this._translations);bs.StopTimeout.reset(this,this.stopTimeoutMS),this.updateElements(t,e,n),""!==e&&(this._newTextPadding=" ")}}}onCanceled(t,e){e.reason===window.SpeechSDK.CancellationReason.Error&&this.error(e.errorDetails)}onSessionStarted(){vs.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()}}rs.Azure=xs,Object.defineProperty(ln,"u",{value:!0});const Ms=un,ks=kn,js=ss,Ss=rs;class As{static toggle(t,e){var i,n;const s=t.toLocaleLowerCase().trim();null!==(i=js.GlobalState.service)&&void 0!==i&&i.recognizing?this.stop():"webspeech"===s?As.startWebSpeech(e):"azure"===s?As.startAzure(e):(console.error("service not found - must be either 'webspeech' or 'azure'"),null===(n=null==e?void 0:e.onError)||void 0===n||n.call(e,"service not found - must be either 'webspeech' or 'azure'"))}static startWebSpeech(t){As.stop()||(js.GlobalState.service=new Ms.WebSpeech,js.GlobalState.service.start(t))}static isWebSpeechSupported(){return!!Ms.WebSpeech.getAPI()}static startAzure(t){var e;As.stop()||null!==(e=js.GlobalState.service)&&void 0!==e&&e.cannotBeStopped||(js.GlobalState.service=new Ss.Azure,js.GlobalState.service.start(t))}static stop(){var t;return!!js.GlobalState.doubleClickDetector()||(!(null===(t=js.GlobalState.service)||void 0===t)&&t.recognizing&&js.GlobalState.service.stop(),!1)}static endCommandMode(){js.GlobalState.service&&ks.CommandUtils.toggleCommandModeOff(js.GlobalState.service)}}var Ts=ln.default=As;class Os extends cn{constructor(t,e,i){var n;super("object"==typeof t.speechToText?null==(n=t.speechToText)?void 0:n.button:{});const{serviceName:s,processedConfig:o}=Os.processConfiguration(e,t.speechToText);if(this._addErrorMessage=i,"webspeech"!==s||Ts.isWebSpeechSupported()){const i=!t.textInput||!t.textInput.disabled;this.elementRef.onclick=this.buttonClick.bind(this,e,i,s,o)}else this.changeToUnsupported()}static processConfiguration(t,e){var i;const n="object"==typeof e?e:{},s="object"==typeof n.webSpeech?n.webSpeech:{},o=n.azure||{},r={displayInterimResults:n.displayInterimResults??void 0,textColor:n.textColor??void 0,translations:n.translations??void 0,commands:n.commands??void 0,...s,...o},a=null==(i=n.commands)?void 0:i.submit;return a&&(r.onPreResult=e=>e.toLowerCase().includes(a)?(setTimeout((()=>{var e;return null==(e=t.submit)?void 0:e.call(t)})),Ts.endCommandMode(),{restart:!0,removeNewText:!0}):null),{serviceName:Os.getServiceName(n),processedConfig:r}}static getServiceName(t){return t.webSpeech?"webspeech":t.azure?"azure":"webspeech"}buttonClick(t,e,i,n){t.removeTextIfPlaceholder(),Ts.toggle(i,{insertInCursorLocation:!1,element:e?t.inputElementRef:void 0,onError:this.onError.bind(this),onStart:this.changeToActive.bind(this),onStop:this.changeToDefault.bind(this),onCommandModeTrigger:this.onCommandModeTrigger.bind(this),...n})}onCommandModeTrigger(t){t?this.changeToCommandMode():this.changeToActive()}onError(){this._addErrorMessage("speechToText","speech input error")}}class Cs{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 Ns extends cn{constructor(t,e){var i,n;super(e.button),this._waitingForBrowserApproval=!1,this._audioType=t,this._extension=(null==(i=e.files)?void 0:i.format)||"mp3",this._maxDurationSeconds=null==(n=e.files)?void 0:n.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=Cs.getFileName(this._newFilePrefix||"audio",this._extension),n=new File([e],i,{type:e.type}),s=new FileReader;s.readAsDataURL(n),s.onload=t=>{this._audioType.completePlaceholderAttachment(n,t.target.result)}}}class Is{static setPropertyValueIfDoesNotExist(t,e,i){const n=e[0];1===e.length?t[n]??(t[n]=i):(t[n]??(t[n]={}),e.shift(),Is.setPropertyValueIfDoesNotExist(t[n],e,i))}static setPropertyValue(t,e,i){const n=e[0];1===e.length?t[n]=i:(t[n]??(t[n]={}),e.shift(),Is.setPropertyValue(t[n],e,i))}static getObjectValue(t,e){const i=t[e[0]];return void 0===i||1===e.length?i:Is.getObjectValue(i,e.slice(1))}static overwritePropertyObjectFromAnother(t,e,i){const n=Is.getObjectValue(e,i);if(n){const e={...n,...Is.getObjectValue(t,i)||{}};Is.setPropertyValue(t,i,e)}}}class Es{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]||{}));Is.overwritePropertyObjectFromAnother(i,t.submit,["container","default"]),Is.overwritePropertyObjectFromAnother(i,t.submit,["text","styles","default"]),Is.overwritePropertyObjectFromAnother(i,t.submit,["svg","styles","default"]),t[e]=i}static setUpDisabledButton(t){Is.setPropertyValueIfDoesNotExist(t,["submit","container","default","backgroundColor"],""),Is.setPropertyValueIfDoesNotExist(t,["disabled","container","default","backgroundColor"],"unset"),Is.setPropertyValueIfDoesNotExist(t.submit,["svg","styles","default","filter"],""),Is.setPropertyValueIfDoesNotExist(t.disabled,["svg","styles","default","filter"],"brightness(0) saturate(100%) invert(70%) sepia(0%) saturate(5564%) hue-rotate(207deg) brightness(100%) contrast(97%)"),Es.overwriteDefaultStyleWithSubmit(t,"disabled")}static process(t){const e=JSON.parse(JSON.stringify(t||{}));return Es.overwriteDefaultStyleWithSubmit(e,"loading"),Es.overwriteDefaultStyleWithSubmit(e,"stop"),null!=t&&t.alwaysEnabled||Es.setUpDisabledButton(e),e}}const zs=class t extends Yi{constructor(e,i,n,s,o){const r=Es.process(e.submitButtonStyles);super(t.createButtonContainerElement(),null==r?void 0:r.position,r),this._isSVGLoadingIconOverriden=!1,this.status={requestInProgress:!1,loadingActive:!1},this._messages=n,this._inputElementRef=i,this._fileAttachments=o,this._innerElements=this.createInnerElements(),this._abortStream=new AbortController,this._stopClicked={listener:()=>{}},this._serviceIO=s,this._alwaysEnabled=!(null==r||!r.alwaysEnabled),e.disableSubmitButton=this.disableSubmitButton.bind(this,s),this.attemptOverwriteLoadingStyle(e),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:n}=Ji.create(this.elementRef,["submit","loading","stop"],this._customStyles),s=e||t.createSubmitIconElement();return{submit:s,loading:i||t.createLoadingIconElement(),stop:n||t.createStopIconElement(),disabled:this.createDisabledIconElement(s)}}static createButtonContainerElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSubmitIconElement(){const t=le.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("dots-jumping"),t}static createStopIconElement(){const t=document.createElement("div");return t.id="stop-icon",t}createDisabledIconElement(t){return Ji.createCustomElement("disabled",this._customStyles)||t.cloneNode(!0)}attemptOverwriteLoadingStyle(t){var e,i,n,s,o,r,a,c,l;if(!(null!=(i=null==(e=this._customStyles)?void 0:e.submit)&&i.svg||null!=(o=null==(s=null==(n=this._customStyles)?void 0:n.loading)?void 0:s.svg)&&o.content||null!=(c=null==(a=null==(r=this._customStyles)?void 0:r.loading)?void 0:a.text)&&c.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==(l=t.shadowRoot)||l.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.deepChat;"object"==typeof e&&"number"==typeof e.simulation&&(this._serviceIO.streamHandlers.simulationInterim=e.simulation)}resetSubmit(t){this.status.requestInProgress=!1,this.status.loadingActive=!1,t()}submitFromInput(){var t;if(this._inputElementRef.classList.contains("text-input-placeholder"))this.submit(!1,"");else{const e=null==(t=this._inputElementRef.textContent)?void 0:t.trim();this.submit(!1,e)}}async submit(t,e){var i,n;let s,o;if(t||(await this._fileAttachments.completePlaceholders(),s=this._fileAttachments.getAllFileData(),o=null==s?void 0:s.map((t=>t.file))),!1===await(null==(i=this._validationHandler)?void 0:i.call(this,t)))return;this.changeToLoadingIcon(),await this.addNewMessages(e,s),this._messages.addLoadingMessage(),t||h.clear(this._inputElementRef);const r={text:""===e?void 0:e,files:o};await this._serviceIO.callAPI(r,this._messages),t||null==(n=this._fileAttachments)||n.removeAllFiles()}async addNewMessages(t,e){const i={};""!==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,!1)}stopStream(){var t;this._abortStream.abort(),null==(t=this._stopClicked)||t.listener()}changeToStopIcon(){this.elementRef.classList.remove(t.LOADING_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),Es.resetSubmit(this,this.status.loadingActive),this.elementRef.onclick=this.submitFromInput.bind(this))}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))}};zs.SUBMIT_CLASS="submit-button",zs.LOADING_CLASS="loading-button",zs.DISABLED_CLASS="disabled-button";let Ls=zs;class Ps extends sn{constructor(t,e,i,n){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:s,submitButton:o}=this.addButtonsAndTheirEvents(e);this._captureButton=s,this._submitButton=o,this._captureIcon=this._captureButton.children[0],this._refreshIcon=le.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==n?void 0:n.format)&&(this._format="image/jpeg"),null!=n&&n.dimensions&&(this._dimensions=n.dimensions),this._contentRef.appendChild(this._canvas),this.extensionCloseCallback=this.stop}addButtonsAndTheirEvents(t){const e=sn.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 n=sn.createSVGButton('<?xml version="1.0" encoding="utf-8"?>\n<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M4.89163 13.2687L9.16582 17.5427L18.7085 8" stroke="#000000" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>\n</svg>');return n.classList.add("modal-svg-submit-button"),this.addButtons(e,n),this.addButtonEvents(e,i,n,t),{captureButton:e,submitButton:n}}addButtonEvents(t,e,i,n){t.onclick=()=>{this.capture()},e.addEventListener("click",this.stop.bind(this)),i.onclick=()=>{const t=this.getFile();t&&en.addFilesToType([t],[n]),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)}),sn.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),n=new Blob([i],{type:this._format}),s="image/jpeg"===this._format?"jpeg":"png",o=Cs.getFileName(this._newFilePrefix||"photo",s);return new File([n],o,{type:n.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,n){const s=new Ps(t,e,i,n);return s.openCameraModal.bind(s,s)}}class Ds extends Yi{constructor(t,e,i){var n;super(Ds.createButtonElement(),null==(n=null==i?void 0:i.button)?void 0:n.position,(null==i?void 0:i.button)||{},"Photo");const s=this.createInnerElements(this._customStyles);i&&this.addClickEvent(t,e,i.modalContainerStyle,i.files),this.elementRef.classList.add("upload-file-button"),this.elementRef.appendChild(s.styles),this.reapplyStateStyle("styles")}createInnerElements(t){return{styles:this.createInnerElement(Ds.createSVGIconElement(),"styles",t)}}createInnerElement(t,e,i){return Ji.createSpecificStateElement(this.elementRef,e,i)||t}static createButtonElement(){const t=document.createElement("div");return t.classList.add("input-button"),t}static createSVGIconElement(){const t=le.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,n){const s=Ps.createCameraModalFunc(t,e,i,n);this.elementRef.onclick=s}}class _s{constructor(t,e,i,n){this.elementRef=_s.createPanelElement(t.inputAreaStyle);const s=new h(t,i),o={},r=this.createFileUploadComponents(t,i,n,o);t.speechToText&&!o.microphone&&(o.microphone={button:new Os(t,s,e.addNewErrorMessage.bind(e))});const a=new Ls(t,s.inputElementRef,e,i,r);s.submit=a.submitFromInput.bind(a),an.attach(t,i,s,r,a),t.submitUserMessage=a.submit.bind(a,!0),o.submit={button:a},_s.addElements(this.elementRef,s,o,n,r,t.dropupStyles)}static createPanelElement(t){const e=document.createElement("div");return e.id="input",Object.assign(e.style,t),e}createFileUploadComponents(t,e,i,n){var s,o,r,a;const c=new en(this.elementRef,t.attachmentContainerStyle,e.demo);if(_s.createUploadButtons(t,e.fileTypes||{},c,i,n),null!=(s=e.camera)&&s.files){const s=(null==(o=n.images)?void 0:o.fileType)||c.addType(t,e.camera.files,"images");n.camera={button:new Ds(i,s,e.camera)}}if(null!=(r=e.recordAudio)&&r.files){const i=(null==(a=n.audio)?void 0:a.fileType)||c.addType(t,e.recordAudio.files,"audio");n.microphone={button:new Ns(i,e.recordAudio)}}return rn.isEnabled(c,t.dragAndDrop)&&rn.create(i,c,t.dragAndDrop),c}static createUploadButtons(t,e,i,n,s){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:c,dropupText:l}=Gi[r],u=new on(n,e,a,o,c,l);s[r]={button:u,fileType:e}}}))}static addElements(t,e,i,n,s,o){bi.addElements(t,e.elementRef);const r=Fi.create(),a=Hi.addButtons(r,i,n,o);Ri.set(e.inputElementRef,r,s.elementRef,a),Fi.add(t,r)}}class Rs{static createElements(t,e,i){const n=document.createElement("div");n.id="chat-view";const s=new Di(t,e,i);e.websocket&&C.createConnection(e,s);const o=new _s(t,s,e,n);return bi.addElements(n,s.elementRef,o.elementRef),n}static render(t,e,i,n){const s=Rs.createElements(t,i,n);e.replaceChildren(s)}}var Fs=Object.defineProperty,Bs=Object.getOwnPropertyDescriptor,Js=(t,e,i,n)=>{for(var s,o=n>1?void 0:n?Bs(e,i):e,r=t.length-1;r>=0;r--)(s=t[r])&&(o=(n?s(e,i,o):s(o))||o);return n&&o&&Fs(e,i,o),o};class qs extends ce{constructor(){super(),this.getMessages=()=>[],this.submitUserMessage=()=>console.warn("submitUserMessage failed - please wait for chat view to render before calling this property."),this.focusInput=()=>d.focusFromParentElement(this._elementRef),this.refreshMessages=()=>{},this.clearMessages=()=>{},this.scrollToBottom=()=>{},this.disableSubmitButton=()=>{},this.onNewMessage=()=>{},this.onClearMessages=()=>{},this.onComponentRender=()=>{},this._hasBeenRendered=!1,this._auxiliaryStyleApplied=!1,pi.appendStyleSheetToHead(),this._elementRef=document.createElement("div"),this._elementRef.id="container",this.attachShadow({mode:"open"}).appendChild(this._elementRef),s.apply('#validate-property-key-view{height:100%;position:relative;display:flex;justify-content:center;align-items:center;padding:8px}#large-loading-ring{display:inline-block;width:50px;height:50px}#large-loading-ring:after{content:" ";display:block;width:38px;height:38px;margin:1px;border-radius:50%;border:5px solid #5fb2ff;border-color:#5fb2ff transparent #5fb2ff transparent;animation:large-loading-ring 1.4s linear infinite}@keyframes large-loading-ring{0%{transform:rotate(0)}to{transform:rotate(360deg)}}#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-ring{display:inline-block;width:16px;height:16px}#loading-ring: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-ring 1.2s linear infinite}@keyframes loading-ring{0%{transform:rotate(0)}to{transform:rotate(360deg)}}#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}.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}.html-message{max-width:unset}.error-message-text{margin:14px auto 10px;background-color:#f4c0c0;color:#474747;text-align:center;max-width:95%}.loading-message-text{width:1em;padding:.6em .75em .6em 1.3em}.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}.dots-jumping{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:dots-jumping 1.5s infinite linear;bottom:-.7em}@keyframes dots-jumping{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}}.dots-flashing{position:relative;width:.45em;height:.45em;border-radius:5px;background-color:var(--message-dots-color);color:var(--message-dots-color);animation:dots-flashing 1s infinite linear alternate;animation-delay:.5s}.dots-flashing:before,.dots-flashing:after{content:"";display:inline-block;position:absolute;top:0}.dots-flashing:before{left:-.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--message-dots-color);color:var(--message-dots-color);animation:dots-flashing 1s infinite alternate;animation-delay:0s}.dots-flashing:after{left:.7em;width:.45em;height:.45em;border-radius:5px;background-color:var(--message-dots-color);color:var(--message-dots-color);animation:dots-flashing 1s infinite alternate;animation-delay:1s}@keyframes dots-flashing{0%{background-color:var(--message-dots-color)}50%,to{background-color:var(--message-dots-color-fade)}}.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}.text-input-placeholder{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}:host{all:initial;display:table-cell}#container{height:inherit;width:inherit;overflow:hidden}\n',this.shadowRoot),setTimeout((()=>{this._hasBeenRendered||this.onRender()}),20)}getCurrentWeather(t){return(t=t.toLowerCase()).includes("tokyo")?JSON.stringify({location:t,temperature:"10",unit:"celsius"}):t.includes("san francisco")?JSON.stringify({location:t,temperature:"72",unit:"fahrenheit"}):JSON.stringify({location:t,temperature:"22",unit:"celsius"})}getCurrentWeather2(t){return console.log("location"),console.log(t),(t=t.toLowerCase()).includes("tokyo")?"Good":t.includes("san francisco")?"Mild":"Very Hot"}changeToChatView(){this._activeService&&(this._activeService.validateConfigKey=!1),this.onRender()}onRender(){this._activeService??(this._activeService=hi.create(this)),this._activeService&&(this.auxiliaryStyle&&!this._auxiliaryStyleApplied&&(s.apply(this.auxiliaryStyle,this.shadowRoot),this._auxiliaryStyleApplied=!0),s.applyDefaultStyleToComponent(this.style),N.checkForContainerStyles(this,this._elementRef),this._activeService.key&&this._activeService.validateConfigKey?e.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):this._activeService instanceof oe&&!this._activeService.key?this._activeService instanceof oe&&de.render(this._elementRef,this.changeToChatView.bind(this),this._activeService):(this._childElement??(this._childElement=this.children[0]),Rs.render(this,this._elementRef,this._activeService,this._childElement)),this._hasBeenRendered=!0,vi.onRender(this))}}Js([fi("object")],qs.prototype,"directConnection",2),Js([fi("object")],qs.prototype,"request",2),Js([fi("object")],qs.prototype,"stream",2),Js([fi("object")],qs.prototype,"requestBodyLimits",2),Js([fi("function")],qs.prototype,"requestInterceptor",2),Js([fi("function")],qs.prototype,"responseInterceptor",2),Js([fi("function")],qs.prototype,"validateInput",2),Js([fi("object")],qs.prototype,"attachmentContainerStyle",2),Js([fi("object")],qs.prototype,"dropupStyles",2),Js([fi("object")],qs.prototype,"inputAreaStyle",2),Js([fi("object")],qs.prototype,"textInput",2),Js([fi("object")],qs.prototype,"submitButtonStyles",2),Js([fi("string")],qs.prototype,"auxiliaryStyle",2),Js([fi("array")],qs.prototype,"initialMessages",2),Js([fi("object")],qs.prototype,"introMessage",2),Js([fi("object")],qs.prototype,"avatars",2),Js([fi("object")],qs.prototype,"names",2),Js([fi("boolean")],qs.prototype,"displayLoadingBubble",2),Js([fi("object")],qs.prototype,"errorMessages",2),Js([fi("object")],qs.prototype,"messageStyles",2),Js([fi("object")],qs.prototype,"textToSpeech",2),Js([fi("object")],qs.prototype,"speechToText",2),Js([fi("object")],qs.prototype,"images",2),Js([fi("object")],qs.prototype,"gifs",2),Js([fi("object")],qs.prototype,"camera",2),Js([fi("object")],qs.prototype,"audio",2),Js([fi("object")],qs.prototype,"microphone",2),Js([fi("object")],qs.prototype,"mixedFiles",2),Js([fi("object")],qs.prototype,"dragAndDrop",2),Js([fi("object")],qs.prototype,"introPanelStyle",2),Js([fi("object")],qs.prototype,"htmlClassUtilities",2),Js([fi("function")],qs.prototype,"onNewMessage",2),Js([fi("function")],qs.prototype,"onClearMessages",2),Js([fi("function")],qs.prototype,"onComponentRender",2),Js([fi("object")],qs.prototype,"demo",2),Js([fi("object")],qs.prototype,"_insertKeyViewStyles",2),customElements.define("deep-chat",qs);export{qs as DeepChat};
|