@deepdesk/deepdesk-sdk 14.3.1-beta.13 → 14.3.1-beta.14

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.
@@ -24,7 +24,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
24
24
  `+St),xn&&Pf([B,V,fe],xt=>{St=_l(St,xt," ")}),S&&Gl?S.createHTML(St):St},t.setConfig=function(){let j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Gf(j),jn=!0},t.clearConfig=function(){pi=null,jn=!1},t.isValidAttribute=function(j,b,L){pi||Gf({});let H=Fe(j),X=Fe(b);return lv(H,X,L)},t.addHook=function(j,b){typeof b=="function"&&(G[j]=G[j]||[],Nl(G[j],b))},t.removeHook=function(j){if(G[j])return rC(G[j])},t.removeHooks=function(j){G[j]&&(G[j]=[])},t.removeAllHooks=function(){G={}},t}var hC=gC();var gr=x(F());var y_={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function yC(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function Dl(e){return(e+"").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Fl(e,t){var n,r,o,i,s,a=/((?:^|\n+)(?:\n---+|\* \*(?: \*)+)\n)|(?:^``` *(\w*)\n([\s\S]*?)\n```$)|((?:(?:^|\n+)(?:\t| {2,}).+)+\n*)|((?:(?:^|\n)([>*+-]|\d+\.)\s+.*)+)|(?:!\[([^\]]*?)\]\(([^)]+?)\))|(\[)|(\](?:\(([^)]+?)\))?)|(?:(?:^|\n+)([^\s].*)\n(-{3,}|={3,})(?:\n+|$))|(?:(?:^|\n+)(#{1,6})\s*(.+)(?:\n+|$))|(?:`([^`].*?)`)|( \n\n*|\n{2,}|__|\*\*|[_*]|~~)/gm,l=[],u="",c=t||{},f=0;function d(y){var v=y_[y[1]||""],m=l[l.length-1]==y;return v?v[1]?(m?l.pop():l.push(y),v[0|m]):v[0]:y}function p(){for(var y="";l.length;)y+=d(l[l.length-1]);return y}for(e=e.replace(/^\[(.+?)\]:\s*(.+)$/gm,function(y,v,m){return c[v.toLowerCase()]=m,""}).replace(/^\n+|\n+$/g,"");o=a.exec(e);)r=e.substring(f,o.index),f=a.lastIndex,n=o[0],r.match(/[^\\](\\\\)*\\$/)||((s=o[3]||o[4])?n='<pre class="code '+(o[4]?"poetry":o[2].toLowerCase())+'"><code'+(o[2]?' class="language-'+o[2].toLowerCase()+'"':"")+">"+yC(Dl(s).replace(/^\n+|\n+$/g,""))+"</code></pre>":(s=o[6])?(s.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),i=Fl(yC(o[5].replace(/^\s*[>*+.-]/gm,""))),s==">"?s="blockquote":(s=s.match(/\./)?"ol":"ul",i=i.replace(/^(.*)(\n|$)/gm,"<li>$1</li>")),n="<"+s+">"+i+"</"+s+">"):o[8]?n='<img src="'+Dl(o[8])+'" alt="'+Dl(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+Dl(o[11]||c[r.toLowerCase()])+'">'),n=p()+"</a>"):o[9]?n="<a>":o[12]||o[14]?n="<"+(s="h"+(o[14]?o[14].length:o[13]>"="?1:2))+">"+Fl(o[12]||o[15],c)+"</"+s+">":o[16]?n="<code>"+Dl(o[16])+"</code>":(o[17]||o[1])&&(n=d(o[17]||"--"))),u+=r,u+=n;return(u+e.substring(f)+p()).replace(/^\n+|\n+$/g,"")}var vC={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};var yn=x(E());function v_(e){return`<button type="button" data-copy-icon class=${e}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function Ry(e){var n;let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(r=>r.remove()),(n=t.textContent)!=null?n:""}function S_(e){return e.replace(/\r\n/g,`
25
25
  `)}var x_=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=A("Markdown",vC),s=(0,gr.useRef)(null),[a,l]=(0,gr.useState)(null),u=(0,gr.useMemo)(()=>{let v=Fl(S_(e));return hC.sanitize(v).replaceAll("</code>",`${v_(i.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[e]),c=v=>{var h;let m=v.target,g=!!((h=s.current)!=null&&h.querySelector("code"));if(["A","BUTTON"].includes(m.tagName)){l(null);return}a||g&&m.tagName!=="CODE"||!g&&m!==s.current||(m.addEventListener("mouseleave",()=>l(null),{once:!0}),l(m))},f=()=>{if(!a)return;l(null);let v=a.querySelector("button");v&&(vs(v,i.fadeup),r(Ry(a)))},d=v=>{let m=v.target;if(m.tagName==="A"){v.stopPropagation();return}"copyIcon"in m.dataset&&(vs(m,i.fadeup),r(Ry(m.parentElement)))},p=()=>{!a||!o||(l(null),o(Ry(a)))},y=v=>{if(v===null)return;let m=v.getBoundingClientRect();m.left<0?v.style.transform=`translateX(${-m.left+2}px)`:m.right>window.innerWidth&&(v.style.transform=`translateX(${window.innerWidth-m.right-2}px)`)};return(0,yn.jsxs)(gr.Fragment,{children:[a&&(0,yn.jsxs)(Cs,{triggerRef:{current:a},className:i.popover,parentNode:a,children:[(0,yn.jsxs)("div",{className:i.options,ref:y,children:[(0,yn.jsx)("button",{type:"button",className:i.option,onClick:f,children:n}),o&&(0,yn.jsxs)(gr.Fragment,{children:[(0,yn.jsx)("div",{className:i.divider}),(0,yn.jsx)("button",{type:"button",className:i.option,onClick:p,children:t})]})]}),(0,yn.jsx)("div",{className:i.arrow})]}),(0,yn.jsx)("div",{ref:s,"data-testid":"widget-markdown-content",className:i.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},Of=x_;var Py={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l",form:"dd-sPNU2",formInput:"dd-F3E4I",formSubmit:"dd-vw5S0",actionButton:"dd-cCWyJ",editableCue:"dd-nWSD-",inputSpace:"dd-DGYB1"};var st=x(E()),w_=500,b_=100,E_=({content:e,onChange:t})=>{let n=(0,Jo.useRef)(null),r=A("WidgetCue",Py);return(0,Jo.useEffect)(()=>{let o=n.current;if(!o)return;o.style.setProperty("height","0px");let i=Math.min(Math.max(o.scrollHeight,b_),w_);o.style.setProperty("height",`${i}px`)},[e]),(0,st.jsx)("textarea",{ref:n,className:r.editableCue,onChange:t,value:e})},T_=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{var v;let i=A("WidgetCue",Py),s=q(Ol),a=Qr(),l=U("hasKeyboardInput"),[u,c]=(0,Jo.useState)(e.text),f=()=>{t&&t(e),n(e)},d=m=>{r&&r(m,e)},p=m=>{o&&o(m,e)},y=m=>{m.preventDefault(),m.stopPropagation(),n(e)};return(0,Jo.useEffect)(()=>{a("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,st.jsxs)(se,{"data-testid":"cue",children:[(0,st.jsx)(ye,{children:(0,st.jsxs)(ye.Content,{children:[e.title&&(0,st.jsx)(ye.Title,{className:i.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?s(e.rule.label):e.title}),e.specialType==="summary"?(0,st.jsx)(E_,{content:u,onChange:m=>{var g;return c((g=m.target.value)!=null?g:"")}}):(0,st.jsx)(Of,{content:e.text,useLabel:s("useCue"),copyLabel:s("copyCue"),onCopy:d,onUse:l?p:void 0})]})}),(0,st.jsxs)(se.ButtonsContainer,{children:[(0,st.jsxs)("div",{className:i.actions,children:[e.specialType==="summary"&&(0,st.jsx)(se.Button,{onClick:()=>d(u),children:s("copyCue")}),e.callToAction&&(0,st.jsx)(se.Button,{onClick:f,children:e.callToAction.label}),(0,st.jsx)(se.Button,{onClick:y,children:s("removeCue")})]}),e.specialType==="summary"?(0,st.jsx)(jo,{eventName:"summary feedback",feedbackText:(v=e.text)!=null?v:"",feedbackType:"summary",eventData:{summary:e.text}}):(0,st.jsx)(jo,{eventName:"Assistant response feedback",eventData:{name:e.rule.name,group:e.rule.label,description:e.rule.description,cueText:e.text},feedbackText:e.text,feedbackType:"assistant"})]})]})},SC=T_;var ks=x(E()),C_=({cues:e})=>{let t=J(),n=Pt(),r=q(Ol),o=Qr(),i=u=>{t(KT({id:u.rule.id})),t(Vb({code:u.rule.label})),o("Assistant response closed",{name:u.rule.name,group:u.rule.label,description:u.rule.description,cueText:u.text})},s=(u,c)=>{switch(Nn(u),c.specialType){case"summary":o("summary copied to clipboard",{originalText:c.text,finalText:u,assistant:c.rule.label});break;default:o("Assistant response copied",{name:c.rule.name,group:c.rule.label,description:c.rule.description,copiedText:u})}},a=u=>{u.callToAction&&(t(Fd(u)),o("Assistant call to action",{name:u.rule.name,group:u.rule.label,description:u.rule.description,eventName:u.callToAction.event,value:u.callToAction.value}))},l=(u,c)=>{n.send(In,{text:u,suggestion:{source:"cue",sourceText:u}}),o("Assistant response used",{name:c.rule.name,group:c.rule.label,description:c.rule.description,usedText:u})};return(0,ks.jsx)(ks.Fragment,{children:e.map(u=>u.isLoading?(0,ks.jsx)(Rf,{title:u.rule.label.startsWith("__")?r(u.rule.label):u.title},u.rule.id):(0,ks.jsx)(SC,{cue:u,onCallToAction:a,onRemove:i,onCopy:s,onUse:l},u.rule.id))})},xC=C_;var Nf=x(F());var wC={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var vn=x(E());function k_(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var bC=({data:e,schema:t})=>{let n=A("WidgetCustomData",wC),r=o=>{Nn(o)};return(0,Nf.useEffect)(()=>{z.info("Custom data",e,t)},[e]),(0,vn.jsx)("dl",{className:n.root,children:t.map(o=>{let i=k_(e,o.path);return(0,vn.jsxs)(Nf.Fragment,{children:[(0,vn.jsx)("dt",{className:n.label,children:o.label}),(0,vn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,vn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,vn.jsx)("span",{className:n.isFalse,children:o.falseValue}):i?(0,vn.jsxs)("button",{type:"button",onClick:()=>r(i),className:n.copyButton,children:[(0,vn.jsx)("span",{className:n.copyButtonText,children:i}),(0,vn.jsx)(Il,{})]}):"-"})]},o.label)})})};var At=x(F());var Ly=x(E()),EC=()=>(0,Ly.jsx)("svg",{focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"ReplayIcon",children:(0,Ly.jsx)("path",{d:"M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8"})});var Rs={};ut(Rs,{enUS:()=>R_,nlNL:()=>P_});var R_={titleKnowledgeAssistant:[{type:0,value:"Knowledge Assistant"}],inputPlaceholder:[{type:0,value:"What is your question?"}],useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Submit"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},P_={titleKnowledgeAssistant:[{type:0,value:"Knowledge Assistant"}],inputPlaceholder:[{type:0,value:"Wat is je vraag?"}],useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Verzend"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var Ay={form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",sources:"dd-xf9c6",source:"dd-a-vyX",link:"dd-PyUPS",linkContent:"dd-gARDA",showMoreSources:"dd-uDGi-"};var ge=x(E()),L_=3,A_=({sources:e,onClick:t})=>{let n=q(Rs),r=A("WidgetKnowledgeAssistant",Ay),[o,i]=(0,At.useState)(!1),s=o?e:e.slice(0,L_);return s.length===0?null:(0,ge.jsxs)("ul",{className:r.sources,children:[s.map(a=>(0,ge.jsx)("li",{className:r.source,"data-testid":"knowledge-assist-source",children:(0,ge.jsx)("a",{className:r.link,rel:"noreferrer",target:"_blank",href:a.url,onClick:l=>{l.stopPropagation(),t(a)},"data-tooltip":a.url?decodeURIComponent(a.url):void 0,children:(0,ge.jsx)("span",{className:r.linkContent,children:a.name})})},a.name)),s<e&&(0,ge.jsx)("button",{type:"button",className:r.showMoreSources,onClick:()=>i(!0),children:n("showMore",{amount:e.length-s.length})})]})},I_=({innerRef:e,item:t,index:n,hasKeyboardInput:r,onCopy:o,onUse:i,onSourceClick:s})=>{var l;let a=q(Rs);return(0,ge.jsxs)(se,{"data-testid":"knowledge-assist-answer",ref:e,children:[(0,ge.jsx)(ye,{children:(0,ge.jsxs)(ye.Content,{children:[(0,ge.jsx)(ye.Title,{children:t.question}),(0,ge.jsx)(Of,{content:t.answer.answer,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:o,onUse:r?i:void 0}),(0,ge.jsx)(A_,{sources:(l=t.answer.sources)!=null?l:[],onClick:u=>s(u,t.question)})]})}),(0,ge.jsxs)(se.ButtonsContainer,{children:[(0,ge.jsx)("div",{}),(0,ge.jsx)(jo,{eventName:"knowledge assist feedback",eventData:{question:t.question,isFollowUpQuestion:n>0,isAgent:!0,answer:t.answer.answer},feedbackText:t.answer.answer,feedbackType:"assistant"})]})]})},Iy=(0,At.createContext)(null),TC=({children:e})=>{let[t,n]=(0,At.useState)(null),r=_(fl("knowledge-assist")),[o,i]=(0,At.useState)(!1),[s,a]=(0,At.useState)(null),l=J(),u=zo(d=>ll({input:d,threadId:t,onNewThreadId(p){n(p)}})),c={isEnabled:r,isSubmitting:o,threadId:t,pendingInput:s,onSubmit(d){return k(this,null,function*(){i(!0),a(d),yield u.call(d),i(!1),a(null)})},onReset(){t&&l(fs(t))}};return(0,ge.jsx)(Iy.Provider,{value:c,children:e})},CC=()=>{let e=q(Rs),t=A("WidgetKnowledgeAssistant",Ay),n=(0,At.useContext)(Iy),r=(0,At.useRef)(null),[o,i]=(0,At.useState)(""),s=u=>{i(u.target.value)},a=u=>{u.preventDefault(),n.onSubmit(o).then(()=>{var c;r.current&&((c=r.current)==null||c.focus(),i(""))})},l=u=>{u.preventDefault(),n.onReset()};return n.isEnabled?(0,ge.jsxs)("form",{className:t.form,onSubmit:a,children:[(0,ge.jsx)("input",{ref:r,className:t.formInput,placeholder:e("inputPlaceholder"),type:"text",disabled:n.isSubmitting,value:o,onChange:s}),(0,ge.jsx)("button",{type:"submit",disabled:n.isSubmitting||o==="",className:t.formSubmit,children:e("submitLabel")}),(0,ge.jsx)("button",{type:"button",title:e("resetLabel"),disabled:n.threadId===null||n.isSubmitting,onClick:l,className:t.actionButton,children:(0,ge.jsx)(EC,{})})]}):null},kC=()=>{var c,f;let e=q(Rs),t=Qr(),n=(0,At.useRef)(null),r=(0,At.useContext)(Iy),o=(f=_(al((c=r.threadId)!=null?c:-1)))!=null?f:[],i=U("hasKeyboardInput"),s=Pt(),a=d=>{Nn(d),t("Assistant response copied",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",copiedText:d})},l=(d,p)=>{t("knowledge assist source viewed",{question:p,sourceViewed:d.url||d.name})},u=d=>{s.send(In,{text:d,suggestion:{source:"cue",sourceText:d}}),t("Assistant response used",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",usedText:d})};return!r.isEnabled||(o==null?void 0:o.length)===0&&!r.isSubmitting?null:(0,ge.jsx)(wn,{type:"knowledge",title:e("titleKnowledgeAssistant"),"data-testid":"knowledge",children:(0,ge.jsxs)(Et,{withDivider:!0,children:[o.map((d,p)=>(0,ge.jsx)(I_,{innerRef:p===o.length-1?n:void 0,item:d,index:p,hasKeyboardInput:i,onCopy:a,onUse:u,onSourceClick:l},`${d.question}_${d.answer}_${p}`)),r.pendingInput&&(0,ge.jsx)(Rf,{title:r.pendingInput})]})})};var PC=x(F());var N_=/(https?:\/\/[^\s]+)/,RC=e=>e.split(" ").find(t=>N_.test(t));var nn=x(E()),__=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=RC(r),i=q(El),s=U("showImages"),a=U("fallbackImage"),l=U("hasKeyboardInput"),u=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},c=(0,PC.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,nn.jsxs)(se,{onClick:l?u:void 0,"data-testid":"edit-suggestion",children:[(0,nn.jsxs)(ye,{children:[s&&e.image&&(0,nn.jsx)(ye.Image,{src:wf(e,"small",a||void 0),title:e.title}),(0,nn.jsxs)(ye.Content,{children:[e.title&&(0,nn.jsx)(ye.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,nn.jsx)(se.Labels,{labels:e.searchKeywords}),(0,nn.jsx)(ye.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,nn.jsxs)(se.Actions,{children:[o&&(0,nn.jsx)(se.ActionButton,{onClick:c,label:i("visitUrl")}),l&&(0,nn.jsx)(se.ActionButton,{primary:!0,onClick:u,label:i("useSuggestion")})]})]})},LC=__;var Hl=x(E()),M_=({lines:e,suggestions:t})=>{let n=Pt(),r=(o,i)=>{n.send(In,{text:o,suggestion:I(C({},i),{source:i.source,sourceText:i.text})})};return(0,Hl.jsx)(Hl.Fragment,{children:t.map(o=>(0,Hl.jsx)(LC,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},AC=M_;var Ul={};ut(Ul,{enUS:()=>D_,nlNL:()=>F_});var D_={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},F_={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var ei={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var K=x(E()),NC=(e,t)=>{let n=_(ft);(0,Ps.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},H_=({onLogIn:e})=>{let t=A("Widget",ei),n=U("isEmbedded"),r=U("adminUrl");return(0,K.jsx)("div",{className:t.loginText,children:(0,K.jsx)("div",{children:(0,K.jsx)(lf,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},IC=({text:e})=>{let t=A("Widget",ei);return(0,K.jsx)("div",{className:t.stateText,children:(0,K.jsx)("div",{children:(0,K.jsx)("p",{children:e})})},"notification")},U_=()=>{let e=q(Ul),t=A("Widget",ei),n=zo(()=>On({})),r=U("showSummaryCommand"),o=_(fl("knowledge-assist"));return(0,K.jsx)(K.Fragment,{children:r&&o&&(0,K.jsx)("button",{type:"button",disabled:n.state==="loading",className:t.footerShortcut,onClick:()=>n.call(),children:e("linkSummary")})})},z_=()=>{let e=q(Ul),t=J(),n=A("Widget",ei),r=U("showSearch"),o=U("showSummaryCommand"),i=U("showKnowledgeSearch"),s=_(fl("knowledge-assist")),a=U("isEmbedded"),l=_(Ss("/admin/")),u=Pt(),c=U("productName"),f=U("hasKeyboardInput"),d=zo(()=>On({})),p=r||o||i||l;return NC(()=>{if(a)return t(py()),()=>{t(zT())}},[t,a]),!p||!f?null:(0,K.jsx)(wn,{title:e("actions"),type:"shortcuts",children:(0,K.jsxs)("div",{className:n.shortcutList,children:[r&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>u.send("ShowCommandPalette",{isOpen:!0}),children:[(0,K.jsx)(gs,{}),e("linkSearch")]}),o&&!s&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary","aria-label":e("linkSummary"),disabled:d.state==="loading",onClick:()=>d.call(),children:[(0,K.jsx)(ZT,{}),e("linkSummary")]}),i&&!s&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":e("linkKnowledgeSearch"),onClick:()=>u.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,K.jsx)(QT,{}),e("linkKnowledgeSearch")]}),l&&(0,K.jsxs)("a",{className:n.shortcut,target:"_blank",href:l,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:c}),rel:"noreferrer",children:[(0,K.jsx)(XT,{}),e("linkStudioLogin",{productName:c})]})]})})},j_=()=>{let e=J(),t=_(dl),n=_(qb),r=_(qT),o=_(rb),i=_(Yd),s=_(Jd),a=_(No),l=_(An);return(0,Ps.useEffect)(()=>{!!o&&!n&&z.warn("Custom data provided, but no schema.")},[o,n]),NC(()=>{t.forEach(({type:u})=>{u==="entities"?e(mn()):du.includes(u)||e(gn(u))})},[e,l,a]),(0,Ps.useEffect)(()=>{r.length>0&&!t.some(u=>u.type==="cues")&&z.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,K.jsx)(Ps.Fragment,{children:t.map(({type:u,title:c,amount:f,lines:d,schema:p})=>{var y,v;switch(u){case"entities":return i&&i.length>0&&(0,K.jsx)(wn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(YT,{entities:i})},u);case"cues":return r&&r.length>0&&(0,K.jsx)(wn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(Et,{withDivider:!0,children:(0,K.jsx)(xC,{cues:r})})},u);case"custom-data":return o&&p&&(0,K.jsx)(wn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(Et,{withDivider:!0,children:(0,K.jsx)(bC,{data:o,schema:p})})},u);default:return((v=(y=s[u])==null?void 0:y.suggestions)==null?void 0:v.length)>0&&(0,K.jsx)(wn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(Et,{withDivider:!0,children:(0,K.jsx)(AC,{lines:d,contentType:u,suggestions:s[u].suggestions.slice(0,f)||[]})})},u)}})})},B_=({children:e})=>{let t=A("Widget",ei);return(0,K.jsx)("div",{className:t.footer,children:e})},V_=({onLogIn:e})=>{let t=q(Ul),n=A("Widget",ei),r=_(as),o=_(ft),i=_(j1),s=_(No);return r===!1?(0,K.jsx)(IC,{text:t("notSupported")}):o===!1?(0,K.jsx)(H_,{onLogIn:e}):!s||!i||o===null?(0,K.jsx)(IC,{text:t("waiting")}):(0,K.jsx)("div",{className:(0,OC.default)(n.root),"data-testid":"widget",children:(0,K.jsxs)(TC,{children:[(0,K.jsxs)(lu,{className:n.sectionList,children:[(0,K.jsx)(z_,{}),(0,K.jsx)(j_,{}),(0,K.jsx)(kC,{})]}),(0,K.jsxs)(B_,{children:[(0,K.jsx)(CC,{}),(0,K.jsx)(U_,{})]})]})})},_C=V_;function Ls(e){let t=new Range;return t.selectNodeContents(e),t}function MC(e,t,n){try{return no(e,t,n),!0}catch(r){return!1}}function _f(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Mf(e){return"tagName"in e&&e.tagName==="BR"}var zl=/[\u200B-\u200D\uFEFF]/g;function no(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(l))return u;for(let d=0;d<=l.length;d++)if(f.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(zl,""),f=o+c.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let y=s(u,t-o);y===0&&!p?r.setStartBefore(l):r.setStart(l,y)}p&&(r.setEnd(l,s(u,n-o)),i=!0),o=f;break}case Node.ELEMENT_NODE:{if(Mf(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;_f(l)&&u&&!_f(u)&&!Mf(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function jl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(f){let d=f===e,p=f===n,y=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let v=f.textContent;p&&(a=u+v.substring(0,r).replace(zl,"").length),y&&(l=u+v.substring(0,i).replace(zl,"").length),u+=v.replace(zl,"").length;break}case Node.ELEMENT_NODE:{if(Mf(f)&&f.nextSibling){u++;break}!d&&_f(f)&&f.previousSibling&&u++;for(let v=0;v<f.childNodes.length;v++){let m=p&&v===r,g=y&&v===i;if(m&&(a=u),g&&(l=u),l!==void 0||((!m||!s)&&c(f.childNodes[v]),y&&v===i-1&&(l=u),l!==void 0))break}y&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function Bl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a=0,l="";function u(c){let f=c===e,d=c===n,p=c===o;switch(d&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let y=d?r:0,v=p?i:void 0;l+=c.textContent.replace(zl,"").substring(y,v);break}case Node.ELEMENT_NODE:{if(!s&&a===1&&Mf(c)&&c.nextSibling){l+=`
26
26
  `;break}!f&&!s&&a===1&&_f(c)&&c.previousSibling&&(l+=`
27
- `);let y=d?r:0,v=p?Math.min(i,c.childNodes.length):c.childNodes.length;for(let m=y;m<v&&(u(c.childNodes[m]),a!==2);m++);break}default:break}p&&(a=2)}return u(e),l}var DC=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(DC||{}),hr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let i=this.getCaretPosition();$r(i,this.cachedCaretPosition)||(this.cachedCaretPosition=i,this.emit("caretposition",i))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(DC).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}off(t,n){if(!this.eventListeners[t])return;let r=this.eventListeners[t].indexOf(n);r!==-1&&this.eventListeners[t].splice(r,1)}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function FC(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ti=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Bl(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!FC(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!FC(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return jl(this.element,n);let r=this.lastKnownSelection;if(r&&MC(this.element,r.start,r.end))return r;let o=Ls(this.element);return o.collapse(!1),jl(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Bl(this.element,no(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var W_=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function HC(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,i=window.getComputedStyle(e),s=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",W_.forEach(function(c){o[c]=i[c]}),n?e.scrollHeight>parseInt(i.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),s.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(i.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(i.borderLeftWidth)};return s.removeChild(r),u}var ni=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return HC(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function UC(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function K_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Oy=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Ny=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=UC(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},_y=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),z.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Ny(t,this.deepdeskUrl,{debug:!0}):new Oy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=K_(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(z.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;z.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(I(C({},o),{channel:this.sessionId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},zC=_y;function $_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function he(e){return Array.isArray(e)?e.map(he):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(C({},t),{[$_(n)]:he(e[n])}),{}):e}function q_(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function qe(e){return Array.isArray(e)?e.map(qe):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(C({},t),{[q_(n)]:qe(e[n])}),{}):e}var As=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var My=e=>new Promise(t=>{setTimeout(t,e)});var Is=class extends As{constructor(){super(...arguments);this.name="ClientError"}},Fy=class extends As{constructor(){super(...arguments);this.name="ServerError"}},Dy=new Map;function G_(e){return k(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(z.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var ro=class ro{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",T=n,{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:y=P=>P instanceof TypeError,retryOnResponse:v=P=>P.status>=500,version:m=null}=T,g=ee(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Dy.has(s)){r(Dy.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=I(C({credentials:"include"},g),{headers:C({Accept:"application/json","Content-Type":"application/json"},g.headers)});!l&&this.csrfToken&&(h.headers=I(C({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof m=="string"&&(h.headers=I(C({},h.headers),{"X-Deepdesk-API-Version":m}));let S=f,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let R=()=>k(this,null,function*(){return S--,a(s,h).then(P=>k(this,null,function*(){return v(P)&&!i.isAborted&&S>0?(yield My(d),R()):P.status===401&&p===!0&&w===!1?(w=!0,yield this.refreshToken(),R()):P})).catch(P=>k(this,null,function*(){if(y(P)&&!i.isAborted&&S>0)return yield My(d),R();throw P}))});R().then(P=>k(this,null,function*(){let N=yield G_(P);if(delete this.latestRequestByUrl[s],P.status>=500){o(new Fy("Server Error",N));return}else if(P.status===401){o(new Is("Unauthorized",N));return}else if(P.status===403){o(new Is("Forbidden",N));return}else if(P.status===404){o(new Is("Not Found",N));return}else if(P.status>=400){o(new Is("Bad Request",N));return}u&&Dy.set(s,N),r(N)})).catch(P=>{o(P)})})}validateToken(){return k(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return ro.refreshingToken||(ro.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{ro.refreshingToken=null},1e3*60)})),ro.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,C({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,C({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,C({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,C({method:"DELETE"},n))}};ro.refreshingToken=null;var ri=ro;var jC;(t=>{let e;(s=>(s.SEND_MESSAGE="Send Message",s.HANDLING_TIME="Handling Time",s.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",s.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||(t.EventType={}))})(jC||(jC={}));function Df(e){return I(C({},he(e)),{tags:e.tags})}var oi=class oi{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new ri(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>k(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return k(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(oi.exchangeTokenPromise||(oi.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),oi.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return k(this,null,function*(){yield this.preflight(),z.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",I(C({},qe(t)),{tags:t.tags}),{version:"v2"});return Df(n)})}getMe(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return he(t)})}postIdentity(t){return k(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",qe(t))})}patchMe(t){return k(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",qe(t));return he(n)})}getProfile(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return he(n)})}getKnowledgeAssistant(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return he(n)})}getContentTypes(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return he(t)})}getAccount(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return he(t)})}getPlatformConfig(t){return k(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return he(r)})}checkUserExists(t){return k(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return k(this,arguments,function*(t,n={}){yield this.preflight(),z.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return z.info(`Successfully retrieved conversation ${s.id} for session ${t}`),Df(s)})}isConversationSupported(r){return k(this,arguments,function*(t,n={}){z.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return k(this,null,function*(){let r=qe(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Df(o)})}postMessages(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>I(C({},qe(o)),{tags:o.tags})),{version:"v2"})).map(o=>Df(o))})}sendEvent(t,n){return k(this,null,function*(){let s=n,{data:r}=s,o=ee(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>I(C({},a),{[l]:u}),{});return this.client.post("/api/events",qe(I(C(C({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return k(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>I(C({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:qe(C(C({},n),r))},{version:"v1"})})}getEntities(t){return k(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return k(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return k(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw z.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return k(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",qe(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return k(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,qe(n),{abortLatest:!0,version:"v1"})).map(s=>I(C({},he(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.text))})}isLoggedIn(){return k(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,qe(n),{abortLatest:!0,version:"v1"})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return k(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return he(n).map(r=>I(C({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return k(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",qe(t),{abortLatest:!0,version:"v1"});return he(n)})}search(t){return k(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,qe(t),{version:"v2"});return he(n)})}knowledgeAssist(i,s,a){return k(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,qe({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return he(l)})}requestLoginByEmail(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return he(n)})}requestPasswordlessToken(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return he(t.token)})}getCsrfToken(){return k(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return he(n)})}evaluateRule(i,s,a){return k(this,arguments,function*(t,n,r,o={}){let l=new URLSearchParams;o.raiseForFailingConditions&&l.set("raise_for_failing_conditions","true");let u=yield this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${l.toString()}`,r,{version:"v2"});return u?he(u.cues):[]})}getSummary(r){return k(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return he(o)})}evaluateAssistant(t,n){return k(this,null,function*(){var a;let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let i=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,s=yield this.client.post(i,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return he(s.output)})}createAssistantThread(t){return k(this,null,function*(){let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return he(r)})}postMessageToAssistantThread(t){return k(this,null,function*(){let{assistantCode:n,threadId:r,message:o}=t,i=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return he(i)})}getRules(){return k(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{useCache:!0});return he(n)})}translateMessages(t){return k(this,null,function*(){let n=yield this.client.post("/api/translate",qe(t),{version:"v2"});return he(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(l0);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&z.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};oi.exchangeTokenPromise=null;var yr=oi;var BC={startTime:null,stopTime:null},VC=e=>e.handlingTime,WC=ne({name:"handlingTime",initialState:BC,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(Ae,()=>BC)}}),{handlingTimeStart:KC,handlingTimeStop:Ff,handlingTimeReset:$C}=WC.actions,qC=WC.reducer;var GC=(e={})=>{let t=C({onAuthError:ss(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Hf={list:{keywordMatches:[]},fetchState:"idle"};var ii=Q("styleSuggestions/getAll",(n,r)=>k(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return Hf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),Y_=ne({name:"styleSuggestions",initialState:Hf,reducers:{},extraReducers:e=>{e.addCase(ii.pending,t=>{t.fetchState="loading"}).addCase(ii.rejected,t=>{t.fetchState="error"}).addCase(ii.fulfilled,(t,n)=>{t.fetchState="done",$r(t.list,n.payload)||(t.list=n.payload)}).addCase(Lo,t=>{t.list=Hf.list}).addCase(Ae,()=>Hf)}}),YC=Y_.reducer;var XC=(e={})=>{let t,n=!0,r=C({getStyleSuggestions:ii,debounce:500},e);return o=>i=>s=>{var p;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((p=u.conversation.current)==null?void 0:p.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function X_(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var QC=(e={})=>{let t=C({getTextSuggestions:gn,getAutocompleteSuggestions:Cl,debounce:200,check:_n},e),n;return r=>o=>i=>{var v;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(v=l.conversation.current)==null?void 0:v.id,d=i.type===ef.toString();if(!f||!u&&!c)return a;let{input:p}=l;return X_(p,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=ls(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var ZC=ii.fulfilled.toString();function Q_(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var JC=e=>t=>n=>r=>{var u;if(r.type!==ZC){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=Q_(o,s);r.type===ZC&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var Z_=Ic({assistants:Wb,auth:I1,conversation:B1,contentTypes:$b,passwordlessToken:jT,entities:SE,knowledgeAssistant:Ub,handlingTime:qC,info:lb,input:eb,settings:T1,profile:Gb,search:mb,styleSuggestions:YC,ui:nT,rules:$T,textSuggestions:zE});function ek(e){return Aw({reducer:Z_,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}),GC(),QC({debounce:200}),XC({debounce:500}),JC(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var J_=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},eM=e=>t=>n=>r=>{var a,l,u,c,f,d,p;let o=t.getState(),i=qa("inlineSuggestions")(o);switch(r.type){case ss.toString():{!r.payload&&e.emit("logout",void 0);break}case mn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case Xt.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Lo.toString():e.logSendMessage(r.payload);break;case Xo.fulfilled.toString():r.isBroadcasted||e.broadcast(fh,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;case Fd.toString():e.emit("call-to-action",{cue:r.payload});break;case rr.fulfilled.toString():r.isBroadcasted||e.broadcast(ph,r,!1);break;default:break}let s=n(r);switch(r.type){case Lo.toString():e.handleAfterSendMessage(r.payload);break;case Rl.toString():e.onUpdateShowTabHint(r.payload);break;case Ff.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case pd.toString():{let{start:y,end:v}=o.input.selection;e.emit("replace",I(C({},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}}));break}case un.toString():{let{start:y,end:v}=o.input.selection;e.emit("select-suggestion",I(C({type:J_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}})),i&&t.dispatch(qr([]));break}case md.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case qr.toString():{i&&r.payload.length>0&&t.dispatch(gd(0));break}case On.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload,assistant:(p=t.getState().profile.data)==null?void 0:p.summarizerAssistantNew}});break}default:break}return s},tk=eM;function Hy(e){return e.toISOString().replace("T"," ").replace("Z","")}var tM=(e,t)=>t.version,nk=ln([cs,An,VC,tM],(e,t,n,r)=>{if(!t)return z.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(z.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:Hy(o),timeStop:Hy(i)}});function rk(e,t,n){var N,M,G,B;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return z.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:f,pastes:d,cuts:p,deletions:y,textSuggestions:v,offeredTextSuggestions:m}}=t[e],g=o.length,S=v.reduce((V,{text:fe,searchTerm:Ye})=>V+fe.length-(Ye?Ye.length:0),0),w=c!=null?c:Date.now(),R=(Date.now()-w)/1e3+(f||0),T=i/R,P=v.reduce((V,{searchTerm:fe})=>V+(fe?fe.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:p,deletions:y,lenTextTyped:i+P,lenTextTotal:g,lenTextAssisted:S,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:R,charsPerSecond:T,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:m.filter(V=>V.source==="gpt").length}],agentId:(M=t.info.agentInfo)==null?void 0:M.agentId,agentName:(G=t.info.agentInfo)==null?void 0:G.agentName,agentEmail:(B=t.info.agentInfo)==null?void 0:B.agentEmail}}function Uy(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Uy(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Uy(o,t):null}function zy(e,t){return Uy(e,t)}function ok(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function nM(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Uf(e){return nM(e)&&(Yo(e)||cf(e))}var sk,Hn=new Map,rM=["bottom","height","left","right","top","width"],ik=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:rM.some(n=>e[n]!==t[n]);function ak(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...ak(t)]:[]}function lk(e,t){return!e||!t?null:I(C({},e),{top:e.top+t.top,left:e.left+t.left})}var zf=!1,uk=()=>{zf=!0;let e=[];if(Hn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Hn.delete(n);return}let r=n.getBoundingClientRect();ik(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(lk,t.rect):t.rect;ik(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Hn.size===0){zf=!1;return}sk=window.requestAnimationFrame(uk)};function jy(e,t){let n=ak(e),r=[],o=n.map((i,s)=>jy(i,a=>{r[s]=a;let l=Hn.get(e);if(!l)return;let u=r.reduce(lk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Hn.has(e)){let s=Hn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Hn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!zf&&uk()},unobserve(){o.forEach(s=>s.unobserve());let i=Hn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Hn.delete(e),Hn.size||(cancelAnimationFrame(sk),zf=!1)}}}}var ck,Un=new Map,dk=()=>{Un.forEach((e,t)=>{if(!t.isConnected){Un.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Un.size!==0&&(ck=window.requestAnimationFrame(dk))};function fk(e,t){return{observe(){let n=Un.size===0;Un.has(e)?Un.get(e).callbacks.push(t):Un.set(e,{visible:void 0,callbacks:[t]}),n&&dk()},unobserve(){let n=Un.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Un.delete(e),Un.size||cancelAnimationFrame(ck)}}}}var By=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function Vy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Os(e){return parseFloat(e)}function jf(e){return Math.round(e*1e6)}function pk(e){return e/1e6}function Wy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Os(e.width),i=Os(e.borderLeftWidth),s=Os(e.borderRightWidth),a=Os(e.paddingRight),l=pk(jf(o)-jf(i)-jf(s)),u=pk(jf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Vl(e,t={}){var c,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",$o(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Vy(r,n,By),Wy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=fk(e,()=>{Vy(r,n,By),Wy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=jy(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Vy(r,n,By),Wy(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),y=window.getComputedStyle(t.closestScrollElement),v=Os(y.borderTopWidth),m=Os(y.borderBottomWidth),g=p.top+v-d.top,h=d.top+d.height+-(p.top+p.height-m);n.style.clipPath=`inset(${g}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var mk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){z.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function oM(e){return e.offsetParent!==null}function gk(e){if(!oM(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Bf(e,t,n=100){let r=gk(e);t({isVisible:r});let o=setInterval(()=>{let i=gk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Me=x(E());var hk=mk("showTabHint",!0),Ns=class Ns{constructor({deepdeskUrl:t,version:n=Ns.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.floatingMenu=null;this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new yr(l,{token:o,fetch:i}),this.version=n,this.instanceId=Ns.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[tk({broadcast:(c,f,d)=>{this.broadcastEvents.send(c,f,d)},emit:(c,f)=>this.emit(c,f),handleAfterSendMessage:c=>this.handleAfterSendMessage(c),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:c=>this.logSendMessage(c),onUpdateShowTabHint:c=>hk.update(c),sendEvent:(c,f)=>this.deepdeskApi.sendEvent(c,f)})]};this.store=ek(u),this.broadcastEvents=new zC({debug:!0,deepdeskUrl:l,eventMap:gb(this.store),createCustomChannel:a}),this.store.dispatch(Rl(hk.value())),this.store.dispatch(ad({locale:r,adminUrl:l,productName:s}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(z.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(z.warn("Profile has not been loaded (yet)"),!0):(z.warn("No conversation loaded (yet)"),!0)}login(){this.store.dispatch(ss(null)),this.store.dispatch(er());let t=n=>ft(n)&&C1(n)!=="loading";return new Promise(n=>{let r=this.subscribe(t,o=>{o&&(r(),n())});this.unmountHandlers.push(()=>{r()})})}isLoggedIn(){return k(this,null,function*(){return(yield this.store.dispatch(er())).payload})}isConversationSupported(t,n){return k(this,null,function*(){return(yield this.store.dispatch(sh({sessionId:t,options:n}))).payload})}createConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(ud(t))).payload})}getConversationBySessionId(t,n){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(cd({sessionId:t,options:n}))).payload})}upsertConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(ah(t))).payload})}postMessages(t){return k(this,null,function*(){return(yield this.store.dispatch(fd(t))).payload})}updateConversation(t){return k(this,null,function*(){return(yield this.store.dispatch(dd(t))).payload})}resetConversation(){this.store.dispatch(Ae()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(ad(t))}setVisitorInfo(t){this.store.dispatch(ib(t))}setCustomData(t){this.store.dispatch(sb(t))}setAgentInfo(t,n){return k(this,null,function*(){yield this.store.dispatch(Xa(C(C({},t),n)))})}setAgentSettings(t){return k(this,null,function*(){yield this.store.dispatch(uh(t))})}getAgentSettings(){return k(this,null,function*(){return(yield this.store.dispatch(ch())).payload})}refresh(){return k(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(ef()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(un(t))}evaluateRule(o){return k(this,arguments,function*(t,n={},r=BT){return(yield this.store.dispatch(Xo({label:t,params:n,options:r}))).payload.cues})}evaluateAssistant(t,n){return k(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:i=!0,includeTags:s,expectFormat:a}=c,l=ee(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(rr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:s,input:r,skipState:!i}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return k(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){z.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,C({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return k(this,null,function*(){var n;if(!this.hasConversation())return z.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||z.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(On({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.settings,u=a?"below":"above",c=o.length>0;if(!_n(this.state)||(this.store.dispatch(q1(lh(t))),t.key!=="Tab"&&!l))return;let f=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(X1()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(Q1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():f();break;case"ArrowDown":{u==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(gd(-1)),this.store.dispatch(Jr({collapse:!0})),this.store.dispatch(eT(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let p=us(this.state);if(!p)return;this.store.dispatch(Rl(!1)),this.store.dispatch(un({text:p.text,suggestion:p,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let p=us(this.state);if(!p)return;this.store.dispatch(un({text:p.text,suggestion:p,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let p=us(this.state);if(!p)return;this.store.dispatch(un({text:p.text,suggestion:p,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(Jr({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(qr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(z.info("Start handling time"),this.store.dispatch(KC()))}handlingTimeStop(){this.state.handlingTime.startTime&&(z.info("Stop handling time"),this.store.dispatch(Ff()))}logSendMessage(t){let n=rk("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=nk(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch($C()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Lo((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(J1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){z.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),z.error(i)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(ab(t))}whenConversationLoaded(t){let n=o=>{var i;return(i=o.conversation.current)==null?void 0:i.id},r=()=>this.loadProfileConfig().then(()=>t());n(this.state)&&r(),this.subscribe(n,o=>{o&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=Vl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Ge.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,u]=Vl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,Ge.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return $o(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Ge.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),z.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(z.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Z1(r.metrics))):z.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Uf(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s,inputMediator:a}=d,l=ee(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),u={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),$o(t),this.inputMediator=a||(Yo(t)?new ni(t):new ti(t)),this.inputMediator.on("change",({plainText:p,rawHTML:y})=>{this.store.dispatch(hd({text:p,html:y}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(G1(lh(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:y})=>{this.store.dispatch(Y1({text:p,selectionText:y}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch($1(p))});let c;this.inputMediator.on("selection",p=>{clearTimeout(c),p===null?c=setTimeout(()=>{p!==null&&this.store.dispatch(yd(p))},500):this.store.dispatch(yd(p))}),this.inputMediator.on("disabled",()=>{var p;(p=this.inputMediator)==null||p.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(rf(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(rf(!0))}),this.renderSuggestions(t,u),this.subscribe(qa("inlineSuggestions"),()=>{this.renderSuggestions(t,u)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(yd(this.inputMediator.getSelection())),this.store.dispatch(rf(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var p;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((p=this.state.conversation.current)==null?void 0:p.sessionId)}),this.isMounted=!0}subscribe(t,n){let r=t(this.store.getState());return this.store.subscribe(()=>{let o=t(this.store.getState());o!==r&&(r=o,n(r))})}unmount(){var t,n,r,o;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(o=this.inputMediator)==null||o.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderSuggestions(t,n){var r,o,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.aboveSuggestions=this.renderAboveSuggestions(t,n)}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret");(0,Ge.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(lT,{})})}),o);let i=s=>{s?(o.style.display="block",o.style.top=`${s.top}px`,o.style.left=`${s.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var s;(0,Ge.unmountComponentAtNode)(o),(s=this.inputMediator)==null||s.off("caretposition",i),o.remove()}}}renderAboveSuggestions(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i}=n,s=o&&zy(t,o)||void 0,a=this.overlayContainerFactory("deepdesk-tab-completion",s||t,{appendTo:i,closestScrollElement:s,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),l=this.overlayContainerFactory("deepdesk-suggestions-overlay",s||t,{appendTo:i},r==null?void 0:r.suggestionsRootNode);return(0,Ge.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(HT,{inputElement:t})})}),a),(0,Ge.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(yT,{onLogIn:()=>this.loginViaPopup().catch(u=>z.warn(u.message))})})}),l),{unmount(){(0,Ge.unmountComponentAtNode)(a),(0,Ge.unmountComponentAtNode)(l),a.remove(),l.remove()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&zy(t,o)||void 0,l=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent);return(0,Ge.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(QE,{onLogIn:()=>this.loginViaPopup().catch(u=>z.warn(u.message))})})}),l),{unmount(){(0,Ge.unmountComponentAtNode)(l),l.remove()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays");return(0,Ge.render)((0,Me.jsx)(Go,{store:this.store,customStyles:n,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)($E,{})})}),r),{unmount(){(0,Ge.unmountComponentAtNode)(r),r.remove()}}}renderWidget(t,n={}){if(this.widgetRoot&&z.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Ge.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(_C,{onLogIn:()=>this.loginViaPopup().catch(s=>z.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Ge.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Bf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){ok(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>k(this,null,function*(){yield this.store.dispatch(cl());let t=No(this.state);t&&(yield this.store.dispatch(il()),this.store.dispatch(ad({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return k(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=p=>k(this,null,function*(){var y,v;if((y=p.data)!=null&&y.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((v=p.data)==null?void 0:v.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Za),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=p=>k(this,null,function*(){var y;if(p.origin===a.origin)switch((y=p.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){z.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),p.data.message==="Timeout"&&z.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return k(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(z.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;z.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return k(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=dl(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(mn()):du.includes(r)||this.store.dispatch(gn(r))})}catch(r){this.handleError(r)}})}};Ns.version="14.3.1-beta.13",Ns.count=0;var Wl=Ns;function iM(e){return k(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function yk(e,t){return k(this,null,function*(){let n=yield iM(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function vk(e,t,n){return k(this,null,function*(){yield new yr(e).authenticateWithKey(t,n)})}function Sk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function xk(r,o){return k(this,arguments,function*(e,t,n={}){var f,d;let{value:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function wk(r,o){return k(this,arguments,function*(e,t,n={}){let i=n.replace?no(e,n.replace.start,n.replace.end):Ls(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
27
+ `);let y=d?r:0,v=p?Math.min(i,c.childNodes.length):c.childNodes.length;for(let m=y;m<v&&(u(c.childNodes[m]),a!==2);m++);break}default:break}p&&(a=2)}return u(e),l}var DC=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(DC||{}),hr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let i=this.getCaretPosition();$r(i,this.cachedCaretPosition)||(this.cachedCaretPosition=i,this.emit("caretposition",i))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(DC).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}off(t,n){if(!this.eventListeners[t])return;let r=this.eventListeners[t].indexOf(n);r!==-1&&this.eventListeners[t].splice(r,1)}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function FC(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ti=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Bl(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!FC(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!FC(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return jl(this.element,n);let r=this.lastKnownSelection;if(r&&MC(this.element,r.start,r.end))return r;let o=Ls(this.element);return o.collapse(!1),jl(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Bl(this.element,no(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var W_=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function HC(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,i=window.getComputedStyle(e),s=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",W_.forEach(function(c){o[c]=i[c]}),n?e.scrollHeight>parseInt(i.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),s.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(i.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(i.borderLeftWidth)};return s.removeChild(r),u}var ni=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return HC(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function UC(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function K_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Oy=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Ny=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=UC(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},_y=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),z.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Ny(t,this.deepdeskUrl,{debug:!0}):new Oy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=K_(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(z.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;z.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(I(C({},o),{channel:this.sessionId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},zC=_y;function $_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function he(e){return Array.isArray(e)?e.map(he):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(C({},t),{[$_(n)]:he(e[n])}),{}):e}function q_(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function qe(e){return Array.isArray(e)?e.map(qe):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(C({},t),{[q_(n)]:qe(e[n])}),{}):e}var As=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var My=e=>new Promise(t=>{setTimeout(t,e)});var Is=class extends As{constructor(){super(...arguments);this.name="ClientError"}},Fy=class extends As{constructor(){super(...arguments);this.name="ServerError"}},Dy=new Map;function G_(e){return k(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(z.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var ro=class ro{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",T=n,{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:y=P=>P instanceof TypeError,retryOnResponse:v=P=>P.status>=500,version:m=null}=T,g=ee(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Dy.has(s)){r(Dy.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=I(C({credentials:"include"},g),{headers:C({Accept:"application/json","Content-Type":"application/json"},g.headers)});!l&&this.csrfToken&&(h.headers=I(C({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof m=="string"&&(h.headers=I(C({},h.headers),{"X-Deepdesk-API-Version":m}));let S=f,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let R=()=>k(this,null,function*(){return S--,a(s,h).then(P=>k(this,null,function*(){return v(P)&&!i.isAborted&&S>0?(yield My(d),R()):P.status===401&&p===!0&&w===!1?(w=!0,yield this.refreshToken(),R()):P})).catch(P=>k(this,null,function*(){if(y(P)&&!i.isAborted&&S>0)return yield My(d),R();throw P}))});R().then(P=>k(this,null,function*(){let N=yield G_(P);if(delete this.latestRequestByUrl[s],P.status>=500){o(new Fy("Server Error",N));return}else if(P.status===401){o(new Is("Unauthorized",N));return}else if(P.status===403){o(new Is("Forbidden",N));return}else if(P.status===404){o(new Is("Not Found",N));return}else if(P.status>=400){o(new Is("Bad Request",N));return}u&&Dy.set(s,N),r(N)})).catch(P=>{o(P)})})}validateToken(){return k(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return ro.refreshingToken||(ro.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{ro.refreshingToken=null},1e3*60)})),ro.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,C({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,C({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,C({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,C({method:"DELETE"},n))}};ro.refreshingToken=null;var ri=ro;var jC;(t=>{let e;(s=>(s.SEND_MESSAGE="Send Message",s.HANDLING_TIME="Handling Time",s.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",s.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||(t.EventType={}))})(jC||(jC={}));function Df(e){return I(C({},he(e)),{tags:e.tags})}var oi=class oi{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new ri(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>k(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return k(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(oi.exchangeTokenPromise||(oi.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),oi.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return k(this,null,function*(){yield this.preflight(),z.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",I(C({},qe(t)),{tags:t.tags}),{version:"v2"});return Df(n)})}getMe(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return he(t)})}postIdentity(t){return k(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",qe(t))})}patchMe(t){return k(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",qe(t));return he(n)})}getProfile(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return he(n)})}getKnowledgeAssistant(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return he(n)})}getContentTypes(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return he(t)})}getAccount(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return he(t)})}getPlatformConfig(t){return k(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return he(r)})}checkUserExists(t){return k(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return k(this,arguments,function*(t,n={}){yield this.preflight(),z.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return z.info(`Successfully retrieved conversation ${s.id} for session ${t}`),Df(s)})}isConversationSupported(r){return k(this,arguments,function*(t,n={}){z.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return k(this,null,function*(){let r=qe(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Df(o)})}postMessages(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>I(C({},qe(o)),{tags:o.tags})),{version:"v2"})).map(o=>Df(o))})}sendEvent(t,n){return k(this,null,function*(){let s=n,{data:r}=s,o=ee(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>I(C({},a),{[l]:u}),{});return this.client.post("/api/events",qe(I(C(C({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return k(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>I(C({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:qe(C(C({},n),r))},{version:"v1"})})}getEntities(t){return k(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return k(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return k(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw z.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return k(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",qe(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return k(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,qe(n),{abortLatest:!0,version:"v1"})).map(s=>I(C({},he(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.text))})}isLoggedIn(){return k(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,qe(n),{abortLatest:!0,version:"v1"})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return k(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return he(n).map(r=>I(C({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return k(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",qe(t),{abortLatest:!0,version:"v1"});return he(n)})}search(t){return k(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,qe(t),{version:"v2"});return he(n)})}knowledgeAssist(i,s,a){return k(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,qe({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return he(l)})}requestLoginByEmail(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return he(n)})}requestPasswordlessToken(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return he(t.token)})}getCsrfToken(){return k(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return he(n)})}evaluateRule(i,s,a){return k(this,arguments,function*(t,n,r,o={}){let l=new URLSearchParams;o.raiseForFailingConditions&&l.set("raise_for_failing_conditions","true");let u=yield this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${l.toString()}`,r,{version:"v2"});return u?he(u.cues):[]})}getSummary(r){return k(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return he(o)})}evaluateAssistant(t,n){return k(this,null,function*(){var a;let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let i=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,s=yield this.client.post(i,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return he(s.output)})}createAssistantThread(t){return k(this,null,function*(){let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return he(r)})}postMessageToAssistantThread(t){return k(this,null,function*(){let{assistantCode:n,threadId:r,message:o}=t,i=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return he(i)})}getRules(){return k(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{useCache:!0});return he(n)})}translateMessages(t){return k(this,null,function*(){let n=yield this.client.post("/api/translate",qe(t),{version:"v2"});return he(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(l0);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&z.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};oi.exchangeTokenPromise=null;var yr=oi;var BC={startTime:null,stopTime:null},VC=e=>e.handlingTime,WC=ne({name:"handlingTime",initialState:BC,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(Ae,()=>BC)}}),{handlingTimeStart:KC,handlingTimeStop:Ff,handlingTimeReset:$C}=WC.actions,qC=WC.reducer;var GC=(e={})=>{let t=C({onAuthError:ss(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Hf={list:{keywordMatches:[]},fetchState:"idle"};var ii=Q("styleSuggestions/getAll",(n,r)=>k(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return Hf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),Y_=ne({name:"styleSuggestions",initialState:Hf,reducers:{},extraReducers:e=>{e.addCase(ii.pending,t=>{t.fetchState="loading"}).addCase(ii.rejected,t=>{t.fetchState="error"}).addCase(ii.fulfilled,(t,n)=>{t.fetchState="done",$r(t.list,n.payload)||(t.list=n.payload)}).addCase(Lo,t=>{t.list=Hf.list}).addCase(Ae,()=>Hf)}}),YC=Y_.reducer;var XC=(e={})=>{let t,n=!0,r=C({getStyleSuggestions:ii,debounce:500},e);return o=>i=>s=>{var p;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((p=u.conversation.current)==null?void 0:p.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function X_(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var QC=(e={})=>{let t=C({getTextSuggestions:gn,getAutocompleteSuggestions:Cl,debounce:200,check:_n},e),n;return r=>o=>i=>{var v;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(v=l.conversation.current)==null?void 0:v.id,d=i.type===ef.toString();if(!f||!u&&!c)return a;let{input:p}=l;return X_(p,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=ls(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var ZC=ii.fulfilled.toString();function Q_(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var JC=e=>t=>n=>r=>{var u;if(r.type!==ZC){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=Q_(o,s);r.type===ZC&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var Z_=Ic({assistants:Wb,auth:I1,conversation:B1,contentTypes:$b,passwordlessToken:jT,entities:SE,knowledgeAssistant:Ub,handlingTime:qC,info:lb,input:eb,settings:T1,profile:Gb,search:mb,styleSuggestions:YC,ui:nT,rules:$T,textSuggestions:zE});function ek(e){return Aw({reducer:Z_,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}),GC(),QC({debounce:200}),XC({debounce:500}),JC(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var J_=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},eM=e=>t=>n=>r=>{var a,l,u,c,f,d,p;let o=t.getState(),i=qa("inlineSuggestions")(o);switch(r.type){case ss.toString():{!r.payload&&e.emit("logout",void 0);break}case mn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case Xt.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Lo.toString():e.logSendMessage(r.payload);break;case Xo.fulfilled.toString():r.isBroadcasted||e.broadcast(fh,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;case Fd.toString():e.emit("call-to-action",{cue:r.payload});break;case rr.fulfilled.toString():r.isBroadcasted||e.broadcast(ph,r,!1);break;default:break}let s=n(r);switch(r.type){case Lo.toString():e.handleAfterSendMessage(r.payload);break;case Rl.toString():e.onUpdateShowTabHint(r.payload);break;case Ff.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case pd.toString():{let{start:y,end:v}=o.input.selection;e.emit("replace",I(C({},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}}));break}case un.toString():{let{start:y,end:v}=o.input.selection;e.emit("select-suggestion",I(C({type:J_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}})),i&&t.dispatch(qr([]));break}case md.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case qr.toString():{i&&r.payload.length>0&&t.dispatch(gd(0));break}case On.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload,assistant:(p=t.getState().profile.data)==null?void 0:p.summarizerAssistantNew}});break}default:break}return s},tk=eM;function Hy(e){return e.toISOString().replace("T"," ").replace("Z","")}var tM=(e,t)=>t.version,nk=ln([cs,An,VC,tM],(e,t,n,r)=>{if(!t)return z.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(z.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:Hy(o),timeStop:Hy(i)}});function rk(e,t,n){var N,M,G,B;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return z.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:f,pastes:d,cuts:p,deletions:y,textSuggestions:v,offeredTextSuggestions:m}}=t[e],g=o.length,S=v.reduce((V,{text:fe,searchTerm:Ye})=>V+fe.length-(Ye?Ye.length:0),0),w=c!=null?c:Date.now(),R=(Date.now()-w)/1e3+(f||0),T=i/R,P=v.reduce((V,{searchTerm:fe})=>V+(fe?fe.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:p,deletions:y,lenTextTyped:i+P,lenTextTotal:g,lenTextAssisted:S,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:R,charsPerSecond:T,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:m.filter(V=>V.source==="gpt").length}],agentId:(M=t.info.agentInfo)==null?void 0:M.agentId,agentName:(G=t.info.agentInfo)==null?void 0:G.agentName,agentEmail:(B=t.info.agentInfo)==null?void 0:B.agentEmail}}function Uy(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Uy(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Uy(o,t):null}function zy(e,t){return Uy(e,t)}function ok(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function nM(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Uf(e){return nM(e)&&(Yo(e)||cf(e))}var sk,Hn=new Map,rM=["bottom","height","left","right","top","width"],ik=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:rM.some(n=>e[n]!==t[n]);function ak(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...ak(t)]:[]}function lk(e,t){return!e||!t?null:I(C({},e),{top:e.top+t.top,left:e.left+t.left})}var zf=!1,uk=()=>{zf=!0;let e=[];if(Hn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Hn.delete(n);return}let r=n.getBoundingClientRect();ik(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(lk,t.rect):t.rect;ik(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Hn.size===0){zf=!1;return}sk=window.requestAnimationFrame(uk)};function jy(e,t){let n=ak(e),r=[],o=n.map((i,s)=>jy(i,a=>{r[s]=a;let l=Hn.get(e);if(!l)return;let u=r.reduce(lk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Hn.has(e)){let s=Hn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Hn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!zf&&uk()},unobserve(){o.forEach(s=>s.unobserve());let i=Hn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Hn.delete(e),Hn.size||(cancelAnimationFrame(sk),zf=!1)}}}}var ck,Un=new Map,dk=()=>{Un.forEach((e,t)=>{if(!t.isConnected){Un.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Un.size!==0&&(ck=window.requestAnimationFrame(dk))};function fk(e,t){return{observe(){let n=Un.size===0;Un.has(e)?Un.get(e).callbacks.push(t):Un.set(e,{visible:void 0,callbacks:[t]}),n&&dk()},unobserve(){let n=Un.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Un.delete(e),Un.size||cancelAnimationFrame(ck)}}}}var By=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function Vy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Os(e){return parseFloat(e)}function jf(e){return Math.round(e*1e6)}function pk(e){return e/1e6}function Wy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Os(e.width),i=Os(e.borderLeftWidth),s=Os(e.borderRightWidth),a=Os(e.paddingRight),l=pk(jf(o)-jf(i)-jf(s)),u=pk(jf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Vl(e,t={}){var c,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",$o(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Vy(r,n,By),Wy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=fk(e,()=>{Vy(r,n,By),Wy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=jy(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Vy(r,n,By),Wy(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),y=window.getComputedStyle(t.closestScrollElement),v=Os(y.borderTopWidth),m=Os(y.borderBottomWidth),g=p.top+v-d.top,h=d.top+d.height+-(p.top+p.height-m);n.style.clipPath=`inset(${g}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var mk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){z.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function oM(e){return e.offsetParent!==null}function gk(e){if(!oM(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Bf(e,t,n=100){let r=gk(e);t({isVisible:r});let o=setInterval(()=>{let i=gk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Me=x(E());var hk=mk("showTabHint",!0),Ns=class Ns{constructor({deepdeskUrl:t,version:n=Ns.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.floatingMenu=null;this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new yr(l,{token:o,fetch:i}),this.version=n,this.instanceId=Ns.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[tk({broadcast:(c,f,d)=>{this.broadcastEvents.send(c,f,d)},emit:(c,f)=>this.emit(c,f),handleAfterSendMessage:c=>this.handleAfterSendMessage(c),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:c=>this.logSendMessage(c),onUpdateShowTabHint:c=>hk.update(c),sendEvent:(c,f)=>this.deepdeskApi.sendEvent(c,f)})]};this.store=ek(u),this.broadcastEvents=new zC({debug:!0,deepdeskUrl:l,eventMap:gb(this.store),createCustomChannel:a}),this.store.dispatch(Rl(hk.value())),this.store.dispatch(ad({locale:r,adminUrl:l,productName:s}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(z.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(z.warn("Profile has not been loaded (yet)"),!0):(z.warn("No conversation loaded (yet)"),!0)}login(){this.store.dispatch(ss(null)),this.store.dispatch(er());let t=n=>ft(n)&&C1(n)!=="loading";return new Promise(n=>{let r=this.subscribe(t,o=>{o&&(r(),n())});this.unmountHandlers.push(()=>{r()})})}isLoggedIn(){return k(this,null,function*(){return(yield this.store.dispatch(er())).payload})}isConversationSupported(t,n){return k(this,null,function*(){return(yield this.store.dispatch(sh({sessionId:t,options:n}))).payload})}createConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(ud(t))).payload})}getConversationBySessionId(t,n){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(cd({sessionId:t,options:n}))).payload})}upsertConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(ah(t))).payload})}postMessages(t){return k(this,null,function*(){return(yield this.store.dispatch(fd(t))).payload})}updateConversation(t){return k(this,null,function*(){return(yield this.store.dispatch(dd(t))).payload})}resetConversation(){this.store.dispatch(Ae()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(ad(t))}setVisitorInfo(t){this.store.dispatch(ib(t))}setCustomData(t){this.store.dispatch(sb(t))}setAgentInfo(t,n){return k(this,null,function*(){yield this.store.dispatch(Xa(C(C({},t),n)))})}setAgentSettings(t){return k(this,null,function*(){yield this.store.dispatch(uh(t))})}getAgentSettings(){return k(this,null,function*(){return(yield this.store.dispatch(ch())).payload})}refresh(){return k(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(ef()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(un(t))}evaluateRule(o){return k(this,arguments,function*(t,n={},r=BT){return(yield this.store.dispatch(Xo({label:t,params:n,options:r}))).payload.cues})}evaluateAssistant(t,n){return k(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:i=!0,includeTags:s,expectFormat:a}=c,l=ee(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(rr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:s,input:r,skipState:!i}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return k(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){z.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,C({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return k(this,null,function*(){var n;if(!this.hasConversation())return z.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||z.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(On({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.settings,u=a?"below":"above",c=o.length>0;if(!_n(this.state)||(this.store.dispatch(q1(lh(t))),t.key!=="Tab"&&!l))return;let f=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(X1()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(Q1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():f();break;case"ArrowDown":{u==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(gd(-1)),this.store.dispatch(Jr({collapse:!0})),this.store.dispatch(eT(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let p=us(this.state);if(!p)return;this.store.dispatch(Rl(!1)),this.store.dispatch(un({text:p.text,suggestion:p,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let p=us(this.state);if(!p)return;this.store.dispatch(un({text:p.text,suggestion:p,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let p=us(this.state);if(!p)return;this.store.dispatch(un({text:p.text,suggestion:p,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(Jr({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(qr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(z.info("Start handling time"),this.store.dispatch(KC()))}handlingTimeStop(){this.state.handlingTime.startTime&&(z.info("Stop handling time"),this.store.dispatch(Ff()))}logSendMessage(t){let n=rk("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=nk(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch($C()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Lo((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(J1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){z.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),z.error(i)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(ab(t))}whenConversationLoaded(t){let n=o=>{var i;return(i=o.conversation.current)==null?void 0:i.id},r=()=>this.loadProfileConfig().then(()=>t());n(this.state)&&r(),this.subscribe(n,o=>{o&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=Vl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Ge.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,u]=Vl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,Ge.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return $o(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Ge.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),z.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(z.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Z1(r.metrics))):z.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Uf(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s,inputMediator:a}=d,l=ee(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),u={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),$o(t),this.inputMediator=a||(Yo(t)?new ni(t):new ti(t)),this.inputMediator.on("change",({plainText:p,rawHTML:y})=>{this.store.dispatch(hd({text:p,html:y}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(G1(lh(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:y})=>{this.store.dispatch(Y1({text:p,selectionText:y}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch($1(p))});let c;this.inputMediator.on("selection",p=>{clearTimeout(c),p===null?c=setTimeout(()=>{p!==null&&this.store.dispatch(yd(p))},500):this.store.dispatch(yd(p))}),this.inputMediator.on("disabled",()=>{var p;(p=this.inputMediator)==null||p.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(rf(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(rf(!0))}),this.renderSuggestions(t,u),this.subscribe(qa("inlineSuggestions"),()=>{this.renderSuggestions(t,u)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(yd(this.inputMediator.getSelection())),this.store.dispatch(rf(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var p;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((p=this.state.conversation.current)==null?void 0:p.sessionId)}),this.isMounted=!0}subscribe(t,n){let r=t(this.store.getState());return this.store.subscribe(()=>{let o=t(this.store.getState());o!==r&&(r=o,n(r))})}unmount(){var t,n,r,o;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(o=this.inputMediator)==null||o.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderSuggestions(t,n){var r,o,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.aboveSuggestions=this.renderAboveSuggestions(t,n)}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret");(0,Ge.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(lT,{})})}),o);let i=s=>{s?(o.style.display="block",o.style.top=`${s.top}px`,o.style.left=`${s.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var s;(0,Ge.unmountComponentAtNode)(o),(s=this.inputMediator)==null||s.off("caretposition",i),o.remove()}}}renderAboveSuggestions(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i}=n,s=o&&zy(t,o)||void 0,a=this.overlayContainerFactory("deepdesk-tab-completion",s||t,{appendTo:i,closestScrollElement:s,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),l=this.overlayContainerFactory("deepdesk-suggestions-overlay",s||t,{appendTo:i},r==null?void 0:r.suggestionsRootNode);return(0,Ge.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(HT,{inputElement:t})})}),a),(0,Ge.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(yT,{onLogIn:()=>this.loginViaPopup().catch(u=>z.warn(u.message))})})}),l),{unmount(){(0,Ge.unmountComponentAtNode)(a),(0,Ge.unmountComponentAtNode)(l),a.remove(),l.remove()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&zy(t,o)||void 0,l=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent);return(0,Ge.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(QE,{onLogIn:()=>this.loginViaPopup().catch(u=>z.warn(u.message))})})}),l),{unmount(){(0,Ge.unmountComponentAtNode)(l),l.remove()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays");return(0,Ge.render)((0,Me.jsx)(Go,{store:this.store,customStyles:n,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)($E,{})})}),r),{unmount(){(0,Ge.unmountComponentAtNode)(r),r.remove()}}}renderWidget(t,n={}){if(this.widgetRoot&&z.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Ge.render)((0,Me.jsx)(Go,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(_C,{onLogIn:()=>this.loginViaPopup().catch(s=>z.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Ge.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Bf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){ok(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>k(this,null,function*(){yield this.store.dispatch(cl());let t=No(this.state);t&&(yield this.store.dispatch(il()),this.store.dispatch(ad({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return k(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=p=>k(this,null,function*(){var y,v;if((y=p.data)!=null&&y.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((v=p.data)==null?void 0:v.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Za),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=p=>k(this,null,function*(){var y;if(p.origin===a.origin)switch((y=p.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){z.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),p.data.message==="Timeout"&&z.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return k(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(z.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;z.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return k(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=dl(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(mn()):du.includes(r)||this.store.dispatch(gn(r))})}catch(r){this.handleError(r)}})}};Ns.version="14.3.1-beta.14",Ns.count=0;var Wl=Ns;function iM(e){return k(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function yk(e,t){return k(this,null,function*(){let n=yield iM(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function vk(e,t,n){return k(this,null,function*(){yield new yr(e).authenticateWithKey(t,n)})}function Sk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function xk(r,o){return k(this,arguments,function*(e,t,n={}){var f,d;let{value:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function wk(r,o){return k(this,arguments,function*(e,t,n={}){let i=n.replace?no(e,n.replace.start,n.replace.end):Ls(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
28
28
  `).reverse().forEach((l,u)=>{u>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(l))}):i.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?no(e,n.selectionAfter.start,n.selectionAfter.end):(i.collapse(!1),i),u=window.getSelection();u==null||u.removeAllRanges(),u==null||u.addRange(l)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}function sM(e){let t=document.createElement("template");return t.innerHTML=e.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),t.content}function aM(e){let t=document.createDocumentFragment();return e.split(`
29
29
  `).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function bk(e,t){let n=e.parentElement;if(!n){console.warn("No insert point found");return}let{display:r}=window.getComputedStyle(n);r.includes("block")||r==="table-cell"?n==null||n.insertBefore(t,e.nextSibling):bk(n,t)}function Ek(o,i){return k(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let s;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let a=()=>{var d;let l=(d=e.ownerDocument.defaultView)!=null?d:window,u=l.getSelection();if((!u||u.rangeCount===0)&&(e.focus(),u=l.getSelection()),!u||u.rangeCount===0)return;let c=u.getRangeAt(0);if(!c)return;s=document.createElement("span"),c.insertNode(s);let f=r?sM(t):aM(t);n?bk(c.startContainer,f):(c.insertNode(f),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}return Hk(lM);})();
30
30
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "14.3.1-beta.13",
3
+ "version": "14.3.1-beta.14",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",