@deepdesk/deepdesk-sdk 19.1.1 → 19.1.2-beta.0

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.
@@ -78,7 +78,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
78
78
  `+tn),ce&&Yc([Q,q,A],hn=>{tn=Da(tn,hn," ")}),S&&ut?S.createHTML(tn):tn},t.setConfig=function(){let re=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Cm(re),Ye=!0},t.clearConfig=function(){ws=null,Ye=!1},t.isValidAttribute=function(re,C,F){ws||Cm({});let Z=ot(re),He=ot(C);return xx(Z,He,F)},t.addHook=function(re,C){typeof C=="function"&&Xc(L[re],C)},t.removeHook=function(re,C){if(C!==void 0){let F=P5(L[re],C);return F===-1?void 0:I5(L[re],F,1)[0]}return qP(L[re])},t.removeHooks=function(re){L[re]=[]},t.removeAllHooks=function(){L=eI()},t}var iI=oI();var bo=w(X());var sI={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 hr=w(R());function K5(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 j0(e){var n,r;let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(o=>o.remove()),(r=(n=t.textContent)==null?void 0:n.trim())!=null?r:""}function G5(e){return e.replace(/\r\n/g,`
79
79
  `)}var q5=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=D("Markdown",sI),s=(0,bo.useRef)(null),[a,c]=(0,bo.useState)(null),l=(0,bo.useMemo)(()=>{let m=Te.parse(G5(e));return iI.sanitize(m.toString()).replaceAll("</code>",`${K5(i.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[e]),u=m=>{var g;let x=m.target,y=!!((g=s.current)!=null&&g.querySelector("code"));if(["A","BUTTON"].includes(x.tagName)){c(null);return}a||y&&x.tagName!=="CODE"||!y&&x!==s.current||(x.addEventListener("mouseleave",()=>c(null),{once:!0}),c(x))},f=()=>{if(!a)return;c(null);let m=a.querySelector("button");m&&(mi(m,i.fadeup),r==null||r(j0(a)))},d=m=>{let x=m.target,y=x instanceof HTMLElement?x:null;if(x instanceof Element?x.closest("a"):null){m.stopPropagation();return}y&&"copyIcon"in y.dataset&&(mi(y,i.fadeup),r==null||r(j0(y.parentElement)))},p=()=>{!a||!o||(c(null),o(j0(a)))},h=m=>{if(m===null)return;let x=m.getBoundingClientRect();x.left<0?m.style.transform=`translateX(${-x.left+2}px)`:x.right>window.innerWidth&&(m.style.transform=`translateX(${window.innerWidth-x.right-2}px)`)};return(0,hr.jsxs)(bo.Fragment,{children:[a&&(r||o)&&(0,hr.jsxs)(La,{triggerRef:{current:a},className:i.popover,parentNode:a,children:[(0,hr.jsxs)("div",{className:i.options,ref:h,children:[r&&(a==null?void 0:a.tagName)==="CODE"&&(0,hr.jsx)("button",{type:"button",className:i.option,onClick:f,children:n}),o&&(0,hr.jsxs)(bo.Fragment,{children:[(0,hr.jsx)("div",{className:i.divider}),(0,hr.jsx)("button",{type:"button",className:i.option,onClick:p,children:t})]})]}),(0,hr.jsx)("div",{className:i.arrow})]}),(0,hr.jsx)("div",{ref:s,"data-testid":"widget-markdown-content",className:i.root,dangerouslySetInnerHTML:{__html:l},onMouseOver:u,onClick:d})]})},ds=q5;var W0={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 Jt=w(R()),Y5=500,X5=100,Q5=({content:e,onChange:t,onCopy:n})=>{let r=(0,fs.useRef)(null),o=D("WidgetCue",W0);return(0,fs.useEffect)(()=>{let i=r.current;if(!i)return;i.style.setProperty("height","0px");let s=Math.min(Math.max(i.scrollHeight,X5),Y5);i.style.setProperty("height",`${s}px`)},[e]),(0,Jt.jsx)("textarea",{ref:r,className:o.editableCue,onCopy:n,onChange:t,value:e})},Z5=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{let i=D("WidgetCue",W0),s=ie(qc),a=Qe(),c=J("hasKeyboardInput"),[l,u]=(0,fs.useState)(e.text),f=()=>{t&&t(l,e),n(e)},d=(m,x)=>{r&&r(m,e),x&&mi(x,i.fadeup)},p=m=>{o&&o(m,e)},h=m=>{m.preventDefault(),m.stopPropagation(),n(e)};return(0,fs.useEffect)(()=>{a("Assistant response displayed",{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text})},[]),(0,Jt.jsxs)(de,{"data-testid":"cue",children:[(0,Jt.jsx)(he,{children:(0,Jt.jsxs)(he.Content,{children:[e.title&&(0,Jt.jsx)(he.Title,{className:i.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?s(e.rule.label):e.title}),e.editable?(0,Jt.jsx)(Q5,{content:l,onCopy:()=>{let m=document.getSelection();m&&d(m.toString())},onChange:m=>{var x;return u((x=m.target.value)!=null?x:"")}}):(0,Jt.jsx)(ds,{content:e.text,useLabel:s("useCue"),copyLabel:s("copyCue"),onCopy:d,onUse:c?p:void 0})]})}),(0,Jt.jsxs)(de.ButtonsContainer,{children:[(0,Jt.jsxs)("div",{className:i.actions,children:[(0,Jt.jsx)(de.Button,{onClick:m=>{var x;return d((x=Gp(l,"reply")[0])!=null?x:l,m.target)},variant:"primary",children:s("copyCue")}),e.callToAction&&(0,Jt.jsx)(de.Button,{onClick:f,variant:"primary",children:e.callToAction.label}),(0,Jt.jsx)(de.Button,{onClick:h,variant:"secondary",children:s("removeCue")})]}),(0,Jt.jsx)(tm,{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text,feedbackText:e.text,feedbackType:"assistant"})]})]})},aI=Z5;var Fa=w(R()),J5=({cues:e})=>{let t=ve(),n=un(),r=ie(qc),o=Qe(),i=l=>{t(Yp({code:l.rule.label})),o("Assistant response closed",{evaluationId:l.evaluationId,assistantCode:l.rule.label,assistantOutput:l.text})},s=(l,u)=>{Ir(l),o("Assistant response copied",{evaluationId:u.evaluationId,assistantCode:u.rule.label,assistantOutput:u.text,copiedText:l})},a=(l,u)=>{var f;u.callToAction&&(t(qp(u)),o("Assistant call to action",{evaluationId:u.evaluationId,assistantCode:u.rule.label,assistantOutput:u.text,eventName:u.callToAction.event,value:(f=u.callToAction.value)!=null?f:l}))},c=(l,u)=>{var f;n.send(no,{text:l,suggestion:{source:"assistant",assistantCode:(f=u.rule)==null?void 0:f.label,sourceText:l}}),o("Assistant response used",{evaluationId:u.evaluationId,assistantCode:u.rule.label,assistantOutput:u.text,usedText:l})};return(0,Fa.jsx)(Fa.Fragment,{children:e.map(l=>l.isLoading?(0,Fa.jsx)(Jp,{title:l.rule.label.startsWith("__")?r(l.rule.label):l.title},l.rule.id):(0,Fa.jsx)(aI,{cue:l,onCallToAction:a,onRemove:i,onCopy:s,onUse:c},l.evaluationId))})},lI=J5;var om=w(X());var cI={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var gn=w(R());function eF(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var uI=({data:e,schema:t})=>{let n=D("WidgetCustomData",cI),r=o=>{Ir(o)};return(0,om.useEffect)(()=>{ee.info("Custom data",e,t)},[e]),(0,gn.jsx)("dl",{className:n.root,children:t.map(o=>{let i=eF(e,o.path);return(0,gn.jsxs)(om.Fragment,{children:[(0,gn.jsx)("dt",{className:n.label,children:o.label}),(0,gn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,gn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,gn.jsx)("span",{className:n.isFalse,children:o.falseValue}):o.type==="array"&&Array.isArray(i)&&i.length>0?(0,gn.jsxs)("button",{type:"button",onClick:()=>r(i.join(", ")),className:n.copyButton,children:[(0,gn.jsx)("span",{className:n.copyButtonText,children:i.join(", ")}),(0,gn.jsx)(Na,{})]}):typeof i=="string"||typeof i=="number"?(0,gn.jsxs)("button",{type:"button",onClick:()=>r(`${i}`),className:n.copyButton,children:[(0,gn.jsx)("span",{className:n.copyButtonText,children:i}),(0,gn.jsx)(Na,{})]}):"-"})]},o.label)})})};var Ze=w(X());var za={};dt(za,{enUS:()=>tF,nlNL:()=>nF});var tF={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"}]},nF={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:"Gesprek wissen"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var im={form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",resetContainer:"dd-qKIDX",sources:"dd-xf9c6",source:"dd-a-vyX",tooltip:"dd-EsgcZ",linkContent:"dd-gARDA",showMoreSources:"dd-uDGi-"};var fI=w(X());var dI={error:"dd-CoAuB"};var $0={};dt($0,{enUS:()=>rF,nlNL:()=>oF});var rF={errorPrefix:[{type:0,value:"Error:"}]},oF={errorPrefix:[{type:0,value:"Foutmelding:"}]};var tu=w(R()),pI=({message:e})=>{let t=(0,fI.useRef)(null),n=D("WidgetCardError",dI),r=ie($0);return Tu(t),(0,tu.jsx)(de,{ref:t,children:(0,tu.jsx)(he,{children:(0,tu.jsxs)(he.Content,{className:n.error,children:[r("errorPrefix")," ",e]})})})};var ge=w(R()),iF=3,sF=({sources:e,onClick:t})=>{let n=ie(za),r=D("WidgetKnowledgeAssistant",im),[o,i]=(0,Ze.useState)(!1),s=o?e:e.slice(0,iF);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.jsxs)(mt,{tooltip:!0,placement:"top-start",children:[(0,ge.jsx)(mt.Trigger,{as:"a",rel:"noreferrer",target:"_blank",href:a.url,onClick:c=>{c.stopPropagation(),t(a)},children:(0,ge.jsx)("span",{className:r.linkContent,children:a.name})}),a.url&&(0,ge.jsx)(mt.Content,{className:r.tooltip,children:decodeURIComponent(a.url)})]})},a.name)),s<e&&(0,ge.jsx)("button",{type:"button",className:r.showMoreSources,onClick:()=>i(!0),children:n("showMore",{amount:e.length-s.length})})]})},aF=({title:e,description:t})=>(0,ge.jsx)(de,{"data-testid":"knowledge-assist-empty-state",children:(0,ge.jsx)(he,{children:(0,ge.jsxs)(he.Content,{children:[(0,ge.jsx)(he.Title,{children:e}),(0,ge.jsx)(ds,{content:t})]})})}),lF=({innerRef:e,item:t,hasKeyboardInput:n,onCopy:r,onUse:o,onSourceClick:i})=>{var c;let s=ie(za),a=(0,Ze.useContext)(sm);return(0,ge.jsxs)(de,{"data-testid":"knowledge-assist-answer",ref:e,children:[(0,ge.jsx)(he,{children:(0,ge.jsxs)(he.Content,{children:[(0,ge.jsx)(he.Title,{children:t.question}),(0,ge.jsx)(ds,{content:t.answer.answer,useLabel:s("useCue"),copyLabel:s("copyCue"),onCopy:r,onUse:n?o:void 0}),(0,ge.jsx)(sF,{sources:(c=t.answer.sources)!=null?c:[],onClick:i})]})}),a.assistantCode&&(0,ge.jsxs)(de.ButtonsContainer,{children:[(0,ge.jsx)("div",{}),(0,ge.jsx)(tm,{evaluationId:t.evaluationId,feedbackType:"assistant",assistantCode:a.assistantCode,assistantOutput:t.answer.answer,feedbackText:t.answer.answer})]})]})},sm=(0,Ze.createContext)(null),am=({assistantCode:e,evaluateKnowledgeAssistFn:t,initialQuestion:n,children:r})=>{let[o,i]=(0,Ze.useState)(null),[s,a]=(0,Ze.useState)(!1),[c,l]=(0,Ze.useState)(null),[u,f]=(0,Ze.useState)(!!n),[d,p]=(0,Ze.useState)(null),h=ve(),m=Qe(),x=Qp(v=>{if(!e)throw new Error("No knowledge assistant was defined");return l(null),t({assistantCode:e,input:v,threadId:o,onNewThreadId(S){i(S)}})},{onSuccess(v){var S;m("Assistant response displayed",{evaluationId:v.evaluationId,assistantCode:e,assistantOutput:v.answer.answer,input:v.question,sources:(S=v.answer.sources)!=null?S:[]}),f(!1)},onError(v){var S;l((S=v.message)!=null?S:"Unknown error")}}),y=v=>_(null,null,function*(){a(!0),p(v),yield x.call(v),a(!1),p(null)}),g={isEnabled:!!e,assistantCode:e,isSubmitting:s,threadId:o,pendingInput:d,errorMessage:c,onSubmit:y,onReset(){o&&h(bP(o)),l(null),i(null),e&&m("Assistant thread reset",{threadId:o!=null?o:void 0,assistantCode:e})}};return(0,Ze.useEffect)(()=>{n&&g.isEnabled&&y(n)},[n]),(0,ge.jsx)(sm.Provider,{value:g,children:r})},lm=()=>{let e=ie(za),t=D("WidgetKnowledgeAssistant",im),n=(0,Ze.useContext)(sm),r=(0,Ze.useRef)(null),[o,i]=(0,Ze.useState)(""),s=c=>{i(c.target.value)},a=c=>{c.preventDefault(),n.onSubmit(o).then(()=>{var l;r.current&&((l=r.current)==null||l.focus(),i(""))})};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")})]}):null},cm=({title:e,emptyState:t})=>{var h,m;let n=ie(za),r=Qe(),o=D("WidgetKnowledgeAssistant",im),i=(0,Ze.useRef)(null),s=(0,Ze.useContext)(sm),a=(m=$(SP((h=s.threadId)!=null?h:-1)))!=null?m:[],c=J("hasKeyboardInput"),l=un(),u=(x,y)=>{Ir(x),s.assistantCode&&r("Assistant response copied",{assistantCode:s.assistantCode,assistantOutput:x,copiedText:x,evaluationId:y.evaluationId})},f=(x,y)=>{s.assistantCode&&r("Assistant source clicked",{evaluationId:y.evaluationId,assistantCode:s.assistantCode,source:x})},d=x=>{x.preventDefault(),s.onReset()},p=(x,y)=>{l.send(no,{text:x,suggestion:{source:"assistant",sourceText:x}}),s.assistantCode&&r("Assistant response used",{assistantCode:s.assistantCode,evaluationId:y.evaluationId,assistantOutput:y.answer.answer,usedText:x})};return!s.isEnabled||(a==null?void 0:a.length)===0&&!s.isSubmitting&&!t&&!s.errorMessage?null:(0,ge.jsxs)(Ze.Fragment,{children:[(0,ge.jsx)(Sr,{type:"knowledge",title:e,"data-testid":"knowledge",children:(0,ge.jsxs)(Ft,{withDivider:!0,children:[t&&a.length===0&&!s.pendingInput&&(0,ge.jsx)(aF,b({},t)),a.map((x,y)=>(0,ge.jsx)(lF,{innerRef:y===a.length-1?i:void 0,item:x,hasKeyboardInput:c,onCopy:g=>u(g,x),onUse:g=>p(g,x),onSourceClick:g=>f(g,x)},`${x.question}_${x.answer}_${y}`)),s.pendingInput&&(0,ge.jsx)(Jp,{title:s.pendingInput}),s.errorMessage&&(0,ge.jsx)(pI,{message:s.errorMessage})]})}),a.length>0&&(0,ge.jsx)("div",{className:o.resetContainer,children:(0,ge.jsx)(de.Button,{disabled:s.threadId===null||s.isSubmitting,onClick:d,children:n("resetLabel")})})]})};var hI=w(X());var cF=/(https?:\/\/[^\s]+)/,gI=e=>e.split(" ").find(t=>cF.test(t));var Wn=w(R()),uF=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=gI(r),i=ie(Lc),s=J("showImages"),a=J("fallbackImage"),c=J("hasKeyboardInput"),l=d=>{d.preventDefault(),d.stopPropagation(),c&&n(r)},u=(0,hI.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,Wn.jsxs)(de,{onClick:c?l:void 0,"data-testid":"edit-suggestion",children:[(0,Wn.jsxs)(he,{children:[s&&e.image&&(0,Wn.jsx)(he.Image,{src:Dp(e,"small",a||void 0),title:e.title}),(0,Wn.jsxs)(he.Content,{children:[e.title&&(0,Wn.jsx)(he.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,Wn.jsx)(de.Labels,{labels:e.searchKeywords}),(0,Wn.jsx)(he.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,Wn.jsxs)(de.Actions,{children:[o&&(0,Wn.jsx)(de.ActionButton,{onClick:u,label:i("visitUrl")}),c&&(0,Wn.jsx)(de.ActionButton,{primary:!0,onClick:l,label:i("useSuggestion")})]})]})},yI=uF;var nu=w(R()),dF=({lines:e,suggestions:t})=>{let n=un(),r=(o,i)=>{n.send(no,{text:o,suggestion:P(b({},i),{source:i.source,sourceText:i.text})})};return(0,nu.jsx)(nu.Fragment,{children:t.map(o=>(0,nu.jsx)(yI,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},vI=dF;var ru={};dt(ru,{enUS:()=>fF,nlNL:()=>pF});var fF={waiting:[{type:0,value:"Loading\u2026"}],waitingForConversation:[{type:0,value:"Waiting for conversation\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"}],close:[{type:0,value:"Close"}]},pF={waiting:[{type:0,value:"Laden\u2026"}],waitingForConversation:[{type:0,value:"Wachten op gesprek\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"}],close:[{type:0,value:"Sluiten"}]};var Ha={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var ae=w(R()),xI=(e,t)=>{let n=$(Et);(0,gi.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},mF=({onLogIn:e})=>{let t=D("Widget",Ha),n=J("isEmbedded"),r=J("adminUrl");return(0,ae.jsx)("div",{className:t.loginText,children:(0,ae.jsx)("div",{children:(0,ae.jsx)(Ep,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},K0=({text:e})=>{let t=D("Widget",Ha);return(0,ae.jsx)("div",{className:t.stateText,children:(0,ae.jsx)("div",{children:(0,ae.jsx)("p",{children:e})})},"notification")},gF=()=>{let e=ie(ru),t=ve(),n=D("Widget",Ha),r=J("showSearch"),o=J("isEmbedded"),i=$(li("/admin/")),s=un(),a=J("productName"),c=Qe();return xI(()=>{if(o)return t(T0()),()=>{t(RP())}},[t,o]),!r&&!i?null:(0,ae.jsxs)("div",{className:n.shortcutList,children:[r&&(0,ae.jsx)(de.Button,{"data-testid":"shortcut-search","aria-label":e("linkSearch"),className:n.shortcut,icon:(0,ae.jsx)(Ra,{}),onClick:()=>{s.send("ShowCommandPalette",{isOpen:!0}),c("open search",{via:"widget-shortcut"})},children:e("linkSearch")}),i&&(0,ae.jsx)(de.Button,{as:"a",target:"_blank",icon:(0,ae.jsx)(MP,{}),href:i,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:a}),className:n.shortcut,rel:"noreferrer",onClick:()=>{c("open my deepdesk",{via:"widget-shortcut"})},children:e("linkStudioLogin",{productName:a})})]})},hF=({title:e,content:t})=>{let n=ie(ru),[r,o]=(0,gi.useState)(!0);return r?(0,ae.jsx)(Sr,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:e,children:(0,ae.jsx)(Ft,{withDivider:!0,children:(0,ae.jsxs)(de,{children:[(0,ae.jsx)(he,{children:(0,ae.jsx)(he.Content,{children:(0,ae.jsx)(ds,{content:t})})}),(0,ae.jsx)(de.ButtonsContainer,{children:(0,ae.jsx)(de.Button,{onClick:()=>o(!1),children:n("close")})})]})})}):null},yF=()=>{let e=ve(),t=$(mc),n=$(q1),r=$(IP),o=$(c1),i=$(dp),s=$(hp),a=$(Ki),c=$(Pr);return(0,gi.useEffect)(()=>{o&&!n&&ee.warn("Custom data provided, but no schema.")},[o,n]),xI(()=>{t.forEach(({type:l})=>{l==="entities"?e(pr()):Pu.includes(l)||e(mr(l))})},[e,c,a]),(0,gi.useEffect)(()=>{r.length>0&&!t.some(l=>l.type==="cues")&&ee.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,ae.jsx)(gi.Fragment,{children:t.map(({type:l,title:u,amount:f,lines:d,schema:p,property:h})=>{var m,x;switch(l){case"entities":return i&&i.length>0&&(0,ae.jsx)(Sr,{type:l,title:u,"data-testid":`type-${l}`,children:(0,ae.jsx)(_P,{entities:i})},l);case"cues":return r&&r.length>0&&(0,ae.jsx)(Sr,{type:l,title:u,"data-testid":`type-${l}`,children:(0,ae.jsx)(Ft,{withDivider:!0,children:(0,ae.jsx)(lI,{cues:r})})},l);case"custom-data-banner":return o&&h&&o[h]&&(0,ae.jsx)(hF,{title:u,content:String(o[h])},l);case"custom-data":return o&&p&&(0,ae.jsx)(Sr,{type:l,title:u,"data-testid":`type-${l}`,children:(0,ae.jsx)(Ft,{withDivider:!0,children:(0,ae.jsx)(uI,{data:o,schema:p})})},l);default:return((x=(m=s[l])==null?void 0:m.suggestions)==null?void 0:x.length)>0&&(0,ae.jsx)(Sr,{type:l,title:u,"data-testid":`type-${l}`,children:(0,ae.jsx)(Ft,{withDivider:!0,children:(0,ae.jsx)(vI,{lines:d,contentType:l,suggestions:s[l].suggestions.slice(0,f)||[]})})},l)}})})},G0=({children:e})=>{let t=D("Widget",Ha);return(0,ae.jsx)("div",{className:t.footer,children:e})},q0=({children:e})=>{let t=D("Widget",Ha);return(0,ae.jsx)("div",{className:t.root,"data-testid":"widget",children:e})},vF=({onLogIn:e,knowledgeAssistOptions:t={},assistantOptions:n={transcript:"in-memory-transcript"}})=>{let r=ie(ru),o=$(ra),i=$(Et),s=$(GC),a=$(Ki),c=$(G1("knowledge-assist")),l=$(Y1);return o===!1?(0,ae.jsx)(K0,{text:r("notSupported")}):i===!1?(0,ae.jsx)(mF,{onLogIn:e}):i===null?(0,ae.jsx)(K0,{text:r("waiting")}):!s||!a?(0,ae.jsx)(K0,{text:r("waitingForConversation")}):(0,ae.jsx)(q0,{children:(0,ae.jsxs)(am,{initialQuestion:t.initialQuestion,assistantCode:l!=null?l:void 0,evaluateKnowledgeAssistFn:Kc,children:[(0,ae.jsxs)(Cs,{children:[(0,ae.jsx)(gF,{}),(0,ae.jsx)(yF,{}),c&&(0,ae.jsx)(cm,{title:c.title,emptyState:t.emptyState})]}),(0,ae.jsxs)(G0,{children:[c&&(0,ae.jsx)(lm,{}),(0,ae.jsx)(BP,{assistantOptions:n})]})]})})},SI=vF;function Ba(e){let t=new Range;return t.selectNodeContents(e),t}function wI(e,t,n){try{return hi(e,t,n),!0}catch(r){return!1}}function um(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function dm(e){return"tagName"in e&&e.tagName==="BR"}var ou=/[\u200B-\u200D\uFEFF]/g;function hi(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(c,l){let u=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(c))return l;for(let d=0;d<=c.length;d++)if(f.test(c[d])||u++,u===l)return d;throw new Error("Offset out of range")}function a(c){switch(c.nodeType){case Node.TEXT_NODE:{let l=c.textContent,u=l.replace(ou,""),f=o+u.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let h=s(l,t-o);h===0&&!p?r.setStartBefore(c):r.setStart(c,h)}p&&(r.setEnd(c,s(l,n-o)),i=!0),o=f;break}case Node.ELEMENT_NODE:{if(dm(c)&&(o===t&&r.setStartBefore(c),o++,o===n)){r.setEndAfter(c),i=!0;return}for(let u=0;u<c.childNodes.length&&(a(c.childNodes[u]),!i);u++);let l=c.lastChild;um(c)&&l&&!um(l)&&!dm(l)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function iu(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,c,l=0;function u(f){let d=f===e,p=f===n,h=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let m=f.textContent;p&&(a=l+m.substring(0,r).replace(ou,"").length),h&&(c=l+m.substring(0,i).replace(ou,"").length),l+=m.replace(ou,"").length;break}case Node.ELEMENT_NODE:{if(dm(f)&&f.nextSibling){l++;break}!d&&um(f)&&f.previousSibling&&l++;for(let m=0;m<f.childNodes.length;m++){let x=p&&m===r,y=h&&m===i;if(x&&(a=l),y&&(c=l),c!==void 0||((!x||!s)&&u(f.childNodes[m]),h&&m===i-1&&(c=l),c!==void 0))break}h&&(c=l);break}default:break}}if(u(e),c===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:c,end:c}}function su(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,c="";function l(u){let f=u===e,d=u===n,p=u===o;switch(d&&(a=1),u.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let h=d?r:0,m=p?i:void 0;c+=u.textContent.replace(ou,"").substring(h,m);break}case Node.ELEMENT_NODE:{if(!s&&a===1&&dm(u)&&u.nextSibling){c+=`
80
80
  `;break}!f&&!s&&a===1&&um(u)&&u.previousSibling&&(c+=`
81
- `);let h=d?r:0,m=p?Math.min(i,u.childNodes.length):u.childNodes.length;for(let x=h;x<m&&(l(u.childNodes[x]),a!==2);x++);break}default:break}p&&(a=2)}return l(e),c}var bI=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(bI||{}),Eo=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();Jo(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(bI).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 EI(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ps=class extends Eo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),su(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){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=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!EI(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!EI(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return iu(this.element,n);let r=this.lastKnownSelection;if(r&&wI(this.element,r.start,r.end))return r;let o=Ba(this.element);return o.collapse(!1),iu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return su(this.element,hi(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 xF=["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 CI(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",xF.forEach(u=>{o[u]=i[u]}),n?e.scrollHeight>Number.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 c=e.getBoundingClientRect(),l={top:c.top-e.scrollTop+a.offsetTop+Number.parseInt(i.borderTopWidth)+a.offsetHeight,left:c.left-e.scrollLeft+a.offsetLeft+Number.parseInt(i.borderLeftWidth)};return s.removeChild(r),l}var ms=class extends Eo{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 CI(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 TI(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,c])=>{s.searchParams.append(a,c)}),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 SF(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Y0=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()}},X0=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=TI(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()}},Q0=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(t){this.externalId!==t&&(this.cleanup(),ee.info("Set externalId",t),this.externalId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new X0(t,this.deepdeskUrl,{debug:!0}):new Y0(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=SF(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(ee.info("Received broadcast event",this.externalId,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;ee.info("Broadcast event",{externalId:this.externalId,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.externalId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(P(b({},o),{channel:this.externalId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),this.channel=void 0,t&&((r=this.defaultChannel)==null||r.close(),this.defaultChannel=void 0)}},kI=Q0;function wF(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function Ue(e){return Array.isArray(e)?e.map(Ue):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(b({},t),{[wF(n)]:Ue(e[n])}),{}):e}function bF(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function en(e){return Array.isArray(e)?e.map(en):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(b({},t),{[bF(n)]:en(e[n])}),{}):e}var Ua=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Z0=e=>new Promise(t=>{setTimeout(t,e)});var gs=class extends Ua{constructor(){super(...arguments);this.name="ClientError"}},ex=class extends Ua{constructor(){super(...arguments);this.name="ServerError"}},J0=new Map;function EF(e){return _(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t!=null&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(ee.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var hs=class{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.refreshingToken=null;this.lastFailedRefreshAt=null;this.failedRefreshCooldown=1e4;var r;this.fetch=(r=n.fetch)!=null?r:window.fetch.bind(window)}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,c=n.method===void 0||n.method.toLowerCase()==="get",T=n,{useCache:l=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:h=k=>k instanceof TypeError,retryOnResponse:m=k=>k.status>=500,version:x=null}=T,y=oe(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l){if(!c)throw new Error(`Can't use 'useCache' for ${n.method}`);if(J0.has(s)){r(J0.get(s));return}}let g=P(b({credentials:"include"},y),{headers:b({Accept:"application/json","Content-Type":"application/json"},y.headers)});!c&&this.csrfToken&&(g.headers=P(b({},g.headers),{"X-CSRFToken":this.csrfToken})),typeof x=="string"&&(g.headers=P(b({},g.headers),{"X-Deepdesk-API-Version":x}));let v=f,S=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&u&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let E=()=>_(this,null,function*(){return v--,a(s,g).then(k=>_(this,null,function*(){return m(k)&&!i.isAborted&&v>0?(yield Z0(d),E()):k.status===401&&p===!0&&S===!1?(S=!0,yield this.refreshToken(),E()):k})).catch(k=>_(this,null,function*(){if(h(k)&&!i.isAborted&&v>0)return yield Z0(d),E();throw k}))});E().then(k=>_(this,null,function*(){let I=yield EF(k);if(delete this.latestRequestByUrl[s],k.status>=500){o(new ex("Server Error",I));return}if(k.status===401){o(new gs("Unauthorized",I));return}if(k.status===403){o(new gs("Forbidden",I));return}if(k.status===404){o(new gs("Not Found",I));return}if(k.status>=400){o(new gs("Bad Request",I));return}l&&J0.set(s,I),r(I)})).catch(k=>{o(k)})})}validateToken(){return _(this,null,function*(){let t,n,r;try{({has_valid_access_token:t,is_logged_in:n,has_valid_refresh_token:r}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1}))}catch(o){return!1}if(!t){if(!r)return!1;try{yield this.refreshToken();let{is_logged_in:o}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1});return o}catch(o){return!1}}return n})}refreshToken(){let t=Date.now();return this.lastFailedRefreshAt&&t-this.lastFailedRefreshAt<this.failedRefreshCooldown?Promise.reject(new gs("Unauthorized","Failed to refresh token")):this.refreshingToken?this.refreshingToken:(this.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).catch(n=>{throw(n==null?void 0:n.message)==="Unauthorized"&&(this.lastFailedRefreshAt=Date.now()),n}).finally(()=>{this.refreshingToken=null}),this.refreshingToken)}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,b({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,b({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,b({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,b({method:"DELETE"},n))}};var RI;(t=>{let e;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(e=t.EvaluationStatus||(t.EvaluationStatus={}))})(RI||(RI={}));function tx(e){return P(b({},Ue(e)),{metadata:e.metadata})}var ys=class ys{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new hs(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>_(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return _(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(ys.exchangeTokenPromise||(ys.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),ys.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return _(this,null,function*(){var r;yield this.preflight(),ee.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",P(b({chat_start_time:new Date().toISOString()},en(t)),{metadata:(r=t.metadata)!=null?r:{}}));return tx(n)})}getMe(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return Ue(t)})}postIdentity(t){return _(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",en(t))})}patchMe(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",en(t));return Ue(n)})}getProfile(t){return _(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return Ue(n)})}getKnowledgeAssistant(t){return _(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return Ue(n)})}getContentTypes(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return Ue(t)})}getAccount(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return Ue(t)})}getPlatformConfig(t){return _(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return Ue(r)})}checkUserExists(t){return _(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return _(this,arguments,function*(t,n={}){yield this.preflight(),ee.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return ee.info(`Successfully retrieved conversation ${s.id} for session ${t}`),tx(s)})}isConversationSupported(r){return _(this,arguments,function*(t,n={}){ee.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return _(this,null,function*(){var i;yield this.preflight();let r=en(n);n.metadata&&(r.metadata=(i=n.metadata)!=null?i:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return tx(o)})}postMessages(t,n){return _(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>P(b({},en(r)),{metadata:r.metadata})))})}sendEvent(t,n){return _(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=oe(a,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((c,[l,u])=>P(b({},c),{[l]:u}),{}),s=["platform","agentId","agentName","agentEmail","conversationId"].reduce((c,l)=>(o[l]&&(c[l]=o[l]),c),{});return this.client.post("/api/v2/events",en(P(b(b({},i),s),{data:r,name:t})),{version:"v2"})})}getEntities(t){return _(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return _(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return _(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw ee.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return _(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",en(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return _(this,arguments,function*(t,n={},r){if(yield this.preflight(),r==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${t}/recommend/${r}`,en(n),{abortLatest:!0})).map(s=>P(b({},Ue(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,c)=>a===c.findIndex(l=>l.text===s.text))})}isLoggedIn(){return _(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return _(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,en(n),{abortLatest:!0})).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 _(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return Ue(n).map(r=>P(b({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return _(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",en(t),{abortLatest:!0,version:"v2"});return Ue(n)})}search(t){return _(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,en(t));return Ue(n)})}requestLoginByEmail(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return Ue(n)})}requestPasswordlessToken(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return Ue(t.token)})}getCsrfToken(){return _(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return _(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return Ue(n)})}evaluateAssistant(t,n){return _(this,null,function*(){var s;yield this.preflight();let r=new URLSearchParams;n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let o=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()}`,i=yield this.client.post(o,{input:(s=n==null?void 0:n.input)!=null?s:{},conversation:n==null?void 0:n.transcript});return Ue(i)})}createAssistantThread(t){return _(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return Ue(r)})}postMessageToAssistantThread(t){return _(this,null,function*(){yield this.preflight();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 Ue(i)})}translateMessages(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",en(t));return Ue(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(dS);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&ee.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};ys.exchangeTokenPromise=null;var Co=ys;var PI={startTime:null,stopTime:null},II=e=>e.handlingTime,AI=Ee({name:"handlingTime",initialState:PI,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(at,()=>PI)}}),{handlingTimeStart:_I,handlingTimeStop:fm,handlingTimeReset:MI}=AI.actions,LI=AI.reducer;var NI=(e={})=>{let t=b({onAuthError:na(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var pm={list:{keywordMatches:[]},fetchState:"idle"};var vs=fe("styleSuggestions/getAll",(n,r)=>_(null,[n,r],function*({text:e},t){var c;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(c=i.conversation.current)==null?void 0:c.profileCode;if(!s)return pm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),CF=Ee({name:"styleSuggestions",initialState:pm,reducers:{},extraReducers:e=>{e.addCase(vs.pending,t=>{t.fetchState="loading"}).addCase(vs.rejected,t=>{t.fetchState="error"}).addCase(vs.fulfilled,(t,n)=>{t.fetchState="done",Jo(t.list,n.payload)||(t.list=n.payload)}).addCase(ji,t=>{t.list=pm.list}).addCase(at,()=>pm)}}),OI=CF.reducer;var DI=(e={})=>{let t,n=!0,r=b({getStyleSuggestions:vs,debounce:500},e);return o=>i=>s=>{var p;let a=o.getState().input.text,c=i(s),l=o.getState();if(l.auth.isLoggedIn!==!0)return c;let{showStyleSuggestions:u}=l.settings;if(!((p=l.conversation.current)==null?void 0:p.id)||!u)return c;let{text:d}=l.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),c}};function TF(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var FI=(e={})=>{let t=b({getTextSuggestions:mr,getAutocompleteSuggestions:Oc,debounce:200,check:Mr},e),n;return r=>o=>i=>{var m;let{input:s}=r.getState(),a=o(i),c=r.getState();if(c.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:u}=c.settings,f=(m=c.conversation.current)==null?void 0:m.id,d=i.type===yp.toString();if(!f||!l&&!u)return a;let{input:p}=c;return TF(p,s)&&!d||(clearTimeout(n),!t.check(c))||(n=setTimeout(()=>{let x=oa(c);x===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(x))},d?0:t.debounce)),a}};var zI=vs.fulfilled.toString();function kF(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(c=>c.keyword===o),s=t.keywordMatches.filter(c=>c.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var HI=e=>t=>n=>r=>{var l;if(r.type!==zI){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(l=i.conversation)==null?void 0:l.current;if(o===s)return;let c=kF(o,s);r.type===zI&&c.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:c}})};var RF=Xd({assistants:TP,auth:UC,conversation:qC,contentTypes:$1,passwordlessToken:PP,entities:Wk,handlingTime:LI,info:h1,input:s1,settings:NC,profile:X1,search:b1,styleSuggestions:OI,ui:hR,textSuggestions:eR});function BI(e){return aC({reducer:RF,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(NI()).concat(FI({debounce:200})).concat(DI({debounce:500})).concat(HI(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,i)=>o.concat(i),n)},preloadedState:e.preloadedState})}var PF=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},IF=e=>t=>n=>r=>{var a,c;let o=t.getState(),i=ta("inlineSuggestions")(o);switch(r.type){case na.toString():{!r.payload&&e.emit("logout",void 0);break}case pr.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 ji.toString():e.logSendMessage(r.payload);break;case qp.toString():e.emit("call-to-action",{cue:r.payload});break;case Dr.fulfilled.toString():r.isBroadcasted||e.broadcast(Oy,r,!1);break;default:break}let s=n(r);switch(r.type){case ji.toString():e.handleAfterSendMessage(r.payload);break;case Fc.toString():e.onUpdateShowTabHint(r.payload);break;case fm.toString():e.logHandlingTime();break;case sa.toString():e.broadcast(wf,r);break;case Vi.toString():e.broadcast(wf,r);break;case Yp.toString():t.dispatch(Vi({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let l=o.assistants.cues.find(u=>u.code===r.meta.arg.data.assistantCode);e.emit("event",P(b({},r.meta.arg),{cue:l}));break}case Cn.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",P(b({type:PF(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}})),i&&t.dispatch(ei([]));break}case mf.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(c=o.conversation.current)==null?void 0:c.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case ei.toString():{i&&r.payload.length>0&&t.dispatch(gf(0));break}default:break}return s},UI=IF;function nx(e){return e.toISOString().replace("T"," ").replace("Z","")}var AF=(e,t)=>t.version,VI=Ut([aa,Pr,II,AF],(e,t,n,r)=>{if(!t)return ee.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(ee.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:nx(o),timeStop:nx(i)}});function jI(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:i}}=e.input,s=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:s,numPastes:r,suggestions:i}}function rx(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return rx(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?rx(o,t):null}function ox(e,t){return rx(e,t)}function WI(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function _F(e){return typeof e=="object"&&e!==null&&"tagName"in e}function mm(e){return _F(e)&&(ls(e)||Tp(e))}var KI,Hr=new Map,MF=["bottom","height","left","right","top","width"],$I=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:MF.some(n=>e[n]!==t[n]);function GI(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,...GI(t)]:[]}function qI(e,t){return!e||!t?null:P(b({},e),{top:e.top+t.top,left:e.left+t.left})}var gm=!1,YI=()=>{gm=!0;let e=[];if(Hr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Hr.delete(n);return}let r=n.getBoundingClientRect();$I(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(qI,t.rect):t.rect;$I(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Hr.size===0){gm=!1;return}KI=window.requestAnimationFrame(YI)};function ix(e,t){let n=GI(e),r=[],o=n.map((i,s)=>ix(i,a=>{r[s]=a;let c=Hr.get(e);if(!c)return;let l=r.reduce(qI,c.rect);c.callbacks.forEach(u=>u(l))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Hr.has(e)){let s=Hr.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Hr.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!gm&&YI()},unobserve(){o.forEach(s=>s.unobserve());let i=Hr.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Hr.delete(e),Hr.size||(cancelAnimationFrame(KI),gm=!1)}}}}var XI,Br=new Map,QI=()=>{Br.forEach((e,t)=>{if(!t.isConnected){Br.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)))}),Br.size!==0&&(XI=window.requestAnimationFrame(QI))};function ZI(e,t){return{observe(){let n=Br.size===0;Br.has(e)?Br.get(e).callbacks.push(t):Br.set(e,{visible:void 0,callbacks:[t]}),n&&QI()},unobserve(){let n=Br.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Br.delete(e),Br.size||cancelAnimationFrame(XI)}}}}var sx=["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 ax(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Va(e){return Number.parseFloat(e)}function hm(e){return Math.round(e*1e6)}function JI(e){return e/1e6}function lx(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Va(e.width),i=Va(e.borderLeftWidth),s=Va(e.borderRightWidth),a=Va(e.paddingRight),c=JI(hm(o)-hm(i)-hm(s)),l=JI(hm(r));if(c-l>2){let u=c-l;n.style.paddingRight=`${a+u}px`}}function au(e,t={}){var u,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(u=t.position)!=null?u:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",as(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};ax(r,n,sx),lx(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=ZI(e,()=>{ax(r,n,sx),lx(r,e,n),i(),setTimeout(i,0)}),a,c=!0,l=ix(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!c&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),c=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),c=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(ax(r,n,sx),lx(r,e,n),i(),t.placement==="below"&&n.classList.add("below"),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),h=window.getComputedStyle(t.closestScrollElement),m=Va(h.borderTopWidth),x=Va(h.borderBottomWidth),y=p.top+m-d.top,g=d.top+d.height+-(p.top+p.height-x);n.style.clipPath=`inset(${y}px 0px ${g}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),l.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),l.unobserve(),s.unobserve(),n.remove()}]}var eA=(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){ee.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function LF(e){return e.offsetParent!==null}function tA(e){if(!LF(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 ym(e,t,n=100){let r=tA(e);t({isVisible:r});let o=setInterval(()=>{let i=tA(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var lu=class extends Error{};function NF(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var vm=class{constructor(){this.queues={}}push(t,n){let r=()=>{let i=this.queues[t][1];i?(this.queues[t]=[i.promise,null],i.resolve()):delete this.queues[t]};if(!this.queues[t]){let i=n().finally(r);return this.queues[t]=[i,null],i}this.queues[t][1]&&this.queues[t][1].reject(new lu("Queued async function is outdated"));let o=NF();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};var OF={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},nA=(e,t)=>{var o,i,s;if(!((s=(i=(o=e.uiConfig)==null?void 0:o.widget)==null?void 0:i.types.find(a=>a.type==="cues"))==null?void 0:s.isActive))return ee.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[OF[t]];return r&&r.length>0?r.map(a=>a.code):(ee.warn(`No assistant set in profile for conversation event "${t}"`),[])};var xm=class{constructor(t){this.options=t;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,r;this.socket,this.eventListeners=new Map,this.url=t.url,this.maxReconnectAttempts=(n=t.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(r=t.reconnectInterval)!=null?r:this.reconnectInterval,this.shouldReconnect=t.shouldReconnect}connect(){let t=()=>this.cleanup();window.addEventListener("beforeunload",t),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",t)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=t=>{var n;try{let r=Ue(JSON.parse(t.data));r.event&&this.eventListeners.has(r.event)&&((n=this.eventListeners.get(r.event))==null||n.forEach(o=>o(r.data)))}catch(r){console.error("Error parsing WebSocket message:",r)}},this.socket.onclose=t=>{console.log("WebSocket connection closed:",t),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=t=>{console.error("WebSocket error:",t)})}reconnect(){var t,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(t=this.socket)==null||t.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(t,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:t,data:n}))}on(t,n){this.eventListeners.has(t)||this.eventListeners.set(t,[]);let r=this.eventListeners.get(t);r&&!r.includes(n)&&r.push(n)}close(){var t;(t=this.socket)==null||t.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(t=>t()),this.cleanupCallbacks=[]}};var yi=w(X());var rA={root:"dd-7zvcP",dialogContent:"dd-4C0lK",continueButton:"dd-YUPQW",buttonContinueWrapper:"dd-IKpYs",nicknameInput:"dd-rxhGp",titleWrapper:"dd-nw3nD",title:"dd-5iof5",closeButtonWrapper:"dd-UUAzA",closeButton:"dd-7rjP5",buttonsWrapper:"dd-5e9Xb",errorMessage:"dd--5VgX",errorLink:"dd-u461n"};var cx={};dt(cx,{enUS:()=>DF,nlNL:()=>FF});var DF={title:[{type:0,value:"Enter your nickname"}],close:[{type:0,value:"Close"}],nicknameDialogTitle:[{type:0,value:"Please enter the name you'd like customers to see during chat conversations. This nickname will be used across your Deepdesk environment."}],nicknameDialogInputPlaceholder:[{type:0,value:"Enter your nickname"}],nicknameDialogContinueButton:[{type:0,value:"Continue"}],nicknameDialogError:[{type:0,value:"Nickname cannot be empty or spaces only"}],nicknameDialogEmojiError:[{type:0,value:"You cannot use emojis in this field."}],nicknameDialogSaveError:[{type:0,value:"We couldn't save your details just now. Please try again, or update it at "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We couldn\u2019t save your details just now. Please try again later, or update them in My Deepdesk \u2192 Settings."}]},FF={title:[{type:0,value:"Voer je bijnaam in"}],close:[{type:0,value:"Sluiten"}],nicknameDialogTitle:[{type:0,value:"Voer de naam in die je wilt dat klanten zien tijdens chatgesprekken. Deze bijnaam wordt gebruikt in je Deepdesk-omgeving."}],nicknameDialogInputPlaceholder:[{type:0,value:"Voer je bijnaam in"}],nicknameDialogContinueButton:[{type:0,value:"Doorgaan"}],nicknameDialogError:[{type:0,value:"Bijnaam mag niet leeg of alleen spaties zijn"}],nicknameDialogEmojiError:[{type:0,value:"Je kunt geen emoji's gebruiken in dit veld."}],nicknameDialogSaveError:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw of werk het bij op "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw later, of werk ze bij in My Deepdesk \u2192 Instellingen."}]};var ct=w(R()),oA=({onClose:e,onSave:t,id:n,error:r})=>{let[o,i]=(0,yi.useState)(""),[s,a]=(0,yi.useState)(!1),[c,l]=(0,yi.useState)(!1),u=D("Nickname",rA),f=yi.default.useRef(null),d=$(y=>y.info.showNicknameDialog),p=ie(cx),h=J("adminUrl");(0,yi.useEffect)(()=>{r&&a(!0)},[r]);let m=()=>{if(!f.current)return;o.trim()?f.current.setCustomValidity(""):f.current.setCustomValidity(p("nicknameDialogError")),f.current.reportValidity()},x=y=>{y.preventDefault();let g=o.trim(),v=y.currentTarget.querySelector("#nickname-input");if(!g){v.setCustomValidity(p("nicknameDialogError")),v.reportValidity();return}v.setCustomValidity(""),t(g)};return(0,ct.jsxs)(ua,{isOpen:d,"datatest-id":n,onClose:e||(()=>{}),onBack:e||(()=>{}),children:[(0,ct.jsx)("div",{className:u.titleWrapper,children:(0,ct.jsx)("h1",{className:u.title,children:p("title")})}),(0,ct.jsxs)("form",{className:u.dialogContent,onSubmit:x,children:[(0,ct.jsx)("p",{children:p("nicknameDialogTitle")}),s&&r&&(0,ct.jsx)("div",{className:u.errorMessage,children:h?(()=>{let y=p("nicknameDialogSaveError",{account:h}),g=`${h}.deepdesk.com/admin/user-settings`,v=y.indexOf(g);if(v!==-1){let S=y.substring(0,v),E=y.substring(v+g.length);return(0,ct.jsxs)(ct.Fragment,{children:[S,(0,ct.jsx)("a",{href:g,target:"_blank",rel:"noopener noreferrer",className:u.errorLink,children:g}),E]})}return y})():p("nicknameDialogSaveErrorWithoutLink")}),(0,ct.jsx)("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:u.nicknameInput,type:"text",placeholder:p("nicknameDialogInputPlaceholder"),value:o,onChange:y=>{l(new RegExp("\\p{Extended_Pictographic}","u").test(y.target.value)),i(y.target.value)},onBlur:m,ref:f}),c&&(0,ct.jsx)("div",{className:u.errorMessage,role:"alert",children:p("nicknameDialogEmojiError")}),(0,ct.jsxs)("div",{className:u.buttonsWrapper,children:[r?(0,ct.jsx)("div",{className:u.closeButtonWrapper,children:(0,ct.jsx)("button",{type:"button",className:u.closeButton,onClick:()=>e==null?void 0:e(),children:p("close")})}):null,(0,ct.jsx)("div",{className:u.buttonContinueWrapper,children:(0,ct.jsx)("button",{type:"submit",className:u.continueButton,disabled:!o.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(o),children:p("nicknameDialogContinueButton")})})]})]})]})};var be=w(R());var iA=eA("showTabHint",!0),ja=class ja{constructor({deepdeskUrl:t,version:n=ja.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a,websocketClient:c=xm}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.belowSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.nicknameDialogUnsubscribe=null;this.nicknameDialogFailed=!1;this.dynamicThunkObject={};this.queues=new vm;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new Co(l,{token:o,fetch:i}),this.version=n,this.instanceId=ja.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[UI({broadcast:(h,m,x)=>{this.broadcastEvents.send(h,m,x)},emit:(h,m)=>this.emit(h,m),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>iA.update(h),sendEvent:(h,m)=>this.deepdeskApi.sendEvent(h,m)})]};this.store=BI(u),this.broadcastEvents=new kI({debug:!0,deepdeskUrl:l,eventMap:E1(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new c({url:`${l}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>_(this,null,function*(){var h;return(h=Et(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Fc(iA.value())),this.store.dispatch(cf({locale:r,adminUrl:l,productName:s}));let f=[],d=h=>{if(!h.conversationId)return;let m=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(CP(h))};this.hasConversation()?m():f.push(m)};this.ws.on("assistants::direct_response",d),this.ws.on("assistants::user_notification",d),this.ws.on("assistants::response_chunk",h=>{if(!h.conversationId)return;let m=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(EP(h))};this.hasConversation()?m():f.push(m)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let m=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(sa([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?m():f.push(m)});let p=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.externalId),f.forEach(m=>m()),f.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),f.length=0,p()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=Ui(this.state)[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}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(ee.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(ee.warn("Profile has not been loaded (yet)"),!0):(ee.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(Et(this.state))t();else{let n=this.subscribe(Et,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(na(null)),this.store.dispatch(to()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return _(this,null,function*(){return(yield this.store.dispatch(to())).payload})}isConversationSupported(t,n){return _(this,null,function*(){return(yield this.store.dispatch(Py({externalId:t,options:n}))).payload})}createConversation(t){return _(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(df(P(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return _(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(ff({externalId:t,options:n}))).payload})}upsertConversation(t){return _(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Iy(P(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return _(this,null,function*(){yield this.store.dispatch(Ay(t))})}updateConversation(t){return _(this,null,function*(){return(yield this.store.dispatch(pf(t))).payload})}resetConversation(){this.store.dispatch(at()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(cf(t))}setVisitorInfo(t){this.store.dispatch(f1(t))}setCustomData(t){this.store.dispatch(p1(t))}setAgentInfo(t,n){return _(this,null,function*(){var o;yield this.store.dispatch(Ql(b(b({},t),n))),(o=this.state.info.agentInfo)!=null&&o.agentNickname||this.broadcastEvents.send(Sf,{showNicknameDialog:!0})})}setAgentSettings(t){return _(this,null,function*(){yield this.store.dispatch(My(t))})}getAgentSettings(){return _(this,null,function*(){return(yield this.store.dispatch(Ly())).payload})}refresh(){return _(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let t=[];return t.push(this.refreshTextSuggestions()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(hf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t))}evaluateAssistant(t,n){return _(this,null,function*(){var c;let{input:r={},transcript:o,showCuesInWidget:i=!0,includeMetadata:s}=n||{},a=yield this.store.dispatch(Dr({assistantCode:t,transcript:o,includeMetadata:s,input:r,skipState:!i}));if(a.error)throw new Error(`Assistant evaluation failed: ${(c=a.payload)!=null?c:a.error.message}`);return a.payload.output})}evaluateConversationAssistant(t,n){return _(this,null,function*(){yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){ee.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=nA(r,t);yield Promise.all(o.map(i=>this.queues.push(i,()=>_(this,null,function*(){yield this.evaluateAssistant(i,b({includeMetadata:!0},n))})).catch(s=>{if(s instanceof lu){ee.warn(`Queued assistant "${i}" was outdated and dropped`);return}throw s})))})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:c,suggestionsPlacement:l}=this.settings,u=l==="inline"||l==="below"?"below":"above",f=o.length>0;if(this.store.dispatch(JC(_y(t))),!Mr(this.state)||t.key!=="Tab"&&!c)return;let d=()=>{n||!f||s&&(t.shiftKey||(this.store.dispatch(n1()),t.preventDefault()))},p=()=>{n||!f||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(r1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?p():d();break;case"ArrowDown":{u==="below"?d():p();break}case"Escape":{n||(this.store.dispatch(gf(-1)),this.store.dispatch(ui({collapse:!0})),this.store.dispatch(mR(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let h=ia(this.state);if(!h)return;this.store.dispatch(Fc(!1)),this.store.dispatch(Cn({text:h.text,suggestion:h,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let h=ia(this.state);if(!h)return;this.store.dispatch(Cn({text:h.text,suggestion:h,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let h=ia(this.state);if(!h)return;this.store.dispatch(Cn({text:h.text,suggestion:h,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(ui({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(ei([]))}handlingTimeStart(){this.state.handlingTime.startTime||(ee.info("Start handling time"),this.store.dispatch(_I()))}handlingTimeStop(){this.state.handlingTime.startTime&&(ee.info("Stop handling time"),this.store.dispatch(fm()))}logSendMessage(t){let n=jI(this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let t=VI(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(MI()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(ji((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(i1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){ee.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),ee.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(m1(t))}whenConversationLoaded(t){let n=i=>{var s;return(s=i.conversation.current)==null?void 0:s.id},r=()=>this.loadProfileConfig().then(()=>t());return n(this.state)&&r(),this.subscribe(n,i=>{i&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=au(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),[i,s]}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[c,l]=au(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});c.dataset.testid=n,c.style.zIndex="2",c.appendChild(r),this.unmountHandlers.push(()=>{l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return as(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),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),ee.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()?(ee.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(o1(r.metrics))):ee.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(!mm(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,c=oe(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(c),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),as(t),this.inputMediator=a||(ls(t)?new ms(t):new ps(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h})=>{this.store.dispatch(hf({text:p,html:h}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(e1(_y(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(t1({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(ZC(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(yf(p))},500):this.store.dispatch(yf(p))}),this.unmountHandlers.push(()=>{clearTimeout(u)}),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(Sp(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Sp(!0))}),this.renderSuggestions(t,l),this.subscribe(ta("inlineSuggestions"),()=>{this.renderSuggestions(t,l)}),this.subscribe(ta("suggestionsPlacement"),()=>{this.renderSuggestions(t,l)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(hf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(yf(this.inputMediator.getSelection())),this.store.dispatch(Sp(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions(),this.promptForNickname()}),this.isMounted=!0}promptForNickname(t){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let r=(0,To.createRoot)(n),o=null,i=a=>{o=a,s()},s=()=>{r==null||r.render((0,be.jsx)(fo,{store:this.store,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(oA,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>_(this,null,function*(){try{yield this.store.dispatch(u1({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(Sf,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(c){ee.error("Error setting agent nickname",c),i("error"),this.nicknameDialogFailed=!0}})})})}))};s(),this.nicknameDialogUnsubscribe=()=>{r.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}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,i;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.belowSuggestions)==null||r.unmount(),(o=this.floatingMenu)==null||o.unmount(),this.unmountHandlers.forEach(s=>s()),this.unmountHandlers=[],(i=this.inputMediator)==null||i.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(t=>t()),this.disposeHandlers=[],this.off()}renderSuggestions(t,n){var r,o,i,s;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),(s=this.belowSuggestions)==null||s.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(t,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(t,n,"above")}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret"),i=(0,To.createRoot)(o);i.render((0,be.jsx)(fo,{store:this.store,customStyles:r,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(TR,{})})}));let s=a=>{a?(o.style.display="block",o.style.top=`${a.top}px`,o.style.left=`${a.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",s),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",s),i.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:i,appendOverlayTo:s}=n,a=i&&ox(t,i)||void 0,[c,l]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:s,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:s,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,To.createRoot)(c);d.render((0,be.jsx)(fo,{store:this.store,customStyles:o,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(tP,{inputElement:t})})}));let p=(0,To.createRoot)(u);return p.render((0,be.jsx)(fo,{store:this.store,customStyles:o,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(NR,{onLogIn:()=>this.loginViaPopup().catch(h=>ee.warn(h.message))})})})),{unmount(){d.unmount(),p.unmount(),l(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&ox(t,o)||void 0,[c,l]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent),u=(0,To.createRoot)(c);return u.render((0,be.jsx)(fo,{store:this.store,customStyles:r,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(dR,{onLogIn:()=>this.loginViaPopup().catch(f=>ee.warn(f.message))})})})),{unmount(){u.unmount(),l()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,To.createRoot)(r);return o.render((0,be.jsx)(fo,{store:this.store,customStyles:n,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(sR,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&ee.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.widgetElement=t,this.configure({showImages:o,isEmbedded:i}),this.widgetRoot=(0,To.createRoot)(t),this.widgetRoot.render((0,be.jsx)(fo,{store:this.store,customStyles:r,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(SI,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(s=>ee.warn(s.message))})})}))}unmountWidget(){var t,n;(n=(t=this.widgetRoot)==null?void 0:t.unmount)==null||n.call(t),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:i}=r,s=(0,To.createRoot)(n);return s.render((0,be.jsx)(fo,{store:this.store,customStyles:o,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(q0,{children:(0,be.jsxs)(am,{assistantCode:t,initialQuestion:i,evaluateKnowledgeAssistFn:Kc,children:[(0,be.jsx)(Cs,{children:(0,be.jsx)(cm,{title:r.title,emptyState:r.emptyState})}),(0,be.jsx)(G0,{children:(0,be.jsx)(lm,{})})]})})})})),{unmount(){s.unmount()}}}setupHandlingTime(t){let n=ym(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){WI(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>_(this,null,function*(){yield this.store.dispatch(pc());let t=Ki(this.state);t&&this.store.dispatch(cf({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(t){return _(this,null,function*(){return new Promise((n,r)=>{this.store.dispatch(uf());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 c=!1,l=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=p=>_(this,null,function*(){var h,m;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((m=p.data)==null?void 0:m.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Jl),c=!0,o.port1.close(),n()}catch(x){console.error(x),r(x)}finally{c=!0,l()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");u===null&&r(new Error("Popup blocked by browser"));let f=p=>_(this,null,function*(){var h;if(p.origin===a.origin)switch((h=p.data)==null?void 0:h.type){case"deepdesk-popup-request-origin":{try{let m=JSON.stringify({type:"deepdesk-popup-parent-origin"});u==null||u.postMessage(m,a.origin)}catch(m){ee.error("Error posting message to popup",m),r(m)}break}case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});u==null||u.postMessage(m,a.origin,[o.port2])}catch(m){ee.error("Error posting message to popup",m),r(m)}break}case"deepdesk-popup-error":{if(l(),p.data.message==="Platform account url mismatch"){let m=`Please contact your administrator: The platform account url (${p.data.targetOrigin}) is misconfigured as it differs from the origin of the page that opened the popup (${p.data.openerOrigin}).`;ee.warn(m),this.store.dispatch(Ty(m)),r(new Error(m))}if(p.data.message==="Timeout"){let m="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";ee.warn(m),this.store.dispatch(Ty(m)),r(new Error(m))}r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{u&&!u.closed||(l(),c||r(new Error("Popup closed by user")))},200);this.disposeHandlers.push(l)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}refreshTextSuggestions(){return _(this,null,function*(){this.isMounted&&(yield this.store.dispatch(yp()))})}refreshWidgetSuggestions(){return _(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=mc(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(pr());break;case"pinned-messages":case"sticky-messages":break;default:Pu.includes(r)||this.store.dispatch(mr(r))}})}catch(r){this.handleError(r)}})}};ja.version="19.1.1",ja.count=0;var cu=ja;function zF(e){return _(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 sA(e,t){return _(this,null,function*(){let n=yield zF(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 aA(e,t,n){return _(this,null,function*(){yield new Co(e).authenticateWithKey(t,n)})}function lA(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function cA(r,o){return _(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},c=`${i.slice(0,s)}${t}${i.slice(a)}`,l=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},u=()=>{if(n.setValue)return n.setValue(c);e.value=c};return Promise.resolve(u()).then(()=>{e.selectionStart=l.start,e.selectionEnd=l.end,e.blur(),e.focus()})})}function uA(r,o){return _(this,arguments,function*(e,t,n={}){let i=n.replace?hi(e,n.replace.start,n.replace.end):Ba(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(`
81
+ `);let h=d?r:0,m=p?Math.min(i,u.childNodes.length):u.childNodes.length;for(let x=h;x<m&&(l(u.childNodes[x]),a!==2);x++);break}default:break}p&&(a=2)}return l(e),c}var bI=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(bI||{}),Eo=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();Jo(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(bI).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 EI(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ps=class extends Eo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),su(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){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=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!EI(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!EI(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return iu(this.element,n);let r=this.lastKnownSelection;if(r&&wI(this.element,r.start,r.end))return r;let o=Ba(this.element);return o.collapse(!1),iu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return su(this.element,hi(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 xF=["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 CI(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",xF.forEach(u=>{o[u]=i[u]}),n?e.scrollHeight>Number.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 c=e.getBoundingClientRect(),l={top:c.top-e.scrollTop+a.offsetTop+Number.parseInt(i.borderTopWidth)+a.offsetHeight,left:c.left-e.scrollLeft+a.offsetLeft+Number.parseInt(i.borderLeftWidth)};return s.removeChild(r),l}var ms=class extends Eo{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 CI(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 TI(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,c])=>{s.searchParams.append(a,c)}),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 SF(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Y0=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()}},X0=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=TI(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()}},Q0=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(t){this.externalId!==t&&(this.cleanup(),ee.info("Set externalId",t),this.externalId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new X0(t,this.deepdeskUrl,{debug:!0}):new Y0(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=SF(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(ee.info("Received broadcast event",this.externalId,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;ee.info("Broadcast event",{externalId:this.externalId,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.externalId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(P(b({},o),{channel:this.externalId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),this.channel=void 0,t&&((r=this.defaultChannel)==null||r.close(),this.defaultChannel=void 0)}},kI=Q0;function wF(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function Ue(e){return Array.isArray(e)?e.map(Ue):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(b({},t),{[wF(n)]:Ue(e[n])}),{}):e}function bF(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function en(e){return Array.isArray(e)?e.map(en):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(b({},t),{[bF(n)]:en(e[n])}),{}):e}var Ua=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Z0=e=>new Promise(t=>{setTimeout(t,e)});var gs=class extends Ua{constructor(){super(...arguments);this.name="ClientError"}},ex=class extends Ua{constructor(){super(...arguments);this.name="ServerError"}},J0=new Map;function EF(e){return _(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t!=null&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(ee.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var hs=class{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.refreshingToken=null;this.lastFailedRefreshAt=null;this.failedRefreshCooldown=1e4;var r;this.fetch=(r=n.fetch)!=null?r:window.fetch.bind(window)}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,c=n.method===void 0||n.method.toLowerCase()==="get",T=n,{useCache:l=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:h=k=>k instanceof TypeError,retryOnResponse:m=k=>k.status>=500,version:x=null}=T,y=oe(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l){if(!c)throw new Error(`Can't use 'useCache' for ${n.method}`);if(J0.has(s)){r(J0.get(s));return}}let g=P(b({credentials:"include"},y),{headers:b({Accept:"application/json","Content-Type":"application/json"},y.headers)});!c&&this.csrfToken&&(g.headers=P(b({},g.headers),{"X-CSRFToken":this.csrfToken})),typeof x=="string"&&(g.headers=P(b({},g.headers),{"X-Deepdesk-API-Version":x}));let v=f,S=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&u&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let E=()=>_(this,null,function*(){return v--,a(s,g).then(k=>_(this,null,function*(){return m(k)&&!i.isAborted&&v>0?(yield Z0(d),E()):k.status===401&&p===!0&&S===!1?(S=!0,yield this.refreshToken(),E()):k})).catch(k=>_(this,null,function*(){if(h(k)&&!i.isAborted&&v>0)return yield Z0(d),E();throw k}))});E().then(k=>_(this,null,function*(){let I=yield EF(k);if(delete this.latestRequestByUrl[s],k.status>=500){o(new ex("Server Error",I));return}if(k.status===401){o(new gs("Unauthorized",I));return}if(k.status===403){o(new gs("Forbidden",I));return}if(k.status===404){o(new gs("Not Found",I));return}if(k.status>=400){o(new gs("Bad Request",I));return}l&&J0.set(s,I),r(I)})).catch(k=>{o(k)})})}validateToken(){return _(this,null,function*(){let t,n,r;try{({has_valid_access_token:t,is_logged_in:n,has_valid_refresh_token:r}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1}))}catch(o){return!1}if(!t){if(!r)return!1;try{yield this.refreshToken();let{is_logged_in:o}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1});return o}catch(o){return!1}}return n})}refreshToken(){let t=Date.now();return this.lastFailedRefreshAt&&t-this.lastFailedRefreshAt<this.failedRefreshCooldown?Promise.reject(new gs("Unauthorized","Failed to refresh token")):this.refreshingToken?this.refreshingToken:(this.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).catch(n=>{throw(n==null?void 0:n.message)==="Unauthorized"&&(this.lastFailedRefreshAt=Date.now()),n}).finally(()=>{this.refreshingToken=null}),this.refreshingToken)}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,b({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,b({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,b({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,b({method:"DELETE"},n))}};var RI;(t=>{let e;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(e=t.EvaluationStatus||(t.EvaluationStatus={}))})(RI||(RI={}));function tx(e){return P(b({},Ue(e)),{metadata:e.metadata})}var ys=class ys{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new hs(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>_(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return _(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(ys.exchangeTokenPromise||(ys.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),ys.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return _(this,null,function*(){var r;yield this.preflight(),ee.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",P(b({chat_start_time:new Date().toISOString()},en(t)),{metadata:(r=t.metadata)!=null?r:{}}));return tx(n)})}getMe(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return Ue(t)})}postIdentity(t){return _(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",en(t))})}patchMe(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",en(t));return Ue(n)})}getProfile(t){return _(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return Ue(n)})}getKnowledgeAssistant(t){return _(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return Ue(n)})}getContentTypes(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return Ue(t)})}getAccount(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return Ue(t)})}getPlatformConfig(t){return _(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return Ue(r)})}checkUserExists(t){return _(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return _(this,arguments,function*(t,n={}){yield this.preflight(),ee.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return ee.info(`Successfully retrieved conversation ${s.id} for session ${t}`),tx(s)})}isConversationSupported(r){return _(this,arguments,function*(t,n={}){ee.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return _(this,null,function*(){var i;yield this.preflight();let r=en(n);n.metadata&&(r.metadata=(i=n.metadata)!=null?i:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return tx(o)})}postMessages(t,n){return _(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>P(b({},en(r)),{metadata:r.metadata})))})}sendEvent(t,n){return _(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=oe(a,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((c,[l,u])=>P(b({},c),{[l]:u}),{}),s=["platform","agentId","agentName","agentEmail","conversationId"].reduce((c,l)=>(o[l]&&(c[l]=o[l]),c),{});return this.client.post("/api/v2/events",en(P(b(b({},i),s),{data:r,name:t})),{version:"v2"})})}getEntities(t){return _(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return _(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return _(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw ee.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return _(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",en(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return _(this,arguments,function*(t,n={},r){if(yield this.preflight(),r==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${t}/recommend/${r}`,en(n),{abortLatest:!0})).map(s=>P(b({},Ue(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,c)=>a===c.findIndex(l=>l.text===s.text))})}isLoggedIn(){return _(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return _(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,en(n),{abortLatest:!0})).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 _(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return Ue(n).map(r=>P(b({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return _(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",en(t),{abortLatest:!0,version:"v2"});return Ue(n)})}search(t){return _(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,en(t));return Ue(n)})}requestLoginByEmail(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return Ue(n)})}requestPasswordlessToken(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return Ue(t.token)})}getCsrfToken(){return _(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return _(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return Ue(n)})}evaluateAssistant(t,n){return _(this,null,function*(){var s;yield this.preflight();let r=new URLSearchParams;n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let o=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()}`,i=yield this.client.post(o,{input:(s=n==null?void 0:n.input)!=null?s:{},conversation:n==null?void 0:n.transcript});return Ue(i)})}createAssistantThread(t){return _(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return Ue(r)})}postMessageToAssistantThread(t){return _(this,null,function*(){yield this.preflight();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 Ue(i)})}translateMessages(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",en(t));return Ue(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(dS);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&ee.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};ys.exchangeTokenPromise=null;var Co=ys;var PI={startTime:null,stopTime:null},II=e=>e.handlingTime,AI=Ee({name:"handlingTime",initialState:PI,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(at,()=>PI)}}),{handlingTimeStart:_I,handlingTimeStop:fm,handlingTimeReset:MI}=AI.actions,LI=AI.reducer;var NI=(e={})=>{let t=b({onAuthError:na(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var pm={list:{keywordMatches:[]},fetchState:"idle"};var vs=fe("styleSuggestions/getAll",(n,r)=>_(null,[n,r],function*({text:e},t){var c;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(c=i.conversation.current)==null?void 0:c.profileCode;if(!s)return pm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),CF=Ee({name:"styleSuggestions",initialState:pm,reducers:{},extraReducers:e=>{e.addCase(vs.pending,t=>{t.fetchState="loading"}).addCase(vs.rejected,t=>{t.fetchState="error"}).addCase(vs.fulfilled,(t,n)=>{t.fetchState="done",Jo(t.list,n.payload)||(t.list=n.payload)}).addCase(ji,t=>{t.list=pm.list}).addCase(at,()=>pm)}}),OI=CF.reducer;var DI=(e={})=>{let t,n=!0,r=b({getStyleSuggestions:vs,debounce:500},e);return o=>i=>s=>{var p;let a=o.getState().input.text,c=i(s),l=o.getState();if(l.auth.isLoggedIn!==!0)return c;let{showStyleSuggestions:u}=l.settings;if(!((p=l.conversation.current)==null?void 0:p.id)||!u)return c;let{text:d}=l.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),c}};function TF(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var FI=(e={})=>{let t=b({getTextSuggestions:mr,getAutocompleteSuggestions:Oc,debounce:200,check:Mr},e),n;return r=>o=>i=>{var m;let{input:s}=r.getState(),a=o(i),c=r.getState();if(c.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:u}=c.settings,f=(m=c.conversation.current)==null?void 0:m.id,d=i.type===yp.toString();if(!f||!l&&!u)return a;let{input:p}=c;return TF(p,s)&&!d||(clearTimeout(n),!t.check(c))||(n=setTimeout(()=>{let x=oa(c);x===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(x))},d?0:t.debounce)),a}};var zI=vs.fulfilled.toString();function kF(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(c=>c.keyword===o),s=t.keywordMatches.filter(c=>c.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var HI=e=>t=>n=>r=>{var l;if(r.type!==zI){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(l=i.conversation)==null?void 0:l.current;if(o===s)return;let c=kF(o,s);r.type===zI&&c.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:c}})};var RF=Xd({assistants:TP,auth:UC,conversation:qC,contentTypes:$1,passwordlessToken:PP,entities:Wk,handlingTime:LI,info:h1,input:s1,settings:NC,profile:X1,search:b1,styleSuggestions:OI,ui:hR,textSuggestions:eR});function BI(e){return aC({reducer:RF,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(NI()).concat(FI({debounce:200})).concat(DI({debounce:500})).concat(HI(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,i)=>o.concat(i),n)},preloadedState:e.preloadedState})}var PF=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},IF=e=>t=>n=>r=>{var a,c;let o=t.getState(),i=ta("inlineSuggestions")(o);switch(r.type){case na.toString():{!r.payload&&e.emit("logout",void 0);break}case pr.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 ji.toString():e.logSendMessage(r.payload);break;case qp.toString():e.emit("call-to-action",{cue:r.payload});break;case Dr.fulfilled.toString():r.isBroadcasted||e.broadcast(Oy,r,!1);break;default:break}let s=n(r);switch(r.type){case ji.toString():e.handleAfterSendMessage(r.payload);break;case Fc.toString():e.onUpdateShowTabHint(r.payload);break;case fm.toString():e.logHandlingTime();break;case sa.toString():e.broadcast(wf,r);break;case Vi.toString():e.broadcast(wf,r);break;case Yp.toString():t.dispatch(Vi({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let l=o.assistants.cues.find(u=>u.code===r.meta.arg.data.assistantCode);e.emit("event",P(b({},r.meta.arg),{cue:l}));break}case Cn.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",P(b({type:PF(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}})),i&&t.dispatch(ei([]));break}case mf.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(c=o.conversation.current)==null?void 0:c.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case ei.toString():{i&&r.payload.length>0&&t.dispatch(gf(0));break}default:break}return s},UI=IF;function nx(e){return e.toISOString().replace("T"," ").replace("Z","")}var AF=(e,t)=>t.version,VI=Ut([aa,Pr,II,AF],(e,t,n,r)=>{if(!t)return ee.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(ee.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:nx(o),timeStop:nx(i)}});function jI(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:i}}=e.input,s=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:s,numPastes:r,suggestions:i}}function rx(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return rx(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?rx(o,t):null}function ox(e,t){return rx(e,t)}function WI(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function _F(e){return typeof e=="object"&&e!==null&&"tagName"in e}function mm(e){return _F(e)&&(ls(e)||Tp(e))}var KI,Hr=new Map,MF=["bottom","height","left","right","top","width"],$I=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:MF.some(n=>e[n]!==t[n]);function GI(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,...GI(t)]:[]}function qI(e,t){return!e||!t?null:P(b({},e),{top:e.top+t.top,left:e.left+t.left})}var gm=!1,YI=()=>{gm=!0;let e=[];if(Hr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Hr.delete(n);return}let r=n.getBoundingClientRect();$I(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(qI,t.rect):t.rect;$I(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Hr.size===0){gm=!1;return}KI=window.requestAnimationFrame(YI)};function ix(e,t){let n=GI(e),r=[],o=n.map((i,s)=>ix(i,a=>{r[s]=a;let c=Hr.get(e);if(!c)return;let l=r.reduce(qI,c.rect);c.callbacks.forEach(u=>u(l))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Hr.has(e)){let s=Hr.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Hr.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!gm&&YI()},unobserve(){o.forEach(s=>s.unobserve());let i=Hr.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Hr.delete(e),Hr.size||(cancelAnimationFrame(KI),gm=!1)}}}}var XI,Br=new Map,QI=()=>{Br.forEach((e,t)=>{if(!t.isConnected){Br.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)))}),Br.size!==0&&(XI=window.requestAnimationFrame(QI))};function ZI(e,t){return{observe(){let n=Br.size===0;Br.has(e)?Br.get(e).callbacks.push(t):Br.set(e,{visible:void 0,callbacks:[t]}),n&&QI()},unobserve(){let n=Br.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Br.delete(e),Br.size||cancelAnimationFrame(XI)}}}}var sx=["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 ax(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Va(e){return Number.parseFloat(e)}function hm(e){return Math.round(e*1e6)}function JI(e){return e/1e6}function lx(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Va(e.width),i=Va(e.borderLeftWidth),s=Va(e.borderRightWidth),a=Va(e.paddingRight),c=JI(hm(o)-hm(i)-hm(s)),l=JI(hm(r));if(c-l>2){let u=c-l;n.style.paddingRight=`${a+u}px`}}function au(e,t={}){var u,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(u=t.position)!=null?u:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",as(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};ax(r,n,sx),lx(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=ZI(e,()=>{ax(r,n,sx),lx(r,e,n),i(),setTimeout(i,0)}),a,c=!0,l=ix(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!c&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),c=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),c=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(ax(r,n,sx),lx(r,e,n),i(),t.placement==="below"&&n.classList.add("below"),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),h=window.getComputedStyle(t.closestScrollElement),m=Va(h.borderTopWidth),x=Va(h.borderBottomWidth),y=p.top+m-d.top,g=d.top+d.height+-(p.top+p.height-x);n.style.clipPath=`inset(${y}px 0px ${g}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),l.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),l.unobserve(),s.unobserve(),n.remove()}]}var eA=(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){ee.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function LF(e){return e.offsetParent!==null}function tA(e){if(!LF(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 ym(e,t,n=100){let r=tA(e);t({isVisible:r});let o=setInterval(()=>{let i=tA(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var lu=class extends Error{};function NF(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var vm=class{constructor(){this.queues={}}push(t,n){let r=()=>{let i=this.queues[t][1];i?(this.queues[t]=[i.promise,null],i.resolve()):delete this.queues[t]};if(!this.queues[t]){let i=n().finally(r);return this.queues[t]=[i,null],i}this.queues[t][1]&&this.queues[t][1].reject(new lu("Queued async function is outdated"));let o=NF();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};var OF={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},nA=(e,t)=>{var o,i,s;if(!((s=(i=(o=e.uiConfig)==null?void 0:o.widget)==null?void 0:i.types.find(a=>a.type==="cues"))==null?void 0:s.isActive))return ee.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[OF[t]];return r&&r.length>0?r.map(a=>a.code):(ee.warn(`No assistant set in profile for conversation event "${t}"`),[])};var xm=class{constructor(t){this.options=t;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,r;this.socket,this.eventListeners=new Map,this.url=t.url,this.maxReconnectAttempts=(n=t.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(r=t.reconnectInterval)!=null?r:this.reconnectInterval,this.shouldReconnect=t.shouldReconnect}connect(){let t=()=>this.cleanup();window.addEventListener("beforeunload",t),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",t)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=t=>{var n;try{let r=Ue(JSON.parse(t.data));r.event&&this.eventListeners.has(r.event)&&((n=this.eventListeners.get(r.event))==null||n.forEach(o=>o(r.data)))}catch(r){console.error("Error parsing WebSocket message:",r)}},this.socket.onclose=t=>{console.log("WebSocket connection closed:",t),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=t=>{console.error("WebSocket error:",t)})}reconnect(){var t,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(t=this.socket)==null||t.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(t,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:t,data:n}))}on(t,n){this.eventListeners.has(t)||this.eventListeners.set(t,[]);let r=this.eventListeners.get(t);r&&!r.includes(n)&&r.push(n)}close(){var t;(t=this.socket)==null||t.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(t=>t()),this.cleanupCallbacks=[]}};var yi=w(X());var rA={root:"dd-7zvcP",dialogContent:"dd-4C0lK",continueButton:"dd-YUPQW",buttonContinueWrapper:"dd-IKpYs",nicknameInput:"dd-rxhGp",titleWrapper:"dd-nw3nD",title:"dd-5iof5",closeButtonWrapper:"dd-UUAzA",closeButton:"dd-7rjP5",buttonsWrapper:"dd-5e9Xb",errorMessage:"dd--5VgX",errorLink:"dd-u461n"};var cx={};dt(cx,{enUS:()=>DF,nlNL:()=>FF});var DF={title:[{type:0,value:"Enter your nickname"}],close:[{type:0,value:"Close"}],nicknameDialogTitle:[{type:0,value:"Please enter the name you'd like customers to see during chat conversations. This nickname will be used across your Deepdesk environment."}],nicknameDialogInputPlaceholder:[{type:0,value:"Enter your nickname"}],nicknameDialogContinueButton:[{type:0,value:"Continue"}],nicknameDialogError:[{type:0,value:"Nickname cannot be empty or spaces only"}],nicknameDialogEmojiError:[{type:0,value:"You cannot use emojis in this field."}],nicknameDialogSaveError:[{type:0,value:"We couldn't save your details just now. Please try again, or update it at "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We couldn\u2019t save your details just now. Please try again later, or update them in My Deepdesk \u2192 Settings."}]},FF={title:[{type:0,value:"Voer je bijnaam in"}],close:[{type:0,value:"Sluiten"}],nicknameDialogTitle:[{type:0,value:"Voer de naam in die je wilt dat klanten zien tijdens chatgesprekken. Deze bijnaam wordt gebruikt in je Deepdesk-omgeving."}],nicknameDialogInputPlaceholder:[{type:0,value:"Voer je bijnaam in"}],nicknameDialogContinueButton:[{type:0,value:"Doorgaan"}],nicknameDialogError:[{type:0,value:"Bijnaam mag niet leeg of alleen spaties zijn"}],nicknameDialogEmojiError:[{type:0,value:"Je kunt geen emoji's gebruiken in dit veld."}],nicknameDialogSaveError:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw of werk het bij op "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw later, of werk ze bij in My Deepdesk \u2192 Instellingen."}]};var ct=w(R()),oA=({onClose:e,onSave:t,id:n,error:r})=>{let[o,i]=(0,yi.useState)(""),[s,a]=(0,yi.useState)(!1),[c,l]=(0,yi.useState)(!1),u=D("Nickname",rA),f=yi.default.useRef(null),d=$(y=>y.info.showNicknameDialog),p=ie(cx),h=J("adminUrl");(0,yi.useEffect)(()=>{r&&a(!0)},[r]);let m=()=>{if(!f.current)return;o.trim()?f.current.setCustomValidity(""):f.current.setCustomValidity(p("nicknameDialogError")),f.current.reportValidity()},x=y=>{y.preventDefault();let g=o.trim(),v=y.currentTarget.querySelector("#nickname-input");if(!g){v.setCustomValidity(p("nicknameDialogError")),v.reportValidity();return}v.setCustomValidity(""),t(g)};return(0,ct.jsxs)(ua,{isOpen:d,"datatest-id":n,onClose:e||(()=>{}),onBack:e||(()=>{}),children:[(0,ct.jsx)("div",{className:u.titleWrapper,children:(0,ct.jsx)("h1",{className:u.title,children:p("title")})}),(0,ct.jsxs)("form",{className:u.dialogContent,onSubmit:x,children:[(0,ct.jsx)("p",{children:p("nicknameDialogTitle")}),s&&r&&(0,ct.jsx)("div",{className:u.errorMessage,children:h?(()=>{let y=p("nicknameDialogSaveError",{account:h}),g=`${h}.deepdesk.com/admin/user-settings`,v=y.indexOf(g);if(v!==-1){let S=y.substring(0,v),E=y.substring(v+g.length);return(0,ct.jsxs)(ct.Fragment,{children:[S,(0,ct.jsx)("a",{href:g,target:"_blank",rel:"noopener noreferrer",className:u.errorLink,children:g}),E]})}return y})():p("nicknameDialogSaveErrorWithoutLink")}),(0,ct.jsx)("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:u.nicknameInput,type:"text",placeholder:p("nicknameDialogInputPlaceholder"),value:o,onChange:y=>{l(new RegExp("\\p{Extended_Pictographic}","u").test(y.target.value)),i(y.target.value)},onBlur:m,ref:f}),c&&(0,ct.jsx)("div",{className:u.errorMessage,role:"alert",children:p("nicknameDialogEmojiError")}),(0,ct.jsxs)("div",{className:u.buttonsWrapper,children:[r?(0,ct.jsx)("div",{className:u.closeButtonWrapper,children:(0,ct.jsx)("button",{type:"button",className:u.closeButton,onClick:()=>e==null?void 0:e(),children:p("close")})}):null,(0,ct.jsx)("div",{className:u.buttonContinueWrapper,children:(0,ct.jsx)("button",{type:"submit",className:u.continueButton,disabled:!o.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(o),children:p("nicknameDialogContinueButton")})})]})]})]})};var be=w(R());var iA=eA("showTabHint",!0),ja=class ja{constructor({deepdeskUrl:t,version:n=ja.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a,websocketClient:c=xm}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.belowSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.nicknameDialogUnsubscribe=null;this.nicknameDialogFailed=!1;this.dynamicThunkObject={};this.queues=new vm;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new Co(l,{token:o,fetch:i}),this.version=n,this.instanceId=ja.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[UI({broadcast:(h,m,x)=>{this.broadcastEvents.send(h,m,x)},emit:(h,m)=>this.emit(h,m),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>iA.update(h),sendEvent:(h,m)=>this.deepdeskApi.sendEvent(h,m)})]};this.store=BI(u),this.broadcastEvents=new kI({debug:!0,deepdeskUrl:l,eventMap:E1(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new c({url:`${l}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>_(this,null,function*(){var h;return(h=Et(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Fc(iA.value())),this.store.dispatch(cf({locale:r,adminUrl:l,productName:s}));let f=[],d=h=>{if(!h.conversationId)return;let m=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(CP(h))};this.hasConversation()?m():f.push(m)};this.ws.on("assistants::direct_response",d),this.ws.on("assistants::user_notification",d),this.ws.on("assistants::response_chunk",h=>{if(!h.conversationId)return;let m=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(EP(h))};this.hasConversation()?m():f.push(m)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let m=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(sa([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?m():f.push(m)});let p=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.externalId),f.forEach(m=>m()),f.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),f.length=0,p()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=Ui(this.state)[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}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(ee.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(ee.warn("Profile has not been loaded (yet)"),!0):(ee.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(Et(this.state))t();else{let n=this.subscribe(Et,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(na(null)),this.store.dispatch(to()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return _(this,null,function*(){return(yield this.store.dispatch(to())).payload})}isConversationSupported(t,n){return _(this,null,function*(){return(yield this.store.dispatch(Py({externalId:t,options:n}))).payload})}createConversation(t){return _(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(df(P(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return _(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(ff({externalId:t,options:n}))).payload})}upsertConversation(t){return _(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Iy(P(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return _(this,null,function*(){yield this.store.dispatch(Ay(t))})}updateConversation(t){return _(this,null,function*(){return(yield this.store.dispatch(pf(t))).payload})}resetConversation(){this.store.dispatch(at()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(cf(t))}setVisitorInfo(t){this.store.dispatch(f1(t))}setCustomData(t){this.store.dispatch(p1(t))}setAgentInfo(t,n){return _(this,null,function*(){var o;yield this.store.dispatch(Ql(b(b({},t),n))),(o=this.state.info.agentInfo)!=null&&o.agentNickname||this.broadcastEvents.send(Sf,{showNicknameDialog:!0})})}setAgentSettings(t){return _(this,null,function*(){yield this.store.dispatch(My(t))})}getAgentSettings(){return _(this,null,function*(){return(yield this.store.dispatch(Ly())).payload})}refresh(){return _(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let t=[];return t.push(this.refreshTextSuggestions()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(hf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t))}evaluateAssistant(t,n){return _(this,null,function*(){var c;let{input:r={},transcript:o,showCuesInWidget:i=!0,includeMetadata:s}=n||{},a=yield this.store.dispatch(Dr({assistantCode:t,transcript:o,includeMetadata:s,input:r,skipState:!i}));if(a.error)throw new Error(`Assistant evaluation failed: ${(c=a.payload)!=null?c:a.error.message}`);return a.payload.output})}evaluateConversationAssistant(t,n){return _(this,null,function*(){yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){ee.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=nA(r,t);yield Promise.all(o.map(i=>this.queues.push(i,()=>_(this,null,function*(){yield this.evaluateAssistant(i,b({includeMetadata:!0},n))})).catch(s=>{if(s instanceof lu){ee.warn(`Queued assistant "${i}" was outdated and dropped`);return}throw s})))})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:c,suggestionsPlacement:l}=this.settings,u=l==="inline"||l==="below"?"below":"above",f=o.length>0;if(this.store.dispatch(JC(_y(t))),!Mr(this.state)||t.key!=="Tab"&&!c)return;let d=()=>{n||!f||s&&(t.shiftKey||(this.store.dispatch(n1()),t.preventDefault()))},p=()=>{n||!f||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(r1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?p():d();break;case"ArrowDown":{u==="below"?d():p();break}case"Escape":{n||(this.store.dispatch(gf(-1)),this.store.dispatch(ui({collapse:!0})),this.store.dispatch(mR(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let h=ia(this.state);if(!h)return;this.store.dispatch(Fc(!1)),this.store.dispatch(Cn({text:h.text,suggestion:h,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let h=ia(this.state);if(!h)return;this.store.dispatch(Cn({text:h.text,suggestion:h,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let h=ia(this.state);if(!h)return;this.store.dispatch(Cn({text:h.text,suggestion:h,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(ui({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(ei([]))}handlingTimeStart(){this.state.handlingTime.startTime||(ee.info("Start handling time"),this.store.dispatch(_I()))}handlingTimeStop(){this.state.handlingTime.startTime&&(ee.info("Stop handling time"),this.store.dispatch(fm()))}logSendMessage(t){let n=jI(this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let t=VI(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(MI()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(ji((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(i1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){ee.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),ee.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(m1(t))}whenConversationLoaded(t){let n=i=>{var s;return(s=i.conversation.current)==null?void 0:s.id},r=()=>this.loadProfileConfig().then(()=>t());return n(this.state)&&r(),this.subscribe(n,i=>{i&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=au(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),[i,s]}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[c,l]=au(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});c.dataset.testid=n,c.style.zIndex="2",c.appendChild(r),this.unmountHandlers.push(()=>{l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return as(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),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),ee.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()?(ee.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(o1(r.metrics))):ee.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(!mm(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,c=oe(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(c),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),as(t),this.inputMediator=a||(ls(t)?new ms(t):new ps(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h})=>{this.store.dispatch(hf({text:p,html:h}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(e1(_y(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(t1({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(ZC(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(yf(p))},500):this.store.dispatch(yf(p))}),this.unmountHandlers.push(()=>{clearTimeout(u)}),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(Sp(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Sp(!0))}),this.renderSuggestions(t,l),this.subscribe(ta("inlineSuggestions"),()=>{this.renderSuggestions(t,l)}),this.subscribe(ta("suggestionsPlacement"),()=>{this.renderSuggestions(t,l)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(hf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(yf(this.inputMediator.getSelection())),this.store.dispatch(Sp(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions(),this.promptForNickname()}),this.isMounted=!0}promptForNickname(t){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let r=(0,To.createRoot)(n),o=null,i=a=>{o=a,s()},s=()=>{r==null||r.render((0,be.jsx)(fo,{store:this.store,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(oA,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>_(this,null,function*(){try{yield this.store.dispatch(u1({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(Sf,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(c){ee.error("Error setting agent nickname",c),i("error"),this.nicknameDialogFailed=!0}})})})}))};s(),this.nicknameDialogUnsubscribe=()=>{r.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}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,i;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.belowSuggestions)==null||r.unmount(),(o=this.floatingMenu)==null||o.unmount(),this.unmountHandlers.forEach(s=>s()),this.unmountHandlers=[],(i=this.inputMediator)==null||i.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(t=>t()),this.disposeHandlers=[],this.off()}renderSuggestions(t,n){var r,o,i,s;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),(s=this.belowSuggestions)==null||s.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(t,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(t,n,"above")}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret"),i=(0,To.createRoot)(o);i.render((0,be.jsx)(fo,{store:this.store,customStyles:r,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(TR,{})})}));let s=a=>{a?(o.style.display="block",o.style.top=`${a.top}px`,o.style.left=`${a.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",s),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",s),i.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:i,appendOverlayTo:s}=n,a=i&&ox(t,i)||void 0,[c,l]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:s,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:s,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,To.createRoot)(c);d.render((0,be.jsx)(fo,{store:this.store,customStyles:o,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(tP,{inputElement:t})})}));let p=(0,To.createRoot)(u);return p.render((0,be.jsx)(fo,{store:this.store,customStyles:o,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(NR,{onLogIn:()=>this.loginViaPopup().catch(h=>ee.warn(h.message))})})})),{unmount(){d.unmount(),p.unmount(),l(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&ox(t,o)||void 0,[c,l]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent),u=(0,To.createRoot)(c);return u.render((0,be.jsx)(fo,{store:this.store,customStyles:r,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(dR,{onLogIn:()=>this.loginViaPopup().catch(f=>ee.warn(f.message))})})})),{unmount(){u.unmount(),l()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,To.createRoot)(r);return o.render((0,be.jsx)(fo,{store:this.store,customStyles:n,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(sR,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&ee.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.widgetElement=t,this.configure({showImages:o,isEmbedded:i}),this.widgetRoot=(0,To.createRoot)(t),this.widgetRoot.render((0,be.jsx)(fo,{store:this.store,customStyles:r,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(SI,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(s=>ee.warn(s.message))})})}))}unmountWidget(){var t,n;(n=(t=this.widgetRoot)==null?void 0:t.unmount)==null||n.call(t),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:i}=r,s=(0,To.createRoot)(n);return s.render((0,be.jsx)(fo,{store:this.store,customStyles:o,children:(0,be.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,be.jsx)(q0,{children:(0,be.jsxs)(am,{assistantCode:t,initialQuestion:i,evaluateKnowledgeAssistFn:Kc,children:[(0,be.jsx)(Cs,{children:(0,be.jsx)(cm,{title:r.title,emptyState:r.emptyState})}),(0,be.jsx)(G0,{children:(0,be.jsx)(lm,{})})]})})})})),{unmount(){s.unmount()}}}setupHandlingTime(t){let n=ym(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){WI(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>_(this,null,function*(){yield this.store.dispatch(pc());let t=Ki(this.state);t&&this.store.dispatch(cf({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(t){return _(this,null,function*(){return new Promise((n,r)=>{this.store.dispatch(uf());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 c=!1,l=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=p=>_(this,null,function*(){var h,m;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((m=p.data)==null?void 0:m.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Jl),c=!0,o.port1.close(),n()}catch(x){console.error(x),r(x)}finally{c=!0,l()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");u===null&&r(new Error("Popup blocked by browser"));let f=p=>_(this,null,function*(){var h;if(p.origin===a.origin)switch((h=p.data)==null?void 0:h.type){case"deepdesk-popup-request-origin":{try{let m=JSON.stringify({type:"deepdesk-popup-parent-origin"});u==null||u.postMessage(m,a.origin)}catch(m){ee.error("Error posting message to popup",m),r(m)}break}case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});u==null||u.postMessage(m,a.origin,[o.port2])}catch(m){ee.error("Error posting message to popup",m),r(m)}break}case"deepdesk-popup-error":{if(l(),p.data.message==="Platform account url mismatch"){let m=`Please contact your administrator: The platform account url (${p.data.targetOrigin}) is misconfigured as it differs from the origin of the page that opened the popup (${p.data.openerOrigin}).`;ee.warn(m),this.store.dispatch(Ty(m)),r(new Error(m))}if(p.data.message==="Timeout"){let m="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";ee.warn(m),this.store.dispatch(Ty(m)),r(new Error(m))}r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{u&&!u.closed||(l(),c||r(new Error("Popup closed by user")))},200);this.disposeHandlers.push(l)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}refreshTextSuggestions(){return _(this,null,function*(){this.isMounted&&(yield this.store.dispatch(yp()))})}refreshWidgetSuggestions(){return _(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=mc(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(pr());break;case"pinned-messages":case"sticky-messages":break;default:Pu.includes(r)||this.store.dispatch(mr(r))}})}catch(r){this.handleError(r)}})}};ja.version="19.1.2-beta.0",ja.count=0;var cu=ja;function zF(e){return _(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 sA(e,t){return _(this,null,function*(){let n=yield zF(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 aA(e,t,n){return _(this,null,function*(){yield new Co(e).authenticateWithKey(t,n)})}function lA(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function cA(r,o){return _(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},c=`${i.slice(0,s)}${t}${i.slice(a)}`,l=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},u=()=>{if(n.setValue)return n.setValue(c);e.value=c};return Promise.resolve(u()).then(()=>{e.selectionStart=l.start,e.selectionEnd=l.end,e.blur(),e.focus()})})}function uA(r,o){return _(this,arguments,function*(e,t,n={}){let i=n.replace?hi(e,n.replace.start,n.replace.end):Ba(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(`
82
82
  `).reverse().forEach((c,l)=>{l>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(c))}):i.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let c=n.selectionAfter?hi(e,n.selectionAfter.start,n.selectionAfter.end):(i.collapse(!1),i),l=window.getSelection();l==null||l.removeAllRanges(),l==null||l.addRange(c)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}function HF(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 BF(e){let t=document.createDocumentFragment();return e.split(`
83
83
  `).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 dA(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):dA(n,t)}function fA(o,i){return _(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 c=(d=e.ownerDocument.defaultView)!=null?d:window,l=c.getSelection();if((!l||l.rangeCount===0)&&(e.focus(),l=c.getSelection()),!l||l.rangeCount===0)return;let u=l.getRangeAt(0);if(!u)return;s=document.createElement("span"),u.insertNode(s);let f=r?HF(t):BF(t);n?dA(u.startContainer,f):(u.insertNode(f),u.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 TA(UF);})();
84
84
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "19.1.1",
3
+ "version": "19.1.2-beta.0",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",